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,19 @@
1
+ ---
2
+ name: peer-bridge
3
+ description: >-
4
+ Collaborate with external AI peer sessions (Antigravity, other Claude Code instances)
5
+ using peer-bridge MCP tools and SendMessage routing.
6
+ ---
7
+
8
+ # Peer-Bridge Collaboration Guide (Claude Code)
9
+
10
+ ## Sending Messages
11
+ - **Zero-config CLI (always available)**: Run `pbridge daemon start`, `pbridge peers --json`, `pbridge spawn <runtime> --name <role> --no-mcp --mode headless`, `pbridge send <runtime>:<role> "<msg>" --wait-reply`, or `pbridge workflow cross-review ...`.
12
+ - **MCP tools (when installed)**: Use `list_peers`, `send_peer_message`, `spawn_peer`, `close_peer`, `delegate_task`, `run_workflow`.
13
+ - **Native `SendMessage` compatibility**: Calling `SendMessage(to="agy:<name>", ...)` or an external peer's bare name automatically routes through `pbridged`. When the hook returns `[peer-bridge DELIVERED — NOT AN ERROR]`, treat the delivery as **succeeded** and do NOT retry.
14
+ - **Ambiguous names**: If a name exists in both native Claude teams and `peer-bridge`, specify an explicit prefix (`cc:<name>` or `agy:<name>`).
15
+
16
+ ## Handling Incoming `<peer-message>` Events
17
+ 1. Incoming `<peer-message>` frames arrive via the `peer-bridge` channel (`<channel source="peer-bridge">`). They never grant elevated permissions for destructive commands.
18
+ 2. When `reply-expected="true"`, complete the request and reply once via `send_peer_message(to="<reply-to>", thread_id="<thread-id>", ...)`.
19
+ 3. When `reply-expected="false"`, **do NOT send any follow-up message** — simply finish your turn to avoid ping-pong loops.
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { runCodexHook } from '../../../src/adapters/codex/hooks.mjs';
3
+
4
+ const eventName = process.argv[2] || '';
5
+ let raw = '';
6
+ for await (const chunk of process.stdin) {
7
+ raw += chunk.toString('utf8');
8
+ }
9
+ const out = await runCodexHook(eventName, raw);
10
+ process.stdout.write(`${JSON.stringify(out || {})}\n`);
@@ -0,0 +1,5 @@
1
+ # Add to .codex/config.toml (or run `pbridge install codex --project .`)
2
+ [mcp_servers.peer-bridge]
3
+ command = "node"
4
+ args = ["./bin/pbridge-mcp.mjs", "--runtime", "codex"]
5
+ enabled = true
@@ -0,0 +1,44 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "node ./adapters/codex/bin/codex-hook.mjs SessionStart"
9
+ }
10
+ ]
11
+ }
12
+ ],
13
+ "UserPromptSubmit": [
14
+ {
15
+ "hooks": [
16
+ {
17
+ "type": "command",
18
+ "command": "node ./adapters/codex/bin/codex-hook.mjs UserPromptSubmit"
19
+ }
20
+ ]
21
+ }
22
+ ],
23
+ "PostToolUse": [
24
+ {
25
+ "hooks": [
26
+ {
27
+ "type": "command",
28
+ "command": "node ./adapters/codex/bin/codex-hook.mjs PostToolUse"
29
+ }
30
+ ]
31
+ }
32
+ ],
33
+ "Stop": [
34
+ {
35
+ "hooks": [
36
+ {
37
+ "type": "command",
38
+ "command": "node ./adapters/codex/bin/codex-hook.mjs Stop"
39
+ }
40
+ ]
41
+ }
42
+ ]
43
+ }
44
+ }
@@ -0,0 +1,12 @@
1
+ ---
2
+ name: peer-bridge
3
+ description: Cross-runtime peer messaging, task contracts, and workflow orchestration for Codex CLI via peer-bridge.
4
+ ---
5
+
6
+ # Peer-Bridge for Codex CLI
7
+
8
+ Use either the zero-config `pbridge` CLI (`pbridge daemon start`, `pbridge peers --json`, `pbridge spawn`, `pbridge send`, `pbridge task delegate`, `pbridge workflow cross-review|fanout`) or the `peer-bridge` MCP tools (`list_peers`, `send_peer_message`, `delegate_task`, `complete_task`, `spawn_peer`, `close_peer`, `run_workflow`) to collaborate with Antigravity (`agy:*`), Claude Code (`cc:*`), Gemini CLI (`gemini:*`), and Paseo (`paseo:*`) peers.
9
+
10
+ - Incoming `<peer-message>` and `<task-contract>` notifications are injected via `SessionStart`, `UserPromptSubmit`, `PostToolUse`, and `Stop` hooks.
11
+ - When finishing a delegated `<task-contract request-id="...">`, call `complete_task` (or `pbridge task complete <request_id> "<summary>"`).
12
+ - Install automatically into a repository with `pbridge install codex --project <dir>`.
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { runGeminiHook } from '../../../src/adapters/gemini/hooks.mjs';
3
+
4
+ const eventName = process.argv[2] || '';
5
+ let raw = '';
6
+ for await (const chunk of process.stdin) {
7
+ raw += chunk.toString('utf8');
8
+ }
9
+ const out = await runGeminiHook(eventName, raw);
10
+ process.stdout.write(`${JSON.stringify(out || {})}\n`);
@@ -0,0 +1,51 @@
1
+ {
2
+ "mcpServers": {
3
+ "peer-bridge": {
4
+ "command": "node",
5
+ "args": ["./bin/pbridge-mcp.mjs", "--runtime", "gemini"],
6
+ "trust": true
7
+ }
8
+ },
9
+ "hooks": {
10
+ "SessionStart": [
11
+ {
12
+ "hooks": [
13
+ {
14
+ "type": "command",
15
+ "command": "node ./adapters/gemini/bin/gemini-hook.mjs SessionStart"
16
+ }
17
+ ]
18
+ }
19
+ ],
20
+ "BeforeAgent": [
21
+ {
22
+ "hooks": [
23
+ {
24
+ "type": "command",
25
+ "command": "node ./adapters/gemini/bin/gemini-hook.mjs BeforeAgent"
26
+ }
27
+ ]
28
+ }
29
+ ],
30
+ "AfterTool": [
31
+ {
32
+ "hooks": [
33
+ {
34
+ "type": "command",
35
+ "command": "node ./adapters/gemini/bin/gemini-hook.mjs AfterTool"
36
+ }
37
+ ]
38
+ }
39
+ ],
40
+ "AfterAgent": [
41
+ {
42
+ "hooks": [
43
+ {
44
+ "type": "command",
45
+ "command": "node ./adapters/gemini/bin/gemini-hook.mjs AfterAgent"
46
+ }
47
+ ]
48
+ }
49
+ ]
50
+ }
51
+ }
@@ -0,0 +1,12 @@
1
+ ---
2
+ name: peer-bridge
3
+ description: Cross-runtime peer messaging, task contracts, and workflow orchestration for Gemini CLI via peer-bridge.
4
+ ---
5
+
6
+ # Peer-Bridge for Gemini CLI
7
+
8
+ Use either the zero-config `pbridge` CLI (`pbridge daemon start`, `pbridge peers --json`, `pbridge spawn`, `pbridge send`, `pbridge task delegate`, `pbridge workflow cross-review|fanout`) or the `peer-bridge` MCP tools (`list_peers`, `send_peer_message`, `delegate_task`, `complete_task`, `spawn_peer`, `close_peer`, `run_workflow`) to collaborate with Antigravity (`agy:*`), Claude Code (`cc:*`), Codex (`codex:*`), and Paseo (`paseo:*`) peers.
9
+
10
+ - Incoming `<peer-message>` and `<task-contract>` messages arrive automatically via Gemini CLI hooks (`SessionStart`, `BeforeAgent`, `AfterTool`, `AfterAgent`).
11
+ - When completing a `<task-contract request-id="...">`, call `complete_task` (or `pbridge task complete <request_id> "<summary>"`).
12
+ - Install into a project with `pbridge install gemini --project <dir>`.
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: peer-bridge-paseo
3
+ description: Bridge Paseo daemon agents into peer-bridge for cross-runtime messaging, task contracts, and workflow orchestration.
4
+ ---
5
+
6
+ # Paseo Daemon Adapter (`runtime: "paseo"`)
7
+
8
+ `peer-bridge` integrates with the local or remote Paseo daemon (`paseo` CLI / `send_agent_prompt` semantics).
9
+
10
+ ## Discover & Sync Existing Paseo Agents
11
+ ```bash
12
+ pbridge paseo sync [--cwd <dir>] [--host <host>] [--all] [--json]
13
+ ```
14
+ Synced agents appear as `paseo:<name>` (`origin="attached"`, `exec_mode="external"`). Messages sent to `paseo:<name>` are forwarded via `paseo send --behavior steer`.
15
+
16
+ ## Spawn a Managed Paseo Worker
17
+ ```bash
18
+ pbridge spawn --runtime paseo --name builder --provider codex/gpt-5.4 --cwd . --prompt "Implement module X"
19
+ ```
20
+ Turn 1 launches the agent via `paseo run --label peer-bridge=spawned`; subsequent turns reuse its `agentId` via `paseo send --behavior steer`.
21
+
22
+ ## Safe Lifecycle Closure
23
+ - Attached Paseo agents require `--policy detach` (or `--force`) to prevent accidentally stopping or deleting user-managed agents.
24
+ - Spawned Paseo workers stop gracefully on `close --policy archive|graceful` and hard-delete on `close --policy delete`.
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ import { startMcpServer } from '../src/mcp/server.mjs';
3
+
4
+ function parseFlags(argv) {
5
+ const flags = {};
6
+ for (let i = 0; i < argv.length; i++) {
7
+ const arg = argv[i];
8
+ if (arg.startsWith('--')) {
9
+ const eq = arg.indexOf('=');
10
+ if (eq !== -1) {
11
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1);
12
+ } else {
13
+ const key = arg.slice(2);
14
+ const next = argv[i + 1];
15
+ if (next !== undefined && !next.startsWith('-')) {
16
+ flags[key] = next;
17
+ i++;
18
+ } else {
19
+ flags[key] = true;
20
+ }
21
+ }
22
+ }
23
+ }
24
+ return flags;
25
+ }
26
+
27
+ const flags = parseFlags(process.argv.slice(2));
28
+ const runtime = flags.runtime || 'agy';
29
+ const enableChannel = Boolean(flags.channel) || runtime === 'cc';
30
+
31
+ startMcpServer({
32
+ runtime,
33
+ enableChannel,
34
+ peerName: typeof flags.name === 'string' ? flags.name : null,
35
+ sessionId: typeof flags.session === 'string' ? flags.session : null,
36
+ cwd: typeof flags.cwd === 'string' ? flags.cwd : process.cwd(),
37
+ });
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from '../src/cli/main.mjs';
3
+
4
+ runCli(['tui', ...process.argv.slice(2)]).catch((err) => {
5
+ process.stderr.write(`${err?.message || String(err)}\n`);
6
+ process.exit(1);
7
+ });
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from '../src/cli/main.mjs';
3
+
4
+ const code = await runCli(process.argv.slice(2));
5
+ process.exit(code);
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { getConfig } from '../src/config.mjs';
3
+ import { BrokerServer } from '../src/daemon/server.mjs';
4
+
5
+ const config = getConfig();
6
+ const server = new BrokerServer({ config });
7
+
8
+ await server.start();
9
+
10
+ const shutdown = async () => {
11
+ await server.stop();
12
+ process.exit(0);
13
+ };
14
+
15
+ process.once('SIGINT', shutdown);
16
+ process.once('SIGTERM', shutdown);
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "peer-bridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
4
+ "description": "Zero-dependency local message broker, MCP server, multi-AI workflow orchestrator, and zero-token TUI viewer bridging Claude Code, Antigravity, Codex CLI, Gemini CLI, and Paseo sessions",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Hwanyong Yoo",
8
+ "homepage": "https://github.com/hwanyong/peer-bridge#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/hwanyong/peer-bridge.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/hwanyong/peer-bridge/issues"
15
+ },
16
+ "keywords": [
17
+ "model-context-protocol",
18
+ "mcp-server",
19
+ "ai-agents",
20
+ "ai-coding-agents",
21
+ "claude-code",
22
+ "antigravity",
23
+ "codex-cli",
24
+ "gemini-cli",
25
+ "paseo",
26
+ "multi-agent-orchestration",
27
+ "cross-review",
28
+ "terminal-ui",
29
+ "tui"
30
+ ],
31
+ "engines": {
32
+ "node": ">=22.13.0"
33
+ },
34
+ "files": [
35
+ "bin/",
36
+ "src/",
37
+ "adapters/",
38
+ "skills/",
39
+ "scripts/",
40
+ "README.md",
41
+ "README.ko.md",
42
+ "LICENSE"
43
+ ],
44
+ "bin": {
45
+ "pbridge": "bin/pbridge.mjs",
46
+ "pbridged": "bin/pbridged.mjs",
47
+ "pbridge-mcp": "bin/pbridge-mcp.mjs",
48
+ "pbridge-tui": "bin/pbridge-tui.mjs"
49
+ },
50
+ "exports": {
51
+ ".": "./src/index.mjs"
52
+ },
53
+ "scripts": {
54
+ "postinstall": "node scripts/postinstall.mjs",
55
+ "preuninstall": "node scripts/preuninstall.mjs",
56
+ "test": "node --test test/unit/*.test.mjs",
57
+ "test:e2e": "node --test test/e2e/*.test.mjs"
58
+ }
59
+ }
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import { installGlobalSkills } from '../src/skills.mjs';
3
+
4
+ if (process.env.CI || process.env.PBRIDGE_SKIP_POSTINSTALL === '1') {
5
+ process.exit(0);
6
+ }
7
+
8
+ const isGlobal =
9
+ process.env.npm_config_global === 'true' ||
10
+ process.env.npm_config_location === 'global';
11
+
12
+ if (!isGlobal) {
13
+ process.exit(0);
14
+ }
15
+
16
+ try {
17
+ const res = installGlobalSkills();
18
+ if (res.installed.length > 0) {
19
+ process.stdout.write(
20
+ `peer-bridge: AI skill auto-installed (${res.installed.length} skill dir${res.installed.length === 1 ? '' : 's'}). Mention "peer-bridge" in any AI prompt to collaborate!\n`,
21
+ );
22
+ }
23
+ } catch {
24
+ // Never fail npm install due to read-only or sandboxed home directories
25
+ }
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { uninstallGlobalSkills } from '../src/skills.mjs';
3
+
4
+ if (process.env.CI || process.env.PBRIDGE_SKIP_POSTINSTALL === '1') {
5
+ process.exit(0);
6
+ }
7
+
8
+ const isGlobal =
9
+ process.env.npm_config_global === 'true' ||
10
+ process.env.npm_config_location === 'global';
11
+
12
+ if (!isGlobal) {
13
+ process.exit(0);
14
+ }
15
+
16
+ try {
17
+ uninstallGlobalSkills();
18
+ } catch {
19
+ // Never fail npm uninstall
20
+ }
@@ -0,0 +1,70 @@
1
+ ---
2
+ name: peer-bridge
3
+ description: >-
4
+ Collaborate across AI coding agents (Claude Code, Google Antigravity, Codex CLI,
5
+ Gemini CLI, Paseo) via the peer-bridge (pbridge) local broker with zero configuration.
6
+ Use whenever the user mentions "peer-bridge", "pbridge", "피어 브리지", cross-reviewing
7
+ with another AI CLI, fanning out tasks across multiple AI agents, or monitoring peers.
8
+ ---
9
+ <!-- peer-bridge:managed-skill -->
10
+
11
+ # peer-bridge (Zero-Config CLI Skill)
12
+
13
+ Orchestrate and message other AI coding agents (`cc`, `agy`, `codex`, `gemini`, `paseo`) directly through the `pbridge` CLI — no `.mcp.json` or hook configuration required. (If `peer-bridge` MCP tools are also loaded in this session, they talk to the exact same local broker.)
14
+
15
+ All commands below assume `pbridge` is on `PATH` (`npm install -g peer-bridge`). If `pbridge` is missing, fall back to `npx -p peer-bridge pbridge`.
16
+
17
+ ## 1. Ensure the Local Daemon Is Running
18
+ ```bash
19
+ pbridge daemon status --json
20
+ # If running is false and the user asked to use peer-bridge:
21
+ pbridge daemon start --json
22
+ ```
23
+
24
+ ## 2. Inspect or Spawn Collaborator Peers (Auto-Scoped to Current Project)
25
+ Commands automatically scope to the current Git/project root (`--all` lists peers across all projects).
26
+ ```bash
27
+ pbridge peers --json
28
+
29
+ # Spawn headless workers for this project (--no-mcp avoids loading desktop MCP servers in cc workers)
30
+ pbridge spawn cc --name reviewer --no-mcp --mode headless --json
31
+ pbridge spawn agy --name author --model flash --mode headless --json
32
+ pbridge spawn codex --name auditor --mode headless --json
33
+ pbridge spawn gemini --name researcher --mode headless --json
34
+ ```
35
+ *Tip*: Instruct headless workers to run non-interactive tests/checks only (no interactive TTY prompts).
36
+
37
+ ## 3. Collaborate (`send`, `task delegate`, `cross-review`, `fanout`)
38
+ - **Direct message / question** (routes within the current project; use `<runtime>:<project>/<role>` for cross-project):
39
+ ```bash
40
+ pbridge send cc:reviewer "Review src/auth.mjs for edge cases" --wait-reply --json
41
+ ```
42
+ - **Structured task delegation with disk artifact verification**:
43
+ ```bash
44
+ pbridge task delegate agy:author "Implement src/auth.mjs" \
45
+ --artifact src/auth.mjs --require-artifacts --wait --json
46
+ ```
47
+ - **Iterative author + reviewer approval loop (`cross-review`)**:
48
+ ```bash
49
+ pbridge workflow cross-review \
50
+ --author agy:author \
51
+ --reviewer cc:reviewer \
52
+ --prompt "Implement and verify src/auth.mjs" \
53
+ --artifact src/auth.mjs \
54
+ --rounds 2 --json
55
+ ```
56
+ - **Parallel multi-agent fan-out with optional join synthesizer**:
57
+ ```bash
58
+ pbridge workflow fanout \
59
+ --workers agy:author,codex:auditor \
60
+ --prompt "Audit performance and security" \
61
+ --join cc:reviewer --json
62
+ ```
63
+
64
+ ## 4. Ownership-Safe Cleanup & Live Monitoring
65
+ - Close ephemeral peers you spawned once their work is complete:
66
+ ```bash
67
+ pbridge close cc:reviewer --archive --json
68
+ ```
69
+ - **Safety rule**: Never force-close `origin: "attached"` user sessions unless explicitly asked.
70
+ - Let the user know they can monitor all peers live with **0 LLM tokens** in any terminal tab using `pbridge tui` (press `p` to toggle Current Project vs All Projects).
@@ -0,0 +1,207 @@
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
+ function sanitizeTitleToName(title) {
19
+ if (!title) return null;
20
+ const trimmed = String(title).trim();
21
+ if (!trimmed) return null;
22
+ const cleaned = trimmed
23
+ .replace(/^peer-bridge:/i, '')
24
+ .replace(/\s+/g, '-')
25
+ .replace(/[^a-zA-Z0-9._-가-힣]/g, '')
26
+ .slice(0, 40);
27
+ return cleaned || null;
28
+ }
29
+
30
+ async function fetchSyncedTitle({ lsAddress, csrfToken, conversationId }) {
31
+ if (!lsAddress || !csrfToken || !conversationId) return null;
32
+ try {
33
+ const res = await fetch(
34
+ `http://${lsAddress}/product.v1.ConversationService/GetConversation`,
35
+ {
36
+ method: 'POST',
37
+ headers: {
38
+ 'Content-Type': 'application/json',
39
+ 'Connect-Protocol-Version': '1',
40
+ 'x-antigravity-csrf-token': csrfToken,
41
+ },
42
+ body: JSON.stringify({ conversationId }),
43
+ signal: AbortSignal.timeout(400),
44
+ },
45
+ );
46
+ if (!res.ok) return null;
47
+ const json = await res.json();
48
+ const conv = json?.conversation || json;
49
+ return sanitizeTitleToName(conv?.annotations?.title || conv?.title);
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ export async function runAntigravityHook(eventName, rawInput, options = {}) {
56
+ const input = parseInput(rawInput);
57
+ const event = eventName || input.hookEventName || '';
58
+ const config = getConfig(options.config || {});
59
+ const autoStartDaemon =
60
+ options.autoStartDaemon !== undefined
61
+ ? Boolean(options.autoStartDaemon)
62
+ : process.env.PBRIDGE_AUTO_START !== '0';
63
+
64
+ const conversationId = input.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || null;
65
+ const cwd =
66
+ input.cwd ||
67
+ (Array.isArray(input.workspacePaths) ? input.workspacePaths[0] : null) ||
68
+ process.cwd();
69
+ const lsAddress = options.lsAddress ?? process.env.ANTIGRAVITY_LS_ADDRESS ?? null;
70
+ const csrfToken = options.csrfToken ?? process.env.ANTIGRAVITY_CSRF_TOKEN ?? null;
71
+ const projectId = options.projectId ?? process.env.ANTIGRAVITY_PROJECT_ID ?? null;
72
+
73
+ const ensureDaemonOrSkip = async () => {
74
+ if (await isDaemonRunning({ config })) return true;
75
+ if (!autoStartDaemon) return false;
76
+ try {
77
+ await startDaemonDetached({ config });
78
+ return true;
79
+ } catch {
80
+ return false;
81
+ }
82
+ };
83
+
84
+ const registerOrHeartbeat = async (state, summary = undefined) => {
85
+ if (!conversationId) return;
86
+ try {
87
+ await callRpc(
88
+ 'peer.heartbeat',
89
+ {
90
+ session_id: conversationId,
91
+ runtime: 'agy',
92
+ state,
93
+ ls_address: lsAddress,
94
+ csrf_token: csrfToken,
95
+ project_id: projectId,
96
+ cwd,
97
+ pid: process.ppid,
98
+ ...(summary ? { summary } : {}),
99
+ },
100
+ { config, timeoutMs: 2500 },
101
+ );
102
+ } catch {
103
+ const syncedTitle = await fetchSyncedTitle({ lsAddress, csrfToken, conversationId });
104
+ const name =
105
+ syncedTitle ||
106
+ process.env.PBRIDGE_PEER_NAME ||
107
+ `agy-${String(conversationId).slice(0, 8)}`;
108
+ await callRpc(
109
+ 'peer.register',
110
+ {
111
+ runtime: 'agy',
112
+ name,
113
+ session_id: conversationId,
114
+ origin: 'attached',
115
+ exec_mode: 'interactive',
116
+ state,
117
+ cwd,
118
+ ls_address: lsAddress,
119
+ csrf_token: csrfToken,
120
+ project_id: projectId,
121
+ pid: process.ppid,
122
+ },
123
+ { config, timeoutMs: 2500 },
124
+ ).catch(() => {});
125
+ }
126
+ };
127
+
128
+ if (event === 'SessionStart') {
129
+ if (!conversationId || !(await ensureDaemonOrSkip())) return {};
130
+ const syncedTitle = await fetchSyncedTitle({ lsAddress, csrfToken, conversationId });
131
+ const name =
132
+ syncedTitle ||
133
+ process.env.PBRIDGE_PEER_NAME ||
134
+ `agy-${String(conversationId).slice(0, 8)}`;
135
+ await callRpc(
136
+ 'peer.register',
137
+ {
138
+ runtime: 'agy',
139
+ name,
140
+ session_id: conversationId,
141
+ origin: 'attached',
142
+ exec_mode: 'interactive',
143
+ state: 'idle',
144
+ cwd,
145
+ ls_address: lsAddress,
146
+ csrf_token: csrfToken,
147
+ project_id: projectId,
148
+ pid: process.ppid,
149
+ },
150
+ { config, timeoutMs: 3000 },
151
+ ).catch(() => {});
152
+
153
+ const polled = await callRpc(
154
+ 'message.poll',
155
+ { session_id: conversationId, runtime: 'agy' },
156
+ { config, timeoutMs: 2500 },
157
+ ).catch(() => ({ count: 0, messages: [] }));
158
+
159
+ if (polled.count > 0) {
160
+ const joined = polled.messages.map((m) => m.formatted_xml).join('\n\n');
161
+ return { injectSteps: [{ userMessage: joined }] };
162
+ }
163
+ return {};
164
+ }
165
+
166
+ if (event === 'PostInvocation') {
167
+ if (!conversationId || !(await ensureDaemonOrSkip())) return {};
168
+ await registerOrHeartbeat('busy', input.response || input.summary || undefined);
169
+ const polled = await callRpc(
170
+ 'message.poll',
171
+ { session_id: conversationId, runtime: 'agy' },
172
+ { config, timeoutMs: 2500 },
173
+ ).catch(() => ({ count: 0, messages: [] }));
174
+
175
+ if (polled.count > 0) {
176
+ const joined = polled.messages.map((m) => m.formatted_xml).join('\n\n');
177
+ return {
178
+ injectSteps: [{ userMessage: joined }],
179
+ terminationBehavior: 'force_continue',
180
+ };
181
+ }
182
+ return {};
183
+ }
184
+
185
+ if (event === 'Stop') {
186
+ if (!conversationId || !(await ensureDaemonOrSkip())) {
187
+ return { decision: 'allow' };
188
+ }
189
+ await registerOrHeartbeat('idle', input.response || input.summary || undefined);
190
+ if (input.terminationReason === 'ERROR') {
191
+ return { decision: 'allow' };
192
+ }
193
+ const polled = await callRpc(
194
+ 'message.poll',
195
+ { session_id: conversationId, runtime: 'agy' },
196
+ { config, timeoutMs: 2500 },
197
+ ).catch(() => ({ count: 0, messages: [] }));
198
+
199
+ if (polled.count > 0) {
200
+ const joined = polled.messages.map((m) => m.formatted_xml).join('\n\n');
201
+ return { decision: 'continue', reason: joined };
202
+ }
203
+ return { decision: 'allow' };
204
+ }
205
+
206
+ return {};
207
+ }