@henryqw/pi-herdr 0.5.2 → 0.6.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 +24 -1
- package/dist/admission.d.ts +50 -0
- package/dist/admission.js +145 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/socket.d.ts +11 -0
- package/dist/socket.js +80 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# `@henryqw/pi-herdr`
|
|
2
2
|
|
|
3
|
-
Call the Herdr CLI from Node through one
|
|
3
|
+
Call the Herdr command-line interface (CLI) or Unix socket from Node through one shared package. Extension authors share process handling without copying the list of Herdr commands. Pi users usually install a Herdr companion extension instead.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -31,8 +31,31 @@ For a ready-to-use Pi workflow, see [`@henryqw/pi-herdr-tools`](https://pi.henry
|
|
|
31
31
|
| `run` | function | Requires a successful exit and returns stdout. |
|
|
32
32
|
| `json` | function | Requires a successful exit and parses a JSON object. |
|
|
33
33
|
| `hasHerdrErrorCode` | function | Detects structured CLI errors in stdout or stderr. |
|
|
34
|
+
| `requestHerdr` | function | Sends one bounded Unix socket request without retries. |
|
|
35
|
+
| `HerdrRequestError` | class | Reports a structured error code and whether dispatch was possible. |
|
|
36
|
+
| `checkoutAdmission` | function | Shares process-local checkout ownership through Pi's public event bus. |
|
|
37
|
+
| `checkoutKey` | function | Resolves the canonical checkout for admission. |
|
|
38
|
+
| `registerCheckoutAdmission` | function | Registers the existing direct-writer policy and returns its ownership hold function. |
|
|
34
39
|
| `startPiAgent` | function | Validates and runs the shared `agent start --kind pi --pane ... --` boundary after a shell-readiness probe. |
|
|
35
40
|
|
|
41
|
+
### Socket requests
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { requestHerdr } from "@henryqw/pi-herdr";
|
|
45
|
+
|
|
46
|
+
const result = await requestHerdr("session.snapshot", {}, { signal });
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`requestHerdr(method, params, options)` uses the inherited `HERDR_SOCKET_PATH`, or an explicit `socketPath`. Requests have unique identities; responses must match. The default timeout is 10000 milliseconds, with an allowed range of 1 to 60000. Request and response limits are 262144 and 1048576 bytes. An optional `AbortSignal` stops the local wait.
|
|
50
|
+
|
|
51
|
+
Errors expose `code` and `dispatched`. If `dispatched` is true, a mutation can have taken effect despite the error. Cancellation, timeout, or a closed connection is not permission to repeat a mutation. This function never retries. Callers validate method-specific results and own durable recovery. The existing CLI client and named-agent startup are unchanged.
|
|
52
|
+
|
|
53
|
+
### Checkout admission
|
|
54
|
+
|
|
55
|
+
`checkoutAdmission(pi)` finds one coordinator through Pi's public event bus. Call `install(pi)` to register tool lifecycle guards. `guard(name, refresh)` installs an awaited recovery check before writes. `reserve(owner, checkout)` returns a release function only when no admitted writer or Main write is active. `restore(owner, checkout)` restores durable ownership; `release(owner)` requires caller-proved completion.
|
|
56
|
+
|
|
57
|
+
`registerCheckoutAdmission(pi, directCanWrite)` keeps the direct-subagent policy: Main writes can overlap, but direct writers must wait for them and exclude other writes. A returned hold function keeps a direct request admitted beyond its tool result. Consumers must restore durable command ownership before allowing writes after restart. These mechanisms do not intercept external processes or provide a sandbox.
|
|
58
|
+
|
|
36
59
|
### `startPiAgent`
|
|
37
60
|
|
|
38
61
|
On macOS, a shell that starts or runs a prompt hook can lose Enter for a launch command longer than 1024 bytes. The pane then waits forever. To prevent this, the helper first checks `pane process-info`. When the pane shell owns the foreground process group, it runs `pane run <pane> "echo <token>"` and polls `pane read` for up to 20 seconds. The probe passes when the token appears on its own line, with a prompt after it.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
interface AdmissionHost {
|
|
2
|
+
events?: {
|
|
3
|
+
on(channel: string, handler: (data: unknown) => void): () => void;
|
|
4
|
+
emit(channel: string, data: unknown): void;
|
|
5
|
+
};
|
|
6
|
+
exec(command: string, args: string[], options: {
|
|
7
|
+
cwd: string;
|
|
8
|
+
timeout: number;
|
|
9
|
+
}): Promise<{
|
|
10
|
+
code: number;
|
|
11
|
+
killed?: boolean;
|
|
12
|
+
stdout: string;
|
|
13
|
+
}>;
|
|
14
|
+
on(event: "tool_call", handler: (event: {
|
|
15
|
+
toolName: string;
|
|
16
|
+
toolCallId: string;
|
|
17
|
+
input: unknown;
|
|
18
|
+
}, ctx: {
|
|
19
|
+
cwd: string;
|
|
20
|
+
}) => Promise<{
|
|
21
|
+
block: true;
|
|
22
|
+
reason: string;
|
|
23
|
+
} | undefined>): unknown;
|
|
24
|
+
on(event: "tool_result" | "tool_execution_end", handler: (event: {
|
|
25
|
+
toolCallId: string;
|
|
26
|
+
}) => void): unknown;
|
|
27
|
+
on(event: "session_start" | "session_shutdown", handler: () => void): unknown;
|
|
28
|
+
}
|
|
29
|
+
export declare function checkoutKey(pi: Pick<AdmissionHost, "exec">, ctx: {
|
|
30
|
+
cwd: string;
|
|
31
|
+
}): Promise<string>;
|
|
32
|
+
/**
|
|
33
|
+
* Reserve checkouts only for direct writers. Main writes can run together, but
|
|
34
|
+
* each call must finish before a direct writer can start in that checkout.
|
|
35
|
+
* External processes and trusted extension lifecycle code are not intercepted.
|
|
36
|
+
*/
|
|
37
|
+
declare function createAdmission(): {
|
|
38
|
+
install: (host: AdmissionHost) => void;
|
|
39
|
+
hold: (toolCallId: string) => () => void;
|
|
40
|
+
classifyDirect: (classify: (input: unknown) => boolean) => void;
|
|
41
|
+
guard: (name: string, refresh: () => Promise<void>) => void;
|
|
42
|
+
restore: (owner: string, checkout: string) => void;
|
|
43
|
+
release: (owner: string) => void;
|
|
44
|
+
reserve(owner: string, checkout: string): Promise<() => void>;
|
|
45
|
+
};
|
|
46
|
+
export type CheckoutAdmission = ReturnType<typeof createAdmission>;
|
|
47
|
+
/** Share admission through Pi's public event bus; its per-extension facades have distinct identities. */
|
|
48
|
+
export declare function checkoutAdmission(pi: AdmissionHost): CheckoutAdmission;
|
|
49
|
+
export declare function registerCheckoutAdmission(pi: AdmissionHost, directCanWrite: (input: unknown) => boolean): (toolCallId: string) => () => void;
|
|
50
|
+
export {};
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { realpath } from "node:fs/promises";
|
|
2
|
+
const CHANNEL = "pi-herdr:checkout-admission";
|
|
3
|
+
// Main's own tools that never change a checkout; every other Main call may write.
|
|
4
|
+
// `codemode` mutates nothing itself: its nested tool calls are admitted by their own names.
|
|
5
|
+
const MAIN_NON_WRITING_TOOLS = new Set([
|
|
6
|
+
"read", "grep", "find", "ffgrep", "fffind", "ls", "codegraph_explore", "subagent_status", "codemode",
|
|
7
|
+
]);
|
|
8
|
+
export async function checkoutKey(pi, ctx) {
|
|
9
|
+
const cwd = await realpath(ctx.cwd);
|
|
10
|
+
const result = await pi.exec("git", ["rev-parse", "--show-toplevel"], { cwd, timeout: 5_000 });
|
|
11
|
+
if (result.code !== 0 || result.killed)
|
|
12
|
+
return cwd;
|
|
13
|
+
const root = result.stdout.replace(/\r?\n$/, "");
|
|
14
|
+
if (!root || /[\r\n\0]/.test(root))
|
|
15
|
+
throw new Error("Git returned a malformed checkout root during delegation admission.");
|
|
16
|
+
return await realpath(root);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Reserve checkouts only for direct writers. Main writes can run together, but
|
|
20
|
+
* each call must finish before a direct writer can start in that checkout.
|
|
21
|
+
* External processes and trusted extension lifecycle code are not intercepted.
|
|
22
|
+
*/
|
|
23
|
+
function createAdmission() {
|
|
24
|
+
let directCanWrite = (_input) => true;
|
|
25
|
+
const guards = new Map();
|
|
26
|
+
const durable = new Map();
|
|
27
|
+
const events = new WeakMap();
|
|
28
|
+
const heldCalls = new Set();
|
|
29
|
+
const ownerByCheckout = new Map();
|
|
30
|
+
const calls = new Map();
|
|
31
|
+
// One Git lookup per working directory per session; a failed lookup is retried.
|
|
32
|
+
const checkouts = new Map();
|
|
33
|
+
const lookup = (host, ctx) => {
|
|
34
|
+
const cached = checkouts.get(ctx.cwd);
|
|
35
|
+
if (cached)
|
|
36
|
+
return cached;
|
|
37
|
+
const key = checkoutKey(host, ctx);
|
|
38
|
+
checkouts.set(ctx.cwd, key);
|
|
39
|
+
key.catch(() => { if (checkouts.get(ctx.cwd) === key)
|
|
40
|
+
checkouts.delete(ctx.cwd); });
|
|
41
|
+
return key;
|
|
42
|
+
};
|
|
43
|
+
const release = (toolCallId) => {
|
|
44
|
+
if (heldCalls.has(toolCallId))
|
|
45
|
+
return;
|
|
46
|
+
const call = calls.get(toolCallId);
|
|
47
|
+
calls.delete(toolCallId);
|
|
48
|
+
if (call?.key && ownerByCheckout.get(call.key) === toolCallId)
|
|
49
|
+
ownerByCheckout.delete(call.key);
|
|
50
|
+
};
|
|
51
|
+
const refresh = async () => { for (const guard of guards.values())
|
|
52
|
+
await guard(); };
|
|
53
|
+
const admit = async (event, ctx, host) => {
|
|
54
|
+
const direct = event.toolName === "delegate_task";
|
|
55
|
+
if (event.toolName === "background_command" || (direct ? !directCanWrite(event.input) : MAIN_NON_WRITING_TOOLS.has(event.toolName)))
|
|
56
|
+
return;
|
|
57
|
+
try {
|
|
58
|
+
await refresh();
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return { block: true, reason: "Command ownership recovery failed; writes are blocked. Inspect /commands." };
|
|
62
|
+
}
|
|
63
|
+
const call = { direct };
|
|
64
|
+
calls.set(event.toolCallId, call);
|
|
65
|
+
const key = await lookup(host, ctx);
|
|
66
|
+
if (calls.get(event.toolCallId) !== call) {
|
|
67
|
+
return { block: true, reason: `Call ${event.toolCallId} already settled; use mode: isolated to keep Main free.` };
|
|
68
|
+
}
|
|
69
|
+
const owner = ownerByCheckout.get(key) ?? [...durable].find(([, checkout]) => checkout === key)?.[0];
|
|
70
|
+
const main = direct ? [...calls].find(([, active]) => !active.direct && active.key === key)?.[0] : undefined;
|
|
71
|
+
if (owner || main) {
|
|
72
|
+
release(event.toolCallId);
|
|
73
|
+
return {
|
|
74
|
+
block: true,
|
|
75
|
+
reason: `Checkout ${key} has ${owner ? `an admitted direct writer (${owner})` : `a Main potentially-writing call in flight (${main})`}; retry after it stops, or use mode: isolated to keep Main free.`,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
call.key = key;
|
|
79
|
+
if (direct)
|
|
80
|
+
ownerByCheckout.set(key, event.toolCallId);
|
|
81
|
+
};
|
|
82
|
+
const install = (host) => {
|
|
83
|
+
host.on("tool_call", (event, ctx) => {
|
|
84
|
+
let result = events.get(event);
|
|
85
|
+
if (!result) {
|
|
86
|
+
result = admit(event, ctx, host);
|
|
87
|
+
events.set(event, result);
|
|
88
|
+
}
|
|
89
|
+
return result;
|
|
90
|
+
});
|
|
91
|
+
host.on("tool_result", (event) => release(event.toolCallId));
|
|
92
|
+
host.on("tool_execution_end", (event) => release(event.toolCallId));
|
|
93
|
+
host.on("session_start", () => checkouts.clear());
|
|
94
|
+
host.on("session_shutdown", () => {
|
|
95
|
+
checkouts.clear();
|
|
96
|
+
for (const toolCallId of calls.keys())
|
|
97
|
+
release(toolCallId);
|
|
98
|
+
});
|
|
99
|
+
};
|
|
100
|
+
const hold = (toolCallId) => {
|
|
101
|
+
const call = calls.get(toolCallId);
|
|
102
|
+
if (!call?.direct || !call.key) {
|
|
103
|
+
throw new Error(`Direct call ${toolCallId} was not admitted as a checkout writer; delegate again.`);
|
|
104
|
+
}
|
|
105
|
+
heldCalls.add(toolCallId);
|
|
106
|
+
return () => { heldCalls.delete(toolCallId); release(toolCallId); };
|
|
107
|
+
};
|
|
108
|
+
return {
|
|
109
|
+
install, hold,
|
|
110
|
+
classifyDirect: (classify) => { directCanWrite = classify; },
|
|
111
|
+
guard: (name, refresh) => { guards.set(name, refresh); },
|
|
112
|
+
restore: (owner, checkout) => { durable.set(owner, checkout); },
|
|
113
|
+
release: (owner) => { durable.delete(owner); },
|
|
114
|
+
async reserve(owner, checkout) {
|
|
115
|
+
await refresh();
|
|
116
|
+
const conflict = [...durable].find(([, key]) => key === checkout)?.[0]
|
|
117
|
+
?? ownerByCheckout.get(checkout)
|
|
118
|
+
?? [...calls].find(([, call]) => call.key === checkout)?.[0];
|
|
119
|
+
if (conflict)
|
|
120
|
+
throw new Error(`Checkout ${checkout} has an active writer (${conflict}); wait until it stops.`);
|
|
121
|
+
durable.set(owner, checkout);
|
|
122
|
+
return () => { durable.delete(owner); };
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/** Share admission through Pi's public event bus; its per-extension facades have distinct identities. */
|
|
127
|
+
export function checkoutAdmission(pi) {
|
|
128
|
+
let admission;
|
|
129
|
+
pi.events?.emit(CHANNEL, { receive: (value) => { admission = value; } });
|
|
130
|
+
if (!admission)
|
|
131
|
+
admission = createAdmission();
|
|
132
|
+
const shared = admission;
|
|
133
|
+
pi.events?.on(CHANNEL, (data) => {
|
|
134
|
+
const request = data;
|
|
135
|
+
if (typeof request?.receive === "function")
|
|
136
|
+
request.receive(shared);
|
|
137
|
+
});
|
|
138
|
+
return shared;
|
|
139
|
+
}
|
|
140
|
+
export function registerCheckoutAdmission(pi, directCanWrite) {
|
|
141
|
+
const admission = checkoutAdmission(pi);
|
|
142
|
+
admission.classifyDirect(directCanWrite);
|
|
143
|
+
admission.install(pi);
|
|
144
|
+
return admission.hold;
|
|
145
|
+
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { lock } from "proper-lockfile";
|
|
2
|
+
export { requestHerdr, HerdrRequestError } from "./socket.js";
|
|
3
|
+
export { checkoutAdmission, checkoutKey, registerCheckoutAdmission } from "./admission.js";
|
|
2
4
|
const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
3
5
|
const MAX_AGENT_START_ATTEMPTS = 5;
|
|
4
6
|
const AGENT_START_RETRY_DELAY_MS = 250;
|
package/dist/socket.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare class HerdrRequestError extends Error {
|
|
2
|
+
readonly code: string;
|
|
3
|
+
readonly dispatched: boolean;
|
|
4
|
+
constructor(code: string, message: string, dispatched: boolean);
|
|
5
|
+
}
|
|
6
|
+
/** One newline-delimited request. A dispatched failure is uncertain; never retry mutations automatically. */
|
|
7
|
+
export declare function requestHerdr(method: string, params: Record<string, unknown>, options?: {
|
|
8
|
+
socketPath?: string;
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}): Promise<Record<string, unknown>>;
|
package/dist/socket.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createConnection } from "node:net";
|
|
3
|
+
export class HerdrRequestError extends Error {
|
|
4
|
+
code;
|
|
5
|
+
dispatched;
|
|
6
|
+
constructor(code, message, dispatched) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.dispatched = dispatched;
|
|
10
|
+
this.name = "HerdrRequestError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** One newline-delimited request. A dispatched failure is uncertain; never retry mutations automatically. */
|
|
14
|
+
export function requestHerdr(method, params, options = {}) {
|
|
15
|
+
const socketPath = options.socketPath ?? process.env.HERDR_SOCKET_PATH;
|
|
16
|
+
const timeoutMs = options.timeoutMs ?? 10_000;
|
|
17
|
+
if (!socketPath || !socketPath.startsWith("/") || socketPath.includes("\0"))
|
|
18
|
+
throw new HerdrRequestError("socket_path", "HERDR_SOCKET_PATH must be an absolute Unix socket path.", false);
|
|
19
|
+
if (!method.trim() || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 60_000)
|
|
20
|
+
throw new TypeError("Invalid Herdr request method or timeout.");
|
|
21
|
+
const id = randomUUID();
|
|
22
|
+
const request = JSON.stringify({ id, method, params }) + "\n";
|
|
23
|
+
if (Buffer.byteLength(request) > 256 * 1024)
|
|
24
|
+
throw new HerdrRequestError("request_limit", "Herdr request exceeds 256 KiB.", false);
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
let dispatched = false;
|
|
27
|
+
let settled = false;
|
|
28
|
+
let data = Buffer.alloc(0);
|
|
29
|
+
const socket = createConnection(socketPath);
|
|
30
|
+
const finish = (error, value) => {
|
|
31
|
+
if (settled)
|
|
32
|
+
return;
|
|
33
|
+
settled = true;
|
|
34
|
+
clearTimeout(timer);
|
|
35
|
+
options.signal?.removeEventListener("abort", abort);
|
|
36
|
+
socket.destroy();
|
|
37
|
+
if (error)
|
|
38
|
+
reject(error);
|
|
39
|
+
else
|
|
40
|
+
resolve(value);
|
|
41
|
+
};
|
|
42
|
+
const fail = (code, message) => finish(new HerdrRequestError(code, message, dispatched));
|
|
43
|
+
const abort = () => fail("aborted", "Herdr request aborted; dispatched mutations can still run.");
|
|
44
|
+
const timer = setTimeout(() => fail("timeout", "Herdr request timed out; dispatched mutations can still run."), timeoutMs);
|
|
45
|
+
socket.on("error", (error) => fail(error.code ?? "transport", "Herdr socket transport failed."));
|
|
46
|
+
socket.on("end", () => fail("closed", "Herdr socket closed before a complete response."));
|
|
47
|
+
socket.on("connect", () => { dispatched = true; socket.write(request); });
|
|
48
|
+
socket.on("data", (chunk) => {
|
|
49
|
+
if (data.length + chunk.length > 1024 * 1024)
|
|
50
|
+
return fail("response_limit", "Herdr response exceeds 1 MiB.");
|
|
51
|
+
data = Buffer.concat([data, chunk]);
|
|
52
|
+
const newline = data.indexOf(10);
|
|
53
|
+
if (newline < 0)
|
|
54
|
+
return;
|
|
55
|
+
let value;
|
|
56
|
+
try {
|
|
57
|
+
value = JSON.parse(data.subarray(0, newline).toString("utf8"));
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return fail("response_invalid", "Herdr returned invalid JSON.");
|
|
61
|
+
}
|
|
62
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
63
|
+
return fail("response_invalid", "Herdr returned a malformed response.");
|
|
64
|
+
const response = value;
|
|
65
|
+
if (response.id !== id)
|
|
66
|
+
return fail("identity", "Herdr response identity does not match the request.");
|
|
67
|
+
if (response.error && typeof response.error === "object") {
|
|
68
|
+
const error = response.error;
|
|
69
|
+
if (typeof error.code === "string" && typeof error.message === "string")
|
|
70
|
+
return fail(error.code, error.message);
|
|
71
|
+
}
|
|
72
|
+
if (!response.result || typeof response.result !== "object" || Array.isArray(response.result) || response.error !== undefined)
|
|
73
|
+
return fail("response_invalid", "Herdr response has no valid result.");
|
|
74
|
+
finish(undefined, response.result);
|
|
75
|
+
});
|
|
76
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
77
|
+
if (options.signal?.aborted)
|
|
78
|
+
abort();
|
|
79
|
+
});
|
|
80
|
+
}
|