benignswarm 0.9.0 → 0.11.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/dist/client.js +50 -23
- package/dist/commands/agent.js +7 -1
- package/dist/commands/goal.js +55 -0
- package/dist/commands/hook.js +61 -18
- package/dist/commands/join.js +26 -3
- package/dist/commands/watch.js +56 -10
- package/dist/commands/wu.js +159 -0
- package/dist/git.js +12 -0
- package/dist/harness.js +2 -0
- package/dist/heartbeat.js +96 -0
- package/dist/help.js +14 -0
- package/dist/index.js +5 -0
- package/dist/lock.js +53 -0
- package/dist/model.js +36 -0
- package/dist/output.js +2 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/client.js
CHANGED
|
@@ -13,8 +13,13 @@ export class Client {
|
|
|
13
13
|
this.auto = auto;
|
|
14
14
|
this.agentName = agentName;
|
|
15
15
|
}
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
/**
|
|
17
|
+
* presence: send the X-Bschat-Auto header, which refreshes the agent's automatic status and
|
|
18
|
+
* marks it seen. True for commands the agent runs itself; false for polls made on its behalf
|
|
19
|
+
* by the hook or the watcher, which say nothing about whether the agent is alive.
|
|
20
|
+
*/
|
|
21
|
+
static forAgent(c, model, opts = {}) {
|
|
22
|
+
return new Client(c.url, c.key, opts.presence === false ? null : { ...collectAuto({ model, machine: c.machine }) }, c.agent);
|
|
18
23
|
}
|
|
19
24
|
static forAdmin(c) {
|
|
20
25
|
return new Client(c.url, c.key, null);
|
|
@@ -28,31 +33,50 @@ export class Client {
|
|
|
28
33
|
h["x-bschat-auto"] = JSON.stringify(this.auto);
|
|
29
34
|
return h;
|
|
30
35
|
}
|
|
31
|
-
|
|
36
|
+
/**
|
|
37
|
+
* opts.retries: how many times to retry on a network failure or a 5xx. Only safe for calls
|
|
38
|
+
* that are idempotent on the server (posts carry a client_id for exactly this reason).
|
|
39
|
+
*/
|
|
40
|
+
async call(method, path, body, opts = {}) {
|
|
32
41
|
const headers = this.headers();
|
|
33
42
|
if (body !== undefined)
|
|
34
43
|
headers["content-type"] = "application/json";
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
res
|
|
44
|
+
const retries = opts.retries ?? 0;
|
|
45
|
+
for (let attempt = 0;; attempt++) {
|
|
46
|
+
let res;
|
|
47
|
+
try {
|
|
48
|
+
res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
if (attempt < retries) {
|
|
52
|
+
await backoff(attempt);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
|
|
56
|
+
}
|
|
57
|
+
noteServerVersions(res.headers, this.agentName);
|
|
58
|
+
const text = await res.text();
|
|
59
|
+
let json;
|
|
60
|
+
try {
|
|
61
|
+
json = JSON.parse(text);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
throw new CliError("bad_response", `${method} ${path} returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
|
|
65
|
+
}
|
|
66
|
+
if (!res.ok) {
|
|
67
|
+
if (res.status >= 500 && attempt < retries) {
|
|
68
|
+
process.stderr.write(`bschat: ${method} ${path} failed (${res.status}${json?.reference ? `, reference ${json.reference}` : ""}); retrying\n`);
|
|
69
|
+
await backoff(attempt);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const err = json;
|
|
73
|
+
const hint = res.status >= 500
|
|
74
|
+
? `This is a platform failure, not something to fix on your side. Do not retry in a loop. Report it once: bschat feedback "<what you were doing>${err.reference ? ` ref ${err.reference}` : ""}" and carry on with other work.`
|
|
75
|
+
: undefined;
|
|
76
|
+
throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, hint);
|
|
77
|
+
}
|
|
78
|
+
return json;
|
|
38
79
|
}
|
|
39
|
-
catch (e) {
|
|
40
|
-
throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
|
|
41
|
-
}
|
|
42
|
-
noteServerVersions(res.headers, this.agentName);
|
|
43
|
-
const text = await res.text();
|
|
44
|
-
let json;
|
|
45
|
-
try {
|
|
46
|
-
json = JSON.parse(text);
|
|
47
|
-
}
|
|
48
|
-
catch {
|
|
49
|
-
throw new CliError("bad_response", `${method} ${path} returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
|
|
50
|
-
}
|
|
51
|
-
if (!res.ok) {
|
|
52
|
-
const err = json;
|
|
53
|
-
throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text);
|
|
54
|
-
}
|
|
55
|
-
return json;
|
|
56
80
|
}
|
|
57
81
|
wsUrl(path) {
|
|
58
82
|
return this.url.replace(/^http/, "ws") + path;
|
|
@@ -63,3 +87,6 @@ export class Client {
|
|
|
63
87
|
return ws;
|
|
64
88
|
}
|
|
65
89
|
}
|
|
90
|
+
function backoff(attempt) {
|
|
91
|
+
return new Promise((r) => setTimeout(r, Math.min(8000, 500 * 2 ** attempt)));
|
|
92
|
+
}
|
package/dist/commands/agent.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { bool, need, str } from "../args.js";
|
|
4
5
|
import { Client } from "../client.js";
|
|
@@ -142,7 +143,10 @@ export async function send(p, out) {
|
|
|
142
143
|
if (replyTo !== undefined && !/^\d+$/.test(replyTo))
|
|
143
144
|
throw new CliError("usage", "--reply-to takes the seq number of the message you are answering");
|
|
144
145
|
const project = projectOf(p, creds);
|
|
145
|
-
|
|
146
|
+
// One client id per post, reused across retries: a timeout or 5xx after the archive write
|
|
147
|
+
// returns the message that landed instead of posting it twice.
|
|
148
|
+
const clientId = randomUUID();
|
|
149
|
+
const r = await client.call("POST", `/projects/${project}/channels/${channel}/messages`, { body, reply_to: replyTo === undefined ? null : Number(replyTo), client_id: clientId }, { retries: 3 });
|
|
146
150
|
{
|
|
147
151
|
// Our own post must not count as unread for us; advance the cursor if we were caught up.
|
|
148
152
|
const st = readState(agentRef(creds));
|
|
@@ -258,9 +262,11 @@ export async function skill(p, out) {
|
|
|
258
262
|
const dir = str(p.flags, "dir") ?? join(process.cwd(), ".claude", "skills", "bschat");
|
|
259
263
|
const main = await fetchText("/skill/SKILL.md");
|
|
260
264
|
const api = await fetchText("/skill/references/api.md");
|
|
265
|
+
const watchers = await fetchText("/skill/references/watchers.md");
|
|
261
266
|
mkdirSync(join(dir, "references"), { recursive: true });
|
|
262
267
|
writeFileSync(join(dir, "SKILL.md"), main);
|
|
263
268
|
writeFileSync(join(dir, "references", "api.md"), api);
|
|
269
|
+
writeFileSync(join(dir, "references", "watchers.md"), watchers);
|
|
264
270
|
out.print(`Installed skill to ${dir}`, { dir });
|
|
265
271
|
return;
|
|
266
272
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { str } from "../args.js";
|
|
2
|
+
import { Client } from "../client.js";
|
|
3
|
+
import { agentRef, loadAgent, resolveAgentName } from "../config.js";
|
|
4
|
+
import { CliError } from "../errors.js";
|
|
5
|
+
import { heartbeatNow, HARNESS_GOAL_STATES } from "../heartbeat.js";
|
|
6
|
+
import { readState, writeState } from "../state.js";
|
|
7
|
+
/**
|
|
8
|
+
* Harness goal self-report, for harnesses whose /goal state lives where no file on this machine
|
|
9
|
+
* shows it (Codex app threads keep it in the cloud; DeepSeek exposes it through get_goal). Claude
|
|
10
|
+
* Code needs none of this: the hook reads the goal from the transcript.
|
|
11
|
+
*
|
|
12
|
+
* bschat goal set "<the /goal text>" [--state pursuing|paused|stalled|achieved|abandoned]
|
|
13
|
+
* bschat goal achieved | paused | stalled | abandoned (same text, new state)
|
|
14
|
+
* bschat goal clear
|
|
15
|
+
* bschat goal (what the server has for you)
|
|
16
|
+
*/
|
|
17
|
+
export async function goal(p, out) {
|
|
18
|
+
const sub = p.positionals[1];
|
|
19
|
+
const name = resolveAgentName(str(p.flags, "as"));
|
|
20
|
+
const creds = loadAgent(name);
|
|
21
|
+
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
22
|
+
const ref = agentRef(creds);
|
|
23
|
+
if (!sub) {
|
|
24
|
+
const path = creds.project ? `/projects/${creds.project}/agents/status` : "/account/agents/status";
|
|
25
|
+
const r = await client.call("GET", path);
|
|
26
|
+
const mine = (creds.project ? r.statuses : r.account.statuses).find((s) => s.agent_name === creds.agent);
|
|
27
|
+
const g = mine?.harness?.goal;
|
|
28
|
+
out.print(g ? `harness goal (${g.state}): ${g.text}\nstatus goal (${mine.goal_source ?? "agent"}): ${mine.goal ?? "-"}` : `no harness goal reported for ${ref}`, { harness_goal: g ?? null, goal: mine?.goal ?? null, goal_source: mine?.goal_source ?? null });
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
let next;
|
|
32
|
+
if (sub === "clear")
|
|
33
|
+
next = null;
|
|
34
|
+
else if (sub === "set") {
|
|
35
|
+
const text = p.positionals.slice(2).join(" ").trim();
|
|
36
|
+
if (!text)
|
|
37
|
+
throw new CliError("usage", 'goal set "<the goal text exactly as given to /goal>" [--state pursuing]');
|
|
38
|
+
const state = str(p.flags, "state") ?? "pursuing";
|
|
39
|
+
if (!HARNESS_GOAL_STATES.includes(state))
|
|
40
|
+
throw new CliError("usage", `--state must be one of ${HARNESS_GOAL_STATES.join(", ")}`);
|
|
41
|
+
next = { text, state: state };
|
|
42
|
+
}
|
|
43
|
+
else if (HARNESS_GOAL_STATES.includes(sub)) {
|
|
44
|
+
const last = readState(ref).harness_goal;
|
|
45
|
+
if (!last)
|
|
46
|
+
throw new CliError("no_goal", `no goal recorded on this machine to mark ${sub}`, 'Report it first: bschat goal set "<text>"');
|
|
47
|
+
next = { text: last.text, state: sub };
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
throw new CliError("usage", `goal [set <text> [--state s] | ${HARNESS_GOAL_STATES.join(" | ")} | clear]`);
|
|
51
|
+
}
|
|
52
|
+
const r = await heartbeatNow(client, "agent-report", next);
|
|
53
|
+
writeState(ref, { ...readState(ref), harness_goal: next ?? undefined });
|
|
54
|
+
out.print(next ? `reported harness goal (${next.state}): ${next.text}` : "reported: no harness goal", { status: r });
|
|
55
|
+
}
|
package/dist/commands/hook.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { str } from "../args.js";
|
|
3
3
|
import { Client } from "../client.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
|
|
5
|
+
import { heartbeatNow } from "../heartbeat.js";
|
|
6
6
|
import { fmtMessage } from "../output.js";
|
|
7
7
|
import { readState, writeState } from "../state.js";
|
|
8
|
-
import {
|
|
9
|
-
|
|
8
|
+
import { goalFromClaudeTranscript, modelFromClaudeTranscript } from "../model.js";
|
|
9
|
+
const HEARTBEAT_MS = 60_000;
|
|
10
10
|
/** Reads the harness's hook payload from stdin without blocking when there is none. */
|
|
11
11
|
function readStdinJson() {
|
|
12
12
|
try {
|
|
@@ -39,7 +39,8 @@ export async function gatherUpdates(name, opts) {
|
|
|
39
39
|
return null;
|
|
40
40
|
let messages;
|
|
41
41
|
let items = [];
|
|
42
|
-
|
|
42
|
+
// A poll on the agent's behalf: no presence header, so last_seen keeps meaning "the agent acted".
|
|
43
|
+
const client = Client.forAgent(creds, resolveModel(opts.model, process.env, process.cwd(), name), { presence: false });
|
|
43
44
|
try {
|
|
44
45
|
const qs = new URLSearchParams({ limit: "20" });
|
|
45
46
|
if (state.inbox_after)
|
|
@@ -149,9 +150,13 @@ export async function gatherUpdates(name, opts) {
|
|
|
149
150
|
export async function hook(p) {
|
|
150
151
|
const harness = p.positionals[1] ?? "plain";
|
|
151
152
|
const event = str(p.flags, "event") ?? (harness === "claude-code" ? "UserPromptSubmit" : "");
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
153
|
+
let name;
|
|
154
|
+
try {
|
|
155
|
+
name = resolveAgentName(str(p.flags, "as"));
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return; // not configured here, or ambiguous: silent by design; the agent's own commands will say so
|
|
159
|
+
}
|
|
155
160
|
// Model observation: hook input (SessionStart `model`, PostModelSwitch `to_model`) or the transcript tail.
|
|
156
161
|
const input = readStdinJson();
|
|
157
162
|
if (input) {
|
|
@@ -162,20 +167,58 @@ export async function hook(p) {
|
|
|
162
167
|
}
|
|
163
168
|
if (event === "PostModelSwitch")
|
|
164
169
|
return;
|
|
170
|
+
// Standing rules die with the context. On SessionStart (startup, resume, and after a compaction)
|
|
171
|
+
// re-deliver the role description and the project's process when the agent has not seen this
|
|
172
|
+
// version, and record that it was shown.
|
|
173
|
+
let standing = null;
|
|
174
|
+
if (harness === "claude-code" && event === "SessionStart") {
|
|
175
|
+
try {
|
|
176
|
+
const creds = loadAgent(name);
|
|
177
|
+
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
178
|
+
const me = await client.call("GET", "/me");
|
|
179
|
+
const proc = me.process;
|
|
180
|
+
const compacted = input?.source === "compact";
|
|
181
|
+
if (proc && (compacted || proc.seen_version !== proc.version)) {
|
|
182
|
+
const lines = [
|
|
183
|
+
`[bschat] ${compacted ? "Your context was compacted; here is what must survive it." : "Your standing role and process."}`,
|
|
184
|
+
me.role ? `Your role: ${me.role.name}. ${me.role.description}` : `You hold no role in ${me.project?.name ?? "this project"}.`,
|
|
185
|
+
`Process v${proc.version}: kinds of work ${proc.definition.kinds.map((t) => `${t.name} (approved by ${t.approver_role})`).join(", ")}; evidence ${proc.definition.require_evidence_to_submit ? "required" : "optional"} before review; max ${proc.definition.max_open_per_agent} open units. Work goes through bschat wu open/submit; nothing is done until approved.`,
|
|
186
|
+
proc.agreements ? `Working agreements:\n${proc.agreements}` : null,
|
|
187
|
+
].filter(Boolean);
|
|
188
|
+
standing = lines.join("\n");
|
|
189
|
+
if (creds.project && proc.version > 0)
|
|
190
|
+
await client.call("POST", `/projects/${creds.project}/process/ack`, { version: proc.version });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
process.stderr.write(`bschat: could not fetch role/process: ${e.message}\n`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
// The hook firing is proof the harness is working; tell the server, at most once a minute.
|
|
198
|
+
// The session goal (/goal) rides along from the transcript, and a change goes out at once.
|
|
199
|
+
if (harness === "claude-code") {
|
|
200
|
+
const st = readState(name);
|
|
201
|
+
const observedGoal = typeof input?.transcript_path === "string" ? goalFromClaudeTranscript(input.transcript_path) : undefined;
|
|
202
|
+
const goalChanged = observedGoal !== undefined && (JSON.stringify(observedGoal) !== JSON.stringify(st.harness_goal ?? null) || !st.harness_goal_reported);
|
|
203
|
+
if (goalChanged || Date.now() - (st.heartbeat_at ?? 0) > HEARTBEAT_MS) {
|
|
204
|
+
try {
|
|
205
|
+
await heartbeatNow(Client.forAgent(loadAgent(name), undefined, { presence: false }), "claude-code-hook", goalChanged ? observedGoal : undefined);
|
|
206
|
+
const cur = readState(name);
|
|
207
|
+
writeState(name, { ...cur, heartbeat_at: Date.now(), ...(goalChanged ? { harness_goal: observedGoal ?? undefined, harness_goal_reported: true } : {}) });
|
|
208
|
+
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
process.stderr.write(`bschat: heartbeat failed: ${e.message}\n`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
165
214
|
const u = await gatherUpdates(name, { force: !!p.flags.force, model: str(p.flags, "model") });
|
|
166
|
-
|
|
215
|
+
const text = [standing, u?.text].filter(Boolean).join("\n\n");
|
|
216
|
+
if (!text)
|
|
167
217
|
return;
|
|
168
218
|
if (harness === "claude-code") {
|
|
169
|
-
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext:
|
|
219
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } }) + "\n");
|
|
170
220
|
}
|
|
171
221
|
else {
|
|
172
|
-
process.stdout.write(
|
|
222
|
+
process.stdout.write(text + "\n");
|
|
173
223
|
}
|
|
174
224
|
}
|
|
175
|
-
function identityFromRepo() {
|
|
176
|
-
const file = findIdentityFile();
|
|
177
|
-
const vendor = detectVendor();
|
|
178
|
-
if (!file || !vendor)
|
|
179
|
-
return null;
|
|
180
|
-
return readIdentityFile(file).agents[vendor]?.name ?? null;
|
|
181
|
-
}
|
package/dist/commands/join.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { CLI_VERSION } from "../version.js";
|
|
2
|
-
import { spawnSync } from "node:child_process";
|
|
3
2
|
import { need, str, bool } from "../args.js";
|
|
4
3
|
import { agentRef, DEFAULT_URL, loadAgent, resolveModel, saveAgent } from "../config.js";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { join as pathJoin } from "node:path";
|
|
5
7
|
import { CliError } from "../errors.js";
|
|
6
8
|
import { defaultMachine } from "../git.js";
|
|
7
9
|
import { HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
|
|
@@ -17,7 +19,7 @@ async function fetchSkill(url) {
|
|
|
17
19
|
throw new CliError("fetch_failed", `${url}${p} returned ${res.status}`);
|
|
18
20
|
return res.text();
|
|
19
21
|
};
|
|
20
|
-
return { skill: await get("/skill/SKILL.md"), api: await get("/skill/references/api.md") };
|
|
22
|
+
return { skill: await get("/skill/SKILL.md"), api: await get("/skill/references/api.md"), watchers: await get("/skill/references/watchers.md") };
|
|
21
23
|
}
|
|
22
24
|
function harnessList(p, vendor) {
|
|
23
25
|
const flag = str(p.flags, "harness");
|
|
@@ -43,7 +45,8 @@ export async function setup(p, out) {
|
|
|
43
45
|
for (const h of harnessList(p, vendor))
|
|
44
46
|
written.push(...installForHarness(root, h, files, ref, creds.url));
|
|
45
47
|
const uniq = [...new Set(written)];
|
|
46
|
-
|
|
48
|
+
const selfTest = harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
|
|
49
|
+
out.print(`Recorded ${vendor} -> ${ref} in ${idPath}\nWrote: ${uniq.join(", ")}${selfTest ? `\n${selfTest}` : ""}`, { identity: idPath, written: uniq, hook_verified: !!selfTest });
|
|
47
50
|
}
|
|
48
51
|
export async function join(p, out) {
|
|
49
52
|
const name = str(p.flags, "as") ?? process.env.BSCHAT_AGENT;
|
|
@@ -88,6 +91,7 @@ export async function join(p, out) {
|
|
|
88
91
|
written.push(...installForHarness(root, h, files, ref, url));
|
|
89
92
|
written = [...new Set(written)];
|
|
90
93
|
}
|
|
94
|
+
const selfTest = !noBind && !bool(p.flags, "no-skill") && harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
|
|
91
95
|
const human = [
|
|
92
96
|
json.project
|
|
93
97
|
? `Joined project "${json.project.name}" as agent "${name}" (${vendor})${json.agent.role_name ? ` with role ${json.agent.role_name}` : ""}.`
|
|
@@ -97,6 +101,7 @@ export async function join(p, out) {
|
|
|
97
101
|
? `This repo's ${vendor} identity was left as is. Address yourself on every call: \`bschat --as ${ref} <command>\` or \`BSCHAT_AGENT=${ref} bschat <command>\`. Never run bare bschat here as ${name}.`
|
|
98
102
|
: `This repo now maps ${vendor} -> ${ref} in ${idPath}, so bschat commands here know who you are, even after a reboot.`,
|
|
99
103
|
written.length ? `Harness files written: ${written.join(", ")}` : null,
|
|
104
|
+
selfTest,
|
|
100
105
|
``,
|
|
101
106
|
`Your model is detected automatically (hook, transcript or harness config); override with --model or BSCHAT_MODEL only if it reports "unknown".`,
|
|
102
107
|
json.revived && json.resume ? `` : null,
|
|
@@ -109,6 +114,24 @@ export async function join(p, out) {
|
|
|
109
114
|
].filter((l) => l !== null).join("\n");
|
|
110
115
|
out.print(human, { agent: json.agent, project: json.project, saved: path, identity: idPath, bound: !noBind, written, revived: !!json.revived, resume: json.resume ?? null, export: { BSCHAT_AGENT: ref } });
|
|
111
116
|
}
|
|
117
|
+
/**
|
|
118
|
+
* Runs the hook command exactly as Claude Code will, with the settings file's own env, and
|
|
119
|
+
* requires it to exit 0 without an error payload. A hook that cannot run is a session that
|
|
120
|
+
* never hears a reply, and it fails silently by design, so it is checked here instead.
|
|
121
|
+
*/
|
|
122
|
+
function verifyClaudeHook(root, ref) {
|
|
123
|
+
const sp = pathJoin(root, ".claude", "settings.local.json");
|
|
124
|
+
const settings = JSON.parse(readFileSync(sp, "utf8"));
|
|
125
|
+
const cmd = settings.hooks?.SessionStart?.flatMap((g) => g.hooks ?? []).map((h) => h.command).find((c) => typeof c === "string" && c.includes("hook claude-code"));
|
|
126
|
+
if (!cmd)
|
|
127
|
+
throw new CliError("hook_missing", `${sp} has no bschat SessionStart hook after install`);
|
|
128
|
+
const r = spawnSync("sh", ["-c", cmd], { cwd: root, input: "{}", encoding: "utf8", env: { ...process.env, BSCHAT_AGENT: ref }, timeout: 60_000 });
|
|
129
|
+
const err = (r.stderr ?? "") + (r.status !== 0 ? (r.stdout ?? "") : "");
|
|
130
|
+
if (r.status !== 0 || /"error"\s*:/.test(r.stdout ?? "")) {
|
|
131
|
+
throw new CliError("hook_selftest_failed", `the installed hook failed when run as Claude Code will run it: ${cmd}`, (err.trim() || `exit ${r.status}`).slice(0, 400));
|
|
132
|
+
}
|
|
133
|
+
return `Hook verified: ran "${cmd}" successfully as ${ref}.`;
|
|
134
|
+
}
|
|
112
135
|
function writeIdentityDryRun(root, vendor, name, replace) {
|
|
113
136
|
const p = findIdentityFile(root);
|
|
114
137
|
if (!p || !p.startsWith(root))
|
package/dist/commands/watch.js
CHANGED
|
@@ -3,8 +3,11 @@ import { mkdirSync, writeFileSync } from "node:fs";
|
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { bool, str } from "../args.js";
|
|
6
|
-
import { resolveAgentName } from "../config.js";
|
|
6
|
+
import { loadAgent, resolveAgentName } from "../config.js";
|
|
7
|
+
import { Client } from "../client.js";
|
|
8
|
+
import { heartbeatIfActive, resolveActivitySource } from "../heartbeat.js";
|
|
7
9
|
import { CliError } from "../errors.js";
|
|
10
|
+
import { acquireWatchLock } from "../lock.js";
|
|
8
11
|
import { gatherUpdates } from "./hook.js";
|
|
9
12
|
import { readState, writeState } from "../state.js";
|
|
10
13
|
/**
|
|
@@ -29,6 +32,9 @@ export async function watch(p, out) {
|
|
|
29
32
|
const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
|
|
30
33
|
if (!Number.isInteger(followDelay) || followDelay < 0)
|
|
31
34
|
throw new CliError("usage", "--follow-delay must be a non-negative number of seconds");
|
|
35
|
+
const maxUnanswered = Number(str(p.flags, "max-unanswered") ?? "3");
|
|
36
|
+
if (!Number.isInteger(maxUnanswered) || maxUnanswered < 1)
|
|
37
|
+
throw new CliError("usage", "--max-unanswered must be a positive integer");
|
|
32
38
|
if (bool(p.flags, "launchd")) {
|
|
33
39
|
if (!exec)
|
|
34
40
|
throw new CliError("usage", "--launchd needs --exec so the agent knows what to run");
|
|
@@ -40,15 +46,35 @@ export async function watch(p, out) {
|
|
|
40
46
|
throw new CliError("usage", `--env ${n}: not set in this shell; run this from a terminal inside the harness (Antigravity's terminal has ANTIGRAVITY_LS_ADDRESS and ANTIGRAVITY_CSRF_TOKEN)`);
|
|
41
47
|
extraEnv[n] = v;
|
|
42
48
|
}
|
|
43
|
-
return installLaunchd(name, exec, interval, followDelay, extraEnv, out);
|
|
49
|
+
return installLaunchd(name, exec, interval, followDelay, extraEnv, str(p.flags, "activity"), out);
|
|
44
50
|
}
|
|
45
51
|
if (!exec && !once)
|
|
46
52
|
throw new CliError("usage", 'watch --exec "<command>" [--interval 30] | watch --once (print and exit) | watch --exec ... --launchd');
|
|
47
53
|
const log = (m) => process.stderr.write(`${new Date().toISOString()} bschat watch[${name}]: ${m}\n`);
|
|
54
|
+
if (!once) {
|
|
55
|
+
// Only one long-running watcher per identity on this machine; a second one exits here.
|
|
56
|
+
const release = acquireWatchLock(name);
|
|
57
|
+
const bye = (code) => { release(); process.exit(code); };
|
|
58
|
+
process.on("exit", release);
|
|
59
|
+
process.on("SIGINT", () => bye(130));
|
|
60
|
+
process.on("SIGTERM", () => bye(143));
|
|
61
|
+
}
|
|
48
62
|
log(`watching${exec ? `, will run: ${exec}` : ""} every ${interval}s (${full ? "full text" : "single wake-up"} mode)`);
|
|
63
|
+
// Harness liveness: the files the harness writes while it works, found from the wake command's
|
|
64
|
+
// session id or given with --activity. Without one the server shows this agent as "unknown"
|
|
65
|
+
// when it goes quiet, which is honest; say so once.
|
|
66
|
+
const activity = resolveActivitySource({ explicit: str(p.flags, "activity"), exec });
|
|
67
|
+
if (activity)
|
|
68
|
+
log(`harness activity source: ${activity.source} (${activity.files().length} file${activity.files().length === 1 ? "" : "s"})`);
|
|
69
|
+
else
|
|
70
|
+
log("no harness activity source found (pass --activity <file-or-dir>); liveness is reported as unknown when the agent is quiet");
|
|
71
|
+
const heartbeatClient = activity ? Client.forAgent(loadAgent(name), undefined, { presence: false }) : null;
|
|
72
|
+
let lastSample = null;
|
|
49
73
|
for (;;) {
|
|
74
|
+
if (activity && heartbeatClient)
|
|
75
|
+
lastSample = await heartbeatIfActive(heartbeatClient, activity, lastSample, interval, log);
|
|
50
76
|
if (!full) {
|
|
51
|
-
await wakeOnce(name, exec, requeueAfter, followDelay, log, str(p.flags, "model"), once);
|
|
77
|
+
await wakeOnce(name, exec, requeueAfter, followDelay, maxUnanswered, log, str(p.flags, "model"), once);
|
|
52
78
|
if (once)
|
|
53
79
|
return;
|
|
54
80
|
await new Promise((r) => setTimeout(r, interval * 1000));
|
|
@@ -77,15 +103,15 @@ export async function watch(p, out) {
|
|
|
77
103
|
await new Promise((r) => setTimeout(r, interval * 1000));
|
|
78
104
|
}
|
|
79
105
|
}
|
|
80
|
-
async function wakeOnce(name, exec, requeueAfter, followDelay, log, model, once) {
|
|
106
|
+
async function wakeOnce(name, exec, requeueAfter, followDelay, maxUnanswered, log, model, once) {
|
|
81
107
|
const state = readState(name);
|
|
82
108
|
const pending = state.watch_pending;
|
|
83
109
|
// Did the agent read since we last woke it? Its own CLI calls advance these cursors.
|
|
84
110
|
if (pending) {
|
|
85
111
|
const readSince = state.inbox_after !== pending.inbox_after || JSON.stringify(state.channel_read ?? {}) !== JSON.stringify(pending.channel_read);
|
|
86
112
|
if (readSince) {
|
|
87
|
-
writeState(name, { ...state, watch_pending: undefined });
|
|
88
|
-
log(
|
|
113
|
+
writeState(name, { ...state, watch_pending: undefined, watch_unanswered: 0, watch_dormant_logged_at: undefined });
|
|
114
|
+
log(`agent has read since the last wake-up; pending cleared${state.watch_unanswered ? " (harness is answering again)" : ""}`);
|
|
89
115
|
}
|
|
90
116
|
}
|
|
91
117
|
const u = await gatherUpdates(name, { force: true, model, delivery: "watch", dryRun: true });
|
|
@@ -100,6 +126,17 @@ async function wakeOnce(name, exec, requeueAfter, followDelay, log, model, once)
|
|
|
100
126
|
const operatorNew = u.latestOperatorAt !== null && u.latestOperatorAt !== (st.watch_operator_at ?? null);
|
|
101
127
|
const stillPending = !!st.watch_pending;
|
|
102
128
|
const stale = stillPending && Date.now() - st.watch_pending.at > requeueAfter * 1000;
|
|
129
|
+
// A thread that has ignored several wake-ups is not sleeping, it is gone (closed session, dead
|
|
130
|
+
// app). Re-queuing forever only hides that. Go dormant and say so once an hour; the agent
|
|
131
|
+
// reading anything (its own cursors moving) ends it, as does an operator writing directly.
|
|
132
|
+
const unanswered = st.watch_unanswered ?? 0;
|
|
133
|
+
if (stale && !operatorNew && unanswered >= maxUnanswered) {
|
|
134
|
+
if (Date.now() - (st.watch_dormant_logged_at ?? 0) > 3_600_000) {
|
|
135
|
+
log(`HARNESS APPEARS DEAD: ${unanswered} wake-ups went unanswered for ${Math.round(requeueAfter / 60)} min each. Not re-queuing. Pending for it: ${u.text.split("\n")[0].slice(0, 160)}. Start a new session for ${name} and re-run bschat watch --launchd with its id, or the agent reads (bschat inbox --unread) to resume.`);
|
|
136
|
+
writeState(name, { ...readState(name), watch_dormant_logged_at: Date.now() });
|
|
137
|
+
}
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
103
140
|
if (stillPending && !operatorNew && !stale) {
|
|
104
141
|
if (once)
|
|
105
142
|
log(`new activity but a wake-up is already pending (${Math.round((Date.now() - st.watch_pending.at) / 1000)}s); not queueing again`);
|
|
@@ -130,7 +167,7 @@ async function wakeOnce(name, exec, requeueAfter, followDelay, log, model, once)
|
|
|
130
167
|
`New since you last looked: ${summary}`,
|
|
131
168
|
`Run these, in order, to read it all:`,
|
|
132
169
|
...u.readCommands.map((c) => ` ${c}`),
|
|
133
|
-
`Reply in chat with bschat send, not here.`,
|
|
170
|
+
`Reply in chat with bschat send, not here. Your role and the project's process: bschat me, bschat process.`,
|
|
134
171
|
].filter(Boolean).join("\n");
|
|
135
172
|
if (exec) {
|
|
136
173
|
const total = u.counts.messages + u.counts.items + u.counts.followed + u.counts.digest;
|
|
@@ -146,7 +183,15 @@ async function wakeOnce(name, exec, requeueAfter, followDelay, log, model, once)
|
|
|
146
183
|
else {
|
|
147
184
|
process.stdout.write(wake + "\n");
|
|
148
185
|
}
|
|
149
|
-
writeState(name, {
|
|
186
|
+
writeState(name, {
|
|
187
|
+
...readState(name),
|
|
188
|
+
watch_pending: { at: Date.now(), inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
|
|
189
|
+
watch_operator_at: u.latestOperatorAt ?? st.watch_operator_at,
|
|
190
|
+
watch_followed_since: undefined,
|
|
191
|
+
watch_unanswered: stale ? unanswered + 1 : operatorNew ? unanswered : 0,
|
|
192
|
+
});
|
|
193
|
+
if (stale && unanswered + 1 >= maxUnanswered)
|
|
194
|
+
log(`${unanswered + 1} consecutive wake-ups unanswered; one more timeout and this watcher goes dormant until the agent reads`);
|
|
150
195
|
}
|
|
151
196
|
function shellQuote(s) {
|
|
152
197
|
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
@@ -160,7 +205,7 @@ function run(cmd, stdin, env) {
|
|
|
160
205
|
});
|
|
161
206
|
}
|
|
162
207
|
/** Writes a launchd agent that keeps `bschat watch` running for this identity on macOS. */
|
|
163
|
-
function installLaunchd(name, exec, interval, followDelay, extraEnv, out) {
|
|
208
|
+
function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out) {
|
|
164
209
|
if (process.platform !== "darwin")
|
|
165
210
|
throw new CliError("unsupported", "--launchd is macOS only; on Linux run `bschat watch` under a systemd user service");
|
|
166
211
|
const slug = name.replace("/", ".");
|
|
@@ -185,7 +230,8 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, out) {
|
|
|
185
230
|
<string>--as</string><string>${name}</string>
|
|
186
231
|
<string>--exec</string><string>${escapeXml(exec)}</string>
|
|
187
232
|
<string>--interval</string><string>${interval}</string>
|
|
188
|
-
<string>--follow-delay</string><string>${followDelay}</string
|
|
233
|
+
<string>--follow-delay</string><string>${followDelay}</string>${activity ? `
|
|
234
|
+
<string>--activity</string><string>${escapeXml(activity)}</string>` : ""}
|
|
189
235
|
</array>
|
|
190
236
|
<key>EnvironmentVariables</key><dict><key>PATH</key><string>${escapeXml(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin")}</string><key>HOME</key><string>${homedir()}</string>${Object.entries(extraEnv).map(([k, v]) => `<key>${escapeXml(k)}</key><string>${escapeXml(v)}</string>`).join("")}</dict>
|
|
191
237
|
<key>WorkingDirectory</key><string>${escapeXml(process.cwd())}</string>
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { str } from "../args.js";
|
|
2
|
+
import { Client } from "../client.js";
|
|
3
|
+
import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
|
|
4
|
+
import { CliError } from "../errors.js";
|
|
5
|
+
import { branchAndHead, isAncestor } from "../git.js";
|
|
6
|
+
import { table } from "../output.js";
|
|
7
|
+
/**
|
|
8
|
+
* Work units under the project's process.
|
|
9
|
+
*
|
|
10
|
+
* bschat wu open "<title>" --scope "<what it covers and does not>" [--kind t] [--tags a,b] [--evidence id,id]
|
|
11
|
+
* bschat wu submit <n> [--evidence id,id] ask for review (routed to the kind's reviewer)
|
|
12
|
+
* bschat wu approve <n> --note "..." reviewer only
|
|
13
|
+
* bschat wu changes <n> --note "..." reviewer only
|
|
14
|
+
* bschat wu reclassify <n> --kind plan [--note ...] reviewer raises the kind
|
|
15
|
+
* bschat wu done <n> [--note ...] owner, after approval
|
|
16
|
+
* bschat wu abandon <n> [--note ...]
|
|
17
|
+
* bschat wu note <n> --note "..." [--evidence id]
|
|
18
|
+
* bschat wu list [--all] [--status s] [--kind t] [--agent name]
|
|
19
|
+
* bschat wu show <n>
|
|
20
|
+
* bschat process the project's process: kinds, gates, agreements
|
|
21
|
+
*/
|
|
22
|
+
export async function wu(p, out) {
|
|
23
|
+
const sub = p.positionals[1];
|
|
24
|
+
const name = resolveAgentName(str(p.flags, "as"));
|
|
25
|
+
const creds = loadAgent(name);
|
|
26
|
+
const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name));
|
|
27
|
+
const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
|
|
28
|
+
if (!project)
|
|
29
|
+
throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
|
|
30
|
+
const base = `/projects/${project}/work-units`;
|
|
31
|
+
const list = (k) => (str(p.flags, k) ?? "").split(",").map((x) => x.trim()).filter(Boolean);
|
|
32
|
+
const num = () => {
|
|
33
|
+
const n = Number(p.positionals[2]);
|
|
34
|
+
if (!Number.isInteger(n) || n < 1)
|
|
35
|
+
throw new CliError("usage", `wu ${sub} <number>`);
|
|
36
|
+
return n;
|
|
37
|
+
};
|
|
38
|
+
const fmt = (u) => `WU #${u.number} [${u.status}] (${u.kind}) ${u.title}\n owner ${u.owner_name}${u.reviewer_name ? ` · reviewer ${u.reviewer_name}` : ""}${u.branch ? ` · ${u.branch}${u.head ? ` @ ${u.head}` : ""}` : ""}${u.pr_url ? ` · ${u.pr_url}` : ""}${u.merged_sha ? ` · merged ${u.merged_sha}` : ""}${u.evidence.length ? ` · evidence ${u.evidence.map((e) => `evidence:${e}`).join(" ")}` : ""}${u.scope ? `\n scope: ${u.scope}` : ""}`;
|
|
39
|
+
switch (sub) {
|
|
40
|
+
case "open": {
|
|
41
|
+
const title = p.positionals.slice(2).join(" ").trim();
|
|
42
|
+
if (!title)
|
|
43
|
+
throw new CliError("usage", 'wu open "<title>" --scope "<what it covers and does not>" [--kind t] [--tags a,b] [--evidence id]');
|
|
44
|
+
const r = await client.call("POST", base, { title, scope: str(p.flags, "scope") ?? "", kind: str(p.flags, "kind"), tags: list("tags"), evidence: list("evidence"), ...branchAndHead() });
|
|
45
|
+
out.print(`${fmt(r.unit)}\nSubmit for review when ready: bschat wu submit ${r.unit.number} --evidence <id>`, r);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
case "submit": {
|
|
49
|
+
// The process may require the branch to contain the target; that is a local git fact, so
|
|
50
|
+
// the CLI checks it here and tells the server what it found. No check, no claim.
|
|
51
|
+
const proc = (await client.call("GET", `/projects/${project}/process`)).process.definition;
|
|
52
|
+
const where = branchAndHead();
|
|
53
|
+
let rebased = null;
|
|
54
|
+
if (proc.merge.require_rebased) {
|
|
55
|
+
if (!where.head)
|
|
56
|
+
throw new CliError("not_a_repo", "this project's process requires a rebased branch before review, but the current directory is not a git repository", "Run bschat wu submit from the worktree that holds the work.");
|
|
57
|
+
rebased = isAncestor(proc.merge.target_branch, "HEAD");
|
|
58
|
+
if (rebased === null)
|
|
59
|
+
throw new CliError("no_target_branch", `cannot find ${proc.merge.target_branch} in this repository to check against`, `git fetch origin ${proc.merge.target_branch}:${proc.merge.target_branch}, then submit again`);
|
|
60
|
+
if (!rebased)
|
|
61
|
+
throw new CliError("not_rebased", `${where.branch ?? "HEAD"} does not contain ${proc.merge.target_branch}; the process requires it before review`, `git rebase ${proc.merge.target_branch} (or merge it in), re-run your checks, then: bschat wu submit ${num()}`);
|
|
62
|
+
}
|
|
63
|
+
const pr = str(p.flags, "pr") ?? null;
|
|
64
|
+
const r = await client.call("POST", `${base}/${num()}/submit`, { evidence: list("evidence"), ...where, pr_url: pr, rebased });
|
|
65
|
+
out.print(`${fmt(r.unit)}\nRouted to @${r.unit.reviewer_name} (${r.unit.approver_role}); you will be told in chat when it is reviewed.`, r);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
case "approve":
|
|
69
|
+
case "changes": {
|
|
70
|
+
const note = str(p.flags, "note");
|
|
71
|
+
if (!note)
|
|
72
|
+
throw new CliError("usage", `wu ${sub} <n> --note "what you checked, or what must change"`);
|
|
73
|
+
const r = await client.call("POST", `${base}/${num()}/${sub}`, { note });
|
|
74
|
+
out.print(fmt(r.unit), r);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
case "bump":
|
|
78
|
+
case "reclassify": {
|
|
79
|
+
const kind = str(p.flags, "kind");
|
|
80
|
+
if (!kind)
|
|
81
|
+
throw new CliError("usage", "wu reclassify <n> --kind <higher kind> [--note ...]");
|
|
82
|
+
const r = await client.call("POST", `${base}/${num()}/reclassify`, { kind, note: str(p.flags, "note") ?? "" });
|
|
83
|
+
out.print(fmt(r.unit), r);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
case "done": {
|
|
87
|
+
// The merge commit is the proof the work landed; verify it is on the target branch here.
|
|
88
|
+
const proc = (await client.call("GET", `/projects/${project}/process`)).process.definition;
|
|
89
|
+
const merged = str(p.flags, "merged") ?? null;
|
|
90
|
+
if (merged) {
|
|
91
|
+
const on = isAncestor(merged, proc.merge.target_branch);
|
|
92
|
+
if (on === null)
|
|
93
|
+
throw new CliError("unknown_commit", `cannot verify ${merged} against ${proc.merge.target_branch} in this repository`, `Run from the repo with ${proc.merge.target_branch} fetched: git fetch origin ${proc.merge.target_branch}:${proc.merge.target_branch}`);
|
|
94
|
+
if (!on)
|
|
95
|
+
throw new CliError("not_merged", `${merged} is not on ${proc.merge.target_branch}`, "Merge first, then pass the merge commit (or the branch head once it is on the target).");
|
|
96
|
+
}
|
|
97
|
+
else if (proc.merge.require_merge_commit) {
|
|
98
|
+
throw new CliError("usage", `this project's process requires the merge commit: bschat wu done ${num()} --merged <sha>`);
|
|
99
|
+
}
|
|
100
|
+
const r = await client.call("POST", `${base}/${num()}/done`, { note: str(p.flags, "note") ?? "", merged });
|
|
101
|
+
out.print(fmt(r.unit), r);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
case "abandon": {
|
|
105
|
+
const r = await client.call("POST", `${base}/${num()}/abandon`, { note: str(p.flags, "note") ?? "" });
|
|
106
|
+
out.print(fmt(r.unit), r);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
case "note": {
|
|
110
|
+
const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence") });
|
|
111
|
+
out.print(fmt(r.unit), r);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
case "show": {
|
|
115
|
+
const r = await client.call("GET", `${base}/${num()}`);
|
|
116
|
+
const events = r.events.map((e) => ` ${e.at.slice(0, 16).replace("T", " ")} ${e.type.padEnd(18)} ${e.actor_name}${e.note ? `: ${e.note}` : ""}`).join("\n");
|
|
117
|
+
out.print(`${fmt(r.unit)}\n${events}`, r);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
case "list":
|
|
121
|
+
case undefined: {
|
|
122
|
+
const qs = new URLSearchParams();
|
|
123
|
+
if (p.flags.all)
|
|
124
|
+
qs.set("all", "1");
|
|
125
|
+
for (const k of ["status", "kind", "agent"])
|
|
126
|
+
if (str(p.flags, k))
|
|
127
|
+
qs.set(k, str(p.flags, k));
|
|
128
|
+
const r = await client.call("GET", `${base}${qs.size ? `?${qs}` : ""}`);
|
|
129
|
+
const rows = r.units.map((u) => ({ n: `#${u.number}`, status: u.status, kind: u.kind, owner: u.owner_name, reviewer: u.reviewer_name ?? "-", title: u.title.slice(0, 60) }));
|
|
130
|
+
out.print(rows.length ? table(rows, ["n", "status", "kind", "owner", "reviewer", "title"]) : "(no open work units; bschat wu list --all for closed ones)", r);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
default:
|
|
134
|
+
throw new CliError("usage", "wu open|submit|approve|changes|reclassify|done|abandon|note|show|list");
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** The project's process: what a unit needs, who reviews which kind, and the working agreements. */
|
|
138
|
+
export async function processCmd(p, out) {
|
|
139
|
+
const name = resolveAgentName(str(p.flags, "as"));
|
|
140
|
+
const creds = loadAgent(name);
|
|
141
|
+
const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name));
|
|
142
|
+
const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
|
|
143
|
+
if (!project)
|
|
144
|
+
throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
|
|
145
|
+
const r = await client.call("GET", `/projects/${project}/process`);
|
|
146
|
+
const d = r.process.definition;
|
|
147
|
+
const lines = [
|
|
148
|
+
`Process v${r.process.version}${r.process.version === 0 ? " (defaults; the operator has not published one)" : ""}`,
|
|
149
|
+
`Kinds (lowest first): ${d.kinds.map((t) => `${t.name} -> reviewed by role ${t.approver_role}`).join("; ")}`,
|
|
150
|
+
d.kind_rules.length ? `Kind rules: ${d.kind_rules.map((x) => `tag "${x.tag}" is at least ${x.min_kind}`).join("; ")}` : null,
|
|
151
|
+
`A work unit needs: a title${d.require_scope ? ", a scope statement" : ""}${d.require_evidence_to_submit ? ", evidence before review" : ""}. Done requires approval by the kind's reviewer.`,
|
|
152
|
+
`Review SLA ${d.review_sla_minutes} min, escalates a kind after ${d.escalate_after_minutes} min. Max ${d.max_open_per_agent} open units per agent. Announcements in #${d.channel}.`,
|
|
153
|
+
`Merging: ${d.merge.merged_by === "owner" ? "the owner" : d.merge.merged_by === "approver" ? "the approver" : `a ${d.merge.integrator_role}`} merges approved work into ${d.merge.target_branch}${d.merge.require_rebased ? "; the branch must contain " + d.merge.target_branch + " before review" : ""}${d.merge.require_merge_commit ? "; done carries the merge commit (bschat wu done <n> --merged <sha>)" : ""}.`,
|
|
154
|
+
r.process.agreements ? `\nWorking agreements:\n${r.process.agreements}` : null,
|
|
155
|
+
].filter(Boolean);
|
|
156
|
+
out.print(lines.join("\n"), r);
|
|
157
|
+
if (creds.project && r.process.version > 0)
|
|
158
|
+
await client.call("POST", `/projects/${project}/process/ack`, { version: r.process.version });
|
|
159
|
+
}
|
package/dist/git.js
CHANGED
|
@@ -25,3 +25,15 @@ export function defaultMachine(label) {
|
|
|
25
25
|
const h = hostname();
|
|
26
26
|
return label ? `${h}/${label}` : h;
|
|
27
27
|
}
|
|
28
|
+
/** True when `ancestor` is reachable from `ref` in the repo at cwd; null when either is unknown to git. */
|
|
29
|
+
export function isAncestor(ancestor, ref, cwd = process.cwd()) {
|
|
30
|
+
if (git(["rev-parse", "--verify", "-q", `${ancestor}^{commit}`], cwd) === null || git(["rev-parse", "--verify", "-q", `${ref}^{commit}`], cwd) === null)
|
|
31
|
+
return null;
|
|
32
|
+
const r = spawnSync("git", ["merge-base", "--is-ancestor", ancestor, ref], { cwd, stdio: "ignore" });
|
|
33
|
+
return r.status === 0;
|
|
34
|
+
}
|
|
35
|
+
/** Branch and short head of the worktree at cwd, or nulls outside a repo. */
|
|
36
|
+
export function branchAndHead(cwd = process.cwd()) {
|
|
37
|
+
const a = collectAuto({ model: undefined, machine: "", cwd });
|
|
38
|
+
return { branch: a.branch, head: a.head };
|
|
39
|
+
}
|
package/dist/harness.js
CHANGED
|
@@ -103,6 +103,7 @@ export function installForHarness(root, harness, files, agentName, apiUrl) {
|
|
|
103
103
|
mkdirSync(join(neutral, "references"), { recursive: true });
|
|
104
104
|
writeFileSync(join(neutral, "SKILL.md"), files.skill);
|
|
105
105
|
writeFileSync(join(neutral, "references", "api.md"), files.api);
|
|
106
|
+
writeFileSync(join(neutral, "references", "watchers.md"), files.watchers);
|
|
106
107
|
written.push(join(neutral, "SKILL.md"));
|
|
107
108
|
switch (harness) {
|
|
108
109
|
case "claude-code": {
|
|
@@ -110,6 +111,7 @@ export function installForHarness(root, harness, files, agentName, apiUrl) {
|
|
|
110
111
|
mkdirSync(join(dir, "references"), { recursive: true });
|
|
111
112
|
writeFileSync(join(dir, "SKILL.md"), files.skill);
|
|
112
113
|
writeFileSync(join(dir, "references", "api.md"), files.api);
|
|
114
|
+
writeFileSync(join(dir, "references", "watchers.md"), files.watchers);
|
|
113
115
|
written.push(join(dir, "SKILL.md"));
|
|
114
116
|
const sp = join(root, ".claude", "settings.local.json");
|
|
115
117
|
let settings = {};
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
export const HARNESS_GOAL_STATES = ["pursuing", "paused", "stalled", "achieved", "abandoned"];
|
|
5
|
+
const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
|
|
6
|
+
/** Recursively lists files under dir whose name satisfies the predicate. */
|
|
7
|
+
function walk(dir, pred, depth = 6) {
|
|
8
|
+
if (depth < 0 || !existsSync(dir))
|
|
9
|
+
return [];
|
|
10
|
+
const out = [];
|
|
11
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
12
|
+
const p = join(dir, e.name);
|
|
13
|
+
if (e.isDirectory())
|
|
14
|
+
out.push(...walk(p, pred, depth - 1));
|
|
15
|
+
else if (pred(e.name))
|
|
16
|
+
out.push(p);
|
|
17
|
+
}
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Picks the activity source for a watcher from the harness's own files. Explicit `--activity`
|
|
22
|
+
* wins (a file or a directory; a directory means every file in it). Otherwise the session id
|
|
23
|
+
* in the wake command locates the Codex rollout or the Antigravity conversation store. Returns
|
|
24
|
+
* null when nothing is known, and the watcher says so once, so liveness stays "unknown" rather
|
|
25
|
+
* than wrong.
|
|
26
|
+
*/
|
|
27
|
+
export function resolveActivitySource(opts) {
|
|
28
|
+
const home = opts.home ?? homedir();
|
|
29
|
+
if (opts.explicit) {
|
|
30
|
+
const p = opts.explicit;
|
|
31
|
+
return {
|
|
32
|
+
source: `file:${p}`,
|
|
33
|
+
files: () => (existsSync(p) && statSync(p).isDirectory() ? walk(p, () => true, 1) : existsSync(p) ? [p] : []),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const id = opts.exec ? UUID.exec(opts.exec)?.[0]?.toLowerCase() : undefined;
|
|
37
|
+
if (!id)
|
|
38
|
+
return null;
|
|
39
|
+
const codexDir = join(home, ".codex", "sessions");
|
|
40
|
+
const codex = walk(codexDir, (n) => n.endsWith(`-${id}.jsonl`));
|
|
41
|
+
if (codex.length)
|
|
42
|
+
return { source: "codex-rollout", files: () => codex };
|
|
43
|
+
const agDir = join(home, ".gemini", "antigravity", "conversations");
|
|
44
|
+
const ag = () => walk(agDir, (n) => n.startsWith(id), 0);
|
|
45
|
+
if (ag().length)
|
|
46
|
+
return { source: "antigravity-conversation", files: ag };
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
/** Newest mtime and total size across the source's files; null when none exist yet. */
|
|
50
|
+
export function sampleActivity(src) {
|
|
51
|
+
let newest = 0;
|
|
52
|
+
let bytes = 0;
|
|
53
|
+
for (const f of src.files()) {
|
|
54
|
+
try {
|
|
55
|
+
const st = statSync(f);
|
|
56
|
+
newest = Math.max(newest, st.mtimeMs);
|
|
57
|
+
bytes += st.size;
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
/* file vanished between listing and stat: not activity */
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return newest ? { active_at: new Date(newest).toISOString(), bytes } : null;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Compares a fresh sample with the previous one and sends a heartbeat only when the harness
|
|
67
|
+
* moved. Returns the sample to keep for the next round. The client must be a non-presence one:
|
|
68
|
+
* a heartbeat describes the harness, not the agent.
|
|
69
|
+
*/
|
|
70
|
+
export async function heartbeatIfActive(client, src, prev, windowSeconds, log) {
|
|
71
|
+
const cur = sampleActivity(src);
|
|
72
|
+
if (!cur)
|
|
73
|
+
return prev;
|
|
74
|
+
if (prev && cur.active_at === prev.active_at && cur.bytes === prev.bytes)
|
|
75
|
+
return cur;
|
|
76
|
+
// Size can shrink (SQLite WAL checkpoints, log rotation); only growth is reported as throughput.
|
|
77
|
+
const delta = prev ? Math.max(0, cur.bytes - prev.bytes) : 0;
|
|
78
|
+
try {
|
|
79
|
+
await client.call("POST", "/agents/me/heartbeat", { active_at: cur.active_at, source: src.source, activity: { window_seconds: windowSeconds, bytes: delta } });
|
|
80
|
+
}
|
|
81
|
+
catch (e) {
|
|
82
|
+
log(`heartbeat failed: ${e.message}`);
|
|
83
|
+
}
|
|
84
|
+
return cur;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The hook variant: the hook running is itself the evidence, so report now, throttled by the
|
|
88
|
+
* caller. `goal` undefined means "unknown, keep what you have"; null means "no goal is set".
|
|
89
|
+
*/
|
|
90
|
+
export async function heartbeatNow(client, source, goal) {
|
|
91
|
+
const body = { active_at: new Date().toISOString(), source, activity: null };
|
|
92
|
+
if (goal !== undefined)
|
|
93
|
+
body.goal = goal;
|
|
94
|
+
const r = await client.call("POST", "/agents/me/heartbeat", body);
|
|
95
|
+
return r.status;
|
|
96
|
+
}
|
package/dist/help.js
CHANGED
|
@@ -28,6 +28,15 @@ Agent commands
|
|
|
28
28
|
bschat inbox [--unread] [--after <iso-time>] [--limit n] mentions of you and replies to your messages
|
|
29
29
|
bschat follow <channel> | unfollow <channel> | following followed channels' new messages are injected by the hook;
|
|
30
30
|
other channels appear as a one-line unread digest
|
|
31
|
+
bschat process the project's process: kinds of work, who approves what, requirements, working agreements
|
|
32
|
+
bschat wu open "<title>" --scope "..." [--kind k] [--tags a,b] [--evidence id] open a work unit under the process
|
|
33
|
+
bschat wu submit <n> [--evidence id] [--pr url] ask for review; records branch@head, checks rebase if required
|
|
34
|
+
bschat wu approve|changes <n> --note ".." approver verdicts (role-checked); reclassify <n> --kind k changes the kind
|
|
35
|
+
bschat wu done <n> --merged <sha> after approval; the CLI verifies the sha is on the target branch
|
|
36
|
+
bschat wu abandon <n> [--note ..] wu list [--all] / wu show <n> for state and timeline
|
|
37
|
+
bschat goal [set "<text>" [--state s] | achieved | paused | stalled | abandoned | clear]
|
|
38
|
+
report your harness's /goal so the board shows what you are held to (Codex app
|
|
39
|
+
threads and DeepSeek keep it where no file shows it; Claude Code's hook reads it itself)
|
|
31
40
|
bschat hook claude-code [--event E] harness hook: prints new inbox items as hook JSON (installed by join)
|
|
32
41
|
bschat watch --exec "<cmd>" [--interval 30] event bridge: queue ONE short wake-up when something new arrives and
|
|
33
42
|
nothing more until the agent has read (bschat inbox --unread). A human operator's
|
|
@@ -37,6 +46,11 @@ Agent commands
|
|
|
37
46
|
--env A,B copies those variables from this shell into the LaunchAgent (Antigravity needs
|
|
38
47
|
ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once / --launchd.
|
|
39
48
|
Codex: bschat watch --exec "codex queue --thread <id> --message {summary}" --launchd
|
|
49
|
+
--max-unanswered N (default 3): after N re-wakes with no read, stop queueing and log
|
|
50
|
+
HARNESS APPEARS DEAD once an hour, until the agent reads or an operator writes.
|
|
51
|
+
Liveness: the watcher reports harness activity (Codex rollout / Antigravity conversation
|
|
52
|
+
found from the session id in --exec, or --activity <file-or-dir>) so you are not shown
|
|
53
|
+
as stale while working. Polls by the watcher or hook never count as "seen".
|
|
40
54
|
bschat activity [--account] [--after <iso>] [--limit n] merged timeline: messages, status, evidence
|
|
41
55
|
bschat projects projects you can access
|
|
42
56
|
bschat channels
|
package/dist/index.js
CHANGED
|
@@ -9,6 +9,8 @@ import { handoffs, retire } from "./commands/retire.js";
|
|
|
9
9
|
import { item, list, lists } from "./commands/lists.js";
|
|
10
10
|
import { watch } from "./commands/watch.js";
|
|
11
11
|
import { feedback } from "./commands/feedback.js";
|
|
12
|
+
import { goal } from "./commands/goal.js";
|
|
13
|
+
import { processCmd, wu } from "./commands/wu.js";
|
|
12
14
|
import { CliError } from "./errors.js";
|
|
13
15
|
import { HELP } from "./help.js";
|
|
14
16
|
import { CLI_VERSION } from "./version.js";
|
|
@@ -41,6 +43,9 @@ const COMMANDS = {
|
|
|
41
43
|
item,
|
|
42
44
|
watch,
|
|
43
45
|
feedback,
|
|
46
|
+
goal,
|
|
47
|
+
wu,
|
|
48
|
+
process: processCmd,
|
|
44
49
|
follow: a.followCmd,
|
|
45
50
|
unfollow: a.followCmd,
|
|
46
51
|
following: a.followCmd,
|
package/dist/lock.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { mkdirSync, openSync, closeSync, readFileSync, unlinkSync, writeSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { configRoot } from "./config.js";
|
|
4
|
+
import { CliError } from "./errors.js";
|
|
5
|
+
/**
|
|
6
|
+
* One watcher per identity per machine. Two watchers for the same agent double every wake-up
|
|
7
|
+
* and fight over the shared cursor state, which is exactly what happened when a plist was
|
|
8
|
+
* renamed and the old one was left loaded. The lock is a pid file created with O_EXCL, so the
|
|
9
|
+
* check-and-create is atomic; a file whose pid is dead is a crash leftover and is replaced.
|
|
10
|
+
*/
|
|
11
|
+
export function lockPath(ref, env = process.env) {
|
|
12
|
+
return join(configRoot(env), "locks", `watch.${ref.replace("/", ".")}.pid`);
|
|
13
|
+
}
|
|
14
|
+
function alive(pid) {
|
|
15
|
+
try {
|
|
16
|
+
process.kill(pid, 0);
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
catch (e) {
|
|
20
|
+
return e.code === "EPERM"; // exists but not ours
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Takes the lock or throws `watch_running`. Returns the release function; call it on every exit path. */
|
|
24
|
+
export function acquireWatchLock(ref, env = process.env, pid = process.pid) {
|
|
25
|
+
const p = lockPath(ref, env);
|
|
26
|
+
mkdirSync(join(p, ".."), { recursive: true });
|
|
27
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
28
|
+
try {
|
|
29
|
+
const fd = openSync(p, "wx");
|
|
30
|
+
writeSync(fd, `${pid}\n`);
|
|
31
|
+
closeSync(fd);
|
|
32
|
+
return () => {
|
|
33
|
+
try {
|
|
34
|
+
if (readFileSync(p, "utf8").trim() === String(pid))
|
|
35
|
+
unlinkSync(p);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
/* already gone */
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
catch (e) {
|
|
43
|
+
if (e.code !== "EEXIST")
|
|
44
|
+
throw e;
|
|
45
|
+
const holder = Number(readFileSync(p, "utf8").trim());
|
|
46
|
+
if (Number.isInteger(holder) && holder > 0 && alive(holder)) {
|
|
47
|
+
throw new CliError("watch_running", `a watcher for ${ref} is already running (pid ${holder})`, `Stop it first: kill ${holder}, or launchctl bootout gui/$(id -u)/org.benignswarm.watch.${ref.replace("/", ".")} if launchd started it. Lock file: ${p}`);
|
|
48
|
+
}
|
|
49
|
+
unlinkSync(p); // stale: the process that wrote it is gone
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
throw new CliError("watch_running", `could not take the watcher lock for ${ref}`, `Lock file: ${p}`);
|
|
53
|
+
}
|
package/dist/model.js
CHANGED
|
@@ -97,3 +97,39 @@ export function resolveModelDetailed(opts) {
|
|
|
97
97
|
return { model: opts.identityModel, source: "identity" };
|
|
98
98
|
return { model: "unknown", source: "unknown" };
|
|
99
99
|
}
|
|
100
|
+
/**
|
|
101
|
+
* The session goal from Claude Code's transcript: the newest `goal_status` attachment
|
|
102
|
+
* (`condition`, `met`) or a newer `/goal clear`. undefined when the tail shows nothing about
|
|
103
|
+
* goals; null when the newest record says it was cleared.
|
|
104
|
+
*/
|
|
105
|
+
export function goalFromClaudeTranscript(transcriptPath) {
|
|
106
|
+
try {
|
|
107
|
+
if (!existsSync(transcriptPath))
|
|
108
|
+
return undefined;
|
|
109
|
+
const size = statSync(transcriptPath).size;
|
|
110
|
+
const want = Math.min(size, 512 * 1024);
|
|
111
|
+
const fd = openSync(transcriptPath, "r");
|
|
112
|
+
const buf = Buffer.alloc(want);
|
|
113
|
+
readSync(fd, buf, 0, want, size - want);
|
|
114
|
+
const lines = buf.toString("utf8").split("\n").reverse();
|
|
115
|
+
for (const line of lines) {
|
|
116
|
+
if (!line.includes("goal_status") && !line.includes('"command":"goal"'))
|
|
117
|
+
continue;
|
|
118
|
+
try {
|
|
119
|
+
const obj = JSON.parse(line);
|
|
120
|
+
if (obj.attachment?.type === "goal_status" && typeof obj.attachment.condition === "string") {
|
|
121
|
+
return { text: obj.attachment.condition, state: obj.attachment.met ? "achieved" : "pursuing" };
|
|
122
|
+
}
|
|
123
|
+
if (obj.commandRun?.command === "goal" && (obj.commandRun.args ?? "").trim() === "clear")
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
/* partial first line of the tail window */
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
}
|
package/dist/output.js
CHANGED
|
@@ -16,7 +16,7 @@ export function fmtMessage(m) {
|
|
|
16
16
|
}
|
|
17
17
|
export function fmtStatus(s) {
|
|
18
18
|
const parts = [
|
|
19
|
-
`${s.agent_name}${s.role_name ? `[${s.role_name}]` : ""}${s.
|
|
19
|
+
`${s.agent_name}${s.role_name ? `[${s.role_name}]` : ""}${s.liveness === "quiet" ? " (quiet: harness went silent)" : s.liveness === "unknown" ? " (stale, harness unmonitored)" : ""}`,
|
|
20
20
|
`state=${s.state ?? "-"}`,
|
|
21
21
|
s.goal ? `goal="${s.goal}"` : null,
|
|
22
22
|
s.task ? `task="${s.task}"` : null,
|
|
@@ -26,6 +26,7 @@ export function fmtStatus(s) {
|
|
|
26
26
|
s.branch ? `branch=${s.branch}${s.dirty ? "*" : ""}@${s.head ?? "?"}` : null,
|
|
27
27
|
s.worktree ? `worktree=${s.worktree}` : null,
|
|
28
28
|
`seen=${s.last_seen}`,
|
|
29
|
+
s.harness ? `harness_active=${s.harness.active_at}` : null,
|
|
29
30
|
].filter(Boolean);
|
|
30
31
|
return parts.join(" ");
|
|
31
32
|
}
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.
|
|
1
|
+
export const CLI_VERSION = "0.11.0";
|