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,142 @@
1
+ import {
2
+ callRpc,
3
+ isDaemonRunning,
4
+ startDaemonDetached,
5
+ } from '../../client/rpc.mjs';
6
+ import { getConfig } from '../../config.mjs';
7
+
8
+ function parseInput(rawInput) {
9
+ if (!rawInput) return {};
10
+ if (typeof rawInput === 'object') return rawInput;
11
+ try {
12
+ return JSON.parse(String(rawInput));
13
+ } catch {
14
+ return {};
15
+ }
16
+ }
17
+
18
+ export async function runCodexHook(eventName, rawInput, options = {}) {
19
+ const input = parseInput(rawInput);
20
+ const event = eventName || input.hook_event_name || input.hookEventName || '';
21
+ const config = getConfig(options.config);
22
+ const autoStart = options.autoStart !== false;
23
+
24
+ const ensureDaemonOrSkip = async () => {
25
+ if (await isDaemonRunning({ config })) return true;
26
+ if (!autoStart) return false;
27
+ try {
28
+ await startDaemonDetached({ config });
29
+ return true;
30
+ } catch {
31
+ return false;
32
+ }
33
+ };
34
+
35
+ const sessionId =
36
+ input.session_id ||
37
+ input.thread_id ||
38
+ input.sessionId ||
39
+ process.env.CODEX_THREAD_ID ||
40
+ process.env.CODEX_SESSION_ID ||
41
+ null;
42
+ const cwd = input.cwd || process.cwd();
43
+ const peerName =
44
+ input.peer_name ||
45
+ process.env.PBRIDGE_PEER_NAME ||
46
+ (sessionId ? `codex-${String(sessionId).slice(0, 8)}` : `codex-${process.pid}`);
47
+
48
+ const pollPending = async () => {
49
+ const polled = await callRpc(
50
+ 'message.poll',
51
+ {
52
+ runtime: 'codex',
53
+ session_id: sessionId || undefined,
54
+ target: !sessionId ? `codex:${peerName}` : undefined,
55
+ limit: 10,
56
+ },
57
+ { config, timeoutMs: 2500 },
58
+ );
59
+ return polled?.messages || [];
60
+ };
61
+
62
+ if (event === 'SessionStart') {
63
+ if (!(await ensureDaemonOrSkip())) return {};
64
+ try {
65
+ await callRpc(
66
+ 'peer.register',
67
+ {
68
+ runtime: 'codex',
69
+ name: peerName,
70
+ session_id: sessionId,
71
+ origin: 'attached',
72
+ exec_mode: 'interactive',
73
+ state: 'idle',
74
+ cwd,
75
+ pid: process.ppid || process.pid,
76
+ metadata: { source: 'codex-hook-session-start' },
77
+ },
78
+ { config, timeoutMs: 3000 },
79
+ );
80
+ const msgs = await pollPending();
81
+ if (msgs.length > 0) {
82
+ return {
83
+ hookSpecificOutput: {
84
+ hookEventName: 'SessionStart',
85
+ additionalContext: msgs.map((m) => m.formatted_xml || m.formatted).join('\n\n'),
86
+ },
87
+ };
88
+ }
89
+ } catch {
90
+ return {};
91
+ }
92
+ return {};
93
+ }
94
+
95
+ if (event === 'UserPromptSubmit' || event === 'PostToolUse') {
96
+ if (!(await ensureDaemonOrSkip())) return {};
97
+ try {
98
+ const msgs = await pollPending();
99
+ if (msgs.length > 0) {
100
+ return {
101
+ hookSpecificOutput: {
102
+ hookEventName: event,
103
+ additionalContext: msgs.map((m) => m.formatted_xml || m.formatted).join('\n\n'),
104
+ },
105
+ };
106
+ }
107
+ } catch {
108
+ return {};
109
+ }
110
+ return {};
111
+ }
112
+
113
+ if (event === 'Stop') {
114
+ if (!(await isDaemonRunning({ config }))) return {};
115
+ try {
116
+ await callRpc(
117
+ 'peer.heartbeat',
118
+ {
119
+ runtime: 'codex',
120
+ session_id: sessionId || undefined,
121
+ target: !sessionId ? `codex:${peerName}` : undefined,
122
+ state: 'idle',
123
+ ...(input.last_assistant_message ? { summary: input.last_assistant_message } : {}),
124
+ },
125
+ { config, timeoutMs: 2500 },
126
+ );
127
+ if (input.stop_hook_active) return {};
128
+ const msgs = await pollPending();
129
+ if (msgs.length > 0) {
130
+ return {
131
+ decision: 'block',
132
+ reason: `[peer-bridge incoming peer message]\n${msgs.map((m) => m.formatted_xml || m.formatted).join('\n\n')}`,
133
+ };
134
+ }
135
+ } catch {
136
+ return {};
137
+ }
138
+ return {};
139
+ }
140
+
141
+ return {};
142
+ }
@@ -0,0 +1,159 @@
1
+ import {
2
+ callRpc,
3
+ isDaemonRunning,
4
+ startDaemonDetached,
5
+ } from '../../client/rpc.mjs';
6
+ import { getConfig } from '../../config.mjs';
7
+
8
+ function parseInput(rawInput) {
9
+ if (!rawInput) return {};
10
+ if (typeof rawInput === 'object') return rawInput;
11
+ try {
12
+ return JSON.parse(String(rawInput));
13
+ } catch {
14
+ return {};
15
+ }
16
+ }
17
+
18
+ export async function runGeminiHook(eventName, rawInput, options = {}) {
19
+ const input = parseInput(rawInput);
20
+ const event = eventName || input.hook_event_name || input.hookEventName || '';
21
+ const config = getConfig(options.config);
22
+ const autoStart = options.autoStart !== false;
23
+
24
+ const ensureDaemonOrSkip = async () => {
25
+ if (await isDaemonRunning({ config })) return true;
26
+ if (!autoStart) return false;
27
+ try {
28
+ await startDaemonDetached({ config });
29
+ return true;
30
+ } catch {
31
+ return false;
32
+ }
33
+ };
34
+
35
+ const sessionId =
36
+ input.session_id ||
37
+ input.sessionId ||
38
+ process.env.GEMINI_SESSION_ID ||
39
+ null;
40
+ const cwd = input.cwd || process.cwd();
41
+ const peerName =
42
+ input.peer_name ||
43
+ process.env.PBRIDGE_PEER_NAME ||
44
+ (sessionId ? `gemini-${String(sessionId).slice(0, 8)}` : `gemini-${process.pid}`);
45
+
46
+ const pollPending = async () => {
47
+ const polled = await callRpc(
48
+ 'message.poll',
49
+ {
50
+ runtime: 'gemini',
51
+ session_id: sessionId || undefined,
52
+ target: !sessionId ? `gemini:${peerName}` : undefined,
53
+ limit: 10,
54
+ },
55
+ { config, timeoutMs: 2500 },
56
+ );
57
+ return polled?.messages || [];
58
+ };
59
+
60
+ if (event === 'SessionStart') {
61
+ if (!(await ensureDaemonOrSkip())) return {};
62
+ try {
63
+ await callRpc(
64
+ 'peer.register',
65
+ {
66
+ runtime: 'gemini',
67
+ name: peerName,
68
+ session_id: sessionId,
69
+ origin: 'attached',
70
+ exec_mode: 'interactive',
71
+ state: 'idle',
72
+ cwd,
73
+ pid: process.ppid || process.pid,
74
+ metadata: { source: 'gemini-hook-session-start' },
75
+ },
76
+ { config, timeoutMs: 3000 },
77
+ );
78
+ const msgs = await pollPending();
79
+ if (msgs.length > 0) {
80
+ return {
81
+ hookSpecificOutput: {
82
+ hookEventName: 'SessionStart',
83
+ additionalContext: msgs.map((m) => m.formatted_xml || m.formatted).join('\n\n'),
84
+ },
85
+ };
86
+ }
87
+ } catch {
88
+ return {};
89
+ }
90
+ return {};
91
+ }
92
+
93
+ if (event === 'BeforeAgent' || event === 'AfterTool') {
94
+ if (!(await ensureDaemonOrSkip())) return {};
95
+ try {
96
+ const msgs = await pollPending();
97
+ if (msgs.length > 0) {
98
+ return {
99
+ hookSpecificOutput: {
100
+ hookEventName: event,
101
+ additionalContext: msgs.map((m) => m.formatted_xml || m.formatted).join('\n\n'),
102
+ },
103
+ };
104
+ }
105
+ } catch {
106
+ return {};
107
+ }
108
+ return {};
109
+ }
110
+
111
+ if (event === 'AfterAgent') {
112
+ if (!(await isDaemonRunning({ config }))) return {};
113
+ try {
114
+ await callRpc(
115
+ 'peer.heartbeat',
116
+ {
117
+ runtime: 'gemini',
118
+ session_id: sessionId || undefined,
119
+ target: !sessionId ? `gemini:${peerName}` : undefined,
120
+ state: 'idle',
121
+ ...(input.prompt_response ? { summary: input.prompt_response } : {}),
122
+ },
123
+ { config, timeoutMs: 2500 },
124
+ );
125
+ if (input.stop_hook_active) return {};
126
+ const msgs = await pollPending();
127
+ if (msgs.length > 0) {
128
+ return {
129
+ decision: 'block',
130
+ reason: `[peer-bridge incoming peer message]\n${msgs.map((m) => m.formatted_xml || m.formatted).join('\n\n')}`,
131
+ };
132
+ }
133
+ } catch {
134
+ return {};
135
+ }
136
+ return {};
137
+ }
138
+
139
+ if (event === 'SessionEnd') {
140
+ if (!(await isDaemonRunning({ config }))) return {};
141
+ try {
142
+ await callRpc(
143
+ 'peer.heartbeat',
144
+ {
145
+ runtime: 'gemini',
146
+ session_id: sessionId || undefined,
147
+ target: !sessionId ? `gemini:${peerName}` : undefined,
148
+ state: 'detached',
149
+ },
150
+ { config, timeoutMs: 2000 },
151
+ );
152
+ } catch {
153
+ return {};
154
+ }
155
+ return {};
156
+ }
157
+
158
+ return {};
159
+ }
@@ -0,0 +1,328 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
+ const REPO_ROOT = path.resolve(__dirname, '../..');
8
+
9
+ function readJsonSafe(filePath) {
10
+ if (!fs.existsSync(filePath)) return null;
11
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
12
+ }
13
+
14
+ function writeJsonWithBackup(filePath, data, { dryRun = false } = {}) {
15
+ const existed = fs.existsSync(filePath);
16
+ const backupPath = existed ? `${filePath}.bak` : null;
17
+ if (!dryRun) {
18
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
19
+ if (existed) {
20
+ fs.copyFileSync(filePath, backupPath);
21
+ }
22
+ fs.writeFileSync(filePath, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
23
+ }
24
+ return { filePath, existed, backupPath };
25
+ }
26
+
27
+ function writeTextWithBackup(filePath, text, { dryRun = false } = {}) {
28
+ const existed = fs.existsSync(filePath);
29
+ const backupPath = existed ? `${filePath}.bak` : null;
30
+ if (!dryRun) {
31
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
32
+ if (existed) {
33
+ fs.copyFileSync(filePath, backupPath);
34
+ }
35
+ fs.writeFileSync(filePath, text, 'utf8');
36
+ }
37
+ return { filePath, existed, backupPath };
38
+ }
39
+
40
+ function tomlString(value) {
41
+ return JSON.stringify(String(value));
42
+ }
43
+
44
+ function upsertTomlSection(existingText, header, bodyLines) {
45
+ const block = `[${header}]\n${bodyLines.join('\n')}\n`;
46
+ if (!existingText || !existingText.trim()) {
47
+ return block;
48
+ }
49
+ const lines = existingText.split(/\r?\n/);
50
+ const targetHeader = `[${header}]`;
51
+ const startIdx = lines.findIndex((l) => l.trim() === targetHeader);
52
+ if (startIdx === -1) {
53
+ const trimmed = existingText.replace(/\s*$/, '');
54
+ return `${trimmed}\n\n${block}`;
55
+ }
56
+ let endIdx = lines.length;
57
+ for (let i = startIdx + 1; i < lines.length; i++) {
58
+ if (/^\s*\[/.test(lines[i])) {
59
+ endIdx = i;
60
+ break;
61
+ }
62
+ }
63
+ const before = lines.slice(0, startIdx);
64
+ const after = lines.slice(endIdx);
65
+ const nextLines = [...before, targetHeader, ...bodyLines];
66
+ if (after.length > 0 && after[0].trim() !== '') {
67
+ nextLines.push('');
68
+ }
69
+ nextLines.push(...after);
70
+ return `${nextLines.join('\n').replace(/\s*$/, '')}\n`;
71
+ }
72
+
73
+ function upsertHookEntry(hooksMap, event, entry, scriptToken) {
74
+ if (!Array.isArray(hooksMap[event])) {
75
+ hooksMap[event] = [];
76
+ }
77
+ const serializedCmd = entry.hooks?.[0]?.command || '';
78
+ const idx = hooksMap[event].findIndex((existing) => {
79
+ const existingMatcher = existing.matcher || '';
80
+ const newMatcher = entry.matcher || '';
81
+ const existingCmd = existing.hooks?.[0]?.command || '';
82
+ return (
83
+ existingMatcher === newMatcher &&
84
+ (existingCmd === serializedCmd || (scriptToken && existingCmd.includes(scriptToken)))
85
+ );
86
+ });
87
+ if (idx >= 0) {
88
+ hooksMap[event][idx] = entry;
89
+ } else {
90
+ hooksMap[event].push(entry);
91
+ }
92
+ }
93
+
94
+ function upsertClaudeHookEntry(hooksMap, event, entry) {
95
+ return upsertHookEntry(hooksMap, event, entry, 'cc-hook.mjs');
96
+ }
97
+
98
+ export function installAdapter({
99
+ runtime,
100
+ targetDir = process.cwd(),
101
+ scope = 'project',
102
+ nodeBin = process.execPath,
103
+ dryRun = false,
104
+ } = {}) {
105
+ if (runtime === 'all') {
106
+ return {
107
+ agy: installAdapter({ runtime: 'agy', targetDir, scope, nodeBin, dryRun }),
108
+ cc: installAdapter({ runtime: 'cc', targetDir, scope, nodeBin, dryRun }),
109
+ codex: installAdapter({ runtime: 'codex', targetDir, scope, nodeBin, dryRun }),
110
+ gemini: installAdapter({ runtime: 'gemini', targetDir, scope, nodeBin, dryRun }),
111
+ };
112
+ }
113
+
114
+ const absMcpBin = path.join(REPO_ROOT, 'bin', 'pbridge-mcp.mjs');
115
+ const absAgyHookBin = path.join(REPO_ROOT, 'adapters', 'antigravity', 'bin', 'agy-hook.mjs');
116
+ const absCcHookBin = path.join(REPO_ROOT, 'adapters', 'claude', 'bin', 'cc-hook.mjs');
117
+ const absCodexHookBin = path.join(REPO_ROOT, 'adapters', 'codex', 'bin', 'codex-hook.mjs');
118
+ const absGeminiHookBin = path.join(REPO_ROOT, 'adapters', 'gemini', 'bin', 'gemini-hook.mjs');
119
+
120
+ if (runtime === 'agy') {
121
+ const pluginDir =
122
+ scope === 'global'
123
+ ? path.join(os.homedir(), '.gemini', 'config', 'plugins', 'peer-bridge')
124
+ : path.join(targetDir, '.agents', 'plugins', 'peer-bridge');
125
+
126
+ const pluginJson = {
127
+ name: 'peer-bridge',
128
+ description:
129
+ 'Bidirectional peer messaging and lifecycle control across Antigravity and Claude Code sessions',
130
+ };
131
+
132
+ const hooksJson = {
133
+ SessionStart: [
134
+ { type: 'command', command: `"${nodeBin}" "${absAgyHookBin}" SessionStart`, timeout: 5 },
135
+ ],
136
+ PostInvocation: [
137
+ { type: 'command', command: `"${nodeBin}" "${absAgyHookBin}" PostInvocation`, timeout: 5 },
138
+ ],
139
+ Stop: [
140
+ { type: 'command', command: `"${nodeBin}" "${absAgyHookBin}" Stop`, timeout: 5 },
141
+ ],
142
+ };
143
+
144
+ const mcpConfigJson = {
145
+ mcpServers: {
146
+ 'peer-bridge': {
147
+ command: nodeBin,
148
+ args: [absMcpBin, '--runtime', 'agy'],
149
+ },
150
+ },
151
+ };
152
+
153
+ const rulesSrc = path.join(REPO_ROOT, 'adapters', 'antigravity', 'rules', 'AGENTS.md');
154
+ const skillSrc = path.join(
155
+ REPO_ROOT,
156
+ 'adapters',
157
+ 'antigravity',
158
+ 'skills',
159
+ 'peer-bridge',
160
+ 'SKILL.md',
161
+ );
162
+
163
+ const files = [
164
+ path.join(pluginDir, 'plugin.json'),
165
+ path.join(pluginDir, 'hooks.json'),
166
+ path.join(pluginDir, 'mcp_config.json'),
167
+ path.join(pluginDir, 'rules', 'AGENTS.md'),
168
+ path.join(pluginDir, 'skills', 'peer-bridge', 'SKILL.md'),
169
+ ];
170
+
171
+ if (!dryRun) {
172
+ fs.mkdirSync(path.join(pluginDir, 'rules'), { recursive: true });
173
+ fs.mkdirSync(path.join(pluginDir, 'skills', 'peer-bridge'), { recursive: true });
174
+ fs.writeFileSync(files[0], `${JSON.stringify(pluginJson, null, 2)}\n`, 'utf8');
175
+ fs.writeFileSync(files[1], `${JSON.stringify(hooksJson, null, 2)}\n`, 'utf8');
176
+ fs.writeFileSync(files[2], `${JSON.stringify(mcpConfigJson, null, 2)}\n`, 'utf8');
177
+ fs.copyFileSync(rulesSrc, files[3]);
178
+ fs.copyFileSync(skillSrc, files[4]);
179
+ }
180
+
181
+ return {
182
+ runtime: 'agy',
183
+ scope,
184
+ dry_run: dryRun,
185
+ plugin_dir: pluginDir,
186
+ files,
187
+ };
188
+ }
189
+
190
+ if (runtime === 'cc') {
191
+ const baseDir = scope === 'global' ? os.homedir() : targetDir;
192
+ const mcpPath =
193
+ scope === 'global'
194
+ ? path.join(os.homedir(), '.claude', 'mcp.json')
195
+ : path.join(baseDir, '.mcp.json');
196
+ const settingsPath =
197
+ scope === 'global'
198
+ ? path.join(os.homedir(), '.claude', 'settings.json')
199
+ : path.join(baseDir, '.claude', 'settings.local.json');
200
+
201
+ const existingMcp = readJsonSafe(mcpPath) || {};
202
+ const nextMcp = {
203
+ ...existingMcp,
204
+ mcpServers: {
205
+ ...(existingMcp.mcpServers || {}),
206
+ 'peer-bridge': {
207
+ command: nodeBin,
208
+ args: [absMcpBin, '--runtime', 'cc', '--channel'],
209
+ },
210
+ },
211
+ };
212
+
213
+ const existingSettings = readJsonSafe(settingsPath) || {};
214
+ const nextHooks = { ...(existingSettings.hooks || {}) };
215
+ upsertClaudeHookEntry(nextHooks, 'SessionStart', {
216
+ hooks: [{ type: 'command', command: `"${nodeBin}" "${absCcHookBin}" SessionStart` }],
217
+ });
218
+ upsertClaudeHookEntry(nextHooks, 'PreToolUse', {
219
+ matcher: 'SendMessage',
220
+ hooks: [{ type: 'command', command: `"${nodeBin}" "${absCcHookBin}" PreToolUse` }],
221
+ });
222
+ upsertClaudeHookEntry(nextHooks, 'PostToolUse', {
223
+ matcher: 'ListAgents',
224
+ hooks: [{ type: 'command', command: `"${nodeBin}" "${absCcHookBin}" PostToolUse` }],
225
+ });
226
+ upsertClaudeHookEntry(nextHooks, 'Stop', {
227
+ hooks: [{ type: 'command', command: `"${nodeBin}" "${absCcHookBin}" Stop` }],
228
+ });
229
+
230
+ const nextSettings = {
231
+ ...existingSettings,
232
+ hooks: nextHooks,
233
+ };
234
+
235
+ const mcpWrite = writeJsonWithBackup(mcpPath, nextMcp, { dryRun });
236
+ const settingsWrite = writeJsonWithBackup(settingsPath, nextSettings, { dryRun });
237
+
238
+ return {
239
+ runtime: 'cc',
240
+ scope,
241
+ dry_run: dryRun,
242
+ files: [mcpPath, settingsPath],
243
+ backups: [mcpWrite.backupPath, settingsWrite.backupPath].filter(Boolean),
244
+ };
245
+ }
246
+
247
+ if (runtime === 'codex') {
248
+ const codexDir =
249
+ scope === 'global'
250
+ ? path.join(os.homedir(), '.codex')
251
+ : path.join(path.resolve(targetDir), '.codex');
252
+ const hooksPath = path.join(codexDir, 'hooks.json');
253
+ const configPath = path.join(codexDir, 'config.toml');
254
+
255
+ const existingHooksDoc = readJsonSafe(hooksPath) || {};
256
+ const nextHooks = { ...(existingHooksDoc.hooks || {}) };
257
+ for (const ev of ['SessionStart', 'UserPromptSubmit', 'PostToolUse', 'Stop']) {
258
+ upsertHookEntry(
259
+ nextHooks,
260
+ ev,
261
+ { hooks: [{ type: 'command', command: `"${nodeBin}" "${absCodexHookBin}" ${ev}` }] },
262
+ 'codex-hook.mjs',
263
+ );
264
+ }
265
+ const nextHooksDoc = { ...existingHooksDoc, hooks: nextHooks };
266
+ const hooksWrite = writeJsonWithBackup(hooksPath, nextHooksDoc, { dryRun });
267
+
268
+ const existingToml = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : '';
269
+ const nextToml = upsertTomlSection(existingToml, 'mcp_servers.peer-bridge', [
270
+ `command = ${tomlString(nodeBin)}`,
271
+ `args = [${tomlString(absMcpBin)}, "--runtime", "codex"]`,
272
+ 'enabled = true',
273
+ ]);
274
+ const configWrite = writeTextWithBackup(configPath, nextToml, { dryRun });
275
+
276
+ return {
277
+ runtime: 'codex',
278
+ scope,
279
+ dry_run: dryRun,
280
+ files: [hooksPath, configPath],
281
+ backups: [hooksWrite.backupPath, configWrite.backupPath].filter(Boolean),
282
+ };
283
+ }
284
+
285
+ if (runtime === 'gemini') {
286
+ const geminiDir =
287
+ scope === 'global'
288
+ ? path.join(os.homedir(), '.gemini')
289
+ : path.join(path.resolve(targetDir), '.gemini');
290
+ const settingsPath = path.join(geminiDir, 'settings.json');
291
+
292
+ const existingSettings = readJsonSafe(settingsPath) || {};
293
+ const nextHooks = { ...(existingSettings.hooks || {}) };
294
+ for (const ev of ['SessionStart', 'BeforeAgent', 'AfterTool', 'AfterAgent']) {
295
+ upsertHookEntry(
296
+ nextHooks,
297
+ ev,
298
+ { hooks: [{ type: 'command', command: `"${nodeBin}" "${absGeminiHookBin}" ${ev}` }] },
299
+ 'gemini-hook.mjs',
300
+ );
301
+ }
302
+ const nextSettings = {
303
+ ...existingSettings,
304
+ mcpServers: {
305
+ ...(existingSettings.mcpServers || {}),
306
+ 'peer-bridge': {
307
+ command: nodeBin,
308
+ args: [absMcpBin, '--runtime', 'gemini'],
309
+ trust: true,
310
+ },
311
+ },
312
+ hooks: nextHooks,
313
+ };
314
+ const settingsWrite = writeJsonWithBackup(settingsPath, nextSettings, { dryRun });
315
+
316
+ return {
317
+ runtime: 'gemini',
318
+ scope,
319
+ dry_run: dryRun,
320
+ files: [settingsPath],
321
+ backups: [settingsWrite.backupPath].filter(Boolean),
322
+ };
323
+ }
324
+
325
+ throw new Error(
326
+ `Unsupported runtime "${runtime}". Expected "agy", "cc", "codex", "gemini", or "all".`,
327
+ );
328
+ }