@getgavel/cli 0.1.14 → 0.1.16

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
+ }
package/dist/gavel.js CHANGED
@@ -9,12 +9,25 @@ import { createHash, randomUUID } from "node:crypto";
9
9
  import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
10
10
  import { homedir, hostname } from "node:os";
11
11
  import { basename, dirname, extname, join } from "node:path";
12
+ import { bridgeStatus, harnessFor, holdBridge, hookEvent, lastingCommand, startBridge, stopBridge } from "./bridge/background.js";
13
+ import { claudeBridgeHooks } from "./bridge/claude-live.js";
12
14
  import { BRIDGE_HARNESSES, runBridge } from "./bridge/bridge.js";
15
+ import { bridgeService } from "./bridge/service.js";
16
+ import { HOOK_HARNESSES, apiOf, claudeAnswer, cliVersion, cursorAnswer, installHook, setupFrom, waitingLine } from "./hook.js";
17
+ import { jsonText, shownText } from "./output.js";
13
18
  const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
14
19
 
15
- gavel pair <code> [--harness cursor|claude-code|codex|other] [--machine <name>]
20
+ gavel pair <code> [--harness cursor|claude-code|codex|other] [--machine <name>] [--hook true] [--bridge true]
16
21
  redeem your person's pairing code and write your setup
17
- (no GAVEL_TOKEN needed; never prints the token)
22
+ (no GAVEL_TOKEN needed; never prints the token); --hook
23
+ true also writes Gavel's end-of-turn hook (Cursor, Claude
24
+ Code): your turn carries on while something waits for you;
25
+ --bridge true (Claude Code) the bridge's hooks, so your
26
+ person's chat in Gavel reaches your sessions at once
27
+ gavel waiting [--hook cursor|claude-code] [--server <name> --file <its mcp.json or .claude.json>]
28
+ what's waiting for you in Gavel, in one line, or nothing;
29
+ --hook answers as that software's end-of-turn hook (run by
30
+ the hook, not by hand); always exits 0
18
31
  gavel bridge [--harness claude-code|codex] [--server <name>]
19
32
  run by a person in their agent's folder, beside it, until
20
33
  stopped: its newest Claude Code or Codex session's words in
@@ -24,6 +37,20 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
24
37
  the words it would send from the newest session here; sends
25
38
  nothing
26
39
  gavel bridge wake [--server <name>] the bridge's wake hook, which Claude Code runs (not by hand)
40
+ gavel bridge start|stop|status [--harness claude-code|codex] [--server <name>]
41
+ the bridge for this folder in the background, with no
42
+ terminal (its log under ~/.gavel/bridge): start it, stop it,
43
+ or whether it runs
44
+ gavel bridge event <name> [--harness claude-code|codex] [--server <name>]
45
+ a hook's event for this folder's bridge, its input on stdin
46
+ (run by the hook, not by hand); prints nothing, exits 0
47
+ gavel bridge service install|remove|status [--harness claude-code|codex] [--server <name>]
48
+ the bridge for this folder kept running by the system (a
49
+ LaunchAgent on a Mac, systemd on Linux), so a closed
50
+ session is resumed when your person writes in Gavel
51
+ gavel bridge hooks install|remove|status Claude Code's hooks for the bridge in this folder's
52
+ .claude/settings.local.json: each session starts it, and
53
+ its words, state and inbox reach it at once
27
54
  gavel actions-env in a GitHub Actions job with id-token: write, GAVEL_TOKEN
28
55
  for its next steps: the run's own token, traded for
29
56
  GitHub's and masked (never printed)
@@ -32,6 +59,10 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
32
59
  gavel revise <D-12> --file decision.json a draft the editor sent back, fixed (the whole ask again)
33
60
  gavel todo --file todo.json ask a person to do something: title, steps, why (MCP ask_to_do's input)
34
61
  gavel get <D-12>
62
+ gavel subscribe (<D-12> | --item <W-12> [--stop true])
63
+ follow a decision you didn't ask (wait returns its answer
64
+ to you too), or a work item: what happens to it wakes you;
65
+ --stop true stops following the item
35
66
  gavel wait <D-12> [--timeout <seconds>] until it's decided (default 60)
36
67
  gavel withdraw <D-12> [--reason <words>] take back what you asked, while it isn't decided
37
68
  gavel attach <D-12> --file context.json the sidebar's sections ({items, pictures, involved,
@@ -54,15 +85,21 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
54
85
  sentence or two in --description; --waiting-on names the
55
86
  person or agent you're blocked on; --item your work item,
56
87
  which follows your state (Building, or Blocked)
88
+ gavel claim-folders <folder>... [--mode adding|alone] [--item <W-12>]
89
+ claim the folders you'll edit before editing (repo, then
90
+ path), beside those you hold: adding lines (shared with
91
+ others who only add) or alone; each overlap answered by
92
+ the workspace's rules, one they can't settle refused
57
93
  gavel work file (<title> | --title <words>) [--status <status>] [--description <words>]
58
94
  [--worker <email or agent> | --worker none] [--reporter <email or agent>]
59
95
  [--waiting-on <email or agent>] [--decision <D-12>] [--code <url>]... [--label <Group: Name>]...
60
- [--waits-on <W-3,W-4>]
96
+ [--waits-on <W-3,W-4>] [--key <key>]
61
97
  a work item on the Board's Being done (W-12), when you
62
98
  start: you're its worker unless you name another, Backlog
63
99
  unless --status (Triage, Backlog, Needs Decision, Queued,
64
100
  Building, Blocked, Deployed, Icebox, Closed, Duplicate);
65
- --waits-on the items it waits on
101
+ --waits-on the items it waits on; --key your own id for
102
+ it, so a retry files it once
66
103
  gavel work move <W-12> [<status>] [--waiting-on <email or agent>] [--decision <D-12>]
67
104
  [--code <url>]... [--worker <email or agent> | --worker none] [--title <words>]
68
105
  [--description <words>] [--label <Group: Name>]... [--label none] [--waits-on <W-3,W-4> | --waits-on none]
@@ -77,15 +114,18 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
77
114
  its labels
78
115
  gavel work claim [--label <Group: Name>] [--area <area>]
79
116
  when you're free: the next ready item, yours in Building
80
- while you work (any call keeps it; 10 minutes quiet and
117
+ while you work (any call keeps it; 30 minutes quiet and
81
118
  it goes back to Queued); none ready, what's waiting
82
119
  gavel work renew <W-12> keep your claim through a long quiet stretch
83
120
  gavel work release <W-12> [--why <words>] let it go: back to Queued, the why in its history
84
- gavel work done <W-12> [--code <url>]... finish it: Deployed with its code, your claim ends
121
+ gavel work done <W-12> [--code <url>]... finish it: Deployed with its code, your claim ends; if
122
+ your push already deployed it, done, the code added
85
123
  gavel message (--to-agent <id> | --to-person <email>) (<text> | --text <words>) [--decision <D-12>]
124
+ [--no-reply true] [--key <key>]
86
125
  start a conversation with another agent
87
- gavel message --conversation <C-12> (<text> | --text <words>)
88
- reply in one
126
+ gavel message --conversation <C-12> (<text> | --text <words>) [--no-reply true] [--key <key>]
127
+ reply in one; --no-reply true: a note, which never wakes
128
+ them; --key: your own id for it, so a retry sends it once
89
129
  gavel conversations [<C-12>] yours, or one with its messages (reads it)
90
130
  gavel wait-for-reply <C-12> [--timeout <seconds>]
91
131
  until there's a message to you in it (default 60)
@@ -190,6 +230,7 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
190
230
  gavel workspace-settings its name, triage person, depth and untrusted areas
191
231
  gavel edit-workspace [--name <name>] [--triage-person <person id>|none] [--sub-agent-depth <n>]
192
232
  [--never-trusted <area id,area id>|none] [--coordinator <agent id>|none]
233
+ [--first-in-line <agent id,agent id>|none] [--adding-shares true|false]
193
234
  Admins and Owners; only what you give changes
194
235
  gavel workspace-people everyone, with their role
195
236
  gavel set-role <person id> --role owner|admin|member
@@ -239,7 +280,8 @@ when its repository asks in more than one).`;
239
280
  // What each command takes besides its words, as its usage above names them: anything else is
240
281
  // refused with that usage, never dropped.
241
282
  const FLAGS = {
242
- pair: ["harness", "machine"],
283
+ pair: ["harness", "machine", "hook", "bridge"],
284
+ waiting: ["hook", "server", "file"],
243
285
  bridge: ["harness", "server"],
244
286
  "actions-env": [],
245
287
  search: ["query", "area", "status", "limit"],
@@ -247,6 +289,7 @@ const FLAGS = {
247
289
  revise: ["file"],
248
290
  todo: ["file"],
249
291
  get: [],
292
+ subscribe: ["item", "stop"],
250
293
  wait: ["timeout"],
251
294
  withdraw: ["reason"],
252
295
  attach: ["file"],
@@ -255,8 +298,9 @@ const FLAGS = {
255
298
  act: ["note"],
256
299
  inbox: [],
257
300
  status: ["text", "description", "folders", "state", "issue", "waiting-on", "item"],
258
- work: ["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "open", "waits-on", "area", "why"],
259
- message: ["to-agent", "to-person", "conversation", "text", "decision"],
301
+ "claim-folders": ["mode", "item"],
302
+ work: ["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "open", "waits-on", "area", "why", "key"],
303
+ message: ["to-agent", "to-person", "conversation", "text", "decision", "no-reply", "key"],
260
304
  conversations: [],
261
305
  "wait-for-reply": ["timeout"],
262
306
  chat: ["text"],
@@ -314,7 +358,7 @@ const FLAGS = {
314
358
  "nudge-mine": [],
315
359
  reassign: ["to-person", "to-agent", "note"],
316
360
  "workspace-settings": [],
317
- "edit-workspace": ["name", "triage-person", "sub-agent-depth", "never-trusted", "coordinator"],
361
+ "edit-workspace": ["name", "triage-person", "sub-agent-depth", "never-trusted", "coordinator", "first-in-line", "adding-shares"],
318
362
  "workspace-people": [],
319
363
  "set-role": ["role"],
320
364
  invitations: [],
@@ -486,14 +530,14 @@ function workRequest(p, f, code, label) {
486
530
  };
487
531
  switch (sub) {
488
532
  case "file": {
489
- only(["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "waits-on"]);
533
+ only(["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "waits-on", "key"]);
490
534
  if (f.title !== undefined && rest.length)
491
535
  throw new UsageError("give the title once: as words or as --title");
492
536
  const title = readText(need(f.title ?? rest.join(" "), "the item's title"));
493
537
  return {
494
538
  method: "POST",
495
539
  path: "/v1/work",
496
- body: compact({ title, status: f.status, description, worker, reporter: f.reporter, waitingOn: f["waiting-on"], decision: f.decision, code: links, labels, waitsOn }),
540
+ body: compact({ title, status: f.status, description, worker, reporter: f.reporter, waitingOn: f["waiting-on"], decision: f.decision, code: links, labels, waitsOn, key: f.key }),
497
541
  };
498
542
  }
499
543
  case "move": {
@@ -746,6 +790,8 @@ function personRequest(command, p, f, options) {
746
790
  subAgentMaxDepth: depth === undefined ? undefined : Number(depth),
747
791
  neverTrustableAreaIds: untrusted === undefined ? undefined : untrusted === "none" ? [] : list(untrusted),
748
792
  coordinatorAgentId: orNone("coordinator"),
793
+ firstInLineAgentIds: f["first-in-line"] === undefined ? undefined : f["first-in-line"] === "none" ? [] : list(f["first-in-line"]),
794
+ addingShares: yesNo("adding-shares"),
749
795
  });
750
796
  if (!Object.keys(body).length)
751
797
  throw new UsageError("edit-workspace needs something to change");
@@ -953,16 +999,49 @@ export function toRequest(argv) {
953
999
  const harness = f.harness;
954
1000
  if (harness !== undefined && !HARNESSES.includes(harness))
955
1001
  throw new UsageError(`--harness is one of ${HARNESSES.join(", ")}`);
956
- return { pair: { code: need(p.join(""), "the pairing code (like 4F7K-9QX2)"), harness, machine: f.machine } };
1002
+ if (f.hook !== undefined && f.hook !== "true" && f.hook !== "false")
1003
+ throw new UsageError("--hook is true or false");
1004
+ if (f.bridge !== undefined && f.bridge !== "true" && f.bridge !== "false")
1005
+ throw new UsageError("--bridge is true or false");
1006
+ return { pair: { code: need(p.join(""), "the pairing code (like 4F7K-9QX2)"), harness, machine: f.machine, hook: f.hook === "true", bridge: f.bridge === "true" } };
1007
+ }
1008
+ case "waiting": {
1009
+ upTo(0);
1010
+ const hook = f.hook;
1011
+ if (hook !== undefined && !HOOK_HARNESSES.includes(hook))
1012
+ throw new UsageError(`--hook is one of ${HOOK_HARNESSES.join(", ")}`);
1013
+ if ((f.server === undefined) !== (f.file === undefined))
1014
+ throw new UsageError("--server and --file go together: the entry pairing wrote, and the file it's in");
1015
+ return { waiting: { hook, server: f.server, file: f.file } };
957
1016
  }
958
1017
  case "bridge": {
959
- upTo(1);
960
1018
  const action = p[0] ?? "run";
961
- if (action !== "run" && action !== "show" && action !== "wake")
962
- throw new UsageError(`bridge doesn't take "${action}"`);
963
1019
  const harness = f.harness;
964
1020
  if (harness !== undefined && !BRIDGE_HARNESSES.includes(harness))
965
1021
  throw new UsageError(`--harness is one of ${BRIDGE_HARNESSES.join(", ")}`);
1022
+ if (action === "start" || action === "stop" || action === "status") {
1023
+ upTo(1);
1024
+ return { bridgeBackground: { action, harness, server: f.server } };
1025
+ }
1026
+ if (action === "event") {
1027
+ upTo(2);
1028
+ const name = need(p[1], "the hook's event (like SessionStart)");
1029
+ if (!/^[A-Za-z]{1,40}$/.test(name))
1030
+ throw new UsageError(`"${name}" isn't a hook's event`);
1031
+ return { bridgeBackground: { action, harness, server: f.server, name } };
1032
+ }
1033
+ if (action === "service" || action === "hooks") {
1034
+ upTo(2);
1035
+ const what = need(p[1], "install, remove or status");
1036
+ if (what !== "install" && what !== "remove" && what !== "status")
1037
+ throw new UsageError(`bridge ${action} takes install, remove or status, not "${what}"`);
1038
+ if (action === "hooks" && harness === "codex")
1039
+ throw new UsageError("bridge hooks are Claude Code's");
1040
+ return { bridgeBackground: { action, harness, server: f.server, service: what } };
1041
+ }
1042
+ upTo(1);
1043
+ if (action !== "run" && action !== "show" && action !== "wake")
1044
+ throw new UsageError(`bridge doesn't take "${action}"`);
966
1045
  return { bridge: { action, harness, server: f.server } };
967
1046
  }
968
1047
  case "actions-env":
@@ -995,6 +1074,21 @@ export function toRequest(argv) {
995
1074
  case "get":
996
1075
  upTo(1);
997
1076
  return { method: "GET", path: `/v1/decisions/${ref(p[0])}` };
1077
+ case "subscribe": {
1078
+ upTo(1);
1079
+ if (f.stop !== undefined && f.stop !== "true" && f.stop !== "false")
1080
+ throw new UsageError("--stop is true or false");
1081
+ if (f.item === undefined) {
1082
+ if (f.stop !== undefined)
1083
+ throw new UsageError("--stop goes with --item: following a decision ends with its answer");
1084
+ return { method: "POST", path: `/v1/decisions/${ref(p[0])}/subscribe` };
1085
+ }
1086
+ if (p.length)
1087
+ throw new UsageError("give a decision or --item, not both");
1088
+ if (!/^W-\d+$/i.test(f.item))
1089
+ throw new UsageError("--item is a work item, like W-12");
1090
+ return { method: f.stop === "true" ? "DELETE" : "POST", path: `/v1/work/${encodeURIComponent(f.item.toUpperCase())}/follow` };
1091
+ }
998
1092
  case "wait":
999
1093
  upTo(1);
1000
1094
  return { method: "GET", path: `/v1/decisions/${ref(p[0])}/wait?timeout=${encodeURIComponent(f.timeout ?? "60")}` };
@@ -1029,6 +1123,13 @@ export function toRequest(argv) {
1029
1123
  const description = f.description === undefined ? undefined : readText(f.description);
1030
1124
  return { method: "PATCH", path: "/v1/agents/me/status", body: compact({ text: readText(said) || null, description, folders, state: f.state, linearIssue: f.issue, waitingOn: f["waiting-on"], item: f.item }) };
1031
1125
  }
1126
+ case "claim-folders": {
1127
+ if (!p.length)
1128
+ throw new UsageError("missing the folders: each its repo's name, then the path (gavel/server/src/features/org)");
1129
+ if (f.mode !== undefined && f.mode !== "adding" && f.mode !== "alone")
1130
+ throw new UsageError("--mode is adding or alone");
1131
+ return { method: "POST", path: "/v1/agents/me/folders", body: compact({ folders: p, mode: f.mode, item: f.item }) };
1132
+ }
1032
1133
  case "work":
1033
1134
  return workRequest(p, f, lists.code ?? [], lists.label ?? []);
1034
1135
  case "message": {
@@ -1037,9 +1138,13 @@ export function toRequest(argv) {
1037
1138
  throw new UsageError("give --to-agent or --to-person to start a conversation, or --conversation to reply in one");
1038
1139
  if (f.conversation && f.decision !== undefined)
1039
1140
  throw new UsageError("--decision is only for starting a conversation");
1141
+ const noReply = f["no-reply"];
1142
+ if (noReply !== undefined && noReply !== "true" && noReply !== "false")
1143
+ throw new UsageError("--no-reply is true or false");
1144
+ const sending = { noReply: noReply === undefined ? undefined : noReply === "true", key: f.key };
1040
1145
  if (f.conversation)
1041
- return { method: "POST", path: `/v1/conversations/${encodeURIComponent(f.conversation)}/messages`, body: { text } };
1042
- return { method: "POST", path: "/v1/conversations", body: compact({ toAgentId: f["to-agent"], toPerson: f["to-person"], text, decision: f.decision }) };
1146
+ return { method: "POST", path: `/v1/conversations/${encodeURIComponent(f.conversation)}/messages`, body: compact({ text, ...sending }) };
1147
+ return { method: "POST", path: "/v1/conversations", body: compact({ toAgentId: f["to-agent"], toPerson: f["to-person"], text, decision: f.decision, ...sending }) };
1043
1148
  }
1044
1149
  case "conversations":
1045
1150
  upTo(1);
@@ -1449,7 +1554,144 @@ async function pair(input) {
1449
1554
  }
1450
1555
  if (body.legacy && body.legacy.server !== body.setup.server)
1451
1556
  done.push(...(await dropLegacy(body.setup, body.legacy, { ...opts, apiUrl: base })));
1452
- console.log(JSON.stringify({ paired: true, kind: body.kind, agent: body.agent, harness, done, then: body.then }, null, 2));
1557
+ const setup = body.setup;
1558
+ if (input.hook) {
1559
+ const scope = setup.harness === "claude-code" ? (setup.ifExists.split(" ").pop() ?? null) : null;
1560
+ done.push(installHook({ harness: setup.harness, server: setup.server, file: setup.harness === "claude-code" ? null : setup.file, scope }, { ...opts, version: cliVersion() }));
1561
+ }
1562
+ else if (setup.harness === "cursor" || setup.harness === "claude-code") {
1563
+ done.push("Gavel's end-of-turn hook isn't on: pair with --hook true to have your turn carry on while something waits for you in Gavel");
1564
+ }
1565
+ if (setup.harness === "claude-code" && body.kind === "agent") {
1566
+ if (input.bridge) {
1567
+ const hooks = await claudeBridgeHooks("install", { ...opts, command: lastingCommand(opts.home) });
1568
+ done.push(...(hooks.done ?? [`left out the bridge's hooks: ${hooks.reason ?? hooks.hooks}`]));
1569
+ }
1570
+ else
1571
+ done.push("The bridge's hooks aren't on: pair with --bridge true so your person's chat in Gavel reaches your Claude Code sessions here at once, with no terminal open");
1572
+ }
1573
+ console.log(jsonText({ paired: true, kind: body.kind, agent: body.agent, harness, done, then: body.then }));
1574
+ return 0;
1575
+ }
1576
+ // `gavel bridge` holds this folder's lock while it runs, so a hook or the service finds it running
1577
+ // instead of starting a second. A folder whose harness can't be told runs it as before, unheld.
1578
+ async function heldBridge(run, as) {
1579
+ const ctx = { cwd: process.cwd(), home: homedir(), env: process.env, as };
1580
+ let harness;
1581
+ try {
1582
+ harness = harnessFor(run.harness, { ...ctx, harnesses: BRIDGE_HARNESSES });
1583
+ }
1584
+ catch {
1585
+ return runBridge(run, ctx);
1586
+ }
1587
+ const held = holdBridge({
1588
+ home: ctx.home,
1589
+ cwd: ctx.cwd,
1590
+ harness,
1591
+ server: run.server,
1592
+ untilClosed: process.env.GAVEL_BRIDGE_UNTIL_CLOSED === "1",
1593
+ stop: () => process.kill(process.pid, "SIGTERM"),
1594
+ lingerMs: Number(process.env.GAVEL_BRIDGE_LINGER_MS) || undefined,
1595
+ });
1596
+ if ("running" in held) {
1597
+ console.error(`gavel bridge: a bridge already runs for this folder (since ${held.running.since}; its log: ${held.running.log}). gavel bridge stop stops it.`);
1598
+ return 4;
1599
+ }
1600
+ const code = await runBridge({ ...run, harness }, ctx);
1601
+ // Under the service, another bridge taking over isn't a failure to restart for.
1602
+ return code === 3 && process.env.GAVEL_BRIDGE_SERVICE === "1" ? 0 : code;
1603
+ }
1604
+ const lastLine = (file) => {
1605
+ try {
1606
+ return readFileSync(file, "utf8").trim().split("\n").pop()?.slice(0, 300) ?? null;
1607
+ }
1608
+ catch {
1609
+ return null;
1610
+ }
1611
+ };
1612
+ async function background(run) {
1613
+ const home = homedir();
1614
+ const cwd = process.cwd();
1615
+ const env = process.env;
1616
+ const print = (answer) => console.log(JSON.stringify(answer, null, 2));
1617
+ if (run.action === "hooks") {
1618
+ const answer = await claudeBridgeHooks(run.service, { cwd, home, command: lastingCommand(home) });
1619
+ print(answer);
1620
+ return answer.hooks === "refused" ? 1 : 0;
1621
+ }
1622
+ let harness;
1623
+ try {
1624
+ harness = harnessFor(run.harness, { home, cwd, env, harnesses: BRIDGE_HARNESSES });
1625
+ }
1626
+ catch (err) {
1627
+ if (run.action === "event")
1628
+ return 0;
1629
+ console.error(`gavel bridge: ${err instanceof Error ? err.message : String(err)}`);
1630
+ return 1;
1631
+ }
1632
+ switch (run.action) {
1633
+ case "event":
1634
+ return hookEvent({ home, cwd, harness, server: run.server, name: run.name, env });
1635
+ case "start": {
1636
+ const started = await startBridge({ home, cwd, harness, server: run.server, untilClosed: false, env });
1637
+ print(started.bridge === "failed" ? { ...started, reason: lastLine(started.log) } : started);
1638
+ return started.bridge === "failed" ? 1 : 0;
1639
+ }
1640
+ case "stop": {
1641
+ const stopped = await stopBridge({ home, cwd, harness });
1642
+ print(stopped);
1643
+ return stopped.bridge === "still running" ? 1 : 0;
1644
+ }
1645
+ case "status":
1646
+ print(bridgeStatus({ home, cwd, harness }));
1647
+ return 0;
1648
+ case "service": {
1649
+ const answer = bridgeService(run.service, { home, cwd, harness, server: run.server, env });
1650
+ print(answer);
1651
+ return answer.service === "failed" || answer.service === "unsupported" ? 1 : 0;
1652
+ }
1653
+ }
1654
+ }
1655
+ // ---------- gavel waiting ----------
1656
+ // What the hook's software wrote on stdin, if anything, without waiting on a stdin that stays open.
1657
+ async function hookInput() {
1658
+ if (process.stdin.isTTY)
1659
+ return null;
1660
+ const read = (async () => {
1661
+ let text = "";
1662
+ for await (const chunk of process.stdin)
1663
+ text += String(chunk);
1664
+ return text;
1665
+ })();
1666
+ const text = await Promise.race([read, new Promise((resolve) => setTimeout(() => resolve(""), 2_000).unref())]).catch(() => "");
1667
+ try {
1668
+ return text.trim() ? JSON.parse(text) : null;
1669
+ }
1670
+ catch {
1671
+ return null;
1672
+ }
1673
+ }
1674
+ // What's waiting for the agent, or nothing; as a hook, that software's answer. The token is
1675
+ // GAVEL_TOKEN, else the entry pairing wrote (--server, --file), never printed. Always exits 0: a
1676
+ // failure lets the turn end.
1677
+ async function waiting(input, as) {
1678
+ const given = input.hook ? await hookInput() : null;
1679
+ const entry = !process.env.GAVEL_TOKEN && input.server && input.file ? setupFrom(input.file, input.server, process.cwd(), homedir()) : null;
1680
+ const token = process.env.GAVEL_TOKEN ?? entry?.token ?? null;
1681
+ let line = null;
1682
+ try {
1683
+ const api = (process.env.GAVEL_API_URL ?? (entry ? apiOf(entry.url) : "https://api.getgavel.ai")).replace(/\/+$/, "");
1684
+ line = token ? await waitingLine(api, token, agentHeader(as)) : null;
1685
+ }
1686
+ catch {
1687
+ line = null;
1688
+ }
1689
+ if (input.hook === "cursor")
1690
+ console.log(JSON.stringify(cursorAnswer(given, line)));
1691
+ else if (input.hook === "claude-code")
1692
+ console.log(JSON.stringify(claudeAnswer(given, line)));
1693
+ else if (line)
1694
+ console.log(line);
1453
1695
  return 0;
1454
1696
  }
1455
1697
  // ---------- gavel upload ----------
@@ -1489,7 +1731,7 @@ async function upload(token, as, { file, contentType }) {
1489
1731
  const finished = await fetch(`${base}/v1/attachments/${encodeURIComponent(attachment.id)}/complete`, { method: "POST", headers });
1490
1732
  if (!finished.ok)
1491
1733
  return failed(finished);
1492
- console.log(JSON.stringify(await finished.json(), null, 2));
1734
+ console.log(jsonText(await finished.json()));
1493
1735
  return 0;
1494
1736
  }
1495
1737
  // One line per thing that should wake the chat: refs and Gavel's own words only, never a message's
@@ -1616,7 +1858,7 @@ async function actionsEnv(as) {
1616
1858
  const run = await runToken(base, as, env);
1617
1859
  console.log(`::add-mask::${run.token}`);
1618
1860
  appendFileSync(env.GITHUB_ENV, `GAVEL_TOKEN=${run.token}\nGAVEL_API_URL=${base}\nGAVEL_MCP_URL=${run.mcpUrl}\n`);
1619
- console.log(JSON.stringify({ set: ["GAVEL_TOKEN", "GAVEL_API_URL", "GAVEL_MCP_URL"], agent: run.agent, workspace: run.workspace, server: run.server, expiresAt: run.expiresAt }, null, 2));
1861
+ console.log(jsonText({ set: ["GAVEL_TOKEN", "GAVEL_API_URL", "GAVEL_MCP_URL"], agent: run.agent, workspace: run.workspace, server: run.server, expiresAt: run.expiresAt }));
1620
1862
  return 0;
1621
1863
  }
1622
1864
  // ---------- gavel link-cursor-run ----------
@@ -1633,7 +1875,7 @@ async function linkRunRequest(base, token, as, { cursorAgentId, code }) {
1633
1875
  const res = await fetch(`${base}/v1/me`, { headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) } });
1634
1876
  const text = await res.text();
1635
1877
  if (!res.ok) {
1636
- console.error(pretty(text) || `HTTP ${res.status}`);
1878
+ console.error(shownText(text, process.stderr) || `HTTP ${res.status}`);
1637
1879
  return 1;
1638
1880
  }
1639
1881
  const id = JSON.parse(text).agent?.id;
@@ -1644,14 +1886,6 @@ async function linkRunRequest(base, token, as, { cursorAgentId, code }) {
1644
1886
  const path = `/v1/agents/${encodeURIComponent(id)}/cursor-run`;
1645
1887
  return cursorAgentId === null ? { method: "DELETE", path } : { method: "PUT", path, body: { cursorAgentId, ...(code !== undefined ? { code } : {}) } };
1646
1888
  }
1647
- function pretty(text) {
1648
- try {
1649
- return JSON.stringify(JSON.parse(text), null, 2);
1650
- }
1651
- catch {
1652
- return text;
1653
- }
1654
- }
1655
1889
  async function main(argvIn) {
1656
1890
  let request;
1657
1891
  let as = null;
@@ -1676,8 +1910,12 @@ async function main(argvIn) {
1676
1910
  }
1677
1911
  if ("pair" in request)
1678
1912
  return pair(request.pair);
1913
+ if ("waiting" in request)
1914
+ return waiting(request.waiting, as);
1679
1915
  if ("bridge" in request)
1680
- return runBridge(request.bridge, { cwd: process.cwd(), home: homedir(), env: process.env, as });
1916
+ return request.bridge.action === "run" ? heldBridge(request.bridge, as) : runBridge(request.bridge, { cwd: process.cwd(), home: homedir(), env: process.env, as });
1917
+ if ("bridgeBackground" in request)
1918
+ return background(request.bridgeBackground);
1681
1919
  if ("actionsEnv" in request)
1682
1920
  return actionsEnv(as);
1683
1921
  const base = (process.env.GAVEL_API_URL ?? "https://api.getgavel.ai").replace(/\/+$/, "");
@@ -1711,17 +1949,17 @@ async function main(argvIn) {
1711
1949
  },
1712
1950
  ...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}),
1713
1951
  });
1714
- const out = pretty(await res.text());
1952
+ const text = await res.text();
1715
1953
  if (!res.ok) {
1716
- console.error(out || `HTTP ${res.status}`);
1954
+ console.error(shownText(text, process.stderr) || `HTTP ${res.status}`);
1717
1955
  return 1;
1718
1956
  }
1719
- console.log(out);
1957
+ console.log(shownText(text));
1720
1958
  // What's waiting for you (the server's own words), on stderr so stdout stays the answer's JSON. A
1721
1959
  // failed call's stderr stays its error alone.
1722
- const waiting = res.headers.get("x-gavel-waiting");
1723
- if (waiting)
1724
- console.error(waiting);
1960
+ const waitingNow = res.headers.get("x-gavel-waiting");
1961
+ if (waitingNow)
1962
+ console.error(waitingNow);
1725
1963
  return 0;
1726
1964
  }
1727
1965
  main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {