@elecnix/bellwether 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -6
- package/dist/cli.js +2 -1
- package/dist/core/adopt.js +59 -0
- package/dist/core/brief.js +61 -0
- package/dist/core/child-lock.js +84 -0
- package/dist/core/classifier.js +38 -4
- package/dist/core/herdr-client.js +24 -10
- package/dist/core/inactivity.js +31 -0
- package/dist/core/label.js +7 -0
- package/dist/core/machine.js +134 -0
- package/dist/core/mcp-config.js +47 -0
- package/dist/core/outbox.js +72 -7
- package/dist/core/paths.js +14 -0
- package/dist/core/registry.js +40 -4
- package/dist/core/report.js +48 -3
- package/dist/core/resume.js +210 -0
- package/dist/core/retire.js +416 -0
- package/dist/core/send.js +17 -0
- package/dist/core/spawn-resume.js +96 -0
- package/dist/core/spawn.js +140 -42
- package/dist/core/startup-dialogs.js +120 -0
- package/dist/core/transcript.js +8 -0
- package/dist/core/types.js +2 -1
- package/dist/core/watcher.js +317 -89
- package/dist/daemon/client.js +90 -8
- package/dist/daemon/main.js +6 -0
- package/dist/daemon/protocol.js +17 -3
- package/dist/daemon/server.js +1 -1
- package/dist/daemon/service.js +8 -4
- package/dist/integrations/claude/channel.js +17 -5
- package/dist/integrations/pi/extension.js +5 -3
- package/dist/integrations/tools.js +135 -41
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ The MVP covers Pi and Claude Code, each as a parent and as a child.
|
|
|
8
8
|
|
|
9
9
|
A parent session runs an adapter: a Pi extension, or a Claude Code MCP channel server. Both are clients of one local daemon that runs the Bellwether core. The daemon starts on demand from the first session that needs it, and one daemon serves every session on the machine. When a session resumes, it receives the events it missed. With nothing left to watch, the daemon exits.
|
|
10
10
|
|
|
11
|
-
- **Daemon.** One per machine, on a socket under the Bellwether home. A lock file and a version handshake keep a second client from starting a second daemon. When a client is newer than the daemon it found, the client sends a drain request and the old daemon exits once no call is in flight. `bellwether daemon` runs it in the foreground when you want to watch it.
|
|
11
|
+
- **Daemon.** One per machine, on a socket under the Bellwether home. It is the only process that holds state: the registry, the outbox and the herdr subscriptions. An adapter keeps none of that. It starts without the identity variables of the session that launched it, so its own environment never decides who a call came from. A lock file and a version handshake keep a second client from starting a second daemon. When a client is newer than the daemon it found, the client sends a drain request and the old daemon exits once no call is in flight. `bellwether daemon` runs it in the foreground when you want to watch it.
|
|
12
12
|
- **herdr client.** Newline-delimited JSON on the herdr socket, one connection per request and one held open for the subscription. The subscription checks the `subscription_started` acknowledgement and buffers any event that arrives with it.
|
|
13
13
|
- **Registry.** One JSON file per parent session, under `~/.bellwether/parents/`, written by the daemon. Each child record stores its name, kind, pane, tab, start time, last status, last `completion_seq` and transcript path. Bellwether writes the record before it asks herdr for anything, so a crash mid-spawn still says what it asked herdr for.
|
|
14
14
|
- **Watcher.** It subscribes to `pane.agent_status_changed` for each child pane, plus `pane.exited`, `pane.closed` and `pane.agent_detected`. On connect it subscribes first, then reads a snapshot on a second connection, then reconciles. A dropped subscription reconnects with backoff and takes a fresh snapshot, because herdr does not replay events.
|
|
@@ -21,22 +21,68 @@ A parent session runs an adapter: a Pi extension, or a Claude Code MCP channel s
|
|
|
21
21
|
| -- | -- | -- |
|
|
22
22
|
| report | The child calls `parent_report`. | none |
|
|
23
23
|
| idle | herdr reports `idle` or `done` with a new `completion_seq`, and no report covered that turn. | 5 s |
|
|
24
|
-
| blocked | herdr reports `blocked
|
|
24
|
+
| blocked | herdr reports `blocked`, on a question other than Claude Code's startup questions. | 3 s |
|
|
25
25
|
| stuck | herdr reports `working` or `unknown` and the child has been quiet past the threshold. | 10 min |
|
|
26
|
+
| inactive | The child has shown no status change, output, new turn or report for its inactivity threshold. Any status counts, `blocked` included. | none |
|
|
26
27
|
| exited | `pane.exited`, `pane.closed`, or herdr stops detecting the agent. | none |
|
|
27
28
|
|
|
29
|
+
A Claude Code child asks two questions before its prompt: whether to trust the folder, and whether to load the development channel. `agent_spawn` answers both before it returns. It moves the selection to "Yes, I trust this folder" and to "I am using this for local development", checks each on screen, and then presses Enter. It says yes to the folder question for any folder, which gives the child write access to whatever directory the spawn names. When a question is still on screen after the spawn's 30 seconds, the spawn fails, and the error names that question. The parent hears about neither question. A resumed session shows the channel question again, and the watcher answers it the same way.
|
|
30
|
+
|
|
31
|
+
At delivery, the watcher drops an unread `blocked` or `stuck` event once the child has moved on. A dialog someone already answered stays out of the parent's next turn.
|
|
32
|
+
|
|
33
|
+
The registry keeps each child's harness session, `session.kind` and `session.value`, and its transcript path after the child exits. To resume a retired child, call `agent_spawn` with `resume`. By hand, a retired Claude Code child resumes with `claude --resume <value>`.
|
|
34
|
+
|
|
35
|
+
The inactivity threshold defaults to 5 minutes. `agent_spawn` takes `inactive_minutes` to set it for one child. A value is clamped to 1 minute through 24 hours, and no value turns the notice off. The notice fires once per quiet period. Output or a report starts a new one.
|
|
36
|
+
|
|
28
37
|
## Tools
|
|
29
38
|
|
|
30
39
|
| Tool | Who gets it | What it does |
|
|
31
40
|
| -- | -- | -- |
|
|
32
|
-
| `agent_spawn` | any session | starts a child in a new tab |
|
|
41
|
+
| `agent_spawn` | any session | starts a child in a new tab, on this machine or on a saved herdr machine named by `machine`, or with `resume` messages an earlier child, reopening its session in a new tab when herdr no longer has it |
|
|
42
|
+
| `agent_adopt` | any session | makes a running agent this session did not start into its child, such as one `herdr-spawn.sh` started, and refuses a pane another session watches |
|
|
33
43
|
| `agent_list` | any session | lists this session's children with status, age and unread events |
|
|
34
44
|
| `agent_read` | any session | returns a child's last assistant message, or its screen when you pass `lines` |
|
|
35
45
|
| `agent_send` | any session | prompts a child, or sends keys when herdr refuses a blocked one |
|
|
36
46
|
| `agent_stop` | any session | closes a child's tab, refusing a working child unless you pass `force` |
|
|
37
|
-
| `parent_report` | a child
|
|
47
|
+
| `parent_report` | a child Bellwether started or resumed on this machine | sends `done`, `needs-input` or `progress` to the parent that holds the child's record |
|
|
48
|
+
| `request_retirement` | a session whose environment carries `BELLWETHER_CHILD` | asks the daemon to remove the child's worktree and branch after herdr drops its pane, and doesn't remove anything itself |
|
|
49
|
+
|
|
50
|
+
Bellwether sends input only to panes that belong to this parent: the ones it started, resumed or adopted.
|
|
51
|
+
|
|
52
|
+
Each adapter sends its session's identity with every tool call: the herdr pane it runs in, and the child id its spawn gave it. The daemon matches that identity against the child records it keeps, so a `parent_report` reaches the parent whose registry lists the child, whichever client process made the call. Adapters read the parent from the daemon's records, never from an environment variable. When no record matches, the error gives the pane and the path of the MCP config file the spawn should have written.
|
|
53
|
+
|
|
54
|
+
### Retirement
|
|
55
|
+
|
|
56
|
+
A child that has finished its work calls `request_retirement`, then closes its own tab. The call runs while the child is alive, so the child hears which checks pass now. Those cover uncommitted changes, stashes on the branch, and whether its commits exist anywhere else. On the child record go `retireRequestedAt` and `retireIntent` (worktree, repository, branch, commit), and nothing on disk changes. Bellwether refuses, and leaves the record as it was, for a caller with no child record, an adopted child, a child on another machine, a detached HEAD, or a main worktree.
|
|
57
|
+
|
|
58
|
+
The daemon does the cleaning. It already holds the registry, watches every pane and keeps running after each child exits, so no other process takes part. When the watcher sees the child's pane exit, it runs these steps in order, and it doesn't remove anything until each one holds:
|
|
59
|
+
|
|
60
|
+
1. herdr lists neither the pane nor any pane in its tab. Otherwise the retirement waits for the next exit event.
|
|
61
|
+
2. The worktree must not be a main worktree. It must also match what the child asked about, with a clean status and no stash on its branch.
|
|
62
|
+
3. The default branch contains the branch, or GitHub shows a merged or closed pull request whose head is the branch's commit.
|
|
63
|
+
4. No process has its working directory inside the worktree.
|
|
64
|
+
5. `git worktree remove`, then `git branch -D`, then a check against git and the filesystem that neither remains.
|
|
38
65
|
|
|
39
|
-
|
|
66
|
+
The daemon writes the outcome to the child record as `retiredAt` and `retireOutcome` (`removed` or `refused`). A refusal also gets `retireReason`, which states the failed condition and what a person would do about it. One JSON line per outcome goes to `~/.bellwether/retire.log`. `retireStage` records each removal as it completes, so a daemon that starts again finishes an unfinished retirement without repeating a step. Bellwether treats a worktree as main when its git directory is the repository itself or git lists it first. The checkout of the default branch counts too, as does any worktree named `main` or `master`. Resuming a child clears its request.
|
|
67
|
+
|
|
68
|
+
### Resume through `agent_spawn`
|
|
69
|
+
|
|
70
|
+
`agent_spawn` accepts a `resume` target: a child's name, its id or its session id. It also takes the same `prompt` as any spawn. herdr, not the registry, decides what happens next.
|
|
71
|
+
|
|
72
|
+
- When herdr shows the child's session in the pane this parent started for it, the prompt goes to that pane as an ordinary message. No tab opens, and the child keeps its id.
|
|
73
|
+
- When herdr has no pane for the session, Bellwether treats the child as retired. It opens a tab on the child's original machine and starts the harness with `--resume` for Claude Code or `--session` for Pi. The child keeps its id, so its events and receipts continue, and Bellwether passes the prompt in a file with mode 0600.
|
|
74
|
+
- When the registry and herdr disagree, herdr wins, and the reply opens with a line that says so. Bellwether resumes a record still marked running whose session herdr no longer has. For a record marked exited whose session herdr still shows in its own pane, Bellwether sends the message and clears the exit mark.
|
|
75
|
+
- When the session runs in a pane this parent did not start, Bellwether refuses. The refusal gives the child, the pane and `agent_adopt`. Bellwether never types into that pane.
|
|
76
|
+
|
|
77
|
+
When the call passes `kind` with a session id that this parent's children did not run, Bellwether starts a new child, with `name`, `cwd` and `machine` as for a spawn.
|
|
78
|
+
|
|
79
|
+
Bellwether also refuses a live agent that isn't a child, a harness without a resume flag, or a retired child whose session was never recorded, along with a target that doesn't match any child or session. Each refusal tells the caller what to pass instead.
|
|
80
|
+
|
|
81
|
+
A lock file under `~/.bellwether/locks/`, one per child, covers the decision and the resume. A second call for the same child fails at once with the process that holds the lock, so two callers open one tab between them. Bellwether takes over a lock whose process has exited or that is older than five minutes.
|
|
82
|
+
|
|
83
|
+
A child on another machine runs on that machine's herdr. Bellwether reaches it the way `herdr --machine` does, through `herdr remote-api-bridge` over SSH to the saved profile's target, so the profile must exist in `herdr machine list` and SSH must log in without a prompt. That child's `parent_report` writes to its own machine's disk, which the parent never reads, so Bellwether follows it through herdr status alone.
|
|
84
|
+
|
|
85
|
+
Each child record keeps its `host` after the child exits, so a resume goes back to the same machine. A registry file written before version 2 gains `host: local` for each child the next time Bellwether writes it.
|
|
40
86
|
|
|
41
87
|
## Install
|
|
42
88
|
|
|
@@ -65,6 +111,10 @@ claude --dangerously-load-development-channels plugin:bellwether@bellwether
|
|
|
65
111
|
|
|
66
112
|
The plugin runs `bin/bellwether-mcp.js` as an MCP server and enables it as a channel, and that declaration is what delivers child events. Load the server as a plain MCP server and the tools arrive, with events waiting in the outbox.
|
|
67
113
|
|
|
114
|
+
The plugin is for a parent session, one you start yourself. You don't set anything up for a child: `agent_spawn`, with or without `resume`, starts each Claude Code child with its own server, passed as `--mcp-config=~/.bellwether/mcp/<child id>.json`. The file has mode 0600 and lists one server, which runs this package's channel entry point with `--child <child id>`. Bellwether deletes it when the child exits or the spawn fails. A child on another machine doesn't get a file, because the daemon on that machine doesn't store a record of it.
|
|
115
|
+
|
|
116
|
+
You don't need a `mcpServers` entry in your Claude Code settings for children. A user-level `bellwether` entry is harmless, and children don't use it. For the tools in a session you start by hand, install the plugin above.
|
|
117
|
+
|
|
68
118
|
The server speaks MCP over stdio, so each log line goes to stderr and stdout carries only the protocol. It exits when stdin closes, which keeps a leftover process from showing the session as listening.
|
|
69
119
|
|
|
70
120
|
### Check the install
|
|
@@ -77,7 +127,7 @@ It reports the herdr socket, the herdr API version, the Pi extension path, the M
|
|
|
77
127
|
|
|
78
128
|
## Environment
|
|
79
129
|
|
|
80
|
-
A child started by `agent_spawn` receives these variables in its tab
|
|
130
|
+
A child started by `agent_spawn` receives these variables in its tab, for its own scripts and for the `bellwether report` command. The MCP server identifies its child with `--child` instead, and the daemon looks up the parent in its records.
|
|
81
131
|
|
|
82
132
|
| Variable | Meaning |
|
|
83
133
|
| -- | -- |
|
package/dist/cli.js
CHANGED
|
@@ -30,7 +30,7 @@ function parseArgs(argv) {
|
|
|
30
30
|
if (key === 'keys' || key === 'args') {
|
|
31
31
|
flags[key] = next;
|
|
32
32
|
}
|
|
33
|
-
else if (key === 'stuck-minutes' || key === 'max-depth' || key === 'lines') {
|
|
33
|
+
else if (key === 'stuck-minutes' || key === 'inactive-minutes' || key === 'max-depth' || key === 'lines') {
|
|
34
34
|
flags[key] = Number(next);
|
|
35
35
|
}
|
|
36
36
|
else {
|
|
@@ -256,6 +256,7 @@ async function main() {
|
|
|
256
256
|
model: str(flags, 'model'),
|
|
257
257
|
focus: flags['focus'] === true,
|
|
258
258
|
stuckMinutes: num(flags, 'stuck-minutes'),
|
|
259
|
+
inactive_minutes: num(flags, 'inactive-minutes'),
|
|
259
260
|
maxDepth: num(flags, 'max-depth'),
|
|
260
261
|
args: str(flags, 'args')?.split('\u0000'),
|
|
261
262
|
}));
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { LOCAL_HOST } from './machine.js';
|
|
2
|
+
import { newChildId } from './outbox.js';
|
|
3
|
+
import { upsertChild, watcherOfPane } from './registry.js';
|
|
4
|
+
import { AGENT_KINDS, harnessOf, herdrLink } from './spawn.js';
|
|
5
|
+
import { resolveTranscript } from './transcript.js';
|
|
6
|
+
import { resolveInactiveMs } from './inactivity.js';
|
|
7
|
+
export async function adoptPane(client, parent, options, signal) {
|
|
8
|
+
const host = options.host ?? LOCAL_HOST;
|
|
9
|
+
const agents = await client.agentList(signal);
|
|
10
|
+
const byPane = agents.find((pane) => pane.paneId === options.target);
|
|
11
|
+
const byName = agents.filter((pane) => pane.name === options.target);
|
|
12
|
+
if (!byPane && byName.length > 1)
|
|
13
|
+
throw new Error(`More than one live agent on ${host} is named ${options.target}. Adopt it by pane id: ${byName.map((pane) => pane.paneId).join(', ')}.`);
|
|
14
|
+
const pane = byPane ?? byName[0];
|
|
15
|
+
if (!pane || !pane.agent) {
|
|
16
|
+
const panes = await client.paneList(signal).catch(() => []);
|
|
17
|
+
const bare = panes.find((entry) => entry.paneId === options.target);
|
|
18
|
+
if (bare)
|
|
19
|
+
throw new Error(`Pane ${options.target} on ${host} holds no agent herdr recognizes, so there is nothing to adopt.`);
|
|
20
|
+
throw new Error(`No pane or live agent on ${host} matches ${options.target}.`);
|
|
21
|
+
}
|
|
22
|
+
if (!AGENT_KINDS.includes(pane.agent))
|
|
23
|
+
throw new Error(`Pane ${pane.paneId} on ${host} runs ${pane.agent}, which is not an agent kind Bellwether supervises.`);
|
|
24
|
+
if (host === LOCAL_HOST && pane.paneId === parent.paneId)
|
|
25
|
+
throw new Error('A session cannot adopt its own pane.');
|
|
26
|
+
const owner = watcherOfPane(host, pane.paneId);
|
|
27
|
+
if (owner && owner.parent.id === parent.id)
|
|
28
|
+
return { child: owner.child, link: herdrLink('pane', pane.paneId), already: true };
|
|
29
|
+
if (owner)
|
|
30
|
+
throw new Error(`Pane ${pane.paneId} on ${host} is already a child of ${owner.parent.id} as ${owner.child.name}, so this session cannot adopt it.`);
|
|
31
|
+
const now = new Date().toISOString();
|
|
32
|
+
const kind = pane.agent;
|
|
33
|
+
const harness = harnessOf(kind);
|
|
34
|
+
const child = {
|
|
35
|
+
id: newChildId(),
|
|
36
|
+
name: options.name ?? pane.name ?? pane.label ?? pane.paneId,
|
|
37
|
+
kind,
|
|
38
|
+
harness,
|
|
39
|
+
paneId: pane.paneId,
|
|
40
|
+
tabId: pane.tabId,
|
|
41
|
+
workspaceId: pane.workspaceId,
|
|
42
|
+
host,
|
|
43
|
+
origin: 'adopt',
|
|
44
|
+
cwd: pane.cwd,
|
|
45
|
+
startedAt: now,
|
|
46
|
+
lastStatus: pane.agentStatus,
|
|
47
|
+
statusChangedAt: now,
|
|
48
|
+
completionSeq: pane.completionSeq,
|
|
49
|
+
session: pane.agentSessionId ? { kind: pane.agentSessionId.includes('/') ? 'path' : 'id', value: pane.agentSessionId } : undefined,
|
|
50
|
+
// A remote child's transcript sits on its own machine's disk.
|
|
51
|
+
transcript: host === LOCAL_HOST ? resolveTranscript(harness, pane.agentSessionId, pane.cwd) : undefined,
|
|
52
|
+
lastBusyAt: now,
|
|
53
|
+
depth: parent.depth + 1,
|
|
54
|
+
stuckMs: options.stuckMinutes === undefined ? undefined : Math.max(1_000, Math.round(options.stuckMinutes * 60_000)),
|
|
55
|
+
inactiveMs: resolveInactiveMs(undefined),
|
|
56
|
+
};
|
|
57
|
+
upsertChild(parent.id, child);
|
|
58
|
+
return { child, link: herdrLink('pane', child.paneId), already: false };
|
|
59
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// A child's brief lives in a private file, and the harness gets a one-line
|
|
2
|
+
// pointer to it. herdr types an agent's arguments into a shell and refuses a
|
|
3
|
+
// line break, and a prompt on a command line shows in `ps` and matches
|
|
4
|
+
// `pkill -f`. A file keeps the line breaks, any length, and the text private.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { promptPath, promptsDir } from './paths.js';
|
|
8
|
+
/** A brief is read when the child starts. One a week old has been read. */
|
|
9
|
+
const BRIEF_MAX_AGE_MS = 7 * 24 * 60 * 60_000;
|
|
10
|
+
/** Write the brief with mode 0600 in a 0700 directory, and return its path. */
|
|
11
|
+
export function writeBrief(childId, text, now = Date.now()) {
|
|
12
|
+
const dir = promptsDir();
|
|
13
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
14
|
+
fs.chmodSync(dir, 0o700);
|
|
15
|
+
pruneBriefs(now);
|
|
16
|
+
const file = promptPath(childId);
|
|
17
|
+
fs.writeFileSync(file, text, { mode: 0o600 });
|
|
18
|
+
fs.chmodSync(file, 0o600);
|
|
19
|
+
return file;
|
|
20
|
+
}
|
|
21
|
+
/** Remove a child's brief. A brief that is already gone is not an error. */
|
|
22
|
+
export function removeBrief(childId) {
|
|
23
|
+
fs.rmSync(promptPath(childId), { force: true });
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Remove the briefs older than a week. A child that exits removes its own, so
|
|
27
|
+
* this only catches a daemon that stopped before its child did.
|
|
28
|
+
*/
|
|
29
|
+
export function pruneBriefs(now = Date.now()) {
|
|
30
|
+
let names;
|
|
31
|
+
try {
|
|
32
|
+
names = fs.readdirSync(promptsDir());
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
for (const name of names) {
|
|
38
|
+
const file = path.join(promptsDir(), name);
|
|
39
|
+
try {
|
|
40
|
+
if (now - fs.statSync(file).mtimeMs > BRIEF_MAX_AGE_MS)
|
|
41
|
+
fs.rmSync(file, { force: true });
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// Another process removed it first.
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The one argument that hands the brief to the harness. Claude Code and Pi
|
|
50
|
+
* attach a file named with @ to the first message, so the child spends no tool
|
|
51
|
+
* call reading it. Any other harness gets a sentence that names the file.
|
|
52
|
+
*/
|
|
53
|
+
export function briefArgument(kind, file) {
|
|
54
|
+
// Claude Code reads a mention out of the prompt text, so a path with a space
|
|
55
|
+
// needs quotes there. Pi takes the argument whole and strips only the @.
|
|
56
|
+
if (kind === 'claude')
|
|
57
|
+
return /\s/.test(file) ? `@"${file}"` : `@${file}`;
|
|
58
|
+
if (kind === 'pi')
|
|
59
|
+
return `@${file}`;
|
|
60
|
+
return `Your task is in ${file}. Read it, then do what it says.`;
|
|
61
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// One writer per child. A spawn that resumes a child holds a lock file on the
|
|
2
|
+
// child's id while it decides whether the child is alive and while it brings it
|
|
3
|
+
// back, so two callers resuming the same session open one tab between them.
|
|
4
|
+
// The lock is a file, not a map in memory, because two daemons on one machine
|
|
5
|
+
// can share a Bellwether home. A lock whose process is gone, or that is older
|
|
6
|
+
// than any resume can take, is stale and is taken over.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { isAlive } from '../daemon/lock.js';
|
|
10
|
+
import { bellwetherHome, slug } from './paths.js';
|
|
11
|
+
/** Longer than a resume can last: the start retries for 60 s and the dialogs wait 30 s. */
|
|
12
|
+
export const CHILD_LOCK_MAX_AGE_MS = 5 * 60_000;
|
|
13
|
+
export function childLockPath(key) {
|
|
14
|
+
return path.join(bellwetherHome(), 'locks', `${slug(key)}.lock`);
|
|
15
|
+
}
|
|
16
|
+
/** Thrown to the caller that finds the lock taken. */
|
|
17
|
+
export class ChildBusyError extends Error {
|
|
18
|
+
key;
|
|
19
|
+
holder;
|
|
20
|
+
constructor(key, holder, label) {
|
|
21
|
+
super(`${label} is already being brought back by another call (process ${holder.pid}, ${holder.purpose}, started ${new Date(holder.at).toISOString()}). Wait for its event, or call agent_list to see where it landed.`);
|
|
22
|
+
this.name = 'ChildBusyError';
|
|
23
|
+
this.key = key;
|
|
24
|
+
this.holder = holder;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function readLock(file) {
|
|
28
|
+
try {
|
|
29
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
30
|
+
if (typeof parsed.pid !== 'number' || typeof parsed.at !== 'number')
|
|
31
|
+
return undefined;
|
|
32
|
+
return { pid: parsed.pid, at: parsed.at, purpose: typeof parsed.purpose === 'string' ? parsed.purpose : 'unknown' };
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Run `work` while holding the lock on `key`. A second caller, in this process
|
|
40
|
+
* or another, gets a ChildBusyError naming `label` instead of waiting.
|
|
41
|
+
*/
|
|
42
|
+
export async function withChildLock(key, label, purpose, work, now = Date.now, alive = isAlive) {
|
|
43
|
+
const file = childLockPath(key);
|
|
44
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
45
|
+
const mine = { pid: process.pid, at: now(), purpose };
|
|
46
|
+
const token = JSON.stringify(mine);
|
|
47
|
+
let taken = false;
|
|
48
|
+
for (let attempt = 0; attempt < 2 && !taken; attempt += 1) {
|
|
49
|
+
try {
|
|
50
|
+
const fd = fs.openSync(file, 'wx', 0o600);
|
|
51
|
+
fs.writeSync(fd, `${token}\n`);
|
|
52
|
+
fs.closeSync(fd);
|
|
53
|
+
taken = true;
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (error.code !== 'EEXIST')
|
|
57
|
+
throw error;
|
|
58
|
+
const held = readLock(file);
|
|
59
|
+
// A half-written file is a holder that is mid-write, so it counts as held.
|
|
60
|
+
if (!held)
|
|
61
|
+
throw new ChildBusyError(key, { pid: 0, at: now(), purpose: 'unknown' }, label);
|
|
62
|
+
if (alive(held.pid) && now() - held.at < CHILD_LOCK_MAX_AGE_MS)
|
|
63
|
+
throw new ChildBusyError(key, held, label);
|
|
64
|
+
fs.rmSync(file, { force: true });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (!taken) {
|
|
68
|
+
const held = readLock(file);
|
|
69
|
+
throw new ChildBusyError(key, held ?? { pid: 0, at: now(), purpose: 'unknown' }, label);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return await work();
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
// Remove the file only while it is still this call's, never a successor's.
|
|
76
|
+
try {
|
|
77
|
+
if (fs.readFileSync(file, 'utf8').trim() === token)
|
|
78
|
+
fs.rmSync(file, { force: true });
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// Already gone.
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
package/dist/core/classifier.js
CHANGED
|
@@ -1,11 +1,35 @@
|
|
|
1
|
+
// The classifier: turns herdr states into child events, with a settle time for
|
|
2
|
+
// each. It is a pure function of (state, clock, observation) so tier 1 can run
|
|
3
|
+
// it against a fake clock without a socket.
|
|
4
|
+
import { DEFAULT_INACTIVE_MS, inactiveMsOf } from './inactivity.js';
|
|
1
5
|
/** Starting values. The lab tunes these; they are not measurements. */
|
|
2
6
|
export const DEFAULT_LIMITS = {
|
|
3
7
|
idleMs: 5_000,
|
|
4
8
|
blockedMs: 3_000,
|
|
5
9
|
stuckMs: 10 * 60_000,
|
|
10
|
+
inactiveMs: DEFAULT_INACTIVE_MS,
|
|
6
11
|
};
|
|
7
|
-
export function initialState(status, now) {
|
|
8
|
-
|
|
12
|
+
export function initialState(status, now, seed = {}) {
|
|
13
|
+
const activityAt = seed.activityAt ?? now;
|
|
14
|
+
return { status, statusSince: now, lastBusyAt: now, lastActivityAt: activityAt, firedInactiveFor: seed.firedInactiveFor };
|
|
15
|
+
}
|
|
16
|
+
/** The limits one child is judged by: the base, with the child's own thresholds. */
|
|
17
|
+
export function limitsFor(child, base) {
|
|
18
|
+
const limits = { ...base, inactiveMs: inactiveMsOf(child) };
|
|
19
|
+
return child.stuckMs === undefined ? limits : { ...limits, stuckMs: child.stuckMs };
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The state a child starts from, recovered from its registry record. A parent
|
|
23
|
+
* that restarts resumes the same quiet period instead of a fresh one, and does
|
|
24
|
+
* not send the inactive event again for a period it already reported.
|
|
25
|
+
*/
|
|
26
|
+
export function seedFor(child, now) {
|
|
27
|
+
const activityAt = Math.max(Date.parse(child.lastBusyAt), Date.parse(child.statusChangedAt));
|
|
28
|
+
const fired = child.inactiveNotifiedFor === undefined ? NaN : Date.parse(child.inactiveNotifiedFor);
|
|
29
|
+
return initialState(child.lastStatus, now, {
|
|
30
|
+
activityAt: Number.isFinite(activityAt) ? activityAt : now,
|
|
31
|
+
firedInactiveFor: Number.isFinite(fired) ? fired : undefined,
|
|
32
|
+
});
|
|
9
33
|
}
|
|
10
34
|
export function isReady(status) {
|
|
11
35
|
return status === 'idle' || status === 'done';
|
|
@@ -16,6 +40,10 @@ export function isReady(status) {
|
|
|
16
40
|
*/
|
|
17
41
|
export function advance(state, observation, now, limits = DEFAULT_LIMITS) {
|
|
18
42
|
const next = { ...state };
|
|
43
|
+
const seqMoved = observation.completionSeq !== undefined && observation.completionSeq !== state.completionSeq;
|
|
44
|
+
if (observation.status !== state.status || seqMoved || observation.busy) {
|
|
45
|
+
next.lastActivityAt = now;
|
|
46
|
+
}
|
|
19
47
|
if (observation.status !== state.status) {
|
|
20
48
|
next.status = observation.status;
|
|
21
49
|
next.statusSince = now;
|
|
@@ -23,7 +51,7 @@ export function advance(state, observation, now, limits = DEFAULT_LIMITS) {
|
|
|
23
51
|
next.firedBlocked = undefined;
|
|
24
52
|
}
|
|
25
53
|
const becameReady = isReady(observation.status) && !isReady(state.status);
|
|
26
|
-
if (
|
|
54
|
+
if (seqMoved) {
|
|
27
55
|
next.completionSeq = observation.completionSeq;
|
|
28
56
|
next.statusSince = now;
|
|
29
57
|
}
|
|
@@ -58,9 +86,15 @@ export function advance(state, observation, now, limits = DEFAULT_LIMITS) {
|
|
|
58
86
|
if ((next.status === 'working' || next.status === 'unknown') && next.firedStuckSince !== next.lastBusyAt && now - next.lastBusyAt >= limits.stuckMs) {
|
|
59
87
|
return { state: { ...next, firedStuckSince: next.lastBusyAt }, event: 'stuck' };
|
|
60
88
|
}
|
|
89
|
+
// Inactivity is checked last, so it never displaces a more specific event
|
|
90
|
+
// from the same pass. Whatever it defers fires on a later pass, because
|
|
91
|
+
// nothing here consumes the inactivity clock until it fires.
|
|
92
|
+
if (now - next.lastActivityAt >= (limits.inactiveMs ?? DEFAULT_INACTIVE_MS) && (next.firedInactiveFor === undefined || next.lastActivityAt > next.firedInactiveFor)) {
|
|
93
|
+
return { state: { ...next, firedInactiveFor: next.lastActivityAt }, event: 'inactive' };
|
|
94
|
+
}
|
|
61
95
|
return { state: next };
|
|
62
96
|
}
|
|
63
97
|
/** Mark the newest turn as covered by a report, so no idle event follows it. */
|
|
64
98
|
export function markReported(state, now) {
|
|
65
|
-
return { ...state, reportedFor: state.completionSeq, lastBusyAt: now, statusSince: now };
|
|
99
|
+
return { ...state, reportedFor: state.completionSeq, lastBusyAt: now, lastActivityAt: now, statusSince: now };
|
|
66
100
|
}
|
|
@@ -17,6 +17,13 @@ export class HerdrApiError extends Error {
|
|
|
17
17
|
this.code = code;
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
|
+
function dial(endpoint, onReady) {
|
|
21
|
+
if (typeof endpoint !== 'string')
|
|
22
|
+
return endpoint(onReady);
|
|
23
|
+
const socket = net.createConnection(endpoint);
|
|
24
|
+
socket.on('connect', onReady);
|
|
25
|
+
return socket;
|
|
26
|
+
}
|
|
20
27
|
let sequence = 0;
|
|
21
28
|
export function nextRequestId(prefix = 'bellwether') {
|
|
22
29
|
sequence += 1;
|
|
@@ -80,11 +87,11 @@ function errorFrom(frame) {
|
|
|
80
87
|
return new HerdrApiError(typeof error['code'] === 'string' ? error['code'] : undefined, typeof error['message'] === 'string' ? error['message'] : 'request failed');
|
|
81
88
|
}
|
|
82
89
|
/** One request on its own connection, resolving with `result` or rejecting with HerdrApiError. */
|
|
83
|
-
export function requestHerdr(
|
|
90
|
+
export function requestHerdr(endpoint, request, signal, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
84
91
|
return new Promise((resolve, reject) => {
|
|
85
92
|
if (signal?.aborted)
|
|
86
93
|
return reject(new Error('herdr request aborted'));
|
|
87
|
-
const socket =
|
|
94
|
+
const socket = dial(endpoint, () => socket.write(`${JSON.stringify(request)}\n`));
|
|
88
95
|
const frames = new NdjsonFrames();
|
|
89
96
|
let settled = false;
|
|
90
97
|
const timer = setTimeout(() => finish(new Error(`herdr ${request.method} timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
@@ -106,7 +113,6 @@ export function requestHerdr(socketPath, request, signal, timeoutMs = DEFAULT_TI
|
|
|
106
113
|
};
|
|
107
114
|
const onAbort = () => finish(new Error('herdr request aborted'));
|
|
108
115
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
109
|
-
socket.on('connect', () => socket.write(`${JSON.stringify(request)}\n`));
|
|
110
116
|
socket.on('error', (error) => finish(error));
|
|
111
117
|
socket.on('end', () => finish(new Error(`herdr closed the connection before answering ${request.method}`)));
|
|
112
118
|
socket.on('data', (chunk) => {
|
|
@@ -138,11 +144,11 @@ export function requestHerdr(socketPath, request, signal, timeoutMs = DEFAULT_TI
|
|
|
138
144
|
* Hold a subscription open. Frames that arrive before the acknowledgement are
|
|
139
145
|
* buffered and replayed, so no event is lost between connect and ack.
|
|
140
146
|
*/
|
|
141
|
-
export function openHerdrSubscription(
|
|
147
|
+
export function openHerdrSubscription(endpoint, request, onEvent, signal, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
142
148
|
return new Promise((resolve, reject) => {
|
|
143
149
|
if (signal.aborted)
|
|
144
150
|
return reject(new Error('herdr subscription aborted'));
|
|
145
|
-
const socket =
|
|
151
|
+
const socket = dial(endpoint, () => socket.write(`${JSON.stringify(request)}\n`));
|
|
146
152
|
const frames = new NdjsonFrames();
|
|
147
153
|
const pending = [];
|
|
148
154
|
let ready = false;
|
|
@@ -224,7 +230,6 @@ export function openHerdrSubscription(socketPath, request, onEvent, signal, time
|
|
|
224
230
|
deliver({ event: frame['event'], data: isRecord(frame['data']) ? frame['data'] : {} });
|
|
225
231
|
}
|
|
226
232
|
signal.addEventListener('abort', onAbort, { once: true });
|
|
227
|
-
socket.on('connect', () => socket.write(`${JSON.stringify(request)}\n`));
|
|
228
233
|
socket.on('error', (error) => finish(error));
|
|
229
234
|
socket.on('end', () => finish(intentional ? undefined : new Error('herdr closed the subscription')));
|
|
230
235
|
socket.on('data', (chunk) => {
|
|
@@ -297,14 +302,23 @@ export function parsePane(value) {
|
|
|
297
302
|
label: optionalString(value['label']),
|
|
298
303
|
};
|
|
299
304
|
}
|
|
300
|
-
/** A thin typed wrapper over one herdr
|
|
305
|
+
/** A thin typed wrapper over one herdr server, local or on a saved machine. */
|
|
301
306
|
export class HerdrClient {
|
|
307
|
+
/** The local socket, or a `machine:` label for a client that dials a bridge. */
|
|
302
308
|
socketPath;
|
|
309
|
+
endpoint;
|
|
303
310
|
constructor(options = {}) {
|
|
304
|
-
|
|
311
|
+
if (options.dial) {
|
|
312
|
+
this.endpoint = options.dial;
|
|
313
|
+
this.socketPath = options.label ?? 'machine';
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
this.socketPath = resolveSocketPath(options);
|
|
317
|
+
this.endpoint = this.socketPath;
|
|
318
|
+
}
|
|
305
319
|
}
|
|
306
320
|
request(method, params = {}, options = {}) {
|
|
307
|
-
return requestHerdr(this.
|
|
321
|
+
return requestHerdr(this.endpoint, { id: options.id ?? nextRequestId(), method, params }, options.signal, options.timeoutMs);
|
|
308
322
|
}
|
|
309
323
|
async agentList(signal) {
|
|
310
324
|
const result = await this.request('agent.list', {}, { signal });
|
|
@@ -363,6 +377,6 @@ export class HerdrClient {
|
|
|
363
377
|
return this.request('pane.current', {}, { signal }).then((result) => (isRecord(result) ? parsePane(result['pane']) : undefined));
|
|
364
378
|
}
|
|
365
379
|
subscribe(subscriptions, onEvent, signal, timeoutMs) {
|
|
366
|
-
return openHerdrSubscription(this.
|
|
380
|
+
return openHerdrSubscription(this.endpoint, { id: nextRequestId('sub'), method: 'events.subscribe', params: { subscriptions } }, onEvent, signal, timeoutMs);
|
|
367
381
|
}
|
|
368
382
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** The threshold when a spawn does not set one. */
|
|
2
|
+
export const DEFAULT_INACTIVE_MS = 5 * 60_000;
|
|
3
|
+
/** The longest threshold a spawn may ask for. Anything above it is clamped. */
|
|
4
|
+
export const MAX_INACTIVE_MS = 24 * 60 * 60_000;
|
|
5
|
+
/**
|
|
6
|
+
* The shortest threshold. A spawn cannot turn the notification off, and a
|
|
7
|
+
* zero or negative value would fire on every tick, so the floor is one minute.
|
|
8
|
+
*/
|
|
9
|
+
export const MIN_INACTIVE_MS = 60_000;
|
|
10
|
+
/**
|
|
11
|
+
* Turn a spawn's minutes into the stored threshold in milliseconds. Leaving
|
|
12
|
+
* the value out gives the default. A value that is not a finite number, such
|
|
13
|
+
* as NaN, also gives the default; a value beyond the range is clamped to it.
|
|
14
|
+
* There is no input that yields no threshold.
|
|
15
|
+
*/
|
|
16
|
+
export function resolveInactiveMs(minutes) {
|
|
17
|
+
if (minutes === undefined || Number.isNaN(minutes))
|
|
18
|
+
return DEFAULT_INACTIVE_MS;
|
|
19
|
+
const ms = minutes * 60_000;
|
|
20
|
+
return Math.min(MAX_INACTIVE_MS, Math.max(MIN_INACTIVE_MS, Math.round(ms)));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The threshold a child's record asks for, bounded again on read. A record
|
|
24
|
+
* written by hand, or by an older version, cannot push it past the range.
|
|
25
|
+
*/
|
|
26
|
+
export function inactiveMsOf(child) {
|
|
27
|
+
const stored = child.inactiveMs;
|
|
28
|
+
if (stored === undefined || !Number.isFinite(stored))
|
|
29
|
+
return DEFAULT_INACTIVE_MS;
|
|
30
|
+
return Math.min(MAX_INACTIVE_MS, Math.max(MIN_INACTIVE_MS, stored));
|
|
31
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// How a message names a child. Two children may share a name, so the name is
|
|
2
|
+
// the human label and the pane id tells them apart. A child whose tab never
|
|
3
|
+
// opened has no pane yet, and its own id stands in.
|
|
4
|
+
export function childLabel(child) {
|
|
5
|
+
const handle = child.paneId || child.id?.slice(0, 8);
|
|
6
|
+
return handle ? `${child.name} (${handle})` : child.name;
|
|
7
|
+
}
|