peer-bridge 0.0.0-stage → 0.7.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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.ko.md +202 -0
  3. package/README.md +242 -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 +19 -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 +57 -4
  28. package/scripts/postinstall.mjs +25 -0
  29. package/scripts/preuninstall.mjs +20 -0
  30. package/skills/peer-bridge/SKILL.md +70 -0
  31. package/src/adapters/antigravity/hooks.mjs +207 -0
  32. package/src/adapters/claude/hooks.mjs +204 -0
  33. package/src/adapters/codex/hooks.mjs +142 -0
  34. package/src/adapters/gemini/hooks.mjs +159 -0
  35. package/src/adapters/installer.mjs +328 -0
  36. package/src/cli/main.mjs +785 -0
  37. package/src/client/rpc.mjs +243 -0
  38. package/src/config.mjs +154 -0
  39. package/src/daemon/broker.mjs +1799 -0
  40. package/src/daemon/resolver.mjs +200 -0
  41. package/src/daemon/server.mjs +221 -0
  42. package/src/index.mjs +60 -0
  43. package/src/mcp/server.mjs +668 -0
  44. package/src/orchestrator/workflows.mjs +496 -0
  45. package/src/project.mjs +81 -0
  46. package/src/protocol.mjs +203 -0
  47. package/src/runtime/conv-api.mjs +101 -0
  48. package/src/runtime/host-discovery.mjs +635 -0
  49. package/src/runtime/native-claude.mjs +88 -0
  50. package/src/runtime/paseo.mjs +289 -0
  51. package/src/runtime/workers.mjs +751 -0
  52. package/src/skills.mjs +115 -0
  53. package/src/storage/db.mjs +704 -0
  54. package/src/tui/render.mjs +472 -0
  55. package/src/tui/viewer.mjs +443 -0
@@ -0,0 +1,1799 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { getConfig } from '../config.mjs';
3
+ import { isSameProjectScope } from '../project.mjs';
4
+ import {
5
+ CLOSE_POLICIES,
6
+ EXEC_MODES,
7
+ MESSAGE_KINDS,
8
+ ORIGINS,
9
+ RUNTIMES,
10
+ RpcError,
11
+ TASK_STATUSES,
12
+ cleanSummary,
13
+ formatPeerMessageXml,
14
+ formatTaskCallbackXml,
15
+ makeHandle,
16
+ makeId,
17
+ nowIso,
18
+ resolveAgyModels,
19
+ verifyArtifacts,
20
+ } from '../protocol.mjs';
21
+ import { StateDB, sanitizePeerForClient } from '../storage/db.mjs';
22
+ import { ConversationApi } from '../runtime/conv-api.mjs';
23
+ import { scanNativeClaudePeers } from '../runtime/native-claude.mjs';
24
+ import { discoverHostPeers, mergeAllPeers } from '../runtime/host-discovery.mjs';
25
+ import { PaseoAgentWorker, PaseoClient } from '../runtime/paseo.mjs';
26
+ import {
27
+ AgyStreamWorker,
28
+ CcStreamWorker,
29
+ CodexExecWorker,
30
+ GeminiCliWorker,
31
+ MockStreamWorker,
32
+ killTmuxPane,
33
+ spawnTmuxPane,
34
+ } from '../runtime/workers.mjs';
35
+ import { WorkflowOrchestrator } from '../orchestrator/workflows.mjs';
36
+ import { resolveTarget } from './resolver.mjs';
37
+
38
+ function buildEnvelope(row, contract = null) {
39
+ const env = {
40
+ msg_id: row.msg_id,
41
+ thread_id: row.thread_id,
42
+ from: {
43
+ id: row.from_peer_id || null,
44
+ runtime: row.from_runtime || null,
45
+ name: row.from_name || null,
46
+ },
47
+ to: row.to_raw,
48
+ to_peer_id: row.to_peer_id,
49
+ kind: row.kind,
50
+ body: row.body,
51
+ reply_expected: Boolean(row.reply_expected),
52
+ hop_count: row.hop_count,
53
+ max_hops: row.max_hops,
54
+ delivery_mode: row.delivery_mode,
55
+ status: row.status,
56
+ created_at: row.created_at,
57
+ };
58
+ if (contract) {
59
+ env.contract = contract;
60
+ }
61
+ return env;
62
+ }
63
+
64
+ function taskToContract(task) {
65
+ if (!task) return null;
66
+ return {
67
+ request_id: task.request_id,
68
+ title: task.title || null,
69
+ expected_artifacts: task.expected_artifacts || [],
70
+ acceptance_criteria: task.acceptance_criteria || [],
71
+ require_artifacts: Boolean(task.require_artifacts),
72
+ notify_on_finish: Boolean(task.notify_on_finish),
73
+ callback_to: task.callback_to || null,
74
+ };
75
+ }
76
+
77
+ function sanitizePaseoName(raw, fallbackId) {
78
+ const cleaned = String(raw || '')
79
+ .trim()
80
+ .replace(/^peer-bridge:/i, '')
81
+ .replace(/\s+/g, '-')
82
+ .replace(/[^a-zA-Z0-9._-가-힣]/g, '')
83
+ .slice(0, 40);
84
+ return cleaned || String(fallbackId || 'agent').slice(0, 12);
85
+ }
86
+
87
+ const SPAWNABLE_RUNTIMES = new Set(['agy', 'cc', 'codex', 'gemini', 'paseo']);
88
+
89
+ export class PeerBroker extends EventEmitter {
90
+ constructor(options = {}) {
91
+ super();
92
+ this.config = getConfig(options.config || {});
93
+ this.db = options.db || new StateDB(this.config.dbPath);
94
+ this.skipNativePidCheck = Boolean(options.skipNativePidCheck);
95
+ this.workerFactory = options.workerFactory || null;
96
+ this.convApiFactory = options.convApiFactory || ((creds) => new ConversationApi(creds));
97
+ this.paseoClientFactory =
98
+ options.paseoClientFactory ||
99
+ ((opts = {}) =>
100
+ new PaseoClient({
101
+ paseoBin: this.config.paseoBin,
102
+ host: opts.host ?? this.config.paseoHost,
103
+ home: opts.home ?? this.config.paseoHome,
104
+ }));
105
+
106
+ /** @type {Map<string, any>} */
107
+ this.workers = new Map();
108
+ /** @type {Map<string, Promise<any>>} */
109
+ this.peerQueues = new Map();
110
+ /** @type {Map<string, Set<{ resolve: Function, reject: Function, timer: any }>>} */
111
+ this.waiters = new Map();
112
+ /** @type {Map<string, Set<(event: any) => void>>} */
113
+ this.channelSubscribers = new Map();
114
+ /** @type {Set<(event: any) => void>} */
115
+ this.monitorSubscribers = new Set();
116
+ /** @type {Map<string, Set<{ resolve: Function, reject: Function, timer: any }>>} */
117
+ this.taskWaiters = new Map();
118
+ /** @type {Map<string, Set<{ resolve: Function, reject: Function, timer: any }>>} */
119
+ this.workflowWaiters = new Map();
120
+
121
+ this.orchestrator = new WorkflowOrchestrator(this);
122
+ this.closed = false;
123
+ this.startedAt = nowIso();
124
+ }
125
+
126
+ _emitMonitorEvent(event, data = {}) {
127
+ if (!this.monitorSubscribers || this.monitorSubscribers.size === 0) return;
128
+ const payload = { kind: 'monitor', event, ts: nowIso(), ...data };
129
+ for (const pushFn of this.monitorSubscribers) {
130
+ try {
131
+ pushFn(payload);
132
+ } catch {
133
+ // ignore broken subscriber; cleanup happens on socket close
134
+ }
135
+ }
136
+ }
137
+
138
+ getStatus() {
139
+ const activePeers = this.db.listPeers({ includeOffline: false });
140
+ return {
141
+ pid: process.pid,
142
+ started_at: this.startedAt,
143
+ home_dir: this.config.homeDir,
144
+ sock_path: this.config.sockPath,
145
+ db_path: this.config.dbPath,
146
+ active_peers: activePeers.length,
147
+ managed_workers: this.workers.size,
148
+ active_waiters: [...this.waiters.values()].reduce((acc, s) => acc + s.size, 0),
149
+ channel_subscribers: [...this.channelSubscribers.values()].reduce((acc, s) => acc + s.size, 0),
150
+ };
151
+ }
152
+
153
+ registerPeer(params = {}) {
154
+ const runtime = String(params.runtime || '').toLowerCase();
155
+ if (!RUNTIMES.has(runtime)) {
156
+ throw new RpcError('INVALID_PARAMS', `Unsupported runtime "${params.runtime}"`);
157
+ }
158
+ const origin = params.origin || 'attached';
159
+ if (!ORIGINS.has(origin)) {
160
+ throw new RpcError('INVALID_PARAMS', `Invalid origin "${origin}"`);
161
+ }
162
+ const execMode = params.exec_mode || (origin === 'spawned' ? 'headless' : 'interactive');
163
+ if (!EXEC_MODES.has(execMode)) {
164
+ throw new RpcError('INVALID_PARAMS', `Invalid exec_mode "${execMode}"`);
165
+ }
166
+
167
+ const name =
168
+ String(params.name || '').trim() ||
169
+ (params.session_id ? String(params.session_id).slice(0, 8) : makeId(runtime).slice(0, 12));
170
+
171
+ const regMeta = { ...(params.metadata || {}) };
172
+ if (params.summary !== undefined) {
173
+ regMeta.summary = cleanSummary(params.summary);
174
+ } else if (regMeta.summary !== undefined) {
175
+ regMeta.summary = cleanSummary(regMeta.summary);
176
+ }
177
+
178
+ const peer = this.db.upsertPeer({
179
+ peer_id: params.peer_id || null,
180
+ runtime,
181
+ name,
182
+ session_id: params.session_id || null,
183
+ origin,
184
+ spawned_by: params.spawned_by || null,
185
+ exec_mode: execMode,
186
+ state: params.state || 'idle',
187
+ cwd: params.cwd || null,
188
+ model: params.model || null,
189
+ pid: params.pid ?? null,
190
+ pane_id: params.pane_id || null,
191
+ ls_address: params.ls_address || null,
192
+ csrf_token: params.csrf_token || null,
193
+ project_id: params.project_id || null,
194
+ metadata: regMeta,
195
+ });
196
+
197
+ if (
198
+ runtime === 'paseo' &&
199
+ peer.session_id &&
200
+ execMode === 'external' &&
201
+ params.attach_paseo_worker !== false &&
202
+ !this.workers.has(peer.peer_id)
203
+ ) {
204
+ const client = this.paseoClientFactory({
205
+ host: params.host || params.metadata?.paseo_host || undefined,
206
+ home: params.home || params.metadata?.paseo_home || undefined,
207
+ });
208
+ const worker = new PaseoAgentWorker({
209
+ peerId: peer.peer_id,
210
+ name: peer.name,
211
+ client,
212
+ sessionId: peer.session_id,
213
+ cwd: peer.cwd || process.cwd(),
214
+ behavior: params.behavior || 'steer',
215
+ wait: params.wait !== undefined ? Boolean(params.wait) : true,
216
+ });
217
+ worker.start();
218
+ this.workers.set(peer.peer_id, worker);
219
+ }
220
+
221
+ this._emitMonitorEvent('peer.updated', { peer_id: peer.peer_id });
222
+ return { peer: sanitizePeerForClient(peer) };
223
+ }
224
+
225
+ heartbeatPeer(params = {}) {
226
+ const peer = this._lookupPeer(params);
227
+ if (!peer) {
228
+ throw new RpcError('NOT_FOUND', 'Peer not found for heartbeat');
229
+ }
230
+ const metaPatch = {};
231
+ if (params.summary !== undefined) {
232
+ metaPatch.summary = cleanSummary(params.summary, 120, { preferLast: true });
233
+ }
234
+ if (params.needs_input !== undefined) {
235
+ metaPatch.needs_input = Boolean(params.needs_input);
236
+ } else if (params.state === 'idle' || params.state === 'busy') {
237
+ metaPatch.needs_input = false;
238
+ }
239
+ const updated = this.db.updatePeerState(peer.peer_id, params.state || peer.state, {
240
+ session_id: params.session_id ?? peer.session_id,
241
+ ls_address: params.ls_address ?? peer.ls_address,
242
+ csrf_token: params.csrf_token ?? peer.csrf_token,
243
+ project_id: params.project_id ?? peer.project_id,
244
+ pid: params.pid ?? peer.pid,
245
+ cwd: params.cwd ?? peer.cwd,
246
+ ...(Object.keys(metaPatch).length ? { metadata: metaPatch } : {}),
247
+ });
248
+ this._emitMonitorEvent('peer.updated', { peer_id: updated.peer_id });
249
+ return { peer: sanitizePeerForClient(updated) };
250
+ }
251
+
252
+ listPeers(params = {}) {
253
+ const scopeCwd = params.cwd || null;
254
+ const peers = this.db
255
+ .listPeers({
256
+ runtime: params.runtime || null,
257
+ includeOffline: Boolean(params.include_offline),
258
+ })
259
+ .filter((p) => !scopeCwd || (p.cwd && isSameProjectScope(p.cwd, scopeCwd)))
260
+ .map((p) => ({
261
+ ...sanitizePeerForClient(p),
262
+ has_worker: this.workers.has(p.peer_id),
263
+ waiting: (this.waiters.get(p.peer_id)?.size || 0) > 0,
264
+ subscribed: (this.channelSubscribers.get(p.peer_id)?.size || 0) > 0,
265
+ }));
266
+
267
+ const result = { peers };
268
+ if (params.include_native_claude) {
269
+ result.native_claude_peers = scanNativeClaudePeers(this.config.claudeDir, {
270
+ skipPidCheck: this.skipNativePidCheck,
271
+ });
272
+ }
273
+ return result;
274
+ }
275
+
276
+ resolvePeer(params = {}) {
277
+ const res = resolveTarget(this.db, params.target, {
278
+ includeOffline: Boolean(params.include_offline),
279
+ checkNativeClaude: params.check_native_claude !== false,
280
+ claudeDir: this.config.claudeDir,
281
+ skipNativePidCheck: this.skipNativePidCheck,
282
+ cwd: params.cwd || null,
283
+ });
284
+ if (!res.ok) return res;
285
+ return {
286
+ ok: true,
287
+ match_type: res.match_type,
288
+ peer: sanitizePeerForClient(res.peer),
289
+ };
290
+ }
291
+
292
+ _lookupPeer({ peer_id, session_id, target, runtime, cwd } = {}) {
293
+ if (peer_id) return this.db.getPeer(peer_id);
294
+ if (session_id) return this.db.getPeerBySession(runtime || null, session_id);
295
+ if (target) {
296
+ const res = resolveTarget(this.db, target, {
297
+ includeOffline: true,
298
+ checkNativeClaude: false,
299
+ cwd: cwd || null,
300
+ });
301
+ return res.ok ? res.peer : null;
302
+ }
303
+ return null;
304
+ }
305
+
306
+ _enqueueForPeer(peerId, fn) {
307
+ const prev = this.peerQueues.get(peerId) || Promise.resolve();
308
+ const next = prev.then(fn, fn);
309
+ const cleanup = next.finally(() => {
310
+ if (this.peerQueues.get(peerId) === cleanup) {
311
+ this.peerQueues.delete(peerId);
312
+ }
313
+ });
314
+ this.peerQueues.set(peerId, cleanup);
315
+ return next;
316
+ }
317
+
318
+ _resolveSender(from, cwd = null) {
319
+ if (!from) {
320
+ return { id: null, runtime: 'cli', name: 'user' };
321
+ }
322
+ if (typeof from === 'string') {
323
+ const res = resolveTarget(this.db, from, {
324
+ includeOffline: true,
325
+ checkNativeClaude: false,
326
+ cwd: cwd || null,
327
+ });
328
+ if (res.ok) {
329
+ return { id: res.peer.peer_id, runtime: res.peer.runtime, name: res.peer.name, cwd: res.peer.cwd || null };
330
+ }
331
+ const idx = from.indexOf(':');
332
+ if (idx > 0 && RUNTIMES.has(from.slice(0, idx))) {
333
+ return { id: null, runtime: from.slice(0, idx), name: from.slice(idx + 1) };
334
+ }
335
+ return { id: null, runtime: 'cli', name: from };
336
+ }
337
+ return {
338
+ id: from.id || from.peer_id || null,
339
+ runtime: from.runtime || 'cli',
340
+ name: from.name || 'external',
341
+ cwd: from.cwd || null,
342
+ };
343
+ }
344
+
345
+ async sendMessage(params = {}) {
346
+ const toRaw = String(params.to || '').trim();
347
+ const body = String(params.body ?? params.message ?? '');
348
+ if (!toRaw) throw new RpcError('INVALID_PARAMS', 'Missing "to" target');
349
+ if (!body) throw new RpcError('INVALID_PARAMS', 'Missing "body" / "message"');
350
+
351
+ const kind = params.kind || 'prompt';
352
+ if (!MESSAGE_KINDS.has(kind)) {
353
+ throw new RpcError('INVALID_PARAMS', `Invalid message kind "${kind}"`);
354
+ }
355
+
356
+ const sender = this._resolveSender(params.from, params.cwd || null);
357
+ const effectiveCwd =
358
+ params.cwd || sender.cwd || (sender.id ? this.db.getPeer(sender.id)?.cwd : null) || null;
359
+
360
+ const resolved = resolveTarget(this.db, toRaw, {
361
+ includeOffline: false,
362
+ checkNativeClaude: params.check_native_claude !== false,
363
+ claudeDir: this.config.claudeDir,
364
+ skipNativePidCheck: this.skipNativePidCheck,
365
+ cwd: effectiveCwd,
366
+ });
367
+ if (!resolved.ok) {
368
+ throw new RpcError(resolved.code, resolved.message, {
369
+ candidates: resolved.candidates,
370
+ native_matches: resolved.native_matches,
371
+ });
372
+ }
373
+
374
+ const target = resolved.peer;
375
+ const threadId = params.thread_id || makeId('thr');
376
+ const existingThread = this.db.getThreadState(threadId);
377
+ const maxHops = Number(params.max_hops ?? existingThread?.max_hops ?? this.config.defaultMaxHops);
378
+ const hopCount = Number(params.hop_count ?? (existingThread ? existingThread.last_hop + 1 : 1));
379
+ const replyExpected = params.reply_expected !== false;
380
+ const deliveryMode = params.delivery_mode || 'immediate';
381
+ const overrideLoopGuard = Boolean(params.override_loop_guard);
382
+
383
+ // Loop Guard checks (enforced hard in broker)
384
+ if (kind !== 'system' && !overrideLoopGuard) {
385
+ if (existingThread?.no_reply_from_peer) {
386
+ const senderKey = sender.id || `${sender.runtime}:${sender.name}`;
387
+ if (senderKey !== existingThread.no_reply_from_peer) {
388
+ const blockedMsg = this.db.insertMessage({
389
+ thread_id: threadId,
390
+ from_peer_id: sender.id,
391
+ from_runtime: sender.runtime,
392
+ from_name: sender.name,
393
+ to_raw: toRaw,
394
+ to_peer_id: target.peer_id,
395
+ kind,
396
+ body,
397
+ reply_expected: replyExpected,
398
+ hop_count: hopCount,
399
+ max_hops: maxHops,
400
+ delivery_mode: deliveryMode,
401
+ status: 'blocked',
402
+ error: 'LOOP_GUARD_NO_REPLY',
403
+ });
404
+ this.db.upsertThreadState({
405
+ thread_id: threadId,
406
+ last_hop: existingThread.last_hop,
407
+ max_hops: maxHops,
408
+ no_reply_from_peer: existingThread.no_reply_from_peer,
409
+ blocked_reason: 'LOOP_GUARD_NO_REPLY',
410
+ });
411
+ return {
412
+ ok: false,
413
+ blocked: true,
414
+ code: 'LOOP_GUARD_NO_REPLY',
415
+ msg_id: blockedMsg.msg_id,
416
+ thread_id: threadId,
417
+ resolved_to: makeHandle(target),
418
+ hop_count: hopCount,
419
+ max_hops: maxHops,
420
+ delivery_status: 'blocked',
421
+ message: `Thread ${threadId} was closed with reply_expected=false; automatic reply blocked.`,
422
+ };
423
+ }
424
+ }
425
+
426
+ if (hopCount > maxHops) {
427
+ const blockedMsg = this.db.insertMessage({
428
+ thread_id: threadId,
429
+ from_peer_id: sender.id,
430
+ from_runtime: sender.runtime,
431
+ from_name: sender.name,
432
+ to_raw: toRaw,
433
+ to_peer_id: target.peer_id,
434
+ kind,
435
+ body,
436
+ reply_expected: replyExpected,
437
+ hop_count: hopCount,
438
+ max_hops: maxHops,
439
+ delivery_mode: deliveryMode,
440
+ status: 'blocked',
441
+ error: 'LOOP_GUARD_MAX_HOPS',
442
+ });
443
+ this.db.upsertThreadState({
444
+ thread_id: threadId,
445
+ last_hop: existingThread?.last_hop || maxHops,
446
+ max_hops: maxHops,
447
+ no_reply_from_peer: existingThread?.no_reply_from_peer || null,
448
+ blocked_reason: 'LOOP_GUARD_MAX_HOPS',
449
+ });
450
+ return {
451
+ ok: false,
452
+ blocked: true,
453
+ code: 'LOOP_GUARD_MAX_HOPS',
454
+ msg_id: blockedMsg.msg_id,
455
+ thread_id: threadId,
456
+ resolved_to: makeHandle(target),
457
+ hop_count: hopCount,
458
+ max_hops: maxHops,
459
+ delivery_status: 'blocked',
460
+ message: `Thread ${threadId} exceeded max_hops (${hopCount}/${maxHops}); delivery blocked by loop guard.`,
461
+ };
462
+ }
463
+ }
464
+
465
+ const senderKey = sender.id || `${sender.runtime}:${sender.name}`;
466
+ this.db.upsertThreadState({
467
+ thread_id: threadId,
468
+ last_hop: hopCount,
469
+ max_hops: maxHops,
470
+ no_reply_from_peer: !replyExpected && kind !== 'system' ? senderKey : null,
471
+ blocked_reason: null,
472
+ });
473
+
474
+ const msgRow = this.db.insertMessage({
475
+ thread_id: threadId,
476
+ from_peer_id: sender.id,
477
+ from_runtime: sender.runtime,
478
+ from_name: sender.name,
479
+ to_raw: toRaw,
480
+ to_peer_id: target.peer_id,
481
+ kind,
482
+ body,
483
+ reply_expected: replyExpected,
484
+ hop_count: hopCount,
485
+ max_hops: maxHops,
486
+ delivery_mode: deliveryMode,
487
+ status: 'queued',
488
+ });
489
+
490
+ const envelope = buildEnvelope(msgRow, params.contract || null);
491
+ const formattedXml = formatPeerMessageXml(envelope);
492
+ const payload = { envelope, formatted_xml: formattedXml };
493
+
494
+ const worker = this.workers.get(target.peer_id);
495
+ if (worker && !worker.closed) {
496
+ const deliveryPromise = this._enqueueForPeer(target.peer_id, async () => {
497
+ try {
498
+ this.db.updatePeerState(target.peer_id, 'busy', {
499
+ metadata: { summary: cleanSummary(body), needs_input: false },
500
+ });
501
+ this._emitMonitorEvent('peer.updated', { peer_id: target.peer_id });
502
+ const turnRes = await worker.sendTurn(params.raw_body ? body : formattedXml, {
503
+ timeoutMs: params.timeout_ms || 180_000,
504
+ behavior: params.behavior || undefined,
505
+ wait: params.paseo_wait !== undefined ? Boolean(params.paseo_wait) : undefined,
506
+ });
507
+ const nextState = turnRes.is_error ? 'error' : 'idle';
508
+ const resultSummary =
509
+ cleanSummary(turnRes.error || turnRes.response || turnRes.text, 120, { preferLast: true }) ||
510
+ cleanSummary(body);
511
+ this.db.updatePeerState(target.peer_id, nextState, {
512
+ ...(turnRes.session_id ? { session_id: turnRes.session_id } : {}),
513
+ metadata: { summary: resultSummary, needs_input: false },
514
+ });
515
+ this._emitMonitorEvent('peer.updated', { peer_id: target.peer_id });
516
+ const status = turnRes.is_error ? 'failed' : 'delivered';
517
+ this.db.updateMessageStatus(msgRow.msg_id, status, turnRes.error || null);
518
+ this.db.insertDelivery({
519
+ msg_id: msgRow.msg_id,
520
+ peer_id: target.peer_id,
521
+ channel: target.runtime === 'paseo' ? 'paseo-send' : 'stream-json',
522
+ status,
523
+ error: turnRes.error || null,
524
+ response_excerpt: String(turnRes.response || '').slice(0, 500),
525
+ });
526
+ if (params.contract?.request_id) {
527
+ await this._finalizeTaskFromWorker(params.contract.request_id, turnRes, null);
528
+ }
529
+ return {
530
+ delivery_status: status,
531
+ channel: target.runtime === 'paseo' ? 'paseo-send' : 'stream-json',
532
+ worker_result: turnRes,
533
+ };
534
+ } catch (err) {
535
+ this.db.updatePeerState(target.peer_id, worker.closed ? 'closed' : 'error', {
536
+ metadata: { summary: cleanSummary(err.message), needs_input: false },
537
+ });
538
+ this._emitMonitorEvent('peer.updated', { peer_id: target.peer_id });
539
+ this.db.updateMessageStatus(msgRow.msg_id, 'failed', err.message);
540
+ this.db.insertDelivery({
541
+ msg_id: msgRow.msg_id,
542
+ peer_id: target.peer_id,
543
+ channel: target.runtime === 'paseo' ? 'paseo-send' : 'stream-json',
544
+ status: 'failed',
545
+ error: err.message,
546
+ });
547
+ if (params.contract?.request_id) {
548
+ await this._finalizeTaskFromWorker(params.contract.request_id, null, err);
549
+ }
550
+ return {
551
+ delivery_status: 'failed',
552
+ channel: target.runtime === 'paseo' ? 'paseo-send' : 'stream-json',
553
+ error: err.message,
554
+ };
555
+ }
556
+ });
557
+
558
+ if (params.wait_reply || params.await_delivery) {
559
+ const out = await deliveryPromise;
560
+ return {
561
+ ok: out.delivery_status === 'delivered',
562
+ msg_id: msgRow.msg_id,
563
+ thread_id: threadId,
564
+ resolved_to: makeHandle(target),
565
+ to_peer_id: target.peer_id,
566
+ target_state: this.db.getPeer(target.peer_id)?.state || target.state,
567
+ hop_count: hopCount,
568
+ max_hops: maxHops,
569
+ ...out,
570
+ };
571
+ }
572
+
573
+ deliveryPromise.catch(() => {});
574
+ return {
575
+ ok: true,
576
+ msg_id: msgRow.msg_id,
577
+ thread_id: threadId,
578
+ resolved_to: makeHandle(target),
579
+ to_peer_id: target.peer_id,
580
+ target_state: 'busy',
581
+ hop_count: hopCount,
582
+ max_hops: maxHops,
583
+ delivery_status: 'dispatched',
584
+ channel: 'stream-json',
585
+ };
586
+ }
587
+
588
+ // Try live channel subscribers (MCP claude/channel push)
589
+ const subs = this.channelSubscribers.get(target.peer_id);
590
+ if (subs && subs.size > 0) {
591
+ let pushed = 0;
592
+ for (const pushFn of subs) {
593
+ try {
594
+ pushFn({ event: 'message', ...payload });
595
+ pushed++;
596
+ } catch {
597
+ // ignore broken subscriber; cleanup happens on socket close
598
+ }
599
+ }
600
+ if (pushed > 0) {
601
+ this.db.updateMessageStatus(msgRow.msg_id, 'delivered');
602
+ this.db.insertDelivery({
603
+ msg_id: msgRow.msg_id,
604
+ peer_id: target.peer_id,
605
+ channel: 'channel',
606
+ status: 'delivered',
607
+ });
608
+ this.db.updatePeerState(target.peer_id, target.state, {
609
+ metadata: {
610
+ summary: cleanSummary(`[from ${sender.runtime}:${sender.name}] ${body}`),
611
+ needs_input: Boolean(replyExpected),
612
+ },
613
+ });
614
+ this._emitMonitorEvent('peer.updated', { peer_id: target.peer_id });
615
+ return {
616
+ ok: true,
617
+ msg_id: msgRow.msg_id,
618
+ thread_id: threadId,
619
+ resolved_to: makeHandle(target),
620
+ to_peer_id: target.peer_id,
621
+ target_state: target.state,
622
+ hop_count: hopCount,
623
+ max_hops: maxHops,
624
+ delivery_status: 'delivered',
625
+ channel: 'channel',
626
+ };
627
+ }
628
+ }
629
+
630
+ // Try active reactive wakeup waiters (pbridge wait)
631
+ const waiterSet = this.waiters.get(target.peer_id);
632
+ if (waiterSet && waiterSet.size > 0) {
633
+ const [firstWaiter] = waiterSet;
634
+ waiterSet.delete(firstWaiter);
635
+ if (waiterSet.size === 0) this.waiters.delete(target.peer_id);
636
+ clearTimeout(firstWaiter.timer);
637
+
638
+ this.db.updateMessageStatus(msgRow.msg_id, 'delivered');
639
+ this.db.insertDelivery({
640
+ msg_id: msgRow.msg_id,
641
+ peer_id: target.peer_id,
642
+ channel: 'wait',
643
+ status: 'delivered',
644
+ });
645
+ this.db.updatePeerState(target.peer_id, 'idle', {
646
+ metadata: {
647
+ summary: cleanSummary(`[from ${sender.runtime}:${sender.name}] ${body}`),
648
+ needs_input: Boolean(replyExpected),
649
+ },
650
+ });
651
+ this._emitMonitorEvent('peer.updated', { peer_id: target.peer_id });
652
+
653
+ firstWaiter.resolve({
654
+ woke: true,
655
+ reason: 'message',
656
+ messages: [payload],
657
+ });
658
+
659
+ return {
660
+ ok: true,
661
+ msg_id: msgRow.msg_id,
662
+ thread_id: threadId,
663
+ resolved_to: makeHandle(target),
664
+ to_peer_id: target.peer_id,
665
+ target_state: 'idle',
666
+ hop_count: hopCount,
667
+ max_hops: maxHops,
668
+ delivery_status: 'delivered',
669
+ channel: 'wait',
670
+ };
671
+ }
672
+
673
+ // Otherwise leave queued in SQLite WAL for next poll/wait/hook
674
+ this.db.insertDelivery({
675
+ msg_id: msgRow.msg_id,
676
+ peer_id: target.peer_id,
677
+ channel: 'queue',
678
+ status: 'queued',
679
+ });
680
+ this.db.updatePeerState(target.peer_id, target.state, {
681
+ metadata: {
682
+ summary: cleanSummary(`[from ${sender.runtime}:${sender.name}] ${body}`),
683
+ needs_input: Boolean(replyExpected),
684
+ },
685
+ });
686
+ this._emitMonitorEvent('peer.updated', { peer_id: target.peer_id });
687
+
688
+ return {
689
+ ok: true,
690
+ msg_id: msgRow.msg_id,
691
+ thread_id: threadId,
692
+ resolved_to: makeHandle(target),
693
+ to_peer_id: target.peer_id,
694
+ target_state: target.state,
695
+ hop_count: hopCount,
696
+ max_hops: maxHops,
697
+ delivery_status: 'queued',
698
+ channel: 'queue',
699
+ };
700
+ }
701
+
702
+ pollMessages(params = {}) {
703
+ const peer = this._lookupPeer(params);
704
+ if (!peer) {
705
+ throw new RpcError('NOT_FOUND', 'Peer not found for poll');
706
+ }
707
+ const rows = this.db.claimPendingMessages(peer.peer_id, params.limit || 20);
708
+ const messages = rows.map((row) => {
709
+ this.db.updateMessageStatus(row.msg_id, 'delivered');
710
+ this.db.insertDelivery({
711
+ msg_id: row.msg_id,
712
+ peer_id: peer.peer_id,
713
+ channel: params.channel || 'poll',
714
+ status: 'delivered',
715
+ });
716
+ const taskRow = this.db.getTaskByMsgId(row.msg_id);
717
+ const envelope = buildEnvelope({ ...row, status: 'delivered' }, taskToContract(taskRow));
718
+ return { envelope, formatted_xml: formatPeerMessageXml(envelope) };
719
+ });
720
+ return {
721
+ peer_id: peer.peer_id,
722
+ handle: makeHandle(peer),
723
+ count: messages.length,
724
+ messages,
725
+ };
726
+ }
727
+
728
+ waitForMessages(params = {}, signal = null) {
729
+ let peer = this._lookupPeer(params);
730
+ if (!peer && params.session_id && params.runtime) {
731
+ peer = this.db.upsertPeer({
732
+ runtime: params.runtime,
733
+ name: params.name || String(params.session_id).slice(0, 8),
734
+ session_id: params.session_id,
735
+ origin: 'attached',
736
+ exec_mode: 'interactive',
737
+ state: 'waiting',
738
+ cwd: params.cwd || null,
739
+ ls_address: params.ls_address || null,
740
+ csrf_token: params.csrf_token || null,
741
+ project_id: params.project_id || null,
742
+ });
743
+ }
744
+ if (!peer) {
745
+ throw new RpcError('NOT_FOUND', 'Peer not found for wait');
746
+ }
747
+
748
+ if (params.ls_address || params.csrf_token) {
749
+ peer = this.db.updatePeerState(peer.peer_id, peer.state, {
750
+ ls_address: params.ls_address ?? peer.ls_address,
751
+ csrf_token: params.csrf_token ?? peer.csrf_token,
752
+ project_id: params.project_id ?? peer.project_id,
753
+ });
754
+ }
755
+
756
+ // Immediate drain if messages are already queued
757
+ const pending = this.db.claimPendingMessages(peer.peer_id, 20);
758
+ if (pending.length > 0) {
759
+ const messages = pending.map((row) => {
760
+ this.db.updateMessageStatus(row.msg_id, 'delivered');
761
+ this.db.insertDelivery({
762
+ msg_id: row.msg_id,
763
+ peer_id: peer.peer_id,
764
+ channel: 'wait',
765
+ status: 'delivered',
766
+ });
767
+ const envelope = buildEnvelope({ ...row, status: 'delivered' });
768
+ return { envelope, formatted_xml: formatPeerMessageXml(envelope) };
769
+ });
770
+ return Promise.resolve({ woke: true, reason: 'queued', messages });
771
+ }
772
+
773
+ const timeoutMs = Number(params.timeout_ms ?? this.config.defaultWaitTimeoutMs);
774
+ this.db.updatePeerState(peer.peer_id, 'waiting');
775
+
776
+ return new Promise((resolve) => {
777
+ let waiterSet = this.waiters.get(peer.peer_id);
778
+ if (!waiterSet) {
779
+ waiterSet = new Set();
780
+ this.waiters.set(peer.peer_id, waiterSet);
781
+ }
782
+
783
+ const cleanup = () => {
784
+ waiterSet.delete(entry);
785
+ if (signal && onAbort) {
786
+ signal.removeEventListener('abort', onAbort);
787
+ }
788
+ if (waiterSet.size === 0) {
789
+ this.waiters.delete(peer.peer_id);
790
+ if (!this.closed) {
791
+ const cur = this.db.getPeer(peer.peer_id);
792
+ if (cur && cur.state === 'waiting') {
793
+ this.db.updatePeerState(peer.peer_id, 'idle');
794
+ }
795
+ }
796
+ }
797
+ };
798
+
799
+ const settle = (value) => {
800
+ clearTimeout(timer);
801
+ cleanup();
802
+ resolve(value);
803
+ };
804
+
805
+ const onAbort = () => {
806
+ settle({ woke: false, reason: 'aborted', messages: [] });
807
+ };
808
+
809
+ const timer = setTimeout(() => {
810
+ settle({ woke: false, reason: 'timeout', messages: [] });
811
+ }, timeoutMs);
812
+
813
+ const entry = { resolve: settle, timer };
814
+ waiterSet.add(entry);
815
+
816
+ if (signal) {
817
+ if (signal.aborted) {
818
+ onAbort();
819
+ } else {
820
+ signal.addEventListener('abort', onAbort, { once: true });
821
+ }
822
+ }
823
+ });
824
+ }
825
+
826
+ subscribeChannel(params = {}, pushFn) {
827
+ const peer = this._lookupPeer(params);
828
+ if (!peer) {
829
+ throw new RpcError('NOT_FOUND', 'Peer not found for channel subscription');
830
+ }
831
+ let set = this.channelSubscribers.get(peer.peer_id);
832
+ if (!set) {
833
+ set = new Set();
834
+ this.channelSubscribers.set(peer.peer_id, set);
835
+ }
836
+ set.add(pushFn);
837
+
838
+ // Immediately flush any queued messages
839
+ const pending = this.db.claimPendingMessages(peer.peer_id, 20);
840
+ for (const row of pending) {
841
+ this.db.updateMessageStatus(row.msg_id, 'delivered');
842
+ this.db.insertDelivery({
843
+ msg_id: row.msg_id,
844
+ peer_id: peer.peer_id,
845
+ channel: 'channel',
846
+ status: 'delivered',
847
+ });
848
+ const envelope = buildEnvelope({ ...row, status: 'delivered' });
849
+ pushFn({ event: 'message', envelope, formatted_xml: formatPeerMessageXml(envelope) });
850
+ }
851
+
852
+ return {
853
+ peer_id: peer.peer_id,
854
+ handle: makeHandle(peer),
855
+ unsubscribe: () => {
856
+ set.delete(pushFn);
857
+ if (set.size === 0) this.channelSubscribers.delete(peer.peer_id);
858
+ },
859
+ };
860
+ }
861
+
862
+ async spawnPeer(params = {}) {
863
+ const runtime = String(params.runtime || '').toLowerCase();
864
+ if (!SPAWNABLE_RUNTIMES.has(runtime)) {
865
+ throw new RpcError(
866
+ 'INVALID_PARAMS',
867
+ `spawn supports runtime "agy", "cc", "codex", "gemini", or "paseo", got "${params.runtime}"`,
868
+ );
869
+ }
870
+ const name = String(params.name || '').trim();
871
+ if (!name) {
872
+ throw new RpcError('INVALID_PARAMS', 'Missing required "name" for spawn');
873
+ }
874
+ const mode = params.mode || (runtime === 'paseo' ? 'external' : 'headless');
875
+ const validModes = runtime === 'paseo' ? new Set(['headless', 'external']) : new Set(['headless', 'pane']);
876
+ if (!validModes.has(mode)) {
877
+ throw new RpcError(
878
+ 'INVALID_PARAMS',
879
+ `Unsupported spawn mode "${mode}" for runtime "${runtime}"`,
880
+ );
881
+ }
882
+
883
+ const cwd = params.cwd || process.cwd();
884
+ const existing = this.db.getActivePeerByName(runtime, name, cwd);
885
+ if (existing && !params.replace) {
886
+ throw new RpcError(
887
+ 'DUPLICATE_PEER',
888
+ `Active peer "${runtime}:${name}" already exists in this project (${existing.peer_id}). Choose another name or close it first.`,
889
+ );
890
+ }
891
+ const model = params.model || (runtime === 'agy' ? 'flash' : null);
892
+ const lsAddress = params.ls_address || process.env.ANTIGRAVITY_LS_ADDRESS || null;
893
+ const csrfToken = params.csrf_token || process.env.ANTIGRAVITY_CSRF_TOKEN || null;
894
+ const projectId = params.project_id || process.env.ANTIGRAVITY_PROJECT_ID || 'default-cli-project';
895
+
896
+ let sessionId = params.session_id || null;
897
+ let convApiUsed = false;
898
+
899
+ // For Antigravity, pre-create a named Conversation via ConversationService when LS creds exist
900
+ if (runtime === 'agy' && !sessionId && !params.mock && params.use_conversation_api !== false) {
901
+ const api = this.convApiFactory({ lsAddress, csrfToken, projectId });
902
+ if (api.isConfigured()) {
903
+ const { apiModel } = resolveAgyModels(model);
904
+ const created = await api.createConversation({
905
+ title: `peer-bridge:${name}`,
906
+ model: apiModel,
907
+ tags: ['peer-bridge', 'spawned'],
908
+ projectId,
909
+ });
910
+ sessionId =
911
+ created.conversationId ||
912
+ created.id ||
913
+ created.conversation?.conversationId ||
914
+ created.conversation?.id ||
915
+ null;
916
+ convApiUsed = Boolean(sessionId);
917
+ }
918
+ }
919
+
920
+ let peer = this.db.upsertPeer({
921
+ runtime,
922
+ name,
923
+ session_id: sessionId,
924
+ origin: 'spawned',
925
+ spawned_by: params.spawned_by || null,
926
+ exec_mode: mode,
927
+ state: 'starting',
928
+ cwd,
929
+ model,
930
+ ls_address: lsAddress,
931
+ csrf_token: csrfToken,
932
+ project_id: projectId,
933
+ metadata: {
934
+ conv_api_created: convApiUsed,
935
+ auto_close_on_finish: Boolean(params.auto_close_on_finish),
936
+ tmux_socket: params.tmux_socket || null,
937
+ paseo_host: params.host || null,
938
+ paseo_home: params.home || null,
939
+ paseo_provider: params.provider || null,
940
+ },
941
+ });
942
+
943
+ if (mode === 'headless' || mode === 'external') {
944
+ let worker;
945
+ if (this.workerFactory) {
946
+ worker = this.workerFactory({ peer, params, config: this.config });
947
+ } else if (params.mock) {
948
+ worker = new MockStreamWorker({ peerId: peer.peer_id, runtime });
949
+ } else if (runtime === 'agy') {
950
+ worker = new AgyStreamWorker({
951
+ peerId: peer.peer_id,
952
+ agyBin: this.config.agyBin,
953
+ conversationId: sessionId,
954
+ model,
955
+ cwd,
956
+ env: params.env,
957
+ });
958
+ } else if (runtime === 'cc') {
959
+ worker = new CcStreamWorker({
960
+ peerId: peer.peer_id,
961
+ claudeBin: this.config.claudeBin,
962
+ model,
963
+ permissionMode: params.permission_mode,
964
+ noMcp: Boolean(params.no_mcp),
965
+ cwd,
966
+ env: params.env,
967
+ });
968
+ } else if (runtime === 'codex') {
969
+ worker = new CodexExecWorker({
970
+ peerId: peer.peer_id,
971
+ codexBin: this.config.codexBin,
972
+ sessionId,
973
+ model,
974
+ sandboxMode: params.sandbox_mode || params.sandbox,
975
+ cwd,
976
+ env: params.env,
977
+ });
978
+ } else if (runtime === 'gemini') {
979
+ worker = new GeminiCliWorker({
980
+ peerId: peer.peer_id,
981
+ geminiBin: this.config.geminiBin,
982
+ sessionId,
983
+ model,
984
+ approvalMode: params.approval_mode,
985
+ cwd,
986
+ env: params.env,
987
+ });
988
+ } else if (runtime === 'paseo') {
989
+ const client = this.paseoClientFactory({
990
+ host: params.host || undefined,
991
+ home: params.home || undefined,
992
+ });
993
+ worker = new PaseoAgentWorker({
994
+ peerId: peer.peer_id,
995
+ name,
996
+ client,
997
+ sessionId,
998
+ provider: params.provider || null,
999
+ model,
1000
+ agentMode: params.agent_mode || params.permission_mode || null,
1001
+ workspaceId: params.workspace_id || null,
1002
+ cwd,
1003
+ behavior: params.behavior || 'steer',
1004
+ wait: params.wait !== undefined ? Boolean(params.wait) : true,
1005
+ });
1006
+ }
1007
+
1008
+ this.workers.set(peer.peer_id, worker);
1009
+ let lastProgressEmitMs = 0;
1010
+ worker.on('progress', (text) => {
1011
+ if (this.closed) return;
1012
+ const nowMs = Date.now();
1013
+ if (nowMs - lastProgressEmitMs < 600) return;
1014
+ const clean = cleanSummary(text, 120);
1015
+ if (!clean) return;
1016
+ lastProgressEmitMs = nowMs;
1017
+ const cur = this.db.getPeer(peer.peer_id);
1018
+ if (cur && cur.state === 'busy') {
1019
+ this.db.updatePeerState(peer.peer_id, 'busy', {
1020
+ metadata: { summary: clean, needs_input: false },
1021
+ });
1022
+ this._emitMonitorEvent('peer.updated', { peer_id: peer.peer_id });
1023
+ }
1024
+ });
1025
+ worker.on('session_id', (sid) => {
1026
+ if (this.closed) return;
1027
+ const cur = this.db.getPeer(peer.peer_id);
1028
+ if (cur && cur.session_id !== sid) {
1029
+ this.db.updatePeerState(peer.peer_id, cur.state, { session_id: sid });
1030
+ }
1031
+ });
1032
+ worker.on('exit', () => {
1033
+ this.workers.delete(peer.peer_id);
1034
+ if (this.closed) return;
1035
+ const cur = this.db.getPeer(peer.peer_id);
1036
+ if (cur && !['archived', 'deleted', 'closed', 'detached'].includes(cur.state)) {
1037
+ this.db.updatePeerState(peer.peer_id, 'closed');
1038
+ this._emitMonitorEvent('peer.closed', { peer_id: peer.peer_id });
1039
+ }
1040
+ });
1041
+
1042
+ worker.start();
1043
+ peer = this.db.updatePeerState(peer.peer_id, 'idle', {
1044
+ pid: worker.pid,
1045
+ session_id: peer.session_id || worker.sessionId,
1046
+ metadata: {
1047
+ summary: cleanSummary(params.initial_prompt) || 'Spawned worker ready',
1048
+ needs_input: false,
1049
+ },
1050
+ });
1051
+ this._emitMonitorEvent('peer.updated', { peer_id: peer.peer_id });
1052
+
1053
+ let initialResult = null;
1054
+ if (params.initial_prompt) {
1055
+ const sendRes = await this.sendMessage({
1056
+ to: peer.peer_id,
1057
+ from: params.spawned_by || { runtime: 'cli', name: 'spawner' },
1058
+ body: params.initial_prompt,
1059
+ reply_expected: params.reply_expected !== false,
1060
+ raw_body: true,
1061
+ await_delivery: params.await_initial !== false,
1062
+ timeout_ms: params.timeout_ms || 180_000,
1063
+ });
1064
+ initialResult = sendRes.worker_result || sendRes;
1065
+ peer = this.db.getPeer(peer.peer_id);
1066
+ }
1067
+
1068
+ return {
1069
+ peer: sanitizePeerForClient(peer),
1070
+ initial_result: initialResult,
1071
+ };
1072
+ }
1073
+
1074
+ // mode === 'pane' (tmux)
1075
+ let args = [];
1076
+ let bin = this.config.claudeBin;
1077
+ if (runtime === 'agy') {
1078
+ bin = this.config.agyBin;
1079
+ args = sessionId ? ['--conversation', sessionId] : [];
1080
+ } else if (runtime === 'cc') {
1081
+ bin = this.config.claudeBin;
1082
+ args = ['--name', name];
1083
+ } else if (runtime === 'codex') {
1084
+ bin = this.config.codexBin;
1085
+ args = ['-C', cwd, ...(model ? ['-m', model] : [])];
1086
+ } else if (runtime === 'gemini') {
1087
+ bin = this.config.geminiBin;
1088
+ args = model ? ['-m', model] : [];
1089
+ }
1090
+ const pane = await spawnTmuxPane({
1091
+ tmuxBin: this.config.tmuxBin,
1092
+ runtime,
1093
+ bin,
1094
+ args,
1095
+ cwd,
1096
+ name,
1097
+ tmuxSocket: params.tmux_socket || null,
1098
+ });
1099
+ peer = this.db.updatePeerState(peer.peer_id, 'idle', {
1100
+ pane_id: pane.paneId,
1101
+ metadata: { ...peer.metadata, tmux_session: pane.tmuxSession, tmux_socket: pane.tmuxSocket },
1102
+ });
1103
+
1104
+ return { peer: sanitizePeerForClient(peer), pane };
1105
+ }
1106
+
1107
+ async closePeer(params = {}) {
1108
+ const targetRaw = String(params.target || params.peer_id || '').trim();
1109
+ if (!targetRaw) {
1110
+ throw new RpcError('INVALID_PARAMS', 'Missing "target" for close');
1111
+ }
1112
+
1113
+ const res = resolveTarget(this.db, targetRaw, {
1114
+ includeOffline: true,
1115
+ checkNativeClaude: false,
1116
+ cwd: params.cwd || null,
1117
+ });
1118
+ if (!res.ok) {
1119
+ throw new RpcError(res.code, res.message, { candidates: res.candidates });
1120
+ }
1121
+
1122
+ const peer = res.peer;
1123
+ const previousState = peer.state;
1124
+ const policy = params.policy || (peer.origin === 'spawned' ? 'archive' : 'graceful');
1125
+ if (!CLOSE_POLICIES.has(policy)) {
1126
+ throw new RpcError('INVALID_PARAMS', `Invalid close policy "${policy}"`);
1127
+ }
1128
+ const force = Boolean(params.force);
1129
+ const reason = params.reason || 'Closed via peer-bridge';
1130
+
1131
+ // Ownership Safety Rule: never destructively close user-opened attached sessions without force=true
1132
+ if (peer.origin === 'attached' && policy !== 'detach' && !force) {
1133
+ throw new RpcError(
1134
+ 'OWNERSHIP_PROTECTED',
1135
+ `Refusing to close attached session "${makeHandle(peer)}" with policy="${policy}". Use policy="detach" to unlink safely or pass force=true to override.`,
1136
+ { peer_id: peer.peer_id, handle: makeHandle(peer), origin: peer.origin },
1137
+ );
1138
+ }
1139
+
1140
+ // Emit shutdown notification to waiters & channel subscribers
1141
+ const shutdownEnvelope = {
1142
+ msg_id: makeId('msg'),
1143
+ kind: 'system',
1144
+ action: 'shutdown',
1145
+ target: makeHandle(peer),
1146
+ policy,
1147
+ reason,
1148
+ created_at: nowIso(),
1149
+ };
1150
+
1151
+ const waiterSet = this.waiters.get(peer.peer_id);
1152
+ if (waiterSet) {
1153
+ for (const entry of waiterSet) {
1154
+ clearTimeout(entry.timer);
1155
+ entry.resolve({ woke: true, reason: 'shutdown', system: shutdownEnvelope, messages: [] });
1156
+ }
1157
+ this.waiters.delete(peer.peer_id);
1158
+ }
1159
+
1160
+ const subs = this.channelSubscribers.get(peer.peer_id);
1161
+ if (subs) {
1162
+ for (const pushFn of subs) {
1163
+ try {
1164
+ pushFn({ event: 'system', system: shutdownEnvelope });
1165
+ } catch {
1166
+ // ignore
1167
+ }
1168
+ }
1169
+ this.channelSubscribers.delete(peer.peer_id);
1170
+ }
1171
+
1172
+ if (policy === 'detach') {
1173
+ const updated = this.db.updatePeerState(peer.peer_id, 'detached');
1174
+ return {
1175
+ closed_peer: sanitizePeerForClient(updated),
1176
+ previous_state: previousState,
1177
+ action_taken: 'detached',
1178
+ conversation_action: 'none',
1179
+ };
1180
+ }
1181
+
1182
+ // Stop managed headless worker if running
1183
+ let workerStopped = false;
1184
+ const worker = this.workers.get(peer.peer_id);
1185
+ if (worker) {
1186
+ await worker.stop();
1187
+ this.workers.delete(peer.peer_id);
1188
+ workerStopped = true;
1189
+ }
1190
+
1191
+ // Close tmux pane if spawned pane
1192
+ let paneClosed = false;
1193
+ if (peer.pane_id && (peer.origin === 'spawned' || force)) {
1194
+ await killTmuxPane({
1195
+ tmuxBin: this.config.tmuxBin,
1196
+ paneId: peer.pane_id,
1197
+ tmuxSocket: peer.metadata?.tmux_socket || null,
1198
+ });
1199
+ paneClosed = true;
1200
+ }
1201
+
1202
+ // Antigravity ConversationService archive / delete
1203
+ let conversationAction = 'none';
1204
+ if (
1205
+ peer.runtime === 'agy' &&
1206
+ peer.session_id &&
1207
+ !String(peer.session_id).startsWith('mock-') &&
1208
+ (policy === 'archive' || policy === 'delete')
1209
+ ) {
1210
+ const lsAddress = params.ls_address || peer.ls_address || process.env.ANTIGRAVITY_LS_ADDRESS;
1211
+ const csrfToken = params.csrf_token || peer.csrf_token || process.env.ANTIGRAVITY_CSRF_TOKEN;
1212
+ const projectId = params.project_id || peer.project_id || process.env.ANTIGRAVITY_PROJECT_ID;
1213
+ const api = this.convApiFactory({ lsAddress, csrfToken, projectId });
1214
+ if (api.isConfigured()) {
1215
+ if (policy === 'archive') {
1216
+ await api.updateConversation(peer.session_id, { archived: true });
1217
+ conversationAction = 'archived';
1218
+ } else if (policy === 'delete') {
1219
+ await api.deleteConversation(peer.session_id, { force });
1220
+ conversationAction = 'deleted';
1221
+ }
1222
+ }
1223
+ }
1224
+
1225
+ // Paseo daemon agent stop / delete
1226
+ let paseoAction = 'none';
1227
+ if (peer.runtime === 'paseo' && peer.session_id && policy !== 'detach') {
1228
+ const client = this.paseoClientFactory({
1229
+ host: params.host || peer.metadata?.paseo_host || undefined,
1230
+ home: params.home || peer.metadata?.paseo_home || undefined,
1231
+ });
1232
+ if (policy === 'delete') {
1233
+ await client.deleteAgent(peer.session_id);
1234
+ paseoAction = 'deleted';
1235
+ } else {
1236
+ await client.stopAgent(peer.session_id);
1237
+ paseoAction = 'stopped';
1238
+ }
1239
+ }
1240
+
1241
+ const finalState = policy === 'delete' ? 'deleted' : policy === 'archive' ? 'archived' : 'closed';
1242
+ const updated = this.db.updatePeerState(peer.peer_id, finalState, {
1243
+ metadata: { summary: cleanSummary(reason), needs_input: false },
1244
+ });
1245
+ this._emitMonitorEvent('peer.closed', { peer_id: peer.peer_id });
1246
+
1247
+ return {
1248
+ closed_peer: sanitizePeerForClient(updated),
1249
+ previous_state: previousState,
1250
+ action_taken: finalState,
1251
+ worker_stopped: workerStopped,
1252
+ pane_closed: paneClosed,
1253
+ conversation_action: conversationAction,
1254
+ paseo_action: paseoAction,
1255
+ };
1256
+ }
1257
+
1258
+ async syncPaseoPeers(params = {}) {
1259
+ const client = this.paseoClientFactory({
1260
+ host: params.host || undefined,
1261
+ home: params.home || undefined,
1262
+ });
1263
+ const agents = await client.listAgents({
1264
+ cwd: params.cwd || null,
1265
+ includeAll: Boolean(params.include_all),
1266
+ global: Boolean(params.global || !params.cwd),
1267
+ });
1268
+
1269
+ const synced = [];
1270
+ for (const agent of agents) {
1271
+ const agentId = agent.agentId || agent.agent_id || agent.id;
1272
+ if (!agentId) continue;
1273
+ const name = sanitizePaseoName(agent.title || agent.name, agentId);
1274
+ const { peer } = this.registerPeer({
1275
+ runtime: 'paseo',
1276
+ name,
1277
+ session_id: agentId,
1278
+ origin: 'attached',
1279
+ exec_mode: 'external',
1280
+ state: agent.status === 'running' || agent.status === 'busy' ? 'busy' : 'idle',
1281
+ cwd: agent.cwd || params.cwd || null,
1282
+ model: agent.provider || agent.model || null,
1283
+ host: params.host || null,
1284
+ home: params.home || null,
1285
+ metadata: {
1286
+ source: 'paseo-sync',
1287
+ paseo_host: params.host || null,
1288
+ paseo_home: params.home || null,
1289
+ paseo_status: agent.status || null,
1290
+ workspace_id: agent.workspaceId || agent.workspace_id || null,
1291
+ },
1292
+ });
1293
+ synced.push(peer);
1294
+ }
1295
+
1296
+ return { synced_count: synced.length, peers: synced };
1297
+ }
1298
+
1299
+ _resolveTaskWaiters(requestId, task) {
1300
+ const set = this.taskWaiters.get(requestId);
1301
+ if (!set) return;
1302
+ for (const entry of set) {
1303
+ clearTimeout(entry.timer);
1304
+ entry.resolve(task);
1305
+ }
1306
+ this.taskWaiters.delete(requestId);
1307
+ }
1308
+
1309
+ _resolveWorkflowWaiters(workflowId, wf) {
1310
+ const set = this.workflowWaiters.get(workflowId);
1311
+ if (!set) return;
1312
+ for (const entry of set) {
1313
+ clearTimeout(entry.timer);
1314
+ entry.resolve(wf);
1315
+ }
1316
+ this.workflowWaiters.delete(workflowId);
1317
+ }
1318
+
1319
+ async _sendTaskCallbackIfNeeded(task) {
1320
+ if (!task || !task.notify_on_finish || task.callback_sent || !task.callback_to) {
1321
+ return task;
1322
+ }
1323
+ const updated = this.db.updateTask(task.request_id, { callback_sent: true });
1324
+ try {
1325
+ await this.sendMessage({
1326
+ to: updated.callback_to,
1327
+ from: updated.to_handle || updated.to_peer_id,
1328
+ thread_id: updated.thread_id,
1329
+ kind: 'reply',
1330
+ reply_expected: false,
1331
+ override_loop_guard: true,
1332
+ body: formatTaskCallbackXml(updated),
1333
+ });
1334
+ } catch {
1335
+ // callback peer may have gone offline; task state remains persisted
1336
+ }
1337
+ return updated;
1338
+ }
1339
+
1340
+ async _finalizeTaskFromWorker(requestId, turnRes, err) {
1341
+ const existing = this.db.getTask(requestId);
1342
+ if (!existing) return null;
1343
+ if (['completed', 'failed', 'cancelled'].includes(existing.status)) {
1344
+ return existing;
1345
+ }
1346
+ const artifactReport = verifyArtifacts(existing.expected_artifacts, existing.cwd || process.cwd());
1347
+ let status = 'completed';
1348
+ let errorMsg = null;
1349
+ let summary = turnRes?.response || '';
1350
+ if (err || turnRes?.is_error) {
1351
+ status = 'failed';
1352
+ errorMsg = err?.message || turnRes?.error || 'Worker task execution failed';
1353
+ } else if (existing.require_artifacts && !artifactReport.verified) {
1354
+ status = 'failed';
1355
+ errorMsg = `Required artifacts missing: ${artifactReport.missing.join(', ')}`;
1356
+ }
1357
+ let updated = this.db.updateTask(requestId, {
1358
+ status,
1359
+ result_summary: summary,
1360
+ artifact_report: artifactReport,
1361
+ error: errorMsg,
1362
+ });
1363
+ updated = await this._sendTaskCallbackIfNeeded(updated);
1364
+ const taskSummary = cleanSummary(
1365
+ updated.result_summary || updated.error || updated.title || updated.status,
1366
+ );
1367
+ if (updated.to_peer_id) {
1368
+ const assignee = this.db.getPeer(updated.to_peer_id);
1369
+ if (assignee) {
1370
+ this.db.updatePeerState(assignee.peer_id, assignee.state, {
1371
+ metadata: { summary: taskSummary, needs_input: false },
1372
+ });
1373
+ }
1374
+ }
1375
+ this._emitMonitorEvent('task.updated', { request_id: requestId, peer_id: updated.to_peer_id });
1376
+ this._resolveTaskWaiters(requestId, updated);
1377
+ return updated;
1378
+ }
1379
+
1380
+ async delegateTask(params = {}) {
1381
+ const toRaw = String(params.to || '').trim();
1382
+ const prompt = String(params.prompt ?? params.body ?? params.message ?? '').trim();
1383
+ if (!toRaw) throw new RpcError('INVALID_PARAMS', 'Missing "to" target for task delegation');
1384
+ if (!prompt) throw new RpcError('INVALID_PARAMS', 'Missing "prompt" / "body" for task delegation');
1385
+
1386
+ const sender = this._resolveSender(params.from, params.cwd || null);
1387
+ const effectiveCwd =
1388
+ params.cwd || sender.cwd || (sender.id ? this.db.getPeer(sender.id)?.cwd : null) || null;
1389
+ const resolved = resolveTarget(this.db, toRaw, {
1390
+ includeOffline: false,
1391
+ checkNativeClaude: false,
1392
+ skipNativePidCheck: this.skipNativePidCheck,
1393
+ cwd: effectiveCwd,
1394
+ });
1395
+ if (!resolved.ok) {
1396
+ throw new RpcError(resolved.code, resolved.message, { candidates: resolved.candidates });
1397
+ }
1398
+
1399
+ const target = resolved.peer;
1400
+ const fromHandle =
1401
+ sender.runtime && sender.name ? `${sender.runtime}:${sender.name}` : sender.name || 'cli:external';
1402
+ const requestId = params.request_id || makeId('req');
1403
+ const threadId = params.thread_id || makeId('thr');
1404
+ const callbackTo =
1405
+ params.callback_to !== undefined
1406
+ ? params.callback_to || null
1407
+ : params.notify_on_finish === false
1408
+ ? null
1409
+ : sender.id || (sender.runtime !== 'cli' ? fromHandle : null);
1410
+
1411
+ const expectedArtifacts = Array.isArray(params.expected_artifacts)
1412
+ ? params.expected_artifacts.map((p) => String(p).trim()).filter(Boolean)
1413
+ : [];
1414
+ const acceptanceCriteria = Array.isArray(params.acceptance_criteria)
1415
+ ? params.acceptance_criteria.map((c) => String(c).trim()).filter(Boolean)
1416
+ : [];
1417
+ const notifyOnFinish = params.notify_on_finish !== false;
1418
+ const requireArtifacts = Boolean(params.require_artifacts);
1419
+ const taskCwd = params.cwd || target.cwd || process.cwd();
1420
+ const hasManagedWorker = Boolean(this.workers.get(target.peer_id) && !this.workers.get(target.peer_id).closed);
1421
+
1422
+ const task = this.db.insertTask({
1423
+ request_id: requestId,
1424
+ workflow_id: params.workflow_id || null,
1425
+ step_key: params.step_key || null,
1426
+ thread_id: threadId,
1427
+ from_handle: fromHandle,
1428
+ callback_to: callbackTo,
1429
+ to_peer_id: target.peer_id,
1430
+ to_handle: makeHandle(target),
1431
+ cwd: taskCwd,
1432
+ title: params.title || null,
1433
+ body: prompt,
1434
+ expected_artifacts: expectedArtifacts,
1435
+ acceptance_criteria: acceptanceCriteria,
1436
+ require_artifacts: requireArtifacts,
1437
+ notify_on_finish: notifyOnFinish,
1438
+ status: hasManagedWorker ? 'running' : 'pending',
1439
+ });
1440
+
1441
+ if (params.title) {
1442
+ this.db.updatePeerState(target.peer_id, target.state, {
1443
+ metadata: { summary: cleanSummary(`Task: ${params.title}`) },
1444
+ });
1445
+ }
1446
+ this._emitMonitorEvent('task.updated', { request_id: requestId, peer_id: target.peer_id });
1447
+
1448
+ const contract = taskToContract(task);
1449
+ const sendRes = await this.sendMessage({
1450
+ to: target.peer_id,
1451
+ from: params.from || fromHandle,
1452
+ thread_id: threadId,
1453
+ kind: 'prompt',
1454
+ body: prompt,
1455
+ reply_expected: true,
1456
+ max_hops: params.max_hops,
1457
+ override_loop_guard: true,
1458
+ contract,
1459
+ await_delivery: Boolean(params.wait && hasManagedWorker),
1460
+ timeout_ms: params.timeout_ms || 180_000,
1461
+ });
1462
+
1463
+ this.db.updateTask(requestId, { msg_id: sendRes.msg_id });
1464
+
1465
+ if (params.wait) {
1466
+ return this.waitForTask({
1467
+ request_id: requestId,
1468
+ timeout_ms: params.timeout_ms || 180_000,
1469
+ });
1470
+ }
1471
+
1472
+ return this.db.getTask(requestId);
1473
+ }
1474
+
1475
+ async completeTask(params = {}) {
1476
+ const requestId = String(params.request_id || '').trim();
1477
+ if (!requestId) {
1478
+ throw new RpcError('INVALID_PARAMS', 'Missing "request_id"');
1479
+ }
1480
+ const existing = this.db.getTask(requestId);
1481
+ if (!existing) {
1482
+ throw new RpcError('NOT_FOUND', `Task "${requestId}" not found`);
1483
+ }
1484
+ const requestedStatus = String(params.status || 'completed').toLowerCase();
1485
+ if (!TASK_STATUSES.has(requestedStatus) || requestedStatus === 'pending' || requestedStatus === 'running') {
1486
+ throw new RpcError('INVALID_PARAMS', `Invalid terminal task status "${requestedStatus}"`);
1487
+ }
1488
+
1489
+ const artifactReport = verifyArtifacts(existing.expected_artifacts, existing.cwd || process.cwd());
1490
+ let finalStatus = requestedStatus;
1491
+ let errorMsg = params.error || null;
1492
+ if (finalStatus === 'completed' && existing.require_artifacts && !artifactReport.verified) {
1493
+ finalStatus = 'failed';
1494
+ errorMsg = `Required artifacts missing: ${artifactReport.missing.join(', ')}`;
1495
+ }
1496
+
1497
+ let updated = this.db.updateTask(requestId, {
1498
+ status: finalStatus,
1499
+ result_summary: params.summary ?? params.result_summary ?? existing.result_summary,
1500
+ artifact_report: artifactReport,
1501
+ error: errorMsg,
1502
+ });
1503
+ updated = await this._sendTaskCallbackIfNeeded(updated);
1504
+ const taskSummary = cleanSummary(
1505
+ updated.result_summary || updated.error || updated.title || updated.status,
1506
+ );
1507
+ if (updated.to_peer_id) {
1508
+ const assignee = this.db.getPeer(updated.to_peer_id);
1509
+ if (assignee) {
1510
+ this.db.updatePeerState(assignee.peer_id, assignee.state, {
1511
+ metadata: { summary: taskSummary, needs_input: false },
1512
+ });
1513
+ }
1514
+ }
1515
+ this._emitMonitorEvent('task.updated', { request_id: requestId, peer_id: updated.to_peer_id });
1516
+ this._resolveTaskWaiters(requestId, updated);
1517
+ return updated;
1518
+ }
1519
+
1520
+ getTask(params = {}) {
1521
+ const requestId = String(params.request_id || '').trim();
1522
+ if (!requestId) throw new RpcError('INVALID_PARAMS', 'Missing "request_id"');
1523
+ const task = this.db.getTask(requestId);
1524
+ if (!task) throw new RpcError('NOT_FOUND', `Task "${requestId}" not found`);
1525
+ return task;
1526
+ }
1527
+
1528
+ listTasks(params = {}) {
1529
+ const scopeCwd = params.cwd || null;
1530
+ let toPeerId = params.to_peer_id || null;
1531
+ if (!toPeerId && params.to) {
1532
+ const peer = this._lookupPeer({ target: params.to, cwd: scopeCwd });
1533
+ if (peer) toPeerId = peer.peer_id;
1534
+ }
1535
+ let tasks = this.db.listTasks({
1536
+ workflowId: params.workflow_id || null,
1537
+ status: params.status || null,
1538
+ toPeerId,
1539
+ limit: scopeCwd ? Math.max(Number(params.limit || 50) * 4, 200) : params.limit || 50,
1540
+ });
1541
+ if (scopeCwd) {
1542
+ tasks = tasks
1543
+ .filter((t) => {
1544
+ if (t.cwd && isSameProjectScope(t.cwd, scopeCwd)) return true;
1545
+ const peer = t.to_peer_id ? this.db.getPeer(t.to_peer_id) : null;
1546
+ return Boolean(peer?.cwd && isSameProjectScope(peer.cwd, scopeCwd));
1547
+ })
1548
+ .slice(0, params.limit || 50);
1549
+ }
1550
+ return { count: tasks.length, tasks };
1551
+ }
1552
+
1553
+ waitForTask(params = {}, signal = null) {
1554
+ const requestId = String(params.request_id || '').trim();
1555
+ if (!requestId) {
1556
+ return Promise.reject(new RpcError('INVALID_PARAMS', 'Missing "request_id"'));
1557
+ }
1558
+ const existing = this.db.getTask(requestId);
1559
+ if (!existing) {
1560
+ return Promise.reject(new RpcError('NOT_FOUND', `Task "${requestId}" not found`));
1561
+ }
1562
+ if (['completed', 'failed', 'cancelled'].includes(existing.status)) {
1563
+ return Promise.resolve(existing);
1564
+ }
1565
+
1566
+ const timeoutMs = Math.max(50, Number(params.timeout_ms ?? 180_000));
1567
+ return new Promise((resolve, reject) => {
1568
+ if (!this.taskWaiters.has(requestId)) {
1569
+ this.taskWaiters.set(requestId, new Set());
1570
+ }
1571
+ const set = this.taskWaiters.get(requestId);
1572
+ const cleanup = () => {
1573
+ set.delete(entry);
1574
+ if (set.size === 0) this.taskWaiters.delete(requestId);
1575
+ };
1576
+ const timer = setTimeout(() => {
1577
+ cleanup();
1578
+ reject(new RpcError('TIMEOUT', `Timed out waiting for task "${requestId}" after ${timeoutMs}ms`));
1579
+ }, timeoutMs);
1580
+
1581
+ const entry = {
1582
+ timer,
1583
+ resolve: (task) => {
1584
+ cleanup();
1585
+ resolve(task);
1586
+ },
1587
+ reject: (err) => {
1588
+ cleanup();
1589
+ reject(err);
1590
+ },
1591
+ };
1592
+ set.add(entry);
1593
+
1594
+ if (signal) {
1595
+ const onAbort = () => {
1596
+ clearTimeout(timer);
1597
+ cleanup();
1598
+ reject(new RpcError('ABORTED', 'Task wait aborted'));
1599
+ };
1600
+ if (signal.aborted) onAbort();
1601
+ else signal.addEventListener('abort', onAbort, { once: true });
1602
+ }
1603
+ });
1604
+ }
1605
+
1606
+ runWorkflow(params = {}) {
1607
+ return this.orchestrator.runWorkflow(params);
1608
+ }
1609
+
1610
+ getWorkflow(params = {}) {
1611
+ const workflowId = String(params.workflow_id || '').trim();
1612
+ if (!workflowId) throw new RpcError('INVALID_PARAMS', 'Missing "workflow_id"');
1613
+ const wf = this.db.getWorkflow(workflowId);
1614
+ if (!wf) throw new RpcError('NOT_FOUND', `Workflow "${workflowId}" not found`);
1615
+ return wf;
1616
+ }
1617
+
1618
+ listWorkflows(params = {}) {
1619
+ const scopeCwd = params.cwd || null;
1620
+ let workflows = this.db.listWorkflows({
1621
+ status: params.status || null,
1622
+ template: params.template || null,
1623
+ limit: scopeCwd ? Math.max(Number(params.limit || 50) * 4, 200) : params.limit || 50,
1624
+ });
1625
+ if (scopeCwd) {
1626
+ workflows = workflows
1627
+ .filter((wf) => wf.spec?.cwd && isSameProjectScope(wf.spec.cwd, scopeCwd))
1628
+ .slice(0, params.limit || 50);
1629
+ }
1630
+ return { count: workflows.length, workflows };
1631
+ }
1632
+
1633
+ waitForWorkflow(params = {}, signal = null) {
1634
+ const workflowId = String(params.workflow_id || '').trim();
1635
+ if (!workflowId) {
1636
+ return Promise.reject(new RpcError('INVALID_PARAMS', 'Missing "workflow_id"'));
1637
+ }
1638
+ const existing = this.db.getWorkflow(workflowId);
1639
+ if (!existing) {
1640
+ return Promise.reject(new RpcError('NOT_FOUND', `Workflow "${workflowId}" not found`));
1641
+ }
1642
+ if (['completed', 'failed', 'cancelled'].includes(existing.status)) {
1643
+ return Promise.resolve(existing);
1644
+ }
1645
+
1646
+ const timeoutMs = Math.max(50, Number(params.timeout_ms ?? 300_000));
1647
+ return new Promise((resolve, reject) => {
1648
+ if (!this.workflowWaiters.has(workflowId)) {
1649
+ this.workflowWaiters.set(workflowId, new Set());
1650
+ }
1651
+ const set = this.workflowWaiters.get(workflowId);
1652
+ const cleanup = () => {
1653
+ set.delete(entry);
1654
+ if (set.size === 0) this.workflowWaiters.delete(workflowId);
1655
+ };
1656
+ const timer = setTimeout(() => {
1657
+ cleanup();
1658
+ reject(
1659
+ new RpcError('TIMEOUT', `Timed out waiting for workflow "${workflowId}" after ${timeoutMs}ms`),
1660
+ );
1661
+ }, timeoutMs);
1662
+
1663
+ const entry = {
1664
+ timer,
1665
+ resolve: (wf) => {
1666
+ cleanup();
1667
+ resolve(wf);
1668
+ },
1669
+ reject: (err) => {
1670
+ cleanup();
1671
+ reject(err);
1672
+ },
1673
+ };
1674
+ set.add(entry);
1675
+
1676
+ if (signal) {
1677
+ const onAbort = () => {
1678
+ clearTimeout(timer);
1679
+ cleanup();
1680
+ reject(new RpcError('ABORTED', 'Workflow wait aborted'));
1681
+ };
1682
+ if (signal.aborted) onAbort();
1683
+ else signal.addEventListener('abort', onAbort, { once: true });
1684
+ }
1685
+ });
1686
+ }
1687
+
1688
+ cancelWorkflow(params = {}) {
1689
+ const workflowId = String(params.workflow_id || '').trim();
1690
+ if (!workflowId) throw new RpcError('INVALID_PARAMS', 'Missing "workflow_id"');
1691
+ const existing = this.db.getWorkflow(workflowId);
1692
+ if (!existing) throw new RpcError('NOT_FOUND', `Workflow "${workflowId}" not found`);
1693
+ if (['completed', 'failed', 'cancelled'].includes(existing.status)) {
1694
+ return existing;
1695
+ }
1696
+ const reason = params.reason || 'Cancelled via workflow.cancel';
1697
+ const updated = this.db.updateWorkflow(workflowId, {
1698
+ status: 'cancelled',
1699
+ state: { ...(existing.state || {}), phase: 'cancelled' },
1700
+ error: reason,
1701
+ });
1702
+ this._emitMonitorEvent('workflow.updated', { workflow_id: workflowId, status: 'cancelled' });
1703
+ this._resolveWorkflowWaiters(workflowId, updated);
1704
+ return updated;
1705
+ }
1706
+
1707
+ async getMonitorSnapshot(params = {}) {
1708
+ const includeOffline = params.include_offline !== false;
1709
+ const includeHost = params.include_host !== false;
1710
+ const brokerPeers = this.listPeers({ include_offline: includeOffline }).peers;
1711
+ const hostPeers = includeHost
1712
+ ? await discoverHostPeers(this.config, {
1713
+ includeStopped: includeOffline,
1714
+ skipPidCheck: this.skipNativePidCheck,
1715
+ paseoClientFactory: this.paseoClientFactory,
1716
+ })
1717
+ : [];
1718
+
1719
+ const { peers, counts } = mergeAllPeers(brokerPeers, hostPeers, {
1720
+ runtime: params.runtime || null,
1721
+ cwd: params.cwd || null,
1722
+ includeStopped: includeOffline,
1723
+ });
1724
+ const activeWorkflows = this.listWorkflows({
1725
+ status: 'running',
1726
+ cwd: params.cwd || null,
1727
+ limit: 50,
1728
+ }).workflows.length;
1729
+
1730
+ return {
1731
+ daemon: this.getStatus(),
1732
+ active_workflows: activeWorkflows,
1733
+ counts,
1734
+ peers,
1735
+ };
1736
+ }
1737
+
1738
+ async subscribeMonitor(params = {}, pushFn) {
1739
+ this.monitorSubscribers.add(pushFn);
1740
+ const snapshot = await this.getMonitorSnapshot(params);
1741
+ return {
1742
+ subscribed: true,
1743
+ snapshot,
1744
+ unsubscribe: () => {
1745
+ this.monitorSubscribers.delete(pushFn);
1746
+ },
1747
+ };
1748
+ }
1749
+
1750
+ tailLogs(params = {}) {
1751
+ let peerId = params.peer_id || null;
1752
+ if (!peerId && params.peer) {
1753
+ const peer = this._lookupPeer({ target: params.peer, cwd: params.cwd || null });
1754
+ if (peer) peerId = peer.peer_id;
1755
+ }
1756
+ const entries = this.db.tailLogs({
1757
+ threadId: params.thread_id || null,
1758
+ peerId,
1759
+ limit: params.limit || 20,
1760
+ });
1761
+ return { count: entries.length, entries };
1762
+ }
1763
+
1764
+ async shutdown() {
1765
+ if (this.closed) return;
1766
+ this.closed = true;
1767
+ for (const [, waiterSet] of this.waiters) {
1768
+ for (const entry of waiterSet) {
1769
+ clearTimeout(entry.timer);
1770
+ entry.resolve({ woke: false, reason: 'daemon_shutdown', messages: [] });
1771
+ }
1772
+ }
1773
+ this.waiters.clear();
1774
+ for (const [, waiterSet] of this.taskWaiters) {
1775
+ for (const entry of waiterSet) {
1776
+ clearTimeout(entry.timer);
1777
+ entry.reject(new RpcError('DAEMON_SHUTDOWN', 'Broker shutting down'));
1778
+ }
1779
+ }
1780
+ this.taskWaiters.clear();
1781
+ for (const [, waiterSet] of this.workflowWaiters) {
1782
+ for (const entry of waiterSet) {
1783
+ clearTimeout(entry.timer);
1784
+ entry.reject(new RpcError('DAEMON_SHUTDOWN', 'Broker shutting down'));
1785
+ }
1786
+ }
1787
+ this.workflowWaiters.clear();
1788
+ this.channelSubscribers.clear();
1789
+ this.monitorSubscribers.clear();
1790
+
1791
+ const stops = [];
1792
+ for (const worker of this.workers.values()) {
1793
+ stops.push(worker.stop().catch(() => {}));
1794
+ }
1795
+ await Promise.all(stops);
1796
+ this.workers.clear();
1797
+ this.db.close();
1798
+ }
1799
+ }