@getgavel/cli 0.0.0-stage → 0.1.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.
- package/README.md +37 -2
- package/dist/gavel.js +647 -0
- package/package.json +24 -4
package/README.md
CHANGED
|
@@ -1,3 +1,38 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gavel
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The command line for [Gavel](https://getgavel.ai), where people make decisions with their agents.
|
|
4
|
+
An agent uses it to bring its person the decisions that are theirs and to carry the answers back:
|
|
5
|
+
the same operations as Gavel's MCP server, over its HTTP API, for agents that prefer a shell.
|
|
6
|
+
|
|
7
|
+
It needs Node 24 or later.
|
|
8
|
+
|
|
9
|
+
## Connect
|
|
10
|
+
|
|
11
|
+
Your person opens Gavel's Settings › Agents, picks Connect and gives you a pairing code. Redeem it
|
|
12
|
+
where you work:
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npx @getgavel/cli pair <code>
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
It writes your setup (Cursor's `mcp.json`, Claude Code, Codex, or an env file) and never prints
|
|
19
|
+
your token. Or install the command once:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm i -g @getgavel/cli
|
|
23
|
+
gavel pair <code>
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Use
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
gavel me # who you are in Gavel
|
|
30
|
+
gavel search "onboarding copy" # before you ask
|
|
31
|
+
gavel ask --file decision.json # put a decision to your person
|
|
32
|
+
gavel wait D-12 --timeout 60 # until it's decided
|
|
33
|
+
gavel watch # one GAVEL_WAKE line per new thing for you; run it in the background
|
|
34
|
+
gavel help # every command
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`GAVEL_TOKEN` is your agent's token (pairing sets it up); `GAVEL_API_URL` defaults to
|
|
38
|
+
`https://api.getgavel.ai`. How an agent works with Gavel: <https://getgavel.ai/agents.md>.
|
package/dist/gavel.js
ADDED
|
@@ -0,0 +1,647 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The `gavel` command-line tool: the MCP server's operations over the HTTP API, for agents that
|
|
3
|
+
// prefer a shell. GAVEL_TOKEN (an agent's token) and GAVEL_API_URL (default https://api.getgavel.ai);
|
|
4
|
+
// on a fleet token, the chat's name with --as or GAVEL_AGENT (sent as X-Gavel-Agent).
|
|
5
|
+
// Prints the API's JSON; on an error, prints it to stderr and exits 1.
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { homedir, hostname } from "node:os";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
|
|
12
|
+
|
|
13
|
+
gavel pair <code> [--harness cursor|claude-code|codex|other] [--machine <name>]
|
|
14
|
+
redeem your person's pairing code and write your setup
|
|
15
|
+
(no GAVEL_TOKEN needed; never prints the token)
|
|
16
|
+
gavel search <words> [--area <slug>] [--status open|decided|any] [--limit <n>]
|
|
17
|
+
gavel ask --file decision.json the decision, as MCP ask's input
|
|
18
|
+
gavel revise <D-12> --file decision.json a draft the editor sent back, fixed (the whole ask again)
|
|
19
|
+
gavel get <D-12>
|
|
20
|
+
gavel wait <D-12> [--timeout <seconds>] until it's decided (default 60)
|
|
21
|
+
gavel withdraw <D-12> [--reason <words>] take back what you asked, while it isn't decided
|
|
22
|
+
gavel attach <D-12> --file context.json a context item, or a list of them
|
|
23
|
+
gavel answer <requestId> <response> answer an Ask someone
|
|
24
|
+
gavel act <D-12> <note> what you did with the answer
|
|
25
|
+
gavel inbox what's waiting on you
|
|
26
|
+
gavel status <text> [--folders <a,b>] [--state working|blocked|idle] [--issue <MA-482>]
|
|
27
|
+
what you're doing now, in plain words ("" clears it)
|
|
28
|
+
gavel message (--to-agent <id> | --to-person <email>) <text> [--decision <D-12>]
|
|
29
|
+
start a conversation with another agent
|
|
30
|
+
gavel message --conversation <C-12> <text>
|
|
31
|
+
reply in one
|
|
32
|
+
gavel conversations [<C-12>] yours, or one with its messages (reads it)
|
|
33
|
+
gavel wait-for-reply <C-12> [--timeout <seconds>]
|
|
34
|
+
until there's a message to you in it (default 60)
|
|
35
|
+
gavel watch runs until stopped: one GAVEL_WAKE line per new
|
|
36
|
+
message, request, decision to decide, answer or
|
|
37
|
+
folder clash, and nothing else (run it in the
|
|
38
|
+
background; one per agent)
|
|
39
|
+
gavel log --question <q> --outcome <o> --reason <why> [--area <slug>] [--trust <id>] [--file context.json]
|
|
40
|
+
gavel log-answer --question <q> --answer <what they decided> [--note <their why>] [--area <slug>]
|
|
41
|
+
what your person answered you in chat, as theirs
|
|
42
|
+
gavel decide <D-12> (--option <id> | --text <words>) [--note <words>]
|
|
43
|
+
a multiple question: --option again for each pick,
|
|
44
|
+
and --text beside them if you like
|
|
45
|
+
gavel decide-for <D-12> (--option <id> | --text <words>) --reason <why> --trust <id>
|
|
46
|
+
gavel priority <D-12> now|later [--note <words>]
|
|
47
|
+
gavel forward <D-12> (--to-person <email> | --to-agent <id>) [--note <words>]
|
|
48
|
+
gavel research-result <requestId> <response> [--file context.json]
|
|
49
|
+
gavel agents you and your sub-agents
|
|
50
|
+
gavel invite --name <name> [--description <words>] [--permissions ask,answer]
|
|
51
|
+
gavel start-cloud-agent --name <task's name> --repo <url> --task <words> [--branch <ref>] [--open-pr true]
|
|
52
|
+
a Cursor cloud agent under you, for a task
|
|
53
|
+
gavel me
|
|
54
|
+
|
|
55
|
+
--as <name> on a fleet token, which chat you are (the name you go by,
|
|
56
|
+
e.g. worker 35 or the task you're on; keep using the same one)
|
|
57
|
+
|
|
58
|
+
A text argument or --file of "-" is read from stdin.
|
|
59
|
+
Environment: GAVEL_TOKEN (required), GAVEL_API_URL (default https://api.getgavel.ai),
|
|
60
|
+
GAVEL_AGENT (instead of --as).`;
|
|
61
|
+
class UsageError extends Error {
|
|
62
|
+
}
|
|
63
|
+
export function parseArgs(argv) {
|
|
64
|
+
const positional = [];
|
|
65
|
+
const flags = {};
|
|
66
|
+
const lists = {};
|
|
67
|
+
const set = (name, value) => {
|
|
68
|
+
flags[name] = value;
|
|
69
|
+
(lists[name] ??= []).push(value);
|
|
70
|
+
};
|
|
71
|
+
for (let i = 0; i < argv.length; i++) {
|
|
72
|
+
const arg = argv[i];
|
|
73
|
+
if (arg.startsWith("--")) {
|
|
74
|
+
const eq = arg.indexOf("=");
|
|
75
|
+
if (eq > 0)
|
|
76
|
+
set(arg.slice(2, eq), arg.slice(eq + 1));
|
|
77
|
+
else {
|
|
78
|
+
const value = argv[i + 1];
|
|
79
|
+
if (value === undefined || (value.startsWith("--") && value !== "-"))
|
|
80
|
+
throw new UsageError(`${arg} needs a value`);
|
|
81
|
+
set(arg.slice(2), value);
|
|
82
|
+
i++;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
else
|
|
86
|
+
positional.push(arg);
|
|
87
|
+
}
|
|
88
|
+
return { positional, flags, lists };
|
|
89
|
+
}
|
|
90
|
+
// One --option is optionId; several, on a multiple question, are optionIds.
|
|
91
|
+
const picks = (options) => (options && options.length > 1 ? { optionIds: options } : { optionId: options?.[0] });
|
|
92
|
+
let stdinCache = null;
|
|
93
|
+
function readText(value) {
|
|
94
|
+
if (value !== "-")
|
|
95
|
+
return value;
|
|
96
|
+
stdinCache ??= readFileSync(0, "utf8");
|
|
97
|
+
return stdinCache.trim();
|
|
98
|
+
}
|
|
99
|
+
function readJson(path) {
|
|
100
|
+
const text = path === "-" ? readText("-") : readFileSync(path, "utf8");
|
|
101
|
+
try {
|
|
102
|
+
return JSON.parse(text);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new UsageError(`${path === "-" ? "stdin" : path} isn't valid JSON`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function need(value, what) {
|
|
109
|
+
if (value === undefined || value === "")
|
|
110
|
+
throw new UsageError(`missing ${what}`);
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
const ref = (value) => encodeURIComponent(need(value, "the decision (D-12 or its id)"));
|
|
114
|
+
const compact = (body) => Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));
|
|
115
|
+
const contextList = (file) => {
|
|
116
|
+
if (!file)
|
|
117
|
+
return undefined;
|
|
118
|
+
const json = readJson(file);
|
|
119
|
+
return Array.isArray(json) ? json : [json];
|
|
120
|
+
};
|
|
121
|
+
// --as <name> (or --as=<name>) may come anywhere on the line; it's the caller's, not the command's.
|
|
122
|
+
export function takeAs(argv) {
|
|
123
|
+
const rest = [];
|
|
124
|
+
let as = null;
|
|
125
|
+
for (let i = 0; i < argv.length; i++) {
|
|
126
|
+
const arg = argv[i];
|
|
127
|
+
if (arg === "--as") {
|
|
128
|
+
const value = argv[++i];
|
|
129
|
+
if (value === undefined || value.startsWith("--"))
|
|
130
|
+
throw new UsageError("--as needs a name");
|
|
131
|
+
as = value;
|
|
132
|
+
}
|
|
133
|
+
else if (arg.startsWith("--as="))
|
|
134
|
+
as = arg.slice(5);
|
|
135
|
+
else
|
|
136
|
+
rest.push(arg);
|
|
137
|
+
}
|
|
138
|
+
return { argv: rest, as };
|
|
139
|
+
}
|
|
140
|
+
// A header carries only Latin-1: the name goes percent-encoded, and the server decodes it.
|
|
141
|
+
export function agentHeader(name) {
|
|
142
|
+
const trimmed = name?.trim();
|
|
143
|
+
return trimmed ? { "x-gavel-agent": encodeURIComponent(trimmed) } : {};
|
|
144
|
+
}
|
|
145
|
+
// A command line → one API request.
|
|
146
|
+
export function toRequest(argv) {
|
|
147
|
+
const [command, ...rest] = argv;
|
|
148
|
+
const { positional: p, flags: f, lists } = parseArgs(rest);
|
|
149
|
+
switch (command) {
|
|
150
|
+
case undefined:
|
|
151
|
+
case "help":
|
|
152
|
+
case "--help":
|
|
153
|
+
case "-h":
|
|
154
|
+
return "help";
|
|
155
|
+
case "search": {
|
|
156
|
+
const query = new URLSearchParams(compact({ q: need(p.join(" "), "the words to search for"), area: f.area, status: f.status, limit: f.limit }));
|
|
157
|
+
return { method: "GET", path: `/v1/search?${query}` };
|
|
158
|
+
}
|
|
159
|
+
case "ask":
|
|
160
|
+
return { method: "POST", path: "/v1/decisions", body: readJson(need(f.file, "--file decision.json")) };
|
|
161
|
+
case "revise":
|
|
162
|
+
return { method: "POST", path: `/v1/decisions/${ref(p[0])}/revise`, body: readJson(need(f.file, "--file decision.json")) };
|
|
163
|
+
case "get":
|
|
164
|
+
return { method: "GET", path: `/v1/decisions/${ref(p[0])}` };
|
|
165
|
+
case "wait":
|
|
166
|
+
return { method: "GET", path: `/v1/decisions/${ref(p[0])}/wait?timeout=${encodeURIComponent(f.timeout ?? "60")}` };
|
|
167
|
+
case "withdraw":
|
|
168
|
+
return { method: "POST", path: `/v1/decisions/${ref(p[0])}/withdraw`, body: compact({ reason: f.reason && readText(f.reason) }) };
|
|
169
|
+
case "attach":
|
|
170
|
+
return { method: "POST", path: `/v1/decisions/${ref(p[0])}/context`, body: { items: contextList(need(f.file, "--file context.json")) } };
|
|
171
|
+
case "answer":
|
|
172
|
+
return { method: "POST", path: `/v1/requests/${encodeURIComponent(need(p[0], "the request id"))}/answer`, body: { response: readText(need(p.slice(1).join(" "), "the response")) } };
|
|
173
|
+
case "act":
|
|
174
|
+
return { method: "POST", path: `/v1/decisions/${ref(p[0])}/act`, body: { note: readText(need(p.slice(1).join(" "), "the note")) } };
|
|
175
|
+
case "inbox":
|
|
176
|
+
return { method: "GET", path: "/v1/inbox" };
|
|
177
|
+
case "status": {
|
|
178
|
+
if (!p.length)
|
|
179
|
+
throw new UsageError('missing what you\'re doing now (or "" to clear it)');
|
|
180
|
+
const folders = f.folders?.split(",").map((s) => s.trim()).filter(Boolean);
|
|
181
|
+
return { method: "PATCH", path: "/v1/agents/me/status", body: compact({ text: readText(p.join(" ")) || null, folders, state: f.state, linearIssue: f.issue }) };
|
|
182
|
+
}
|
|
183
|
+
case "message": {
|
|
184
|
+
const text = readText(need(p.join(" "), "what to say"));
|
|
185
|
+
if ([f.conversation, f["to-agent"], f["to-person"]].filter(Boolean).length !== 1)
|
|
186
|
+
throw new UsageError("give --to-agent or --to-person to start a conversation, or --conversation to reply in one");
|
|
187
|
+
if (f.conversation)
|
|
188
|
+
return { method: "POST", path: `/v1/conversations/${encodeURIComponent(f.conversation)}/messages`, body: { text } };
|
|
189
|
+
return { method: "POST", path: "/v1/conversations", body: compact({ toAgentId: f["to-agent"], toPerson: f["to-person"], text, decision: f.decision }) };
|
|
190
|
+
}
|
|
191
|
+
case "conversations":
|
|
192
|
+
return { method: "GET", path: p[0] ? `/v1/conversations/${encodeURIComponent(p[0])}` : "/v1/conversations" };
|
|
193
|
+
case "wait-for-reply":
|
|
194
|
+
return { method: "GET", path: `/v1/conversations/${encodeURIComponent(need(p[0], "the conversation (C-12)"))}/wait?timeout=${encodeURIComponent(f.timeout ?? "60")}` };
|
|
195
|
+
case "log":
|
|
196
|
+
return {
|
|
197
|
+
method: "POST",
|
|
198
|
+
path: "/v1/decided",
|
|
199
|
+
body: compact({
|
|
200
|
+
question: need(f.question, "--question"),
|
|
201
|
+
outcome: readText(need(f.outcome, "--outcome")),
|
|
202
|
+
reason: readText(need(f.reason, "--reason")),
|
|
203
|
+
area: f.area,
|
|
204
|
+
trustId: f.trust,
|
|
205
|
+
context: contextList(f.file),
|
|
206
|
+
}),
|
|
207
|
+
};
|
|
208
|
+
case "log-answer":
|
|
209
|
+
return {
|
|
210
|
+
method: "POST",
|
|
211
|
+
path: "/v1/decided/answers",
|
|
212
|
+
body: compact({ question: need(f.question, "--question"), answer: readText(need(f.answer, "--answer")), note: f.note && readText(f.note), area: f.area, context: contextList(f.file) }),
|
|
213
|
+
};
|
|
214
|
+
case "decide":
|
|
215
|
+
return { method: "POST", path: `/v1/decisions/${ref(p[0])}/decide`, body: compact({ ...picks(lists.option), text: f.text && readText(f.text), note: f.note }) };
|
|
216
|
+
case "decide-for":
|
|
217
|
+
return {
|
|
218
|
+
method: "POST",
|
|
219
|
+
path: `/v1/decisions/${ref(p[0])}/decide-for`,
|
|
220
|
+
body: compact({ ...picks(lists.option), text: f.text && readText(f.text), reason: readText(need(f.reason, "--reason")), trustId: need(f.trust, "--trust") }),
|
|
221
|
+
};
|
|
222
|
+
case "priority": {
|
|
223
|
+
const priority = need(p[1], "now or later");
|
|
224
|
+
if (priority !== "now" && priority !== "later")
|
|
225
|
+
throw new UsageError("the priority is now or later");
|
|
226
|
+
return { method: "POST", path: `/v1/decisions/${ref(p[0])}/priority`, body: compact({ priority, note: f.note }) };
|
|
227
|
+
}
|
|
228
|
+
case "forward":
|
|
229
|
+
return { method: "POST", path: `/v1/decisions/${ref(p[0])}/forward`, body: compact({ toPerson: f["to-person"], toAgentId: f["to-agent"], note: f.note }) };
|
|
230
|
+
case "research-result":
|
|
231
|
+
return {
|
|
232
|
+
method: "POST",
|
|
233
|
+
path: `/v1/requests/${encodeURIComponent(need(p[0], "the request id"))}/research-result`,
|
|
234
|
+
body: compact({ response: readText(need(p.slice(1).join(" "), "the response")), context: contextList(f.file) }),
|
|
235
|
+
};
|
|
236
|
+
case "agents":
|
|
237
|
+
return { method: "GET", path: "/v1/agents" };
|
|
238
|
+
case "invite":
|
|
239
|
+
return {
|
|
240
|
+
method: "POST",
|
|
241
|
+
path: "/v1/sub-agents",
|
|
242
|
+
body: compact({ name: need(f.name, "--name"), description: f.description, permissions: f.permissions?.split(",").map((s) => s.trim()) }),
|
|
243
|
+
};
|
|
244
|
+
case "start-cloud-agent":
|
|
245
|
+
return {
|
|
246
|
+
method: "POST",
|
|
247
|
+
path: "/v1/cloud-agents",
|
|
248
|
+
body: compact({
|
|
249
|
+
name: need(f.name, "--name"),
|
|
250
|
+
repo: need(f.repo, "--repo"),
|
|
251
|
+
task: readText(need(f.task, "--task")),
|
|
252
|
+
branch: f.branch,
|
|
253
|
+
openPullRequest: f["open-pr"] === undefined ? undefined : f["open-pr"] === "true",
|
|
254
|
+
}),
|
|
255
|
+
};
|
|
256
|
+
case "me":
|
|
257
|
+
return { method: "GET", path: "/v1/me" };
|
|
258
|
+
default:
|
|
259
|
+
throw new UsageError(`unknown command "${command}"`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
// ---------- gavel pair ----------
|
|
263
|
+
const HARNESSES = ["cursor", "claude-code", "codex", "other"];
|
|
264
|
+
// Where this runs, from what each software sets in its shells; else other.
|
|
265
|
+
export function detectHarness(env) {
|
|
266
|
+
if (env.CLAUDECODE)
|
|
267
|
+
return "claude-code";
|
|
268
|
+
if (env.CURSOR_TRACE_ID || env.CURSOR_AGENT)
|
|
269
|
+
return "cursor";
|
|
270
|
+
if (env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED || env.CODEX_HOME)
|
|
271
|
+
return "codex";
|
|
272
|
+
return "other";
|
|
273
|
+
}
|
|
274
|
+
const expand = (file, home) => (file.startsWith("~/") ? join(home, file.slice(2)) : file);
|
|
275
|
+
// A file that git tracks would carry the token into a commit.
|
|
276
|
+
function tracked(file, cwd) {
|
|
277
|
+
try {
|
|
278
|
+
execFileSync("git", ["ls-files", "--error-unmatch", file], { cwd, stdio: "ignore" });
|
|
279
|
+
return true;
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
function writePrivate(path, text) {
|
|
286
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
287
|
+
writeFileSync(path, text, { mode: 0o600 });
|
|
288
|
+
chmodSync(path, 0o600);
|
|
289
|
+
}
|
|
290
|
+
function ensureGitignore(line, cwd) {
|
|
291
|
+
const path = join(cwd, ".gitignore");
|
|
292
|
+
const lines = existsSync(path) ? readFileSync(path, "utf8").split("\n") : [];
|
|
293
|
+
if (lines.some((l) => l.trim() === line || l.trim() === `/${line}`))
|
|
294
|
+
return;
|
|
295
|
+
const text = existsSync(path) ? readFileSync(path, "utf8") : "";
|
|
296
|
+
appendFileSync(path, `${text && !text.endsWith("\n") ? "\n" : ""}${line}\n`);
|
|
297
|
+
}
|
|
298
|
+
function parseMcpJson(existing) {
|
|
299
|
+
if (!existing?.trim())
|
|
300
|
+
return {};
|
|
301
|
+
try {
|
|
302
|
+
return JSON.parse(existing);
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
throw new Error("the existing mcp.json isn't plain JSON: add the Gavel server by hand");
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
// mcp.json's other servers stay (another workspace's gavel-… too); the one named `name` is replaced.
|
|
309
|
+
export function mergeMcpJson(existing, name, server) {
|
|
310
|
+
const json = parseMcpJson(existing);
|
|
311
|
+
return `${JSON.stringify({ ...json, mcpServers: { ...(json.mcpServers ?? {}), [name]: server } }, null, 2)}\n`;
|
|
312
|
+
}
|
|
313
|
+
export function removeMcpJsonServer(existing, name) {
|
|
314
|
+
const json = parseMcpJson(existing);
|
|
315
|
+
const { [name]: _gone, ...rest } = json.mcpServers ?? {};
|
|
316
|
+
return `${JSON.stringify({ ...json, mcpServers: rest }, null, 2)}\n`;
|
|
317
|
+
}
|
|
318
|
+
// A header is [mcp_servers.<name>] itself, one of its sub-tables, or another table.
|
|
319
|
+
function tableOf(header, name) {
|
|
320
|
+
const key = header.replace(/\s/g, "");
|
|
321
|
+
for (const n of [name, `"${name}"`]) {
|
|
322
|
+
if (key === `mcp_servers.${n}`)
|
|
323
|
+
return "main";
|
|
324
|
+
if (key.startsWith(`mcp_servers.${n}.`))
|
|
325
|
+
return "sub";
|
|
326
|
+
}
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
// A Codex config without its [mcp_servers.<name>] table and sub-tables; and that table's own lines.
|
|
330
|
+
function splitTomlTable(existing, name) {
|
|
331
|
+
const out = [];
|
|
332
|
+
let table = null;
|
|
333
|
+
let inside = null;
|
|
334
|
+
for (const line of (existing ?? "").split("\n")) {
|
|
335
|
+
const header = /^\s*\[\s*([^\]]+?)\s*\]\s*$/.exec(line);
|
|
336
|
+
if (header) {
|
|
337
|
+
inside = tableOf(header[1], name);
|
|
338
|
+
if (inside === "main")
|
|
339
|
+
table ??= [];
|
|
340
|
+
}
|
|
341
|
+
else if (inside === "main")
|
|
342
|
+
table.push(line);
|
|
343
|
+
if (!inside)
|
|
344
|
+
out.push(line);
|
|
345
|
+
}
|
|
346
|
+
return { kept: out.join("\n").replace(/\s+$/, ""), table };
|
|
347
|
+
}
|
|
348
|
+
// A Codex config with its [mcp_servers.<name>] table (and any of its sub-tables) replaced by the block.
|
|
349
|
+
export function replaceTomlTable(existing, name, block) {
|
|
350
|
+
const { kept } = splitTomlTable(existing, name);
|
|
351
|
+
return `${kept ? `${kept}\n\n` : ""}${block}\n`;
|
|
352
|
+
}
|
|
353
|
+
export function removeTomlTable(existing, name) {
|
|
354
|
+
const { kept } = splitTomlTable(existing, name);
|
|
355
|
+
return kept ? `${kept}\n` : "";
|
|
356
|
+
}
|
|
357
|
+
// Writes a redeemed setup where it goes; returns what it did, in words, without the token.
|
|
358
|
+
export function writeSetup(setup, opts) {
|
|
359
|
+
const done = [];
|
|
360
|
+
const named = setup.harness === "claude-code" ? null : setup.file;
|
|
361
|
+
const file = named ? expand(named, opts.home) : null;
|
|
362
|
+
if (named && !named.startsWith("~/") && tracked(named, opts.cwd)) {
|
|
363
|
+
throw new Error(`${named} is tracked by git, so the token would be committed: untrack it, or ask your person`);
|
|
364
|
+
}
|
|
365
|
+
const at = (f) => (f.startsWith("/") ? f : join(opts.cwd, f));
|
|
366
|
+
switch (setup.harness) {
|
|
367
|
+
case "cursor": {
|
|
368
|
+
const path = at(file);
|
|
369
|
+
writePrivate(path, mergeMcpJson(existsSync(path) ? readFileSync(path, "utf8") : null, setup.server, setup.json.mcpServers[setup.server]));
|
|
370
|
+
done.push(`wrote the ${setup.server} server into ${setup.file}`);
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
case "codex": {
|
|
374
|
+
const path = at(file);
|
|
375
|
+
writePrivate(path, replaceTomlTable(existsSync(path) ? readFileSync(path, "utf8") : null, setup.server, setup.toml));
|
|
376
|
+
done.push(`wrote [mcp_servers.${setup.server}] into ${setup.file}`);
|
|
377
|
+
break;
|
|
378
|
+
}
|
|
379
|
+
case "other":
|
|
380
|
+
writePrivate(at(file), `${setup.env}\n`);
|
|
381
|
+
done.push(`wrote ${setup.file}; call Gavel with: ${setup.cli}`);
|
|
382
|
+
break;
|
|
383
|
+
case "claude-code": {
|
|
384
|
+
const run = opts.run ?? ((cmd, args) => execFileSync(cmd, args, { cwd: opts.cwd, stdio: "ignore" }));
|
|
385
|
+
// The command's words, split as a shell would: only the header is quoted.
|
|
386
|
+
const words = setup.command.match(/"[^"]*"|\S+/g).map((w) => w.replace(/^"|"$/g, ""));
|
|
387
|
+
const removeWords = setup.ifExists.split(" ");
|
|
388
|
+
try {
|
|
389
|
+
run(removeWords[0], removeWords.slice(1));
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
// none there yet
|
|
393
|
+
}
|
|
394
|
+
run(words[0], words.slice(1));
|
|
395
|
+
done.push(`ran claude mcp add ${setup.server} (scope ${words[words.length - 1]})`);
|
|
396
|
+
break;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if ("gitignore" in setup && setup.gitignore) {
|
|
400
|
+
ensureGitignore(setup.gitignore, opts.cwd);
|
|
401
|
+
done.push(`.gitignore has ${setup.gitignore}`);
|
|
402
|
+
}
|
|
403
|
+
return done;
|
|
404
|
+
}
|
|
405
|
+
const literalToken = (authorization) => (typeof authorization === "string" ? (/^Bearer (gvl_\S+)$/.exec(authorization)?.[1] ?? null) : null);
|
|
406
|
+
const tomlString = (lines, key) => lines.map((l) => new RegExp(`^\\s*${key}\\s*=\\s*"([^"]*)"`).exec(l)?.[1]).find(Boolean) ?? null;
|
|
407
|
+
const envValue = (text, key) => new RegExp(`^${key}=(.*)$`, "m").exec(text)?.[1]?.trim() ?? null;
|
|
408
|
+
// The legacy entry beside the new one, if it's for this same Gavel and holds a token of its own
|
|
409
|
+
// (not ${env:…}): an entry for another Gavel can't be checked here, so it's left alone.
|
|
410
|
+
function legacyEntry(setup, legacy, opts) {
|
|
411
|
+
const at = (f) => {
|
|
412
|
+
const expanded = expand(f, opts.home);
|
|
413
|
+
return expanded.startsWith("/") ? expanded : join(opts.cwd, expanded);
|
|
414
|
+
};
|
|
415
|
+
const read = (path) => (existsSync(path) ? readFileSync(path, "utf8") : null);
|
|
416
|
+
switch (setup.harness) {
|
|
417
|
+
case "cursor": {
|
|
418
|
+
const path = at(setup.file);
|
|
419
|
+
const text = read(path);
|
|
420
|
+
const old = text ? parseMcpJson(text).mcpServers?.[legacy.server] : undefined;
|
|
421
|
+
const token = literalToken(old?.headers?.Authorization);
|
|
422
|
+
if (!token || old?.url !== setup.json.mcpServers[setup.server]?.url)
|
|
423
|
+
return null;
|
|
424
|
+
return { token, where: setup.file, remove: () => writePrivate(path, removeMcpJsonServer(read(path), legacy.server)) };
|
|
425
|
+
}
|
|
426
|
+
case "codex": {
|
|
427
|
+
const path = at(setup.file);
|
|
428
|
+
const table = splitTomlTable(read(path), legacy.server).table;
|
|
429
|
+
if (!table)
|
|
430
|
+
return null;
|
|
431
|
+
const token = /"Authorization"\s*=\s*"Bearer (gvl_[^"]+)"/.exec(table.join("\n"))?.[1];
|
|
432
|
+
if (!token || tomlString(table, "url") !== tomlString(setup.toml.split("\n"), "url"))
|
|
433
|
+
return null;
|
|
434
|
+
return { token, where: setup.file, remove: () => writePrivate(path, removeTomlTable(read(path), legacy.server)) };
|
|
435
|
+
}
|
|
436
|
+
case "other": {
|
|
437
|
+
if (!legacy.file)
|
|
438
|
+
return null;
|
|
439
|
+
const path = at(legacy.file);
|
|
440
|
+
const text = read(path);
|
|
441
|
+
const token = text && envValue(text, "GAVEL_TOKEN");
|
|
442
|
+
if (!token?.startsWith("gvl_") || envValue(text, "GAVEL_API_URL") !== envValue(setup.env, "GAVEL_API_URL"))
|
|
443
|
+
return null;
|
|
444
|
+
return { token, where: legacy.file, remove: () => unlinkSync(path) };
|
|
445
|
+
}
|
|
446
|
+
case "claude-code": {
|
|
447
|
+
// Claude Code keeps both scopes in ~/.claude.json: user at the top, local under the project.
|
|
448
|
+
const text = read(join(opts.home, ".claude.json"));
|
|
449
|
+
if (!text)
|
|
450
|
+
return null;
|
|
451
|
+
const scope = setup.ifExists.split(" ").pop();
|
|
452
|
+
let json;
|
|
453
|
+
try {
|
|
454
|
+
json = JSON.parse(text);
|
|
455
|
+
}
|
|
456
|
+
catch {
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
const servers = scope === "user" ? json.mcpServers : (json.projects?.[opts.cwd] ?? json.projects?.[realpathSync(opts.cwd)])?.mcpServers;
|
|
460
|
+
const old = servers?.[legacy.server];
|
|
461
|
+
const token = literalToken(old?.headers?.Authorization);
|
|
462
|
+
const words = setup.command.split(" ");
|
|
463
|
+
const url = words[words.indexOf(setup.server) + 1];
|
|
464
|
+
if (!token || old?.url !== url)
|
|
465
|
+
return null;
|
|
466
|
+
return { token, where: `Claude Code (scope ${scope})`, remove: () => opts.run("claude", ["mcp", "remove", legacy.server, "--scope", scope]) };
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
// An old entry named plain gavel: removed only if its token is revoked (401, as by this re-pair);
|
|
471
|
+
// any other answer means it's live, another workspace's or agent's, and it stays.
|
|
472
|
+
export async function dropLegacy(setup, legacy, opts) {
|
|
473
|
+
const run = opts.run ?? ((cmd, args) => execFileSync(cmd, args, { cwd: opts.cwd, stdio: "ignore" }));
|
|
474
|
+
const old = legacyEntry(setup, legacy, { ...opts, run });
|
|
475
|
+
if (!old)
|
|
476
|
+
return [];
|
|
477
|
+
let status = null;
|
|
478
|
+
try {
|
|
479
|
+
status = (await fetch(`${opts.apiUrl}/v1/me`, { headers: { authorization: `Bearer ${old.token}`, accept: "application/json" } })).status;
|
|
480
|
+
}
|
|
481
|
+
catch {
|
|
482
|
+
// unreachable: leave it
|
|
483
|
+
}
|
|
484
|
+
if (status === 401) {
|
|
485
|
+
old.remove();
|
|
486
|
+
return [`removed the old ${legacy.server} entry from ${old.where}: its token was revoked`];
|
|
487
|
+
}
|
|
488
|
+
if (status !== null && status < 500)
|
|
489
|
+
return [`left the old ${legacy.server} entry in ${old.where}: its token still works (another workspace's or agent's)`];
|
|
490
|
+
return [`left the old ${legacy.server} entry in ${old.where}: couldn't check its token`];
|
|
491
|
+
}
|
|
492
|
+
async function pair(argv) {
|
|
493
|
+
const { positional, flags } = parseArgs(argv);
|
|
494
|
+
const code = need(positional.join(""), "the pairing code (like 4F7K-9QX2)");
|
|
495
|
+
const harness = (flags.harness ?? detectHarness(process.env));
|
|
496
|
+
if (!HARNESSES.includes(harness))
|
|
497
|
+
throw new UsageError(`--harness is one of ${HARNESSES.join(", ")}`);
|
|
498
|
+
const base = (process.env.GAVEL_API_URL ?? "https://api.getgavel.ai").replace(/\/+$/, "");
|
|
499
|
+
const res = await fetch(`${base}/v1/pair`, {
|
|
500
|
+
method: "POST",
|
|
501
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
502
|
+
body: JSON.stringify({ code, harness, machine: flags.machine ?? hostname().split(".")[0] }),
|
|
503
|
+
});
|
|
504
|
+
const body = (await res.json().catch(() => ({})));
|
|
505
|
+
if (!res.ok) {
|
|
506
|
+
console.error(`gavel: ${body.error?.message ?? `HTTP ${res.status}`}`);
|
|
507
|
+
return 1;
|
|
508
|
+
}
|
|
509
|
+
const opts = { cwd: process.cwd(), home: homedir() };
|
|
510
|
+
const done = writeSetup(body.setup, opts);
|
|
511
|
+
if (body.legacy && body.legacy.server !== body.setup.server)
|
|
512
|
+
done.push(...(await dropLegacy(body.setup, body.legacy, { ...opts, apiUrl: base })));
|
|
513
|
+
console.log(JSON.stringify({ paired: true, kind: body.kind, agent: body.agent, harness, done, then: body.then }, null, 2));
|
|
514
|
+
return 0;
|
|
515
|
+
}
|
|
516
|
+
// One line per thing that should wake the chat: refs and Gavel's own words only, never a message's
|
|
517
|
+
// text, so the line itself is never someone else's instructions.
|
|
518
|
+
export function wakeLine(item) {
|
|
519
|
+
switch (item.kind) {
|
|
520
|
+
case "message":
|
|
521
|
+
return `GAVEL_WAKE message ${item.ref}: read it with gavel conversations ${item.ref}`;
|
|
522
|
+
case "request":
|
|
523
|
+
return `GAVEL_WAKE request ${item.type ?? ""} on ${item.ref}: see gavel inbox`;
|
|
524
|
+
case "decision":
|
|
525
|
+
return `GAVEL_WAKE decision ${item.ref} to decide: gavel get ${item.ref}`;
|
|
526
|
+
case "answer":
|
|
527
|
+
return `GAVEL_WAKE answer ${item.ref} ${item.type ?? ""}: gavel get ${item.ref}, then carry it on and act`;
|
|
528
|
+
case "clash":
|
|
529
|
+
return item.type === "under"
|
|
530
|
+
? "GAVEL_WAKE clash between agents under you: see gavel inbox, then tell one of them who gets the folder"
|
|
531
|
+
: "GAVEL_WAKE clash in your folders: see gavel inbox, and wait for the agent above to say who gets it";
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
const backoff = (failures) => Math.min(30_000, 1000 * 2 ** Math.min(failures - 1, 5));
|
|
535
|
+
// Long-polls the agent's inbox until stopped and prints wake lines on stdout, nothing else; trouble
|
|
536
|
+
// goes to stderr and it tries again. Starting takes over from any watch before it; taken over, it ends.
|
|
537
|
+
async function watch(token, as) {
|
|
538
|
+
const base = (process.env.GAVEL_API_URL ?? "https://api.getgavel.ai").replace(/\/+$/, "");
|
|
539
|
+
const id = randomUUID();
|
|
540
|
+
let start = true;
|
|
541
|
+
let failures = 0;
|
|
542
|
+
for (;;) {
|
|
543
|
+
let res;
|
|
544
|
+
try {
|
|
545
|
+
res = await fetch(`${base}/v1/inbox/watch?watch=${id}&timeout=50${start ? "&start=true" : ""}`, {
|
|
546
|
+
headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) },
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
catch (err) {
|
|
550
|
+
failures++;
|
|
551
|
+
console.error(`gavel watch: ${err instanceof Error ? err.message : String(err)}; trying again`);
|
|
552
|
+
await new Promise((r) => setTimeout(r, backoff(failures)));
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
if (res.status === 409) {
|
|
556
|
+
console.error("gavel watch: another watch for this agent took over; this one stops");
|
|
557
|
+
return 3;
|
|
558
|
+
}
|
|
559
|
+
if (res.status === 400 || res.status === 401 || res.status === 403) {
|
|
560
|
+
console.error(`gavel watch: ${await res.text()}`);
|
|
561
|
+
return 1;
|
|
562
|
+
}
|
|
563
|
+
if (!res.ok) {
|
|
564
|
+
failures++;
|
|
565
|
+
console.error(`gavel watch: HTTP ${res.status}; trying again`);
|
|
566
|
+
await new Promise((r) => setTimeout(r, backoff(failures)));
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
failures = 0;
|
|
570
|
+
start = false;
|
|
571
|
+
const { items } = (await res.json());
|
|
572
|
+
for (const item of items)
|
|
573
|
+
console.log(wakeLine(item));
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
async function main(argvIn) {
|
|
577
|
+
let request;
|
|
578
|
+
let as = null;
|
|
579
|
+
if (argvIn[0] === "pair") {
|
|
580
|
+
try {
|
|
581
|
+
return await pair(argvIn.slice(1));
|
|
582
|
+
}
|
|
583
|
+
catch (err) {
|
|
584
|
+
if (err instanceof UsageError) {
|
|
585
|
+
console.error(`gavel: ${err.message}\n\n${USAGE}`);
|
|
586
|
+
return 2;
|
|
587
|
+
}
|
|
588
|
+
console.error(`gavel: ${err instanceof Error ? err.message : String(err)}`);
|
|
589
|
+
return 1;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
try {
|
|
593
|
+
const taken = takeAs(argvIn);
|
|
594
|
+
as = taken.as ?? process.env.GAVEL_AGENT ?? null;
|
|
595
|
+
if (taken.argv[0] === "watch") {
|
|
596
|
+
const token = process.env.GAVEL_TOKEN;
|
|
597
|
+
if (!token)
|
|
598
|
+
throw new UsageError("set GAVEL_TOKEN to your agent token (gvl_agent_…)");
|
|
599
|
+
return await watch(token, as);
|
|
600
|
+
}
|
|
601
|
+
request = toRequest(taken.argv);
|
|
602
|
+
}
|
|
603
|
+
catch (err) {
|
|
604
|
+
if (!(err instanceof UsageError))
|
|
605
|
+
throw err;
|
|
606
|
+
console.error(`gavel: ${err.message}\n\n${USAGE}`);
|
|
607
|
+
return 2;
|
|
608
|
+
}
|
|
609
|
+
if (request === "help") {
|
|
610
|
+
console.log(USAGE);
|
|
611
|
+
return 0;
|
|
612
|
+
}
|
|
613
|
+
const token = process.env.GAVEL_TOKEN;
|
|
614
|
+
if (!token) {
|
|
615
|
+
console.error("gavel: set GAVEL_TOKEN to your agent token (gvl_agent_…)");
|
|
616
|
+
return 2;
|
|
617
|
+
}
|
|
618
|
+
const base = (process.env.GAVEL_API_URL ?? "https://api.getgavel.ai").replace(/\/+$/, "");
|
|
619
|
+
const res = await fetch(base + request.path, {
|
|
620
|
+
method: request.method,
|
|
621
|
+
headers: {
|
|
622
|
+
authorization: `Bearer ${token}`,
|
|
623
|
+
accept: "application/json",
|
|
624
|
+
...agentHeader(as),
|
|
625
|
+
...(request.body !== undefined ? { "content-type": "application/json" } : {}),
|
|
626
|
+
},
|
|
627
|
+
...(request.body !== undefined ? { body: JSON.stringify(request.body) } : {}),
|
|
628
|
+
});
|
|
629
|
+
const text = await res.text();
|
|
630
|
+
let out = text;
|
|
631
|
+
try {
|
|
632
|
+
out = JSON.stringify(JSON.parse(text), null, 2);
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
// not JSON: print as it came
|
|
636
|
+
}
|
|
637
|
+
if (!res.ok) {
|
|
638
|
+
console.error(out || `HTTP ${res.status}`);
|
|
639
|
+
return 1;
|
|
640
|
+
}
|
|
641
|
+
console.log(out);
|
|
642
|
+
return 0;
|
|
643
|
+
}
|
|
644
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
|
|
645
|
+
console.error(`gavel: ${err instanceof Error ? err.message : String(err)}`);
|
|
646
|
+
process.exit(1);
|
|
647
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@getgavel/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The gavel command: an agent's Gavel from a shell (pair, ask, wait, watch and the rest)",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"homepage": "https://getgavel.ai/agents",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"bin": {
|
|
9
|
+
"gavel": "dist/gavel.js"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist/gavel.js"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=24"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc -p tsconfig.json",
|
|
19
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
20
|
+
"prepack": "npm run build"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "^24.19.2",
|
|
24
|
+
"typescript": "^7.0.2"
|
|
25
|
+
}
|
|
26
|
+
}
|