@hcflabs/pi-herdr-tools 1.7.1 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -0
- package/extensions/index.ts +4 -0
- package/internal/command-runner.mjs +73 -0
- package/internal/command.ts +438 -0
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -18,11 +18,15 @@ Configure `fast` in `/task-models`.
|
|
|
18
18
|
| Package | Relationship | Purpose |
|
|
19
19
|
| --- | --- | --- |
|
|
20
20
|
| [`@hcflabs/pi-herdr`](https://github.com/hcflabs/pi-harness/tree/main/packages/pi-herdr) | Required | Herdr CLI access. |
|
|
21
|
+
| [`@hcflabs/pi-process`](https://github.com/hcflabs/pi-harness/tree/main/packages/pi-process) | Required | Process-lease checks for command panes. |
|
|
22
|
+
| [`@hcflabs/pi-repo`](https://github.com/hcflabs/pi-harness/tree/main/packages/pi-repo) | Required | Repository target validation for handoffs and command panes. |
|
|
21
23
|
| [`@hcflabs/pi-memory`](https://github.com/hcflabs/pi-harness/tree/main/extensions/pi-memory) | Improves | Keeps Main-only memory and dream advice out of side threads. |
|
|
22
24
|
| [`@hcflabs/pi-task-models`](https://github.com/hcflabs/pi-harness/tree/main/extensions/pi-task-models) | Required | Model profiles for titles, idle recaps, and side threads. |
|
|
23
25
|
|
|
24
26
|
## Use
|
|
25
27
|
|
|
28
|
+
Use `/diagnostics` to read recent config reports and command recovery errors.
|
|
29
|
+
|
|
26
30
|
Run `/clone-tab`; the original session stays active. Commands and prompts are for humans; tools are for agents.
|
|
27
31
|
|
|
28
32
|
| Surface | Type | Purpose |
|
|
@@ -31,6 +35,7 @@ Run `/clone-tab`; the original session stays active. Commands and prompts are fo
|
|
|
31
35
|
| `/clone-worktree` | command | Clone into a new Git worktree workspace. |
|
|
32
36
|
| `/handoff-worktree <issue>` | prompt | Prepare a task for `herdr_handoff`. |
|
|
33
37
|
| `herdr_handoff` | tool | Start a separate task from local `main`, without changing focus. |
|
|
38
|
+
| `herdr_command` | tool | Run a long command in a new pane, read its output and saved exit status, and stop it. Main only. |
|
|
34
39
|
| `/done [-f]` | command | Remove the worktree and close its workspace tabs. `--force` aliases `-f`. |
|
|
35
40
|
| `/btw [<question...>]` | command | Open a side pane with an optional editable draft. |
|
|
36
41
|
| `/btw ask <question...>` | command | Ask a question starting with a subcommand name. |
|
|
@@ -80,6 +85,28 @@ The tool never selects a child repository automatically. All parameters must be
|
|
|
80
85
|
|
|
81
86
|
After validation, the tool runs `herdr worktree create --workspace <parent> --branch <branch> --base main --label <label> --no-focus`. With `repo`, it uses `--cwd <repository>` instead of `--workspace <parent>`. Herdr then opens the primary workspace of the repository, or creates it, and does not close it later. It starts Pi without session arguments. It submits `herdr agent prompt <agentName> <prompt> --wait --until working --timeout 30000`, with the prompt as one argument, not a shell command or file. The result includes workspace ID, tab, pane, branch, checkout path, agent name, and `repo` when set.
|
|
82
87
|
|
|
88
|
+
### Command panes
|
|
89
|
+
|
|
90
|
+
Main uses `herdr_command` for a command that runs longer than a tool call should wait, such as a full test suite or a build. The tool registers only with `HERDR_ENV=1`.
|
|
91
|
+
|
|
92
|
+
| Action | Fields | Result |
|
|
93
|
+
| --- | --- | --- |
|
|
94
|
+
| `start` | `command`, `access`, and optional `args`, `repo`, and `cwd` | Opens an unfocused split of Main's pane and returns a job ID at once. |
|
|
95
|
+
| `read` | `id`, optional `lines` | Shows the recent pane output and the saved process status. It never waits. |
|
|
96
|
+
| `stop` | `id` | Stops the job processes, closes the job pane, and proves the end. |
|
|
97
|
+
|
|
98
|
+
`command` is one executable and `args` is its argument list. No shell parses them. To use a shell, name the shell, for example `bash` with `["-lc", "make test"]`. `repo` selects a child repository of the Pi working directory. `cwd` selects a directory inside `repo`, or inside the Pi working directory without `repo`.
|
|
99
|
+
|
|
100
|
+
A small runner script starts the command without a shell and saves its exit code or signal in a private file. Pane output is untrusted terminal text. The tool never reads the exit status from the screen, because a command can print any text.
|
|
101
|
+
|
|
102
|
+
Set `access` to `write` when the command can change files, Git state, or external resources. A write job blocks direct `pi-subagent` writers in its checkout until `stop` proves that the job ended. Nothing enforces `read`.
|
|
103
|
+
|
|
104
|
+
`stop` signals the processes that hold the job's private lease file, and the job's process group. It then closes only the job pane and requires two empty `lsof` scans of the lease and an empty process group. The proof does not cover a process that leaves the group and closes the lease. Examples are a daemon, a `sudo` or `ssh` session, and a container. `read` and `stop` check the pane's terminal identity, so they never act on a later pane with the same ID.
|
|
105
|
+
|
|
106
|
+
Session shutdown stops each job in the same way. If a stop cannot prove the end, the next session restores the job and its write activity, so `stop` can try again. Delegated subagents cannot use the tool.
|
|
107
|
+
|
|
108
|
+
The tool is not a sandbox. It does not authorize a push, a publication, a deployment, or the use of credentials. It does not hide secrets that a command prints.
|
|
109
|
+
|
|
83
110
|
### Side questions
|
|
84
111
|
|
|
85
112
|
With a conversation open, run `/btw Why is this test failing?`, then submit the draft. Exact first words `ask`, `config`, `merge`, and `help` select subcommands; other input is a question.
|
|
@@ -136,6 +163,18 @@ Package-owned: `~/.pi/agent/config/pi-herdr-btw/config.json`
|
|
|
136
163
|
|
|
137
164
|
File and fields are optional. Launch reports unknown keys and invalid values, using field defaults; malformed files use all defaults. `/btw` continues without changing the file. `/btw config show` prints effective values. Updates fail until you correct issues or run `/btw config reset`. Reset reports issues, then replaces the file with defaults.
|
|
138
165
|
|
|
166
|
+
Package-owned: `~/.pi/agent/config/pi-herdr-tools/config.json`, key `commandPane`
|
|
167
|
+
|
|
168
|
+
| Name | Description | Values | Default |
|
|
169
|
+
| --- | --- | --- | --- |
|
|
170
|
+
| `split` | Command-pane placement. | `right` or `down`. | `right` |
|
|
171
|
+
| `maxActive` | Jobs that are not stopped, at one time. | 1 to 16. | `4` |
|
|
172
|
+
| `maxRuntimeMinutes` | Run time before the runner stops the command with `SIGTERM`, then `SIGKILL` after 10 seconds. | 1 to 1440. | `120` |
|
|
173
|
+
| `readLines` | Default line count for `read`. | 1 to 1000. | `200` |
|
|
174
|
+
| `maxReadBytes` | Output bytes that `read` returns. | 1024 to 65536. | `32768` |
|
|
175
|
+
|
|
176
|
+
An invalid value warns and uses its default. No value removes a limit. A malformed file blocks `start` until you correct it.
|
|
177
|
+
|
|
139
178
|
### Model profiles
|
|
140
179
|
|
|
141
180
|
See [`@hcflabs/pi-task-models`](https://github.com/hcflabs/pi-harness/tree/main/extensions/pi-task-models) for profile defaults, assignments, and config errors.
|
|
@@ -144,6 +183,8 @@ Side threads select the first authenticated viable route before launch. Titles u
|
|
|
144
183
|
|
|
145
184
|
## State and storage
|
|
146
185
|
|
|
186
|
+
Each `herdr_command` job keeps its launch record, saved status, and lease file in `~/.pi/agent/config/pi-herdr-tools/commands/<id>/`. A proved stop removes that directory. A new session restores each job whose pane or leased processes remain, and it never restarts a command.
|
|
187
|
+
|
|
147
188
|
Clones are separate session files in the Pi-selected session directory. Each contains only the active path. Pi names the clone file for a saved source session; otherwise, the extension creates and names it. Saved `pi-herdr-rename/title` entries restore display titles and semantic branches without another model request. Older titles get no migration.
|
|
148
189
|
|
|
149
190
|
## Limits and recovery
|
|
@@ -160,6 +201,9 @@ Clones are separate session files in the Pi-selected session directory. Each con
|
|
|
160
201
|
| Handoff cancellation | Before creation, nothing remains. After creation, reported resources remain; later launch or delivery steps stop. |
|
|
161
202
|
| Handoff start or prompt failure | Resources remain. Errors identify worktree, branch, workspace, tab, pane, and agent. No automatic cleanup occurs. |
|
|
162
203
|
| `agent_blocked` or `agent_prompt_stalled` | Prompt delivery failed. Inspect the agent before retrying. |
|
|
204
|
+
| `herdr_command` start before the command runs | The tool closes its pane and ends its write activity. Nothing ran. |
|
|
205
|
+
| `herdr_command` start with an unconfirmed `pane run` | The job and its write activity remain. Use `read`, then `stop`. |
|
|
206
|
+
| `herdr_command` stop that cannot prove the end | The job, its write activity, and its evidence in `config/pi-herdr-tools/commands/<id>/` remain. Stop the reported processes, then call `stop` again. |
|
|
163
207
|
|
|
164
208
|
Timed-out prompts can still arrive. Check `herdr agent get` and `herdr agent read`; resend with `herdr agent prompt` only if absent. Alternatively, run `/done` in the new worktree. Remove personal `handoff-worktree.md` copies to resolve package-prompt name collisions.
|
|
165
209
|
|
package/extensions/index.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { registerDiagnosticsCommand } from "@hcflabs/pi-config-store";
|
|
2
3
|
import registerBtwExtension, { BTW_TASK } from "../internal/btw.ts";
|
|
3
4
|
import herdrCloneExtension from "../internal/clone-tab.ts";
|
|
5
|
+
import herdrCommandExtension from "../internal/command.ts";
|
|
4
6
|
import herdrDoneExtension from "../internal/done.ts";
|
|
5
7
|
import herdrHandoffExtension from "../internal/handoff.ts";
|
|
6
8
|
import idleRecapExtension, { RECAP_TASK } from "../internal/recap.ts";
|
|
@@ -8,6 +10,7 @@ import herdrRenameExtension, { RENAME_TASK } from "../internal/rename.ts";
|
|
|
8
10
|
import { registerTaskModelsWarning } from "../internal/task-models.ts";
|
|
9
11
|
|
|
10
12
|
export default async function herdrToolsExtension(pi: ExtensionAPI): Promise<void> {
|
|
13
|
+
registerDiagnosticsCommand(pi);
|
|
11
14
|
registerTaskModelsWarning(pi, [RENAME_TASK, BTW_TASK, RECAP_TASK]);
|
|
12
15
|
herdrRenameExtension(pi);
|
|
13
16
|
idleRecapExtension(pi);
|
|
@@ -15,6 +18,7 @@ export default async function herdrToolsExtension(pi: ExtensionAPI): Promise<voi
|
|
|
15
18
|
herdrCloneExtension(pi);
|
|
16
19
|
herdrDoneExtension(pi);
|
|
17
20
|
herdrHandoffExtension(pi);
|
|
21
|
+
herdrCommandExtension(pi);
|
|
18
22
|
registerDialogStatus(pi);
|
|
19
23
|
}
|
|
20
24
|
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Run one herdr_command job in its pane. Usage: node command-runner.mjs <job-directory>
|
|
3
|
+
// The runner reads the command from launch.json, so the shell never parses the argument list.
|
|
4
|
+
// It saves the exit status in status.json, outside the terminal, because pane output can imitate any text.
|
|
5
|
+
// The command and its children inherit the open process lease file. A child that closes inherited files drops the lease,
|
|
6
|
+
// so the runner also records its process group. The shell makes the runner the leader of its own job group.
|
|
7
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
8
|
+
import { closeSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
|
|
11
|
+
const KILL_GRACE_MS = 10_000;
|
|
12
|
+
const directory = process.argv[2];
|
|
13
|
+
if (!directory) {
|
|
14
|
+
console.error("herdr_command runner: the job directory is missing.");
|
|
15
|
+
process.exit(2);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function save(name, value) {
|
|
19
|
+
const path = join(directory, name);
|
|
20
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
21
|
+
writeFileSync(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600, flag: "wx" });
|
|
22
|
+
renameSync(temporary, path);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const launch = JSON.parse(readFileSync(join(directory, "launch.json"), "utf8"));
|
|
26
|
+
let group;
|
|
27
|
+
try {
|
|
28
|
+
const pgid = Number(execFileSync("ps", ["-o", "pgid=", "-p", String(process.pid)], { encoding: "utf8" }).trim());
|
|
29
|
+
if (pgid === process.pid) group = pgid;
|
|
30
|
+
} catch { /* Without ps, the lease is the only process evidence. */ }
|
|
31
|
+
const lease = openSync(join(directory, "process.lease"), "r");
|
|
32
|
+
let timedOut = false;
|
|
33
|
+
let finished = false;
|
|
34
|
+
let killTimer;
|
|
35
|
+
|
|
36
|
+
const child = spawn(launch.command, launch.args, {
|
|
37
|
+
cwd: launch.cwd,
|
|
38
|
+
stdio: ["inherit", "inherit", "inherit", lease],
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
function finish(status) {
|
|
42
|
+
if (finished) return;
|
|
43
|
+
finished = true;
|
|
44
|
+
clearTimeout(runtimeTimer);
|
|
45
|
+
clearTimeout(killTimer);
|
|
46
|
+
save("status.json", { token: launch.token, ...status, timedOut, endedAt: Date.now() });
|
|
47
|
+
closeSync(lease);
|
|
48
|
+
const outcome = status.error ? `failed to start: ${status.error}` : status.signal ? `stopped by ${status.signal}` : `exited with code ${status.code}`;
|
|
49
|
+
console.log(`\n[herdr_command ${launch.id}] ${outcome}${timedOut ? " after the runtime limit" : ""}.`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Signal the whole job group when the runner leads it, so children that dropped the lease also get the signal. */
|
|
53
|
+
function signalJob(signal) {
|
|
54
|
+
if (group !== undefined) {
|
|
55
|
+
try { process.kill(-group, signal); return; } catch { /* Fall back to the direct child. */ }
|
|
56
|
+
}
|
|
57
|
+
child.kill(signal);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const runtimeTimer = setTimeout(() => {
|
|
61
|
+
timedOut = true;
|
|
62
|
+
signalJob("SIGTERM");
|
|
63
|
+
killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
|
|
64
|
+
}, launch.maxRuntimeMs);
|
|
65
|
+
|
|
66
|
+
child.once("spawn", () => save("started.json", { token: launch.token, pid: child.pid, runnerPid: process.pid, ...(group === undefined ? {} : { group }), startedAt: Date.now() }));
|
|
67
|
+
child.once("error", (error) => finish({ error: error.message.slice(0, 500) }));
|
|
68
|
+
child.once("exit", (code, signal) => finish({ code, signal }));
|
|
69
|
+
|
|
70
|
+
// Ctrl-C reaches the whole foreground group. The runner stays alive to save the child's status.
|
|
71
|
+
process.on("SIGINT", () => {});
|
|
72
|
+
process.on("SIGTERM", () => child.kill("SIGTERM"));
|
|
73
|
+
process.on("SIGHUP", () => child.kill("SIGHUP"));
|
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { createConfigStore, extensionConfigDir, field, formatConfigIssues, parsers, recordDiagnostic, registerConfigReporting } from "@hcflabs/pi-config-store";
|
|
8
|
+
import { awaitShellPrompt, createHerdrClient, hasHerdrErrorCode, herdrCommandFailure } from "@hcflabs/pi-herdr";
|
|
9
|
+
import { scanProcessLease } from "@hcflabs/pi-process";
|
|
10
|
+
import { isWithin, resolveRepoTarget } from "@hcflabs/pi-repo";
|
|
11
|
+
import { Type, type Static } from "typebox";
|
|
12
|
+
import { Check, Errors } from "typebox/value";
|
|
13
|
+
|
|
14
|
+
/** Event that tells checkout admission a long-running Main command can write in `cwd`. Payload: `{ jobId, cwd }`. */
|
|
15
|
+
export const CHECKOUT_ACTIVITY_START = "pi:checkout-activity:start";
|
|
16
|
+
/** Event that ends the activity of `jobId` after the job's processes are proved stopped. Payload: `{ jobId }`. */
|
|
17
|
+
export const CHECKOUT_ACTIVITY_END = "pi:checkout-activity:end";
|
|
18
|
+
|
|
19
|
+
const RUNNER = fileURLToPath(new URL("./command-runner.mjs", import.meta.url));
|
|
20
|
+
const JOB_ID = /^cmd-[0-9a-f]{16}$/;
|
|
21
|
+
const MAX_ARGV_BYTES = 64 * 1024;
|
|
22
|
+
const STATUS_MAX_BYTES = 4096;
|
|
23
|
+
const STOP_WAIT_MS = 5_000;
|
|
24
|
+
const POLL_MS = 100;
|
|
25
|
+
|
|
26
|
+
export type CommandSplit = "right" | "down";
|
|
27
|
+
export interface CommandPaneConfig {
|
|
28
|
+
split: CommandSplit;
|
|
29
|
+
maxActive: number;
|
|
30
|
+
maxRuntimeMinutes: number;
|
|
31
|
+
readLines: number;
|
|
32
|
+
maxReadBytes: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const DEFAULT_COMMAND_CONFIG: Readonly<CommandPaneConfig> = Object.freeze({
|
|
36
|
+
split: "right",
|
|
37
|
+
maxActive: 4,
|
|
38
|
+
maxRuntimeMinutes: 120,
|
|
39
|
+
readLines: 200,
|
|
40
|
+
maxReadBytes: 32 * 1024,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
/** `config/pi-herdr-tools/config.json`. An invalid value warns and uses its default. No value removes a limit. */
|
|
44
|
+
export function createCommandConfigStore(agentDir?: string) {
|
|
45
|
+
return createConfigStore({
|
|
46
|
+
extensionId: "pi-herdr-tools",
|
|
47
|
+
agentDir,
|
|
48
|
+
fields: {
|
|
49
|
+
commandPane: field(parsers.object({
|
|
50
|
+
split: field(parsers.oneOf(["right", "down"] as const), DEFAULT_COMMAND_CONFIG.split),
|
|
51
|
+
maxActive: field(parsers.integer({ min: 1, max: 16 }), DEFAULT_COMMAND_CONFIG.maxActive),
|
|
52
|
+
maxRuntimeMinutes: field(parsers.integer({ min: 1, max: 1440 }), DEFAULT_COMMAND_CONFIG.maxRuntimeMinutes),
|
|
53
|
+
readLines: field(parsers.integer({ min: 1, max: 1000 }), DEFAULT_COMMAND_CONFIG.readLines),
|
|
54
|
+
maxReadBytes: field(parsers.integer({ min: 1024, max: 65_536 }), DEFAULT_COMMAND_CONFIG.maxReadBytes),
|
|
55
|
+
}), DEFAULT_COMMAND_CONFIG),
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const Text = (description: string) => Type.String({ minLength: 1, description });
|
|
61
|
+
const CommandParams = Type.Object({
|
|
62
|
+
action: Type.Union([Type.Literal("start"), Type.Literal("read"), Type.Literal("stop")], {
|
|
63
|
+
description: "start runs a command in a new pane, read shows recent output and status, stop ends the job and closes its pane",
|
|
64
|
+
}),
|
|
65
|
+
command: Type.Optional(Text("start: the executable. No shell parses it. To use a shell, name the shell, for example bash with args [\"-lc\", \"make test\"].")),
|
|
66
|
+
args: Type.Optional(Type.Array(Type.String(), { maxItems: 128, description: "start: the argument list. The default is []." })),
|
|
67
|
+
repo: Type.Optional(Text("start: a child Git repository, as a path relative to the Pi working directory")),
|
|
68
|
+
cwd: Type.Optional(Text("start: a directory relative to repo, or to the Pi working directory without repo")),
|
|
69
|
+
access: Type.Optional(Type.Union([Type.Literal("read"), Type.Literal("write")], {
|
|
70
|
+
description: "start: write when the command can change files, Git state, or external resources. A write job blocks direct subagent writers in its checkout until stop proves it ended. Nothing enforces read.",
|
|
71
|
+
})),
|
|
72
|
+
id: Type.Optional(Type.String({ pattern: JOB_ID.source, description: "read and stop: the job ID that start returned" })),
|
|
73
|
+
lines: Type.Optional(Type.Integer({ minimum: 1, maximum: 1000, description: "read: the number of recent lines" })),
|
|
74
|
+
}, { additionalProperties: false });
|
|
75
|
+
type Params = Static<typeof CommandParams>;
|
|
76
|
+
|
|
77
|
+
const START_ONLY = ["command", "args", "repo", "cwd", "access"] as const;
|
|
78
|
+
|
|
79
|
+
/** Check the fields of each action. The tool takes no shell string and no raw pane ID. */
|
|
80
|
+
export function parseCommandParams(value: unknown): Params {
|
|
81
|
+
if (!Check(CommandParams, value)) {
|
|
82
|
+
const issue = Errors(CommandParams, value)[0];
|
|
83
|
+
throw new Error(`herdr_command parameters are invalid${issue ? ` at ${issue.instancePath || "/"}: ${issue.message}` : ""}.`);
|
|
84
|
+
}
|
|
85
|
+
const params = value as Params;
|
|
86
|
+
if (params.action === "start") {
|
|
87
|
+
if (params.command === undefined || params.access === undefined) throw new Error("herdr_command start requires command and access.");
|
|
88
|
+
if (params.id !== undefined || params.lines !== undefined) throw new Error("herdr_command start does not accept id or lines.");
|
|
89
|
+
const argv = [params.command, ...(params.args ?? [])];
|
|
90
|
+
if (argv.some((arg) => arg.includes("\0"))) throw new Error("herdr_command arguments cannot contain NUL.");
|
|
91
|
+
if (Buffer.byteLength(argv.join("\0"), "utf8") > MAX_ARGV_BYTES) throw new Error("herdr_command arguments are larger than 64 KiB.");
|
|
92
|
+
} else {
|
|
93
|
+
if (params.id === undefined) throw new Error(`herdr_command ${params.action} requires id.`);
|
|
94
|
+
const extra = START_ONLY.filter((key) => params[key] !== undefined);
|
|
95
|
+
if (extra.length) throw new Error(`herdr_command ${params.action} does not accept ${extra.join(", ")}.`);
|
|
96
|
+
if (params.action === "stop" && params.lines !== undefined) throw new Error("herdr_command stop does not accept lines.");
|
|
97
|
+
}
|
|
98
|
+
return params;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Quote one word for a POSIX shell. */
|
|
102
|
+
const shellQuote = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;
|
|
103
|
+
|
|
104
|
+
type Job = {
|
|
105
|
+
id: string;
|
|
106
|
+
token: string;
|
|
107
|
+
directory: string;
|
|
108
|
+
paneId: string;
|
|
109
|
+
/** Herdr's terminal identity of the job pane. A pane ID alone can name a later pane. */
|
|
110
|
+
terminalId: string;
|
|
111
|
+
/** Device and inode of the lease file at creation. A replaced or hard-linked lease fails the check. */
|
|
112
|
+
lease: { dev: number; ino: number };
|
|
113
|
+
cwd: string;
|
|
114
|
+
command: string;
|
|
115
|
+
args: string[];
|
|
116
|
+
access: "read" | "write";
|
|
117
|
+
maxRuntimeMs: number;
|
|
118
|
+
activity: boolean;
|
|
119
|
+
/** Set when stop proved that the pane is closed and the lease has no holders. */
|
|
120
|
+
stopped?: boolean;
|
|
121
|
+
/** Set when command submission could not be confirmed. The job keeps its activity. */
|
|
122
|
+
uncertain?: string;
|
|
123
|
+
/** The status at a proved stop. The job directory is removed after the proof. */
|
|
124
|
+
finalStatus?: Status;
|
|
125
|
+
/** The runner's process group, when the runner leads its own job group. */
|
|
126
|
+
group?: number;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
type Status =
|
|
130
|
+
| { state: "starting" }
|
|
131
|
+
| { state: "running"; pid: number; group?: number }
|
|
132
|
+
| { state: "ended"; code: number | null; signal: string | null; timedOut: boolean; error?: string };
|
|
133
|
+
|
|
134
|
+
async function readJson(path: string): Promise<Record<string, unknown> | undefined> {
|
|
135
|
+
let text: string;
|
|
136
|
+
try { text = await readFile(path, "utf8"); }
|
|
137
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }
|
|
138
|
+
if (Buffer.byteLength(text, "utf8") > STATUS_MAX_BYTES) throw new Error(`${path} is larger than ${STATUS_MAX_BYTES} bytes.`);
|
|
139
|
+
const value: unknown = JSON.parse(text);
|
|
140
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${path} is not a JSON object.`);
|
|
141
|
+
return value as Record<string, unknown>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Saved process status. The runner writes it outside the terminal; screen text is never status evidence. */
|
|
145
|
+
export async function jobStatus(job: Pick<Job, "directory" | "token">): Promise<Status> {
|
|
146
|
+
const ended = await readJson(join(job.directory, "status.json"));
|
|
147
|
+
if (ended) {
|
|
148
|
+
if (ended.token !== job.token) throw new Error("The job status belongs to another job token.");
|
|
149
|
+
return {
|
|
150
|
+
state: "ended",
|
|
151
|
+
code: typeof ended.code === "number" ? ended.code : null,
|
|
152
|
+
signal: typeof ended.signal === "string" ? ended.signal : null,
|
|
153
|
+
timedOut: ended.timedOut === true,
|
|
154
|
+
...(typeof ended.error === "string" ? { error: ended.error } : {}),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
const started = await readJson(join(job.directory, "started.json"));
|
|
158
|
+
if (!started) return { state: "starting" };
|
|
159
|
+
const positive = (value: unknown) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
160
|
+
if (started.token !== job.token || !positive(started.pid) || (started.group !== undefined && !positive(started.group))) {
|
|
161
|
+
throw new Error("The job start record is malformed or belongs to another job token.");
|
|
162
|
+
}
|
|
163
|
+
return { state: "running", pid: started.pid as number, ...(started.group === undefined ? {} : { group: started.group as number }) };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const describeStatus = (status: Status) => status.state === "ended"
|
|
167
|
+
? status.error ? `failed to start: ${status.error}` : `${status.signal ? `stopped by ${status.signal}` : `exited with code ${status.code}`}${status.timedOut ? " after the runtime limit" : ""}`
|
|
168
|
+
: status.state;
|
|
169
|
+
|
|
170
|
+
/** Register `herdr_command` only inside Herdr. Main uses it to run a long command in a pane and read its output. */
|
|
171
|
+
export default function herdrCommandExtension(pi: ExtensionAPI, options: { agentDir?: string; lsof?: string } = {}): void {
|
|
172
|
+
if (process.env.HERDR_ENV !== "1") return;
|
|
173
|
+
const herdr = createHerdrClient<{ cwd: string; signal?: AbortSignal }>(pi.exec.bind(pi));
|
|
174
|
+
const store = createCommandConfigStore(options.agentDir);
|
|
175
|
+
const reporter = registerConfigReporting(pi, [store]);
|
|
176
|
+
const jobs = new Map<string, Job>();
|
|
177
|
+
const lsof = options.lsof ?? "lsof";
|
|
178
|
+
const commandsDirectory = join(extensionConfigDir("pi-herdr-tools", options.agentDir), "commands");
|
|
179
|
+
let closed = false;
|
|
180
|
+
|
|
181
|
+
const endActivity = (job: Job) => {
|
|
182
|
+
if (!job.activity) return;
|
|
183
|
+
job.activity = false;
|
|
184
|
+
pi.events.emit(CHECKOUT_ACTIVITY_END, { jobId: job.id });
|
|
185
|
+
};
|
|
186
|
+
const leaseHolders = async (job: Job) => {
|
|
187
|
+
const path = join(job.directory, "process.lease");
|
|
188
|
+
const info = await lstat(path);
|
|
189
|
+
if (info.dev !== job.lease.dev || info.ino !== job.lease.ino) throw new Error(`Job ${job.id}: the lease file was replaced; stop is unproved. Evidence: ${job.directory}.`);
|
|
190
|
+
return await scanProcessLease(path, (args) => pi.exec(lsof, args, { cwd: job.directory, timeout: 5_000 }));
|
|
191
|
+
};
|
|
192
|
+
/** Whether the job pane still exists. A pane with the same ID but another terminal is a later pane, not the job pane. */
|
|
193
|
+
const paneExists = async (job: Job) => {
|
|
194
|
+
const result = await herdr.exec(["pane", "get", job.paneId], { cwd: job.cwd });
|
|
195
|
+
if (hasHerdrErrorCode(result, "pane_not_found")) return false;
|
|
196
|
+
if (result.code !== 0 || result.killed) throw new Error(`Herdr could not inspect pane ${job.paneId}: ${herdrCommandFailure(["pane", "get", job.paneId], result)}`);
|
|
197
|
+
const pane = (JSON.parse(result.stdout) as { result?: { pane?: Record<string, unknown> } }).result?.pane;
|
|
198
|
+
return pane?.pane_id === job.paneId && pane.terminal_id === job.terminalId;
|
|
199
|
+
};
|
|
200
|
+
/** PIDs in the job's process group. The group outlives the runner while a child that dropped the lease runs. */
|
|
201
|
+
const groupMembers = async (job: Job, group: number) => {
|
|
202
|
+
const result = await pi.exec("pgrep", ["-g", String(group)], { cwd: job.directory, timeout: 5_000 });
|
|
203
|
+
if (result.code === 1 && !result.stdout.trim()) return [];
|
|
204
|
+
if (result.code !== 0 || result.killed) throw new Error(`Job ${job.id}: pgrep could not list process group ${group}; stop is unproved.`);
|
|
205
|
+
return result.stdout.trim().split(/\s+/).map(Number).filter((pid) => Number.isSafeInteger(pid) && pid > 0);
|
|
206
|
+
};
|
|
207
|
+
const signal = (target: number, name: NodeJS.Signals) => {
|
|
208
|
+
try { process.kill(target, name); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
/** Stop the exact job: signal leased processes, close its own pane, then prove pane absence and empty lease scans. */
|
|
212
|
+
const stopJob = async (job: Job): Promise<string> => {
|
|
213
|
+
if (job.stopped) return `Job ${job.id} is already stopped.`;
|
|
214
|
+
// The start record keeps the runner's process group also after the runner saved its status.
|
|
215
|
+
const started = await readJson(join(job.directory, "started.json")).catch(() => undefined);
|
|
216
|
+
const savedGroup = started?.token === job.token && typeof started.group === "number" && Number.isSafeInteger(started.group) && started.group > 1
|
|
217
|
+
? started.group : undefined;
|
|
218
|
+
const group = job.group ?? savedGroup;
|
|
219
|
+
if (group !== undefined) job.group = group;
|
|
220
|
+
// Signal the processes that hold this job's private lease, also after the runner saved a status:
|
|
221
|
+
// a background child can outlive the command. While a lease holder runs, the job group is still ours.
|
|
222
|
+
for (const name of ["SIGTERM", "SIGKILL"] as const) {
|
|
223
|
+
const holders = await leaseHolders(job);
|
|
224
|
+
if (!holders.length) break;
|
|
225
|
+
if (group !== undefined) signal(-group, name);
|
|
226
|
+
for (const pid of holders) signal(pid, name);
|
|
227
|
+
for (let waited = 0; waited < STOP_WAIT_MS && (await leaseHolders(job)).length; waited += POLL_MS) await delay(POLL_MS);
|
|
228
|
+
}
|
|
229
|
+
if (group !== undefined) {
|
|
230
|
+
let members = await groupMembers(job, group);
|
|
231
|
+
if (members.length) {
|
|
232
|
+
// The runner is dead here, because it holds the lease until it exits. A live process with the group ID
|
|
233
|
+
// is a later process that reused the number, so its group is not the job group.
|
|
234
|
+
let leaderAlive = true;
|
|
235
|
+
try { process.kill(group, 0); } catch (error) { leaderAlive = (error as NodeJS.ErrnoException).code !== "ESRCH"; }
|
|
236
|
+
if (leaderAlive) throw new Error(`Job ${job.id}: process group ${group} now has another leader; stop is unproved. Check processes ${members.join(", ")}.`);
|
|
237
|
+
for (const name of ["SIGTERM", "SIGKILL"] as const) {
|
|
238
|
+
signal(-group, name);
|
|
239
|
+
for (let waited = 0; waited < STOP_WAIT_MS && (members = await groupMembers(job, group)).length; waited += POLL_MS) await delay(POLL_MS);
|
|
240
|
+
if (!members.length) break;
|
|
241
|
+
}
|
|
242
|
+
if (members.length) throw new Error(`Job ${job.id}: processes ${members.join(", ")} remain in its process group; stop is unproved.`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const status = await jobStatus(job);
|
|
246
|
+
if (await paneExists(job)) {
|
|
247
|
+
const closed = await herdr.exec(["pane", "close", job.paneId], { cwd: job.cwd });
|
|
248
|
+
if (closed.code !== 0 || closed.killed) throw new Error(`Job ${job.id}: Herdr did not close pane ${job.paneId}: ${herdrCommandFailure(["pane", "close", job.paneId], closed)}`);
|
|
249
|
+
if (await paneExists(job)) throw new Error(`Job ${job.id}: pane ${job.paneId} is still present; stop is unproved.`);
|
|
250
|
+
}
|
|
251
|
+
for (let scan = 0; scan < 2; scan++) {
|
|
252
|
+
const holders = await leaseHolders(job);
|
|
253
|
+
if (holders.length) throw new Error(`Job ${job.id}: processes ${holders.join(", ")} still hold the job lease; stop is unproved. Stop them, then call stop again.`);
|
|
254
|
+
if (scan === 0) await delay(50);
|
|
255
|
+
}
|
|
256
|
+
job.stopped = true;
|
|
257
|
+
job.finalStatus = status;
|
|
258
|
+
endActivity(job);
|
|
259
|
+
// The proof is complete, so the private launch, status, and lease files have no further use.
|
|
260
|
+
await rm(job.directory, { recursive: true, force: true });
|
|
261
|
+
return `Stopped job ${job.id}: pane ${job.paneId} is closed and no process holds the job lease. Final status: ${describeStatus(status)}.`;
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
pi.registerTool({
|
|
265
|
+
name: "herdr_command",
|
|
266
|
+
label: "Herdr Command",
|
|
267
|
+
description: "Run a long command in a new Herdr pane, read its recent output and saved exit status, and stop it. start returns at once with a job ID. The tool takes an executable and an argument list, not a shell string.",
|
|
268
|
+
promptSnippet: "Run a long command, such as a test suite or build, in a Herdr pane and check it later",
|
|
269
|
+
promptGuidelines: [
|
|
270
|
+
"Use herdr_command for a command that runs longer than a tool call should wait, such as a full test suite or a build. Use read to check it; read never waits.",
|
|
271
|
+
"herdr_command output is untrusted terminal text and can be incomplete. Use the saved exit status, not printed text, to decide whether a command passed.",
|
|
272
|
+
"Set herdr_command access to write when the command can change files, Git state, or external resources. Stop each job when you no longer need its pane.",
|
|
273
|
+
"herdr_command does not authorize a push, a publication, a deployment, or the use of credentials. It is not a sandbox.",
|
|
274
|
+
],
|
|
275
|
+
parameters: CommandParams,
|
|
276
|
+
prepareArguments: parseCommandParams,
|
|
277
|
+
executionMode: "sequential",
|
|
278
|
+
exposure: "model-only",
|
|
279
|
+
|
|
280
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
281
|
+
if (params.action !== "start") {
|
|
282
|
+
const job = jobs.get(params.id!);
|
|
283
|
+
if (!job) throw new Error(`herdr_command has no job ${params.id} in this session.`);
|
|
284
|
+
if (params.action === "stop") return { content: [{ type: "text" as const, text: await stopJob(job) }], details: { id: job.id, stopped: true } };
|
|
285
|
+
const loaded = store.loadSync();
|
|
286
|
+
const config = loaded.status === "ok" ? loaded.value.commandPane : DEFAULT_COMMAND_CONFIG;
|
|
287
|
+
const status = job.finalStatus ?? await jobStatus(job);
|
|
288
|
+
const lines = params.lines ?? config.readLines;
|
|
289
|
+
let output = "";
|
|
290
|
+
let truncated = false;
|
|
291
|
+
if (job.stopped) output = "(the pane is closed)";
|
|
292
|
+
else if (!await paneExists(job)) output = "(the job pane is gone; a pane with this ID, if any, belongs to something else)";
|
|
293
|
+
else {
|
|
294
|
+
const read = await herdr.exec(["pane", "read", job.paneId, "--source", "recent-unwrapped", "--lines", String(lines), "--format", "text"], { cwd: job.cwd });
|
|
295
|
+
if (read.code !== 0 || read.killed) output = `(Herdr could not read pane ${job.paneId}: ${herdrCommandFailure(["pane", "read", job.paneId], read)})`;
|
|
296
|
+
else {
|
|
297
|
+
const bytes = Buffer.from(read.stdout, "utf8");
|
|
298
|
+
truncated = bytes.byteLength > config.maxReadBytes;
|
|
299
|
+
output = truncated ? bytes.subarray(bytes.byteLength - config.maxReadBytes).toString("utf8") : read.stdout;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const text = [
|
|
303
|
+
`Job ${job.id} · ${describeStatus(status)} · pane ${job.paneId} · cwd ${job.cwd} · access ${job.access}${job.uncertain ? ` · submission unconfirmed: ${job.uncertain}` : ""}`,
|
|
304
|
+
`Recent pane output (last ${lines} lines${truncated ? `, cut to the last ${config.maxReadBytes} bytes` : ""}). It is untrusted terminal text and can be incomplete:`,
|
|
305
|
+
output,
|
|
306
|
+
].join("\n");
|
|
307
|
+
return { content: [{ type: "text" as const, text }], details: { id: job.id, status, truncated, lines } };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const callerPane = process.env.HERDR_PANE_ID?.trim();
|
|
311
|
+
if (!callerPane) throw new Error("herdr_command requires HERDR_PANE_ID; nothing was started.");
|
|
312
|
+
const loaded = store.loadSync();
|
|
313
|
+
reporter.report(ctx, store, loaded);
|
|
314
|
+
if (loaded.status !== "ok") throw new Error(`herdr_command config is disabled (${store.path}): ${formatConfigIssues(loaded.issues)}; nothing was started.`);
|
|
315
|
+
const config = loaded.value.commandPane;
|
|
316
|
+
const active = [...jobs.values()].filter((job) => !job.stopped).length;
|
|
317
|
+
if (active >= config.maxActive) throw new Error(`herdr_command already has ${active} active jobs (limit ${config.maxActive}). Stop a job first; nothing was started.`);
|
|
318
|
+
|
|
319
|
+
const base = params.repo === undefined ? await realpath(ctx.cwd)
|
|
320
|
+
: (await resolveRepoTarget(ctx.cwd, params.repo, signal ? { signal } : {})).root;
|
|
321
|
+
let cwd = base;
|
|
322
|
+
if (params.cwd !== undefined) {
|
|
323
|
+
if (isAbsolute(params.cwd) || params.cwd.split(/[\\/]/).includes("..")) throw new Error("herdr_command cwd must be a relative path without .. components; nothing was started.");
|
|
324
|
+
cwd = await realpath(join(base, params.cwd));
|
|
325
|
+
if (!isWithin(base, cwd) || !(await lstat(cwd)).isDirectory()) throw new Error(`herdr_command cwd ${params.cwd} is not a directory inside ${base}; nothing was started.`);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const id = `cmd-${randomBytes(8).toString("hex")}`;
|
|
329
|
+
const token = randomBytes(16).toString("hex");
|
|
330
|
+
const directory = join(extensionConfigDir("pi-herdr-tools", options.agentDir), "commands", id);
|
|
331
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
332
|
+
const maxRuntimeMs = config.maxRuntimeMinutes * 60_000;
|
|
333
|
+
await writeFile(join(directory, "launch.json"), `${JSON.stringify({ id, token, command: params.command, args: params.args ?? [], cwd, maxRuntimeMs })}\n`, { mode: 0o600, flag: "wx" });
|
|
334
|
+
await writeFile(join(directory, "process.lease"), "", { mode: 0o600, flag: "wx" });
|
|
335
|
+
const leaseInfo = await lstat(join(directory, "process.lease"));
|
|
336
|
+
signal?.throwIfAborted();
|
|
337
|
+
|
|
338
|
+
const job: Job = { id, token, directory, paneId: "", terminalId: "", lease: { dev: leaseInfo.dev, ino: leaseInfo.ino }, cwd, command: params.command!, args: params.args ?? [], access: params.access!, maxRuntimeMs, activity: false };
|
|
339
|
+
// Register the activity before the command can start, so a direct writer cannot start in the same checkout.
|
|
340
|
+
if (job.access === "write") {
|
|
341
|
+
job.activity = true;
|
|
342
|
+
pi.events.emit(CHECKOUT_ACTIVITY_START, { jobId: id, cwd });
|
|
343
|
+
}
|
|
344
|
+
const splitArgs = ["pane", "split", callerPane, "--direction", config.split, "--no-focus", "--cwd", cwd];
|
|
345
|
+
const split = await herdr.exec(splitArgs, { cwd });
|
|
346
|
+
let paneId: string | undefined;
|
|
347
|
+
let terminalId: string | undefined;
|
|
348
|
+
try {
|
|
349
|
+
if (split.code !== 0 || split.killed) throw new Error(herdrCommandFailure(splitArgs, split));
|
|
350
|
+
const pane = (JSON.parse(split.stdout) as { result?: { pane?: Record<string, unknown> } }).result?.pane;
|
|
351
|
+
paneId = typeof pane?.pane_id === "string" ? pane.pane_id : undefined;
|
|
352
|
+
terminalId = typeof pane?.terminal_id === "string" && pane.terminal_id ? pane.terminal_id : undefined;
|
|
353
|
+
if (!paneId || !terminalId || paneId === callerPane || pane?.focused !== false || typeof pane.cwd !== "string" || await realpath(pane.cwd) !== cwd) {
|
|
354
|
+
throw new Error(`Herdr returned an unverified pane (${paneId ?? "no pane ID"}).`);
|
|
355
|
+
}
|
|
356
|
+
} catch (error) {
|
|
357
|
+
// No command was submitted, so no job process can exist.
|
|
358
|
+
endActivity(job);
|
|
359
|
+
throw new Error(`herdr_command could not create a verified pane${paneId ? `; inspect pane ${paneId}` : ""}: ${error instanceof Error ? error.message : String(error)}. No command was started.`, { cause: error });
|
|
360
|
+
}
|
|
361
|
+
job.paneId = paneId;
|
|
362
|
+
job.terminalId = terminalId!;
|
|
363
|
+
jobs.set(id, job);
|
|
364
|
+
await writeFile(join(directory, "job.json"), `${JSON.stringify({ id, token, paneId, terminalId, cwd, access: job.access })}\n`, { mode: 0o600, flag: "wx" });
|
|
365
|
+
// A session that ended during the split must not receive a new command.
|
|
366
|
+
if (closed) {
|
|
367
|
+
await herdr.exec(["pane", "close", paneId], { cwd });
|
|
368
|
+
jobs.delete(id);
|
|
369
|
+
endActivity(job);
|
|
370
|
+
throw new Error("herdr_command: the session ended during start. The pane was closed; no command was started.");
|
|
371
|
+
}
|
|
372
|
+
const ready = await awaitShellPrompt(herdr, paneId, { cwd }, undefined, true, true);
|
|
373
|
+
if (ready) {
|
|
374
|
+
await herdr.exec(["pane", "close", paneId], { cwd });
|
|
375
|
+
jobs.delete(id);
|
|
376
|
+
endActivity(job);
|
|
377
|
+
throw new Error(`herdr_command pane ${paneId} did not show a ready shell: ${herdrCommandFailure(["pane", "process-info", paneId], ready)}. The pane was closed; no command was started.`);
|
|
378
|
+
}
|
|
379
|
+
const line = [process.execPath, RUNNER, directory].map(shellQuote).join(" ");
|
|
380
|
+
const ran = await herdr.exec(["pane", "run", paneId, line], { cwd });
|
|
381
|
+
if (ran.code !== 0 || ran.killed) {
|
|
382
|
+
// The text can still have reached the shell. Keep the job and its activity until stop proves the end.
|
|
383
|
+
job.uncertain = herdrCommandFailure(["pane", "run", paneId], ran);
|
|
384
|
+
throw new Error(`herdr_command could not confirm the start of job ${id} in pane ${paneId}: ${job.uncertain}. Use read, then stop, for this job.`);
|
|
385
|
+
}
|
|
386
|
+
const text = `Started job ${id} in pane ${paneId} (cwd ${cwd}, access ${job.access}). Use herdr_command read with this id to check it; read never waits. Use stop to end the job and close its pane.`;
|
|
387
|
+
return { content: [{ type: "text" as const, text }], details: { id, paneId, cwd, access: job.access } };
|
|
388
|
+
},
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
// Jobs of an earlier session runtime can still run. Restore each job whose pane or leased processes remain,
|
|
392
|
+
// and its write activity, so that stop can still prove its end. Do not restart any command.
|
|
393
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
394
|
+
closed = false;
|
|
395
|
+
let entries: string[];
|
|
396
|
+
try { entries = await readdir(commandsDirectory); }
|
|
397
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return; throw error; }
|
|
398
|
+
for (const id of entries) {
|
|
399
|
+
if (!JOB_ID.test(id) || jobs.has(id)) continue;
|
|
400
|
+
const directory = join(commandsDirectory, id);
|
|
401
|
+
try {
|
|
402
|
+
const saved = await readJson(join(directory, "job.json"));
|
|
403
|
+
const launch = await readJson(join(directory, "launch.json"));
|
|
404
|
+
if (!saved || !launch || saved.id !== id || saved.token !== launch.token || typeof saved.paneId !== "string"
|
|
405
|
+
|| typeof saved.terminalId !== "string" || typeof saved.cwd !== "string" || (saved.access !== "read" && saved.access !== "write")) continue;
|
|
406
|
+
const leaseInfo = await lstat(join(directory, "process.lease"));
|
|
407
|
+
const job: Job = { id, token: saved.token as string, directory, paneId: saved.paneId, terminalId: saved.terminalId,
|
|
408
|
+
lease: { dev: leaseInfo.dev, ino: leaseInfo.ino }, cwd: saved.cwd, command: String(launch.command), args: [],
|
|
409
|
+
access: saved.access, maxRuntimeMs: 0, activity: false };
|
|
410
|
+
if (!(await leaseHolders(job)).length && !await paneExists(job)) {
|
|
411
|
+
await rm(directory, { recursive: true, force: true });
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
jobs.set(id, job);
|
|
415
|
+
if (job.access === "write") {
|
|
416
|
+
job.activity = true;
|
|
417
|
+
pi.events.emit(CHECKOUT_ACTIVITY_START, { jobId: id, cwd: job.cwd });
|
|
418
|
+
}
|
|
419
|
+
const text = `herdr_command restored job ${id} from an earlier session (pane ${job.paneId}, access ${job.access}). Use herdr_command stop with this id to end it.`;
|
|
420
|
+
if (ctx.hasUI) ctx.ui.notify(text, "warning");
|
|
421
|
+
else process.stderr.write(`${text}\n`);
|
|
422
|
+
} catch (error) {
|
|
423
|
+
recordDiagnostic("pi-herdr-tools", "error", `herdr_command: job ${id} could not be restored: ${error instanceof Error ? error.message : String(error)} Evidence: ${directory}.`, ctx);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
429
|
+
closed = true;
|
|
430
|
+
// A job does not outlive its session. Unproved stops keep their evidence in the job directory.
|
|
431
|
+
for (const job of jobs.values()) {
|
|
432
|
+
if (job.stopped) continue;
|
|
433
|
+
try { await stopJob(job); }
|
|
434
|
+
catch (error) { recordDiagnostic("pi-herdr-tools", "error", `herdr_command: ${error instanceof Error ? error.message : String(error)} Evidence: ${job.directory}.`, ctx); }
|
|
435
|
+
}
|
|
436
|
+
jobs.clear();
|
|
437
|
+
});
|
|
438
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hcflabs/pi-herdr-tools",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.0",
|
|
4
4
|
"description": "Clone, hand off, name, and finish Pi conversations in Herdr, with mergeable side questions.",
|
|
5
5
|
"keywords": ["pi-package", "pi", "herdr", "session", "clone", "side-thread", "title"],
|
|
6
6
|
"type": "module",
|
|
@@ -19,8 +19,9 @@
|
|
|
19
19
|
"typebox": "^1.3.15"
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@hcflabs/pi-config-store": "^4.
|
|
23
|
-
"@hcflabs/pi-herdr": "^0.
|
|
22
|
+
"@hcflabs/pi-config-store": "^4.2.0",
|
|
23
|
+
"@hcflabs/pi-herdr": "^0.7.0",
|
|
24
|
+
"@hcflabs/pi-process": "^0.3.0",
|
|
24
25
|
"@hcflabs/pi-repo": "^0.1.0",
|
|
25
26
|
"@hcflabs/pi-task-models": "^9.0.0"
|
|
26
27
|
},
|