@getgavel/cli 0.1.15 → 0.1.17

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.
@@ -0,0 +1,134 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { bridgePaths, lastingCommand } from "./background.js";
5
+ const exec = (command, args) => {
6
+ try {
7
+ return { ok: true, out: execFileSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) };
8
+ }
9
+ catch (err) {
10
+ const e = err;
11
+ return { ok: false, out: `${typeof e.stdout === "string" ? e.stdout : ""}${typeof e.stderr === "string" ? e.stderr : ""}` };
12
+ }
13
+ };
14
+ export function serviceSpec(opts) {
15
+ const paths = bridgePaths(opts.home, opts.cwd, opts.harness);
16
+ return {
17
+ label: `ai.getgavel.bridge.${paths.key}`,
18
+ folder: opts.cwd,
19
+ command: [...lastingCommand(opts.home), "bridge", "--harness", opts.harness, ...(opts.server ? ["--server", opts.server] : [])],
20
+ log: paths.log,
21
+ // The bridge runs claude or codex: the PATH they're found on now.
22
+ path: opts.env.PATH ?? "/usr/local/bin:/usr/bin:/bin",
23
+ };
24
+ }
25
+ const xml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
26
+ export function launchdPlist(spec) {
27
+ const strings = (items) => items.map((s) => ` <string>${xml(s)}</string>`).join("\n");
28
+ return `<?xml version="1.0" encoding="UTF-8"?>
29
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
30
+ <plist version="1.0">
31
+ <dict>
32
+ <key>Label</key>
33
+ <string>${xml(spec.label)}</string>
34
+ <key>ProgramArguments</key>
35
+ <array>
36
+ ${strings(spec.command)}
37
+ </array>
38
+ <key>WorkingDirectory</key>
39
+ <string>${xml(spec.folder)}</string>
40
+ <key>EnvironmentVariables</key>
41
+ <dict>
42
+ <key>PATH</key>
43
+ <string>${xml(spec.path)}</string>
44
+ <key>GAVEL_BRIDGE_SERVICE</key>
45
+ <string>1</string>
46
+ </dict>
47
+ <key>RunAtLoad</key>
48
+ <true/>
49
+ <key>KeepAlive</key>
50
+ <dict>
51
+ <key>SuccessfulExit</key>
52
+ <false/>
53
+ </dict>
54
+ <key>ThrottleInterval</key>
55
+ <integer>10</integer>
56
+ <key>StandardOutPath</key>
57
+ <string>${xml(spec.log)}</string>
58
+ <key>StandardErrorPath</key>
59
+ <string>${xml(spec.log)}</string>
60
+ </dict>
61
+ </plist>
62
+ `;
63
+ }
64
+ // systemd's own quoting: each word in double quotes, its backslashes, quotes and % escaped.
65
+ const unitWord = (word) => `"${word.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
66
+ export function systemdUnit(spec) {
67
+ return `[Unit]
68
+ Description=Gavel bridge for ${spec.folder.replace(/%/g, "%%")}
69
+
70
+ [Service]
71
+ WorkingDirectory=${unitWord(spec.folder)}
72
+ ExecStart=${spec.command.map(unitWord).join(" ")}
73
+ Environment=${unitWord(`PATH=${spec.path}`)}
74
+ Environment=GAVEL_BRIDGE_SERVICE=1
75
+ Restart=on-failure
76
+ RestartSec=10
77
+ StandardOutput=append:${spec.log}
78
+ StandardError=append:${spec.log}
79
+
80
+ [Install]
81
+ WantedBy=default.target
82
+ `;
83
+ }
84
+ function whereFor(spec, home, platform) {
85
+ if (platform === "darwin")
86
+ return { kind: "launchd", file: join(home, "Library", "LaunchAgents", `${spec.label}.plist`) };
87
+ if (platform === "linux")
88
+ return { kind: "systemd", file: join(home, ".config", "systemd", "user", `${spec.label}.service`) };
89
+ return null;
90
+ }
91
+ export function bridgeService(action, opts) {
92
+ const run = opts.exec ?? exec;
93
+ const spec = serviceSpec(opts);
94
+ const where = whereFor(spec, opts.home, opts.platform ?? process.platform);
95
+ if (!where)
96
+ return { service: "unsupported", reason: "The bridge's background service is for a Mac (launchd) or Linux (systemd). Here, run gavel bridge in a terminal." };
97
+ const uid = process.getuid?.() ?? 0;
98
+ const unit = `${spec.label}.service`;
99
+ const manager = where.kind === "launchd" ? "launchd" : "systemd --user";
100
+ if (action === "status") {
101
+ if (!existsSync(where.file))
102
+ return { service: "not installed", manager };
103
+ const live = where.kind === "launchd" ? run("launchctl", ["print", `gui/${uid}/${spec.label}`]) : run("systemctl", ["--user", "is-active", unit]);
104
+ const running = where.kind === "launchd" ? live.ok && /\bstate = running\b/.test(live.out) : live.ok && live.out.trim() === "active";
105
+ return { service: running ? "running" : "not running", manager, file: where.file, log: spec.log };
106
+ }
107
+ if (action === "remove") {
108
+ if (!existsSync(where.file))
109
+ return { service: "not installed", manager };
110
+ if (where.kind === "launchd")
111
+ run("launchctl", ["bootout", `gui/${uid}/${spec.label}`]);
112
+ else
113
+ run("systemctl", ["--user", "disable", "--now", unit]);
114
+ unlinkSync(where.file);
115
+ if (where.kind === "systemd")
116
+ run("systemctl", ["--user", "daemon-reload"]);
117
+ return { service: "removed", manager, file: where.file };
118
+ }
119
+ mkdirSync(join(where.file, ".."), { recursive: true });
120
+ writeFileSync(where.file, where.kind === "launchd" ? launchdPlist(spec) : systemdUnit(spec), { mode: 0o644 });
121
+ if (where.kind === "launchd") {
122
+ run("launchctl", ["bootout", `gui/${uid}/${spec.label}`]);
123
+ const loaded = run("launchctl", ["bootstrap", `gui/${uid}`, where.file]);
124
+ if (!loaded.ok)
125
+ return { service: "failed", manager, file: where.file, reason: `launchctl didn't load it: ${loaded.out.trim().split("\n")[0] ?? ""}`.slice(0, 300) };
126
+ }
127
+ else {
128
+ run("systemctl", ["--user", "daemon-reload"]);
129
+ const enabled = run("systemctl", ["--user", "enable", "--now", unit]);
130
+ if (!enabled.ok)
131
+ return { service: "failed", manager, file: where.file, reason: `systemctl didn't start it: ${enabled.out.trim().split("\n")[0] ?? ""}`.slice(0, 300) };
132
+ }
133
+ return { service: "installed", manager, file: where.file, log: spec.log };
134
+ }
@@ -39,6 +39,31 @@ export function claudeSetups(cwd, home) {
39
39
  }
40
40
  // [mcp_servers.<name>] and its http_headers table, the name bare or quoted.
41
41
  const TABLE = /^\s*\[\s*mcp_servers\.(?:"([^"]+)"|([A-Za-z0-9_-]+))(\.http_headers)?\s*\]\s*$/;
42
+ // Each Gavel server's entry in a Codex config.toml, by name: its address and its token.
43
+ function codexEntries(toml) {
44
+ const tables = new Map();
45
+ let current = null;
46
+ for (const line of toml.split("\n")) {
47
+ if (/^\s*\[/.test(line)) {
48
+ const m = TABLE.exec(line);
49
+ const name = m ? (m[1] ?? m[2]) : null;
50
+ current = name && isGavel(name) ? (tables.get(name) ?? tables.set(name, []).get(name)) : null;
51
+ }
52
+ else
53
+ current?.push(line);
54
+ }
55
+ const out = new Map();
56
+ for (const [name, lines] of tables) {
57
+ const text = lines.join("\n");
58
+ const url = /^\s*url\s*=\s*"([^"]+)"/m.exec(text)?.[1];
59
+ const token = /"?Authorization"?\s*=\s*"Bearer (gvl_[^"\s]+)"/.exec(text)?.[1];
60
+ if (url && token)
61
+ out.set(name, { url, token });
62
+ }
63
+ return out;
64
+ }
65
+ // The named server's entry in a Codex config.toml's text, or null.
66
+ export const codexEntry = (toml, server) => codexEntries(toml).get(server) ?? null;
42
67
  // Codex: the project's .codex/config.toml (an agent's), then the user's (a fleet's).
43
68
  export function codexSetups(cwd, home, env) {
44
69
  const out = [];
@@ -48,24 +73,8 @@ export function codexSetups(cwd, home, env) {
48
73
  ]) {
49
74
  if (!existsSync(file))
50
75
  continue;
51
- const tables = new Map();
52
- let current = null;
53
- for (const line of readFileSync(file, "utf8").split("\n")) {
54
- if (/^\s*\[/.test(line)) {
55
- const m = TABLE.exec(line);
56
- const name = m ? (m[1] ?? m[2]) : null;
57
- current = name && isGavel(name) ? (tables.get(name) ?? tables.set(name, []).get(name)) : null;
58
- }
59
- else
60
- current?.push(line);
61
- }
62
- for (const [name, lines] of tables) {
63
- const text = lines.join("\n");
64
- const url = /^\s*url\s*=\s*"([^"]+)"/m.exec(text)?.[1];
65
- const token = /"?Authorization"?\s*=\s*"Bearer (gvl_[^"\s]+)"/.exec(text)?.[1];
66
- if (url && token)
67
- out.push({ server: name, url, token, where: `Codex's setup for ${scope}` });
68
- }
76
+ for (const [server, entry] of codexEntries(readFileSync(file, "utf8")))
77
+ out.push({ server, ...entry, where: `Codex's setup for ${scope}` });
69
78
  }
70
79
  return out;
71
80
  }
@@ -0,0 +1,166 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { connect } from "node:net";
3
+ // A WebSocket client (RFC 6455) over a Unix socket: how a local client talks to Codex's shared
4
+ // app-server, whose control socket takes an HTTP Upgrade and then frames, one JSON-RPC message
5
+ // a text frame. Text frames only; the CLI takes no dependency, so it's the few parts used here.
6
+ const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
7
+ const MAX_MESSAGE = 64 * 1024 * 1024;
8
+ export class WebSocketError extends Error {
9
+ code;
10
+ constructor(message, code) {
11
+ super(message);
12
+ this.code = code;
13
+ }
14
+ }
15
+ function frame(opcode, payload) {
16
+ const mask = randomBytes(4);
17
+ const length = payload.length;
18
+ const head = length < 126 ? Buffer.alloc(2) : length < 65_536 ? Buffer.alloc(4) : Buffer.alloc(10);
19
+ head[0] = 0x80 | opcode;
20
+ if (length < 126)
21
+ head[1] = 0x80 | length;
22
+ else if (length < 65_536) {
23
+ head[1] = 0x80 | 126;
24
+ head.writeUInt16BE(length, 2);
25
+ }
26
+ else {
27
+ head[1] = 0x80 | 127;
28
+ head.writeBigUInt64BE(BigInt(length), 2);
29
+ }
30
+ const body = Buffer.alloc(length);
31
+ for (let i = 0; i < length; i++)
32
+ body[i] = payload[i] ^ mask[i % 4];
33
+ return Buffer.concat([head, mask, body]);
34
+ }
35
+ // Opens the socket, upgrades it and calls `message` with each text message, whole.
36
+ export function openWebSocket(path, handlers, timeoutMs = 10_000) {
37
+ return new Promise((resolve, reject) => {
38
+ const key = randomBytes(16).toString("base64");
39
+ const accept = createHash("sha1").update(key + GUID).digest("base64");
40
+ const socket = connect({ path });
41
+ let upgraded = false;
42
+ let buffer = Buffer.alloc(0);
43
+ let parts = [];
44
+ let partsLength = 0;
45
+ let ended = false;
46
+ let endClosed = () => undefined;
47
+ const closed = new Promise((r) => (endClosed = r));
48
+ const timer = setTimeout(() => fail(new WebSocketError("Codex's server didn't answer the connection", "ETIMEDOUT")), timeoutMs);
49
+ const finish = (why) => {
50
+ if (ended)
51
+ return;
52
+ ended = true;
53
+ clearTimeout(timer);
54
+ socket.destroy();
55
+ endClosed(why);
56
+ };
57
+ const fail = (err) => {
58
+ if (!upgraded)
59
+ reject(err);
60
+ finish(err.message);
61
+ };
62
+ const write = (opcode, payload) => {
63
+ if (!ended && !socket.destroyed)
64
+ socket.write(frame(opcode, payload));
65
+ };
66
+ const frames = () => {
67
+ for (;;) {
68
+ if (buffer.length < 2)
69
+ return;
70
+ const fin = (buffer[0] & 0x80) !== 0;
71
+ const opcode = buffer[0] & 0x0f;
72
+ const masked = (buffer[1] & 0x80) !== 0;
73
+ let length = buffer[1] & 0x7f;
74
+ let at = 2;
75
+ if (length === 126) {
76
+ if (buffer.length < 4)
77
+ return;
78
+ length = buffer.readUInt16BE(2);
79
+ at = 4;
80
+ }
81
+ else if (length === 127) {
82
+ if (buffer.length < 10)
83
+ return;
84
+ const big = buffer.readBigUInt64BE(2);
85
+ if (big > BigInt(MAX_MESSAGE))
86
+ return fail(new WebSocketError("Codex's server sent a message too large to read"));
87
+ length = Number(big);
88
+ at = 10;
89
+ }
90
+ const maskAt = at;
91
+ if (masked)
92
+ at += 4;
93
+ if (buffer.length < at + length)
94
+ return;
95
+ let payload = buffer.subarray(at, at + length);
96
+ if (masked) {
97
+ const mask = buffer.subarray(maskAt, maskAt + 4);
98
+ payload = Buffer.from(payload.map((b, i) => b ^ mask[i % 4]));
99
+ }
100
+ buffer = buffer.subarray(at + length);
101
+ if (opcode === 0x8) {
102
+ write(0x8, payload.subarray(0, 2));
103
+ return finish(null);
104
+ }
105
+ if (opcode === 0x9) {
106
+ write(0xa, payload);
107
+ continue;
108
+ }
109
+ if (opcode === 0xa)
110
+ continue;
111
+ if (opcode !== 0x0 && opcode !== 0x1 && opcode !== 0x2)
112
+ return fail(new WebSocketError(`Codex's server sent an unknown frame (${opcode})`));
113
+ parts.push(Buffer.from(payload));
114
+ partsLength += payload.length;
115
+ if (partsLength > MAX_MESSAGE)
116
+ return fail(new WebSocketError("Codex's server sent a message too large to read"));
117
+ if (!fin)
118
+ continue;
119
+ const whole = Buffer.concat(parts, partsLength);
120
+ parts = [];
121
+ partsLength = 0;
122
+ try {
123
+ handlers.message(whole.toString("utf8"));
124
+ }
125
+ catch {
126
+ // a handler's trouble is its own
127
+ }
128
+ }
129
+ };
130
+ socket.on("connect", () => {
131
+ socket.write(`GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n\r\n`);
132
+ });
133
+ socket.on("data", (chunk) => {
134
+ buffer = Buffer.concat([buffer, chunk]);
135
+ if (!upgraded) {
136
+ const end = buffer.indexOf("\r\n\r\n");
137
+ if (end < 0) {
138
+ if (buffer.length > 16 * 1024)
139
+ fail(new WebSocketError("Codex's server didn't upgrade the connection"));
140
+ return;
141
+ }
142
+ const head = buffer.subarray(0, end).toString("latin1").split("\r\n");
143
+ const status = /^HTTP\/1\.1 (\d{3})/.exec(head[0] ?? "")?.[1];
144
+ const headers = new Map(head.slice(1).map((l) => [l.slice(0, l.indexOf(":")).trim().toLowerCase(), l.slice(l.indexOf(":") + 1).trim()]));
145
+ if (status !== "101" || headers.get("sec-websocket-accept") !== accept)
146
+ return fail(new WebSocketError(`Codex's server refused the connection (${status ?? "no answer"})`));
147
+ buffer = buffer.subarray(end + 4);
148
+ upgraded = true;
149
+ clearTimeout(timer);
150
+ resolve({
151
+ send: (text) => write(0x1, Buffer.from(text, "utf8")),
152
+ close: () => {
153
+ write(0x8, Buffer.from([0x03, 0xe8]));
154
+ finish(null);
155
+ },
156
+ closed,
157
+ });
158
+ }
159
+ frames();
160
+ });
161
+ socket.on("error", (err) => fail(new WebSocketError(err.message, err.code)));
162
+ const gone = () => (upgraded ? finish("the connection closed") : fail(new WebSocketError("Codex's server closed the connection")));
163
+ socket.on("close", gone);
164
+ socket.on("end", gone);
165
+ });
166
+ }