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,200 @@
1
+ import path from 'node:path';
2
+ import { getProjectLabel, isSameProjectScope } from '../project.mjs';
3
+ import { makeHandle, parseAddress } from '../protocol.mjs';
4
+ import { matchNativeClaudePeers, scanNativeClaudePeers } from '../runtime/native-claude.mjs';
5
+
6
+ function formatCandidate(peer) {
7
+ const shortId = (peer.session_id || peer.peer_id || '').slice(0, 8);
8
+ if (peer.cwd) {
9
+ return `${peer.runtime}:${getProjectLabel(peer.cwd)}/${peer.name} (${shortId})`;
10
+ }
11
+ return `${makeHandle(peer)} (${shortId})`;
12
+ }
13
+
14
+ function formatNativeCandidate(nativePeer) {
15
+ const shortId = String(nativePeer.id || '').slice(0, 8);
16
+ return `cc:${nativePeer.name} (${shortId}, native)`;
17
+ }
18
+
19
+ function matchPeersByQuery(peers, query) {
20
+ const slashIdx = query.lastIndexOf('/');
21
+ if (slashIdx > 0 && slashIdx < query.length - 1) {
22
+ const projPart = query.slice(0, slashIdx);
23
+ const namePart = query.slice(slashIdx + 1);
24
+ const qualified = peers.filter((p) => {
25
+ if (p.name !== namePart || !p.cwd) return false;
26
+ return (
27
+ getProjectLabel(p.cwd) === projPart ||
28
+ path.basename(p.cwd) === projPart ||
29
+ p.cwd.endsWith(`/${projPart}`) ||
30
+ p.cwd.endsWith(`\\${projPart}`)
31
+ );
32
+ });
33
+ if (qualified.length) return { matches: qualified, matchType: 'project_qualified_name' };
34
+ }
35
+
36
+ const exactName = peers.filter((p) => p.name === query);
37
+ if (exactName.length) return { matches: exactName, matchType: 'exact_name' };
38
+
39
+ const exactId = peers.filter((p) => p.peer_id === query || p.session_id === query);
40
+ if (exactId.length) return { matches: exactId, matchType: 'exact_id' };
41
+
42
+ if (query.length >= 6) {
43
+ const prefix = peers.filter(
44
+ (p) =>
45
+ (p.peer_id && p.peer_id.startsWith(query)) ||
46
+ (p.session_id && p.session_id.startsWith(query)),
47
+ );
48
+ if (prefix.length) return { matches: prefix, matchType: 'id_prefix' };
49
+ }
50
+
51
+ return { matches: [], matchType: null };
52
+ }
53
+
54
+ export function resolveTarget(db, rawTarget, opts = {}) {
55
+ const parsed = parseAddress(rawTarget);
56
+ if (!parsed.query) {
57
+ return {
58
+ ok: false,
59
+ code: 'INVALID_TARGET',
60
+ message: 'Target address is empty.',
61
+ };
62
+ }
63
+
64
+ const includeOffline = Boolean(opts.includeOffline);
65
+ const checkNativeClaude = opts.checkNativeClaude !== false;
66
+ const claudeDir = opts.claudeDir || null;
67
+ const skipNativePidCheck = Boolean(opts.skipNativePidCheck);
68
+ const scopeCwd = opts.cwd || null;
69
+
70
+ const activePeers = db.listPeers({
71
+ runtime: parsed.runtime || null,
72
+ includeOffline,
73
+ });
74
+
75
+ // Priority 1: explicit <runtime>:<name|id>
76
+ if (parsed.runtime) {
77
+ const { matches, matchType } = matchPeersByQuery(activePeers, parsed.query);
78
+ if (matches.length === 1) {
79
+ return { ok: true, peer: matches[0], match_type: `explicit_${matchType}` };
80
+ }
81
+ if (matches.length > 1) {
82
+ if (scopeCwd) {
83
+ const scoped = matches.filter((p) => p.cwd && isSameProjectScope(p.cwd, scopeCwd));
84
+ if (scoped.length === 1) {
85
+ return { ok: true, peer: scoped[0], match_type: `explicit_project_scoped_${matchType}` };
86
+ }
87
+ }
88
+ const candidates = matches.map(formatCandidate);
89
+ return {
90
+ ok: false,
91
+ code: 'AMBIGUOUS_TARGET',
92
+ candidates,
93
+ message: `Ambiguous target "${rawTarget}". Candidates: ${candidates.join(', ')}`,
94
+ };
95
+ }
96
+
97
+ if (parsed.runtime === 'cc' && checkNativeClaude && claudeDir) {
98
+ const nativePeers = scanNativeClaudePeers(claudeDir, { skipPidCheck: skipNativePidCheck });
99
+ const nativeMatches = matchNativeClaudePeers(nativePeers, parsed.query);
100
+ if (nativeMatches.length) {
101
+ return {
102
+ ok: false,
103
+ code: 'NATIVE_ONLY',
104
+ native_matches: nativeMatches,
105
+ message: `Target "${rawTarget}" matches native Claude Code session(s): ${nativeMatches
106
+ .map(formatNativeCandidate)
107
+ .join(', ')}`,
108
+ };
109
+ }
110
+ }
111
+
112
+ return {
113
+ ok: false,
114
+ code: 'NOT_FOUND',
115
+ message: `No active ${parsed.runtime} peer matches "${parsed.query}".`,
116
+ };
117
+ }
118
+
119
+ // Priority 2 & 3: bare <name> or <id-prefix>
120
+ const { matches, matchType } = matchPeersByQuery(activePeers, parsed.query);
121
+
122
+ // Check native Claude peers for collision or passthrough
123
+ let nativeMatches = [];
124
+ if (checkNativeClaude && claudeDir) {
125
+ const nativePeers = scanNativeClaudePeers(claudeDir, { skipPidCheck: skipNativePidCheck });
126
+ nativeMatches = matchNativeClaudePeers(nativePeers, parsed.query);
127
+ // Filter out native peers already registered as the exact same cc session in broker
128
+ const registeredCcSessionIds = new Set(
129
+ matches.filter((m) => m.runtime === 'cc' && m.session_id).map((m) => m.session_id),
130
+ );
131
+ nativeMatches = nativeMatches.filter((n) => !registeredCcSessionIds.has(n.id));
132
+ }
133
+
134
+ const externalMatches = matches.filter((m) => m.runtime !== 'cc');
135
+ const brokerCcMatches = matches.filter((m) => m.runtime === 'cc');
136
+
137
+ // Native Claude + external broker peer collision!
138
+ if (nativeMatches.length > 0 && externalMatches.length > 0) {
139
+ const candidates = [
140
+ ...nativeMatches.map(formatNativeCandidate),
141
+ ...matches.map(formatCandidate),
142
+ ];
143
+ return {
144
+ ok: false,
145
+ code: 'AMBIGUOUS_TARGET',
146
+ candidates,
147
+ native_matches: nativeMatches,
148
+ broker_matches: matches.map(formatCandidate),
149
+ message: `Name collision for "${rawTarget}" across native Claude and peer-bridge. Specify an explicit prefix: ${candidates.join(', ')}`,
150
+ };
151
+ }
152
+
153
+ // Pure native Claude target (preserve 100% native SendMessage)
154
+ if (nativeMatches.length > 0 && matches.length === 0) {
155
+ return {
156
+ ok: false,
157
+ code: 'NATIVE_ONLY',
158
+ native_matches: nativeMatches,
159
+ message: `Target "${rawTarget}" is a native Claude Code peer: ${nativeMatches
160
+ .map(formatNativeCandidate)
161
+ .join(', ')}`,
162
+ };
163
+ }
164
+
165
+ // Multiple broker peers (e.g., cc:backend and agy:backend, or duplicate prefix)
166
+ if (matches.length > 1) {
167
+ if (scopeCwd) {
168
+ const scoped = matches.filter((p) => p.cwd && isSameProjectScope(p.cwd, scopeCwd));
169
+ if (scoped.length === 1) {
170
+ return { ok: true, peer: scoped[0], match_type: `project_scoped_${matchType}` };
171
+ }
172
+ }
173
+ const candidates = matches.map(formatCandidate);
174
+ return {
175
+ ok: false,
176
+ code: 'AMBIGUOUS_TARGET',
177
+ candidates,
178
+ message: `Ambiguous target "${rawTarget}". Specify an explicit prefix or longer ID: ${candidates.join(', ')}`,
179
+ };
180
+ }
181
+
182
+ if (matches.length === 1) {
183
+ return { ok: true, peer: matches[0], match_type: matchType };
184
+ }
185
+
186
+ // Also check if an explicit cc match collided with another native peer
187
+ if (brokerCcMatches.length === 0 && nativeMatches.length === 0) {
188
+ return {
189
+ ok: false,
190
+ code: 'NOT_FOUND',
191
+ message: `No active peer matches "${rawTarget}".`,
192
+ };
193
+ }
194
+
195
+ return {
196
+ ok: false,
197
+ code: 'NOT_FOUND',
198
+ message: `No active peer matches "${rawTarget}".`,
199
+ };
200
+ }
@@ -0,0 +1,221 @@
1
+ import fs from 'node:fs';
2
+ import net from 'node:net';
3
+ import { ensureHomeDir, getConfig, isNamedPipePath, isProcessAlive } from '../config.mjs';
4
+ import { RpcError, createLineSplitter, encodeFrame } from '../protocol.mjs';
5
+ import { PeerBroker } from './broker.mjs';
6
+
7
+ export class BrokerServer {
8
+ constructor(options = {}) {
9
+ this.config = getConfig(options.config || {});
10
+ this.broker = options.broker || new PeerBroker({ config: this.config, ...options });
11
+ this.server = null;
12
+ this.sockets = new Set();
13
+ this.closing = false;
14
+ }
15
+
16
+ async start() {
17
+ ensureHomeDir(this.config.homeDir);
18
+
19
+ // Check for existing live daemon
20
+ if (fs.existsSync(this.config.pidPath)) {
21
+ const existingPid = Number(fs.readFileSync(this.config.pidPath, 'utf8').trim());
22
+ if (existingPid && existingPid !== process.pid && isProcessAlive(existingPid)) {
23
+ throw new Error(`pbridged is already running (pid=${existingPid})`);
24
+ }
25
+ fs.rmSync(this.config.pidPath, { force: true });
26
+ }
27
+
28
+ const namedPipe = isNamedPipePath(this.config.sockPath);
29
+ if (!namedPipe && fs.existsSync(this.config.sockPath)) {
30
+ fs.rmSync(this.config.sockPath, { force: true });
31
+ }
32
+
33
+ this.server = net.createServer((socket) => this._handleConnection(socket));
34
+ await new Promise((resolve, reject) => {
35
+ this.server.once('error', reject);
36
+ this.server.listen(this.config.sockPath, () => {
37
+ this.server.removeListener('error', reject);
38
+ resolve();
39
+ });
40
+ });
41
+
42
+ if (!namedPipe) {
43
+ try {
44
+ fs.chmodSync(this.config.sockPath, 0o600);
45
+ } catch {
46
+ // ignore chmod failures on exotic filesystems
47
+ }
48
+ }
49
+
50
+ fs.writeFileSync(this.config.pidPath, `${process.pid}\n`, { mode: 0o600 });
51
+ return this.broker.getStatus();
52
+ }
53
+
54
+ _handleConnection(socket) {
55
+ this.sockets.add(socket);
56
+ const ac = new AbortController();
57
+ const unsubscribes = [];
58
+
59
+ const cleanup = () => {
60
+ this.sockets.delete(socket);
61
+ ac.abort();
62
+ for (const unsub of unsubscribes) {
63
+ try {
64
+ unsub();
65
+ } catch {
66
+ // ignore
67
+ }
68
+ }
69
+ unsubscribes.length = 0;
70
+ };
71
+
72
+ socket.on('close', cleanup);
73
+ socket.on('error', cleanup);
74
+
75
+ const writeSafe = (obj) => {
76
+ if (!socket.destroyed && socket.writable) {
77
+ socket.write(encodeFrame(obj));
78
+ }
79
+ };
80
+
81
+ const onLine = async (line) => {
82
+ let req;
83
+ try {
84
+ req = JSON.parse(line);
85
+ } catch {
86
+ writeSafe({
87
+ jsonrpc: '2.0',
88
+ id: null,
89
+ error: { code: 'PARSE_ERROR', message: 'Invalid JSON frame' },
90
+ });
91
+ return;
92
+ }
93
+
94
+ const { id, method, params = {} } = req;
95
+ try {
96
+ const result = await this._dispatch(method, params, {
97
+ signal: ac.signal,
98
+ push: (ev) => writeSafe({ jsonrpc: '2.0', method: 'channel.push', params: ev }),
99
+ onUnsubscribe: (fn) => unsubscribes.push(fn),
100
+ });
101
+ if (id !== undefined) {
102
+ writeSafe({ jsonrpc: '2.0', id, result });
103
+ }
104
+ } catch (err) {
105
+ const code = err instanceof RpcError ? err.code : 'INTERNAL_ERROR';
106
+ const data = err instanceof RpcError ? err.data : undefined;
107
+ if (id !== undefined) {
108
+ writeSafe({
109
+ jsonrpc: '2.0',
110
+ id,
111
+ error: { code, message: err.message, ...(data !== undefined ? { data } : {}) },
112
+ });
113
+ }
114
+ }
115
+ };
116
+
117
+ socket.on('data', createLineSplitter(onLine));
118
+ }
119
+
120
+ async _dispatch(method, params, ctx) {
121
+ switch (method) {
122
+ case 'daemon.ping':
123
+ return { pong: true, pid: process.pid };
124
+ case 'daemon.status':
125
+ return this.broker.getStatus();
126
+ case 'daemon.shutdown':
127
+ setImmediate(() => this.stop());
128
+ return { shutting_down: true };
129
+ case 'peer.register':
130
+ return this.broker.registerPeer(params);
131
+ case 'peer.heartbeat':
132
+ return this.broker.heartbeatPeer(params);
133
+ case 'peer.list':
134
+ return this.broker.listPeers(params);
135
+ case 'peer.resolve':
136
+ return this.broker.resolvePeer(params);
137
+ case 'peer.spawn':
138
+ return this.broker.spawnPeer(params);
139
+ case 'peer.close':
140
+ return this.broker.closePeer(params);
141
+ case 'message.send':
142
+ return this.broker.sendMessage(params);
143
+ case 'message.poll':
144
+ return this.broker.pollMessages(params);
145
+ case 'message.wait':
146
+ return this.broker.waitForMessages(params, ctx.signal);
147
+ case 'channel.subscribe': {
148
+ const sub = this.broker.subscribeChannel(params, ctx.push);
149
+ ctx.onUnsubscribe(sub.unsubscribe);
150
+ return { subscribed: true, peer_id: sub.peer_id, handle: sub.handle };
151
+ }
152
+ case 'monitor.snapshot':
153
+ return this.broker.getMonitorSnapshot(params);
154
+ case 'monitor.subscribe': {
155
+ const sub = await this.broker.subscribeMonitor(params, ctx.push);
156
+ ctx.onUnsubscribe(sub.unsubscribe);
157
+ return { subscribed: true, snapshot: sub.snapshot };
158
+ }
159
+ case 'paseo.sync':
160
+ return this.broker.syncPaseoPeers(params);
161
+ case 'task.create':
162
+ return this.broker.delegateTask(params);
163
+ case 'task.complete':
164
+ return this.broker.completeTask(params);
165
+ case 'task.get':
166
+ return this.broker.getTask(params);
167
+ case 'task.list':
168
+ return this.broker.listTasks(params);
169
+ case 'task.wait':
170
+ return this.broker.waitForTask(params, ctx.signal);
171
+ case 'workflow.run':
172
+ return this.broker.runWorkflow(params);
173
+ case 'workflow.get':
174
+ return this.broker.getWorkflow(params);
175
+ case 'workflow.list':
176
+ return this.broker.listWorkflows(params);
177
+ case 'workflow.wait':
178
+ return this.broker.waitForWorkflow(params, ctx.signal);
179
+ case 'workflow.cancel':
180
+ return this.broker.cancelWorkflow(params);
181
+ case 'logs.tail':
182
+ return this.broker.tailLogs(params);
183
+ default:
184
+ throw new RpcError('METHOD_NOT_FOUND', `Unknown RPC method "${method}"`);
185
+ }
186
+ }
187
+
188
+ async stop() {
189
+ if (this.closing) return;
190
+ this.closing = true;
191
+
192
+ for (const sock of this.sockets) {
193
+ try {
194
+ sock.destroy();
195
+ } catch {
196
+ // ignore
197
+ }
198
+ }
199
+ this.sockets.clear();
200
+
201
+ if (this.server) {
202
+ await new Promise((resolve) => this.server.close(() => resolve()));
203
+ this.server = null;
204
+ }
205
+
206
+ await this.broker.shutdown();
207
+
208
+ try {
209
+ if (!isNamedPipePath(this.config.sockPath) && fs.existsSync(this.config.sockPath)) {
210
+ fs.rmSync(this.config.sockPath, { force: true });
211
+ }
212
+ } catch {
213
+ // ignore
214
+ }
215
+ try {
216
+ if (fs.existsSync(this.config.pidPath)) fs.rmSync(this.config.pidPath, { force: true });
217
+ } catch {
218
+ // ignore
219
+ }
220
+ }
221
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,53 @@
1
+ export { defaultSockPath, getConfig, isNamedPipePath, resolveRuntimeBin } from './config.mjs';
2
+ export {
3
+ detectDefaultProjectCwd,
4
+ findProjectRoot,
5
+ getProjectLabel,
6
+ isSameOrSubPath,
7
+ isSameProjectScope,
8
+ normalizeProjectPath,
9
+ } from './project.mjs';
10
+ export { StateDB, sanitizePeerForClient } from './storage/db.mjs';
11
+ export { PeerBroker } from './daemon/broker.mjs';
12
+ export { BrokerServer } from './daemon/server.mjs';
13
+ export { resolveTarget } from './daemon/resolver.mjs';
14
+ export { ConversationApi } from './runtime/conv-api.mjs';
15
+ export {
16
+ AgyStreamWorker,
17
+ CcStreamWorker,
18
+ CodexExecWorker,
19
+ GeminiCliWorker,
20
+ MockStreamWorker,
21
+ spawnTmuxPane,
22
+ killTmuxPane,
23
+ } from './runtime/workers.mjs';
24
+ export { PaseoClient, PaseoAgentWorker } from './runtime/paseo.mjs';
25
+ export { WorkflowOrchestrator } from './orchestrator/workflows.mjs';
26
+ export {
27
+ callRpc,
28
+ subscribeChannel,
29
+ subscribeMonitor,
30
+ isDaemonRunning,
31
+ startDaemonDetached,
32
+ stopDaemon,
33
+ } from './client/rpc.mjs';
34
+ export {
35
+ cleanSummary,
36
+ formatPeerMessageXml,
37
+ formatTaskCallbackXml,
38
+ makeHandle,
39
+ makeId,
40
+ parseAddress,
41
+ resolveAgyModels,
42
+ verifyArtifacts,
43
+ RpcError,
44
+ } from './protocol.mjs';
45
+ export { startMcpServer } from './mcp/server.mjs';
46
+ export { runClaudeHook } from './adapters/claude/hooks.mjs';
47
+ export { runAntigravityHook } from './adapters/antigravity/hooks.mjs';
48
+ export { runCodexHook } from './adapters/codex/hooks.mjs';
49
+ export { runGeminiHook } from './adapters/gemini/hooks.mjs';
50
+ export { installAdapter } from './adapters/installer.mjs';
51
+ export { discoverHostPeers, mergeAllPeers } from './runtime/host-discovery.mjs';
52
+ export { renderFrame } from './tui/render.mjs';
53
+ export { runTuiViewer } from './tui/viewer.mjs';