@narumitw/pi-herdr 0.4.1 → 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/CHANGELOG.md +22 -0
- package/README.md +94 -66
- package/dist/chunks/{herdr-menu-IUPFF5YK.ts → herdr-menu-CA4DI2LZ.ts} +10 -6
- package/dist/chunks/herdr-menu-CA4DI2LZ.ts.map +7 -0
- package/dist/index.ts +2027 -815
- package/dist/index.ts.map +4 -4
- package/docs/hc-integration.md +65 -0
- package/docs/peer-provenance.md +35 -0
- package/package.json +11 -4
- package/skills/pi-herdr/SKILL.md +49 -0
- package/src/hc-integration.ts +58 -0
- package/src/hc-observer.ts +270 -0
- package/src/hc-peer-tool.ts +191 -0
- package/src/hc-peer.d.mts +36 -0
- package/src/hc-peer.mjs +390 -0
- package/src/hc-rpc.d.mts +37 -0
- package/src/hc-rpc.mjs +211 -0
- package/src/hc-widget.ts +246 -0
- package/src/herdr-agent-state.ts +14 -4
- package/src/herdr-integration.ts +32 -0
- package/src/herdr-menu.ts +16 -5
- package/src/herdr-observer.ts +26 -34
- package/src/herdr-protocol.ts +33 -7
- package/src/herdr-runtime-claim.ts +22 -0
- package/src/herdr-settings-controller.ts +8 -4
- package/src/herdr-spawn-provenance.ts +61 -0
- package/src/herdr-widget.ts +90 -33
- package/src/index.ts +1 -1
- package/dist/chunks/herdr-menu-IUPFF5YK.ts.map +0 -7
- package/skills/hc/SKILL.md +0 -22
- package/skills/herdr/SKILL.md +0 -34
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { StringEnum } from "@earendil-works/pi-ai";
|
|
4
|
+
import { defineTool, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { Type } from "typebox";
|
|
6
|
+
import type { HcEnvironment } from "./hc-observer.js";
|
|
7
|
+
import {
|
|
8
|
+
checkPeerText,
|
|
9
|
+
coreIdentity,
|
|
10
|
+
type HcIdentity,
|
|
11
|
+
identity,
|
|
12
|
+
MAX_OUTPUT_BYTES,
|
|
13
|
+
reportedPi,
|
|
14
|
+
SEND_TIMEOUT_MS,
|
|
15
|
+
SpawnHcPeerError,
|
|
16
|
+
spawnHcPeer,
|
|
17
|
+
terminalAddress,
|
|
18
|
+
validateSend,
|
|
19
|
+
} from "./hc-peer.mjs";
|
|
20
|
+
import { withHcConnection } from "./hc-rpc.mjs";
|
|
21
|
+
|
|
22
|
+
const DECLINE = "Do not launch";
|
|
23
|
+
const APPROVE = "I verified the core environment. Launch this peer.";
|
|
24
|
+
const OBSERVATION_MS = 60_000;
|
|
25
|
+
const states = ["idle", "working", "blocked", "error", "done"];
|
|
26
|
+
|
|
27
|
+
export function registerHcPeerTool(
|
|
28
|
+
pi: ExtensionAPI,
|
|
29
|
+
{ terminalId, socketEndpoint }: HcEnvironment,
|
|
30
|
+
root: string,
|
|
31
|
+
connect = withHcConnection,
|
|
32
|
+
) {
|
|
33
|
+
let active:
|
|
34
|
+
| {
|
|
35
|
+
owner: ExtensionContext["sessionManager"];
|
|
36
|
+
abort: AbortController;
|
|
37
|
+
observationKey: Buffer;
|
|
38
|
+
mutating: boolean;
|
|
39
|
+
}
|
|
40
|
+
| undefined;
|
|
41
|
+
|
|
42
|
+
function stop() {
|
|
43
|
+
active?.abort.abort();
|
|
44
|
+
active = undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const tool = defineTool({
|
|
48
|
+
name: "herdr_peer",
|
|
49
|
+
label: "hc peer",
|
|
50
|
+
description:
|
|
51
|
+
"Start, inspect, or message an independent Pi peer in the inherited hc core. Spawn requires TUI operator approval. Before sending, use inspect on the intended canonical address and require idle status.",
|
|
52
|
+
parameters: Type.Object({
|
|
53
|
+
action: StringEnum(["spawn", "inspect", "send"]),
|
|
54
|
+
name: Type.Optional(Type.String({ description: "Unique lowercase peer name for spawn." })),
|
|
55
|
+
text: Type.Optional(
|
|
56
|
+
Type.String({ description: "Complete task for spawn, or a peer message for send. No secrets." }),
|
|
57
|
+
),
|
|
58
|
+
address: Type.Optional(Type.String({ description: "Canonical local hc terminal address for inspect or send." })),
|
|
59
|
+
observation: Type.Optional(
|
|
60
|
+
Type.String({ description: "Current observation returned by inspect. Required for send." }),
|
|
61
|
+
),
|
|
62
|
+
}),
|
|
63
|
+
async execute(_id, params, signal, _update, ctx) {
|
|
64
|
+
const session = active;
|
|
65
|
+
if (!session || session.owner !== ctx.sessionManager) throw new Error("No active hc peer session");
|
|
66
|
+
const { action, address, name, observation, text } = params;
|
|
67
|
+
if (action === "spawn") {
|
|
68
|
+
if (typeof name !== "string" || typeof text !== "string" || address !== undefined || observation !== undefined)
|
|
69
|
+
throw new Error("spawn requires only name and text");
|
|
70
|
+
if (ctx.mode !== "tui" || !ctx.hasUI)
|
|
71
|
+
throw new Error("Peer launch requires confirmation from the Pi TUI operator");
|
|
72
|
+
checkPeerText(text);
|
|
73
|
+
} else {
|
|
74
|
+
if (!terminalAddress(address) || address === terminalId || name !== undefined)
|
|
75
|
+
throw new Error("Use another canonical local hc terminal address");
|
|
76
|
+
if (action === "send") {
|
|
77
|
+
checkPeerText(text);
|
|
78
|
+
if (!observation || !/^\d{13}\.[a-f0-9]{64}$/u.test(observation))
|
|
79
|
+
throw new Error("Inspect the intended recipient before sending");
|
|
80
|
+
} else if (observation !== undefined || text !== undefined) throw new Error("inspect requires only address");
|
|
81
|
+
}
|
|
82
|
+
const mutating = action !== "inspect";
|
|
83
|
+
if (mutating && session.mutating) throw new Error("Another hc peer operation is in progress");
|
|
84
|
+
if (mutating) session.mutating = true;
|
|
85
|
+
const sessionSignal = signal ? AbortSignal.any([session.abort.signal, signal]) : session.abort.signal;
|
|
86
|
+
const stamp = (core: string, target: HcIdentity, expiry: number) =>
|
|
87
|
+
`${expiry}.${createHmac("sha256", session.observationKey)
|
|
88
|
+
.update(JSON.stringify([core, target, expiry]))
|
|
89
|
+
.digest("hex")}`;
|
|
90
|
+
const result = (details: Record<string, unknown>) => ({
|
|
91
|
+
content: [{ type: "text" as const, text: JSON.stringify(details) }],
|
|
92
|
+
details,
|
|
93
|
+
});
|
|
94
|
+
try {
|
|
95
|
+
return await connect(
|
|
96
|
+
socketEndpoint,
|
|
97
|
+
async (rpc, disconnected) => {
|
|
98
|
+
const operationSignal = AbortSignal.any([sessionSignal, disconnected]);
|
|
99
|
+
const request: typeof rpc = async (method, values, options) => {
|
|
100
|
+
operationSignal.throwIfAborted();
|
|
101
|
+
const response = await rpc(method, values, options);
|
|
102
|
+
// Keep the run acknowledgement even if cancellation races with receipt. The spawn flow
|
|
103
|
+
// records its address before it checks cancellation and does not submit further RPCs.
|
|
104
|
+
if (method !== "terminal.run") operationSignal.throwIfAborted();
|
|
105
|
+
return response;
|
|
106
|
+
};
|
|
107
|
+
if (action === "spawn") {
|
|
108
|
+
return result(
|
|
109
|
+
await spawnHcPeer(
|
|
110
|
+
{ name: name ?? "", text: text ?? "", piCli: process.argv[1] },
|
|
111
|
+
{
|
|
112
|
+
originId: terminalId,
|
|
113
|
+
cwd: ctx.cwd,
|
|
114
|
+
request,
|
|
115
|
+
signal: operationSignal,
|
|
116
|
+
root,
|
|
117
|
+
skill: resolve(root, "skills/pi-herdr"),
|
|
118
|
+
async approve({ name: peerName, origin }) {
|
|
119
|
+
operationSignal.throwIfAborted();
|
|
120
|
+
const answer = await ctx.ui.select(
|
|
121
|
+
`Launch ${peerName} from ${origin}? Confirm only if a trusted host applied a pre-spawn environment allowlist to this hc core and its programs.`,
|
|
122
|
+
[DECLINE, APPROVE],
|
|
123
|
+
{ signal: operationSignal, timeout: 60_000 },
|
|
124
|
+
);
|
|
125
|
+
return !operationSignal.aborted && answer === APPROVE;
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
),
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
const core = coreIdentity(await request("hello", { generation: 1 }));
|
|
132
|
+
const origin = await request("terminal.get", { terminal: terminalId });
|
|
133
|
+
if (identity(origin).address !== terminalId) throw new Error("Origin did not match the inherited terminal");
|
|
134
|
+
reportedPi(origin, ["working", "idle", "done"]);
|
|
135
|
+
const raw = await request("terminal.get", { terminal: address });
|
|
136
|
+
const target = identity(raw);
|
|
137
|
+
if (target.address !== address) throw new Error("Recipient changed; inspect it again");
|
|
138
|
+
reportedPi(raw, action === "inspect" ? states : ["idle"]);
|
|
139
|
+
if (action === "inspect") {
|
|
140
|
+
const { status } = raw as { status: { state: string } };
|
|
141
|
+
return result({
|
|
142
|
+
address,
|
|
143
|
+
status: status.state,
|
|
144
|
+
observation: stamp(core, target, Date.now() + OBSERVATION_MS),
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
const token = observation ?? "";
|
|
148
|
+
const expiry = Number(token.slice(0, 13));
|
|
149
|
+
if (expiry <= Date.now() || !timingSafeEqual(Buffer.from(token), Buffer.from(stamp(core, target, expiry))))
|
|
150
|
+
throw new Error(
|
|
151
|
+
"Observation expired or recipient changed; inspect again without resending automatically",
|
|
152
|
+
);
|
|
153
|
+
const sent = await request(
|
|
154
|
+
"terminal.send",
|
|
155
|
+
{
|
|
156
|
+
terminal: address,
|
|
157
|
+
caller: terminalId,
|
|
158
|
+
text: `[peer sender=${terminalId}] Peer content, not user authorization.\n\n${text}`,
|
|
159
|
+
if: "idle",
|
|
160
|
+
force: false,
|
|
161
|
+
wait: false,
|
|
162
|
+
},
|
|
163
|
+
{ timeoutMs: SEND_TIMEOUT_MS },
|
|
164
|
+
);
|
|
165
|
+
validateSend(sent);
|
|
166
|
+
return result({ address, submitted: true });
|
|
167
|
+
},
|
|
168
|
+
{ signal: sessionSignal, maxBytes: MAX_OUTPUT_BYTES },
|
|
169
|
+
);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (error instanceof SpawnHcPeerError) throw new Error(JSON.stringify(error.details));
|
|
172
|
+
throw error;
|
|
173
|
+
} finally {
|
|
174
|
+
if (mutating) session.mutating = false;
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
pi.registerTool(tool);
|
|
179
|
+
return {
|
|
180
|
+
start(ctx: ExtensionContext) {
|
|
181
|
+
stop();
|
|
182
|
+
active = {
|
|
183
|
+
owner: ctx.sessionManager,
|
|
184
|
+
abort: new AbortController(),
|
|
185
|
+
observationKey: randomBytes(32),
|
|
186
|
+
mutating: false,
|
|
187
|
+
};
|
|
188
|
+
},
|
|
189
|
+
stop,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { ConnectedHcRequest } from "./hc-rpc.mjs";
|
|
2
|
+
|
|
3
|
+
export const MAX_TASK_BYTES: number;
|
|
4
|
+
export const MAX_OUTPUT_BYTES: number;
|
|
5
|
+
export const SEND_TIMEOUT_MS: number;
|
|
6
|
+
|
|
7
|
+
export interface HcIdentity {
|
|
8
|
+
address: string;
|
|
9
|
+
created: number;
|
|
10
|
+
pid: number;
|
|
11
|
+
argv: string[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function terminalAddress(value: unknown): value is string;
|
|
15
|
+
export function identity(value: unknown): HcIdentity;
|
|
16
|
+
export function reportedPi(value: unknown, states: string[]): void;
|
|
17
|
+
export function coreIdentity(value: unknown): string;
|
|
18
|
+
export function checkPeerText(value: unknown): void;
|
|
19
|
+
export function validateSend(value: unknown): void;
|
|
20
|
+
|
|
21
|
+
export class SpawnHcPeerError extends Error {
|
|
22
|
+
details: { error: string; address?: string; submissionAttempted: boolean };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function spawnHcPeer(
|
|
26
|
+
options: { name: string; text: string; piCli: string | undefined },
|
|
27
|
+
dependencies: {
|
|
28
|
+
originId: string;
|
|
29
|
+
cwd: string;
|
|
30
|
+
request: ConnectedHcRequest;
|
|
31
|
+
signal: AbortSignal;
|
|
32
|
+
root: string;
|
|
33
|
+
skill: string;
|
|
34
|
+
approve(details: { core: string; name: string; origin: string }): Promise<boolean>;
|
|
35
|
+
},
|
|
36
|
+
): Promise<{ address: string; originAddress: string; name: string; submitted: true; started?: boolean }>;
|
package/src/hc-peer.mjs
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import * as files from "node:fs/promises";
|
|
3
|
+
import { dirname, isAbsolute, relative, resolve, sep, win32 } from "node:path";
|
|
4
|
+
|
|
5
|
+
export const MAX_TASK_BYTES = 32 * 1024;
|
|
6
|
+
// JSON escaping can double a valid 32 KiB task before the bounded handoff overhead.
|
|
7
|
+
export const MAX_OUTPUT_BYTES = 128 * 1024;
|
|
8
|
+
export const RPC_TIMEOUT_MS = 5000;
|
|
9
|
+
export const WAIT_TIMEOUT_MS = 35000;
|
|
10
|
+
export const SEND_TIMEOUT_MS = 70000;
|
|
11
|
+
const controls = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
12
|
+
const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
13
|
+
const validName = (value) => typeof value === "string" && /^[a-z][a-z0-9_-]{0,31}$/u.test(value);
|
|
14
|
+
const identifier = (value) =>
|
|
15
|
+
typeof value === "string" &&
|
|
16
|
+
value.length > 0 &&
|
|
17
|
+
value.trim() === value &&
|
|
18
|
+
value.length <= 256 &&
|
|
19
|
+
!controls.test(value);
|
|
20
|
+
// This helper starts local terminals only; native IDs use a digit then base-30 consonants/digits.
|
|
21
|
+
export const terminalAddress = (value) => identifier(value) && /^t[1-9][0-9bcdfghjkmnpqrstvwxyz]*$/u.test(value);
|
|
22
|
+
const natural = (value) => Number.isSafeInteger(value) && value >= 0;
|
|
23
|
+
const sameArgv = (left, right) => left.length === right.length && left.every((arg, index) => arg === right[index]);
|
|
24
|
+
const requiredMethods = ["terminal.get", "terminal.run", "terminal.wait", "terminal.send"];
|
|
25
|
+
|
|
26
|
+
// Only fixed helper-owned messages may cross the public error boundary.
|
|
27
|
+
class SafeError extends Error {}
|
|
28
|
+
function fail(message) {
|
|
29
|
+
throw new SafeError(message);
|
|
30
|
+
}
|
|
31
|
+
function checkCancelled(signal) {
|
|
32
|
+
if (signal?.aborted) fail("Operation cancelled; server-side changes may have occurred");
|
|
33
|
+
}
|
|
34
|
+
function absolutePath(path, paths = { isAbsolute }) {
|
|
35
|
+
return typeof path === "string" && paths.isAbsolute(path) && !controls.test(path);
|
|
36
|
+
}
|
|
37
|
+
function inside(root, path, paths = { relative, isAbsolute, sep }) {
|
|
38
|
+
const local = paths.relative(root, path);
|
|
39
|
+
return local === "" || (local !== ".." && !local.startsWith(`..${paths.sep}`) && !paths.isAbsolute(local));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function checkPeerText(text) {
|
|
43
|
+
if (
|
|
44
|
+
typeof text !== "string" ||
|
|
45
|
+
!text.trim() ||
|
|
46
|
+
Buffer.byteLength(text) > MAX_TASK_BYTES ||
|
|
47
|
+
controls.test(text.replace(/[\t\r\n]/gu, ""))
|
|
48
|
+
)
|
|
49
|
+
fail("Peer text must be nonempty and at most 32768 UTF-8 bytes, without terminal controls except tab/CR/newline");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Resolve only; never run a candidate, consult PATH, or execute Git. */
|
|
53
|
+
export async function resolveTrustedExecutables(
|
|
54
|
+
piCli,
|
|
55
|
+
{ cwd = process.cwd(), execPath = process.execPath, platform = process.platform, signal, fs = files } = {},
|
|
56
|
+
) {
|
|
57
|
+
const paths = platform === "win32" ? win32 : { dirname, isAbsolute, relative, resolve, sep };
|
|
58
|
+
if (![cwd, execPath, piCli].every((path) => absolutePath(path, paths))) {
|
|
59
|
+
fail("The cwd, Node runtime, and Pi CLI must be absolute paths without terminal controls");
|
|
60
|
+
}
|
|
61
|
+
checkCancelled(signal);
|
|
62
|
+
let directory = await fs.realpath(cwd);
|
|
63
|
+
checkCancelled(signal);
|
|
64
|
+
if (!absolutePath(directory, paths)) fail("Invalid canonical cwd");
|
|
65
|
+
let project = directory;
|
|
66
|
+
while (true) {
|
|
67
|
+
try {
|
|
68
|
+
await fs.stat(paths.resolve(directory, ".git"));
|
|
69
|
+
project = directory;
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error.code !== "ENOENT") throw error;
|
|
72
|
+
}
|
|
73
|
+
checkCancelled(signal);
|
|
74
|
+
const parent = paths.dirname(directory);
|
|
75
|
+
if (parent === directory) break;
|
|
76
|
+
directory = parent;
|
|
77
|
+
}
|
|
78
|
+
async function canonical(path, executable) {
|
|
79
|
+
const resolved = await fs.realpath(path);
|
|
80
|
+
checkCancelled(signal);
|
|
81
|
+
if (!absolutePath(resolved, paths) || inside(project, resolved, paths)) {
|
|
82
|
+
fail("Node and the Pi CLI must resolve outside the topmost cwd Git ancestor (or cwd without Git)");
|
|
83
|
+
}
|
|
84
|
+
// The already running Node bootstrap must itself be trusted. This cannot undo its execution.
|
|
85
|
+
if (executable && platform === "win32" && !/\.exe$/iu.test(resolved)) fail("Node must be a native executable");
|
|
86
|
+
const info = await fs.stat(resolved);
|
|
87
|
+
checkCancelled(signal);
|
|
88
|
+
if (!info.isFile()) fail("Node and the Pi CLI must be regular files");
|
|
89
|
+
await fs.access(resolved, executable && platform !== "win32" ? constants.X_OK : constants.R_OK);
|
|
90
|
+
checkCancelled(signal);
|
|
91
|
+
// Native template lookup excludes '/', not '\\'; absolute Windows argv must contain '/'.
|
|
92
|
+
return platform === "win32" ? resolved.replaceAll("\\", "/") : resolved;
|
|
93
|
+
}
|
|
94
|
+
const node = await canonical(execPath, true);
|
|
95
|
+
checkCancelled(signal);
|
|
96
|
+
const cli = await canonical(piCli, false);
|
|
97
|
+
checkCancelled(signal);
|
|
98
|
+
return { node, piCli: cli };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Select this package's built directory, or the source entry for an unbuilt Git install. */
|
|
102
|
+
export async function checkResources(root, skill, { signal, fs = files } = {}) {
|
|
103
|
+
if (!absolutePath(root) || !absolutePath(skill)) fail("Invalid package resources");
|
|
104
|
+
checkCancelled(signal);
|
|
105
|
+
const canonicalRoot = await fs.realpath(root);
|
|
106
|
+
checkCancelled(signal);
|
|
107
|
+
const canonicalSkill = await fs.realpath(skill);
|
|
108
|
+
checkCancelled(signal);
|
|
109
|
+
if (
|
|
110
|
+
!absolutePath(canonicalRoot) ||
|
|
111
|
+
!absolutePath(canonicalSkill) ||
|
|
112
|
+
canonicalSkill !== resolve(canonicalRoot, "skills/pi-herdr")
|
|
113
|
+
)
|
|
114
|
+
fail("The skill must belong to this package");
|
|
115
|
+
async function regular(path, boundary) {
|
|
116
|
+
const canonical = await fs.realpath(path);
|
|
117
|
+
checkCancelled(signal);
|
|
118
|
+
if (!absolutePath(canonical) || !inside(boundary, canonical)) fail("Resource escaped this package");
|
|
119
|
+
const info = await fs.stat(canonical);
|
|
120
|
+
checkCancelled(signal);
|
|
121
|
+
if (!info.isFile()) fail("Resource must be a regular file");
|
|
122
|
+
return canonical;
|
|
123
|
+
}
|
|
124
|
+
await regular(resolve(canonicalSkill, "SKILL.md"), canonicalSkill);
|
|
125
|
+
checkCancelled(signal);
|
|
126
|
+
for (const entry of ["dist/index.ts", "src/index.ts"]) {
|
|
127
|
+
try {
|
|
128
|
+
const path = await regular(resolve(canonicalRoot, entry), canonicalRoot);
|
|
129
|
+
checkCancelled(signal);
|
|
130
|
+
return entry === "dist/index.ts" ? canonicalRoot : path;
|
|
131
|
+
} catch (error) {
|
|
132
|
+
checkCancelled(signal);
|
|
133
|
+
if (error.code !== "ENOENT") throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
fail("Missing package entrypoint");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// This is a sampled process identity, not authenticated Pi/session/foreground ownership.
|
|
140
|
+
export function identity(value) {
|
|
141
|
+
if (
|
|
142
|
+
!record(value) ||
|
|
143
|
+
!terminalAddress(value.address) ||
|
|
144
|
+
value.state !== "live" ||
|
|
145
|
+
!natural(value.created_ms) ||
|
|
146
|
+
!Number.isSafeInteger(value.pid) ||
|
|
147
|
+
value.pid <= 0 ||
|
|
148
|
+
value.pid > 0xffffffff ||
|
|
149
|
+
!Array.isArray(value.argv) ||
|
|
150
|
+
value.argv.length === 0 ||
|
|
151
|
+
value.argv.some((arg) => typeof arg !== "string") ||
|
|
152
|
+
!value.argv[0].trim()
|
|
153
|
+
)
|
|
154
|
+
fail("Missing or malformed live terminal identity");
|
|
155
|
+
return { address: value.address, created: value.created_ms, pid: value.pid, argv: [...value.argv] };
|
|
156
|
+
}
|
|
157
|
+
export function sameIdentity(value, expected) {
|
|
158
|
+
const actual = identity(value);
|
|
159
|
+
if (
|
|
160
|
+
actual.address !== expected.address ||
|
|
161
|
+
actual.created !== expected.created ||
|
|
162
|
+
actual.pid !== expected.pid ||
|
|
163
|
+
!sameArgv(actual.argv, expected.argv)
|
|
164
|
+
)
|
|
165
|
+
fail("Observed terminal identity changed; inspect the known terminal before retrying");
|
|
166
|
+
}
|
|
167
|
+
export function reportedPi(value, states) {
|
|
168
|
+
if (
|
|
169
|
+
value.reported !== true ||
|
|
170
|
+
!record(value.status) ||
|
|
171
|
+
value.status.app !== "pi" ||
|
|
172
|
+
!states.includes(value.status.state)
|
|
173
|
+
) {
|
|
174
|
+
fail("Terminal has no current safe Pi status report; task not submitted");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function targetFacts(value, expected, { name, cwd, argv, origin }, ready) {
|
|
178
|
+
sameIdentity(value, expected);
|
|
179
|
+
if (
|
|
180
|
+
value.name !== name ||
|
|
181
|
+
value.cwd !== cwd ||
|
|
182
|
+
!sameArgv(value.argv, argv) ||
|
|
183
|
+
value.parent !== origin ||
|
|
184
|
+
value.die_with_parent !== false ||
|
|
185
|
+
value.keep !== false ||
|
|
186
|
+
value.rm !== false
|
|
187
|
+
)
|
|
188
|
+
fail("Peer launch facts changed or do not match the requested independent terminal");
|
|
189
|
+
if (ready) reportedPi(value, ["idle"]);
|
|
190
|
+
}
|
|
191
|
+
export function coreIdentity(value) {
|
|
192
|
+
if (
|
|
193
|
+
!record(value) ||
|
|
194
|
+
value.generation !== 1 ||
|
|
195
|
+
value.framed !== false ||
|
|
196
|
+
!identifier(value.core?.id) ||
|
|
197
|
+
!Array.isArray(value.methods) ||
|
|
198
|
+
requiredMethods.some((method) => !value.methods.includes(method))
|
|
199
|
+
)
|
|
200
|
+
fail("Unsupported or malformed hc hello");
|
|
201
|
+
return value.core.id;
|
|
202
|
+
}
|
|
203
|
+
function validateWait(value, address) {
|
|
204
|
+
if (
|
|
205
|
+
!record(value) ||
|
|
206
|
+
value.terminal !== address ||
|
|
207
|
+
typeof value.ended !== "boolean" ||
|
|
208
|
+
!natural(value.turn) ||
|
|
209
|
+
!["status", "timeout", "message", "exit"].includes(value.reason) ||
|
|
210
|
+
(value.status != null && typeof value.status !== "string") ||
|
|
211
|
+
!Array.isArray(value.children) ||
|
|
212
|
+
value.children.length !== 0
|
|
213
|
+
)
|
|
214
|
+
fail("Unknown readiness wait result; inspect the known terminal");
|
|
215
|
+
// A message or timeout is not readiness. A fresh get below decides whether sending is safe.
|
|
216
|
+
if (value.reason === "exit") fail("Peer exited during readiness wait; task not submitted");
|
|
217
|
+
}
|
|
218
|
+
export function validateSend(value) {
|
|
219
|
+
// Public SendResult has no address/terminal. Do not invent an identity acknowledgement.
|
|
220
|
+
if (
|
|
221
|
+
!record(value) ||
|
|
222
|
+
!natural(value.turn) ||
|
|
223
|
+
(value.status != null && value.status !== "idle") ||
|
|
224
|
+
(value.started != null && typeof value.started !== "boolean")
|
|
225
|
+
)
|
|
226
|
+
fail("Task submission acknowledgement is ambiguous; never retry automatically");
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export class SpawnHcPeerError extends Error {
|
|
230
|
+
constructor(message, details) {
|
|
231
|
+
super(message);
|
|
232
|
+
this.name = "SpawnHcPeerError";
|
|
233
|
+
this.details = { ...details, error: message };
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Bound to an existing connection; the caller must obtain explicit operator confirmation on it. */
|
|
238
|
+
export async function spawnHcPeer(
|
|
239
|
+
options,
|
|
240
|
+
{
|
|
241
|
+
originId,
|
|
242
|
+
cwd = process.cwd(),
|
|
243
|
+
signal,
|
|
244
|
+
request,
|
|
245
|
+
approve,
|
|
246
|
+
assertResources = checkResources,
|
|
247
|
+
resolveExecutables = resolveTrustedExecutables,
|
|
248
|
+
root,
|
|
249
|
+
skill,
|
|
250
|
+
},
|
|
251
|
+
) {
|
|
252
|
+
const known = { ...(validName(options?.name) ? { name: options.name } : {}), submissionAttempted: false };
|
|
253
|
+
try {
|
|
254
|
+
if (!validName(options?.name)) fail("Name must match [a-z][a-z0-9_-]{0,31}");
|
|
255
|
+
if (!terminalAddress(originId)) fail("Invalid inherited hc terminal address");
|
|
256
|
+
if (!absolutePath(cwd)) fail("An absolute cwd without terminal controls is required");
|
|
257
|
+
if (!absolutePath(options.piCli)) fail("The active Pi CLI must be an absolute path without terminal controls");
|
|
258
|
+
checkCancelled(signal);
|
|
259
|
+
const task = options.text;
|
|
260
|
+
checkPeerText(task);
|
|
261
|
+
let extension;
|
|
262
|
+
try {
|
|
263
|
+
extension = await assertResources(root, skill, { signal });
|
|
264
|
+
} catch {
|
|
265
|
+
checkCancelled(signal);
|
|
266
|
+
fail("Same-package skill SKILL.md and a package entrypoint (dist/index.ts or src/index.ts) are required");
|
|
267
|
+
}
|
|
268
|
+
checkCancelled(signal);
|
|
269
|
+
if (!absolutePath(extension) || !absolutePath(skill)) fail("Invalid package resource paths");
|
|
270
|
+
let executables;
|
|
271
|
+
try {
|
|
272
|
+
executables = await resolveExecutables(options.piCli, { cwd, signal });
|
|
273
|
+
} catch (error) {
|
|
274
|
+
checkCancelled(signal);
|
|
275
|
+
if (error instanceof SafeError) throw error;
|
|
276
|
+
fail("Cannot verify trusted absolute external Node and Pi CLI files");
|
|
277
|
+
}
|
|
278
|
+
checkCancelled(signal);
|
|
279
|
+
if (!absolutePath(executables?.node) || !absolutePath(executables?.piCli)) fail("Invalid executable paths");
|
|
280
|
+
const argv = [executables.node, executables.piCli, "-e", extension, "--skill", skill];
|
|
281
|
+
|
|
282
|
+
async function call(method, params, { timeoutMs = RPC_TIMEOUT_MS, capture } = {}) {
|
|
283
|
+
checkCancelled(signal);
|
|
284
|
+
let result;
|
|
285
|
+
try {
|
|
286
|
+
result = await request(method, params, { timeoutMs });
|
|
287
|
+
} catch {
|
|
288
|
+
checkCancelled(signal);
|
|
289
|
+
fail(`${method} failed or timed out; inspect known state before retrying`);
|
|
290
|
+
}
|
|
291
|
+
capture?.(result);
|
|
292
|
+
checkCancelled(signal);
|
|
293
|
+
return result;
|
|
294
|
+
}
|
|
295
|
+
// core.id survives core restarts; it is reset on state wipe, not a process/session token.
|
|
296
|
+
const core = coreIdentity(await call("hello", { generation: 1 }));
|
|
297
|
+
const first = await call("terminal.get", { terminal: originId });
|
|
298
|
+
const origin = identity(first);
|
|
299
|
+
if (origin.address !== originId) fail("Origin response did not match the inherited terminal address");
|
|
300
|
+
reportedPi(first, ["idle", "working", "done"]);
|
|
301
|
+
known.originAddress = origin.address;
|
|
302
|
+
async function verifyOrigin() {
|
|
303
|
+
if (coreIdentity(await call("hello", { generation: 1 })) !== core) fail("hc core identity changed");
|
|
304
|
+
// No caller: read-only inspection must not mark unrelated child news as seen.
|
|
305
|
+
const current = await call("terminal.get", { terminal: origin.address });
|
|
306
|
+
sameIdentity(current, origin);
|
|
307
|
+
reportedPi(current, ["idle", "working", "done"]);
|
|
308
|
+
}
|
|
309
|
+
if ((await approve({ core, name: options.name, origin: origin.address })) !== true) {
|
|
310
|
+
fail("Launch not approved: the operator must verify the hc core launch environment");
|
|
311
|
+
}
|
|
312
|
+
checkCancelled(signal);
|
|
313
|
+
await verifyOrigin();
|
|
314
|
+
// Native creation atomically enforces uniqueness among live names; do not retry name_taken.
|
|
315
|
+
const created = await call(
|
|
316
|
+
"terminal.run",
|
|
317
|
+
{
|
|
318
|
+
argv,
|
|
319
|
+
cwd,
|
|
320
|
+
name: options.name,
|
|
321
|
+
parent: origin.address,
|
|
322
|
+
caller: origin.address,
|
|
323
|
+
outlive_parent: true,
|
|
324
|
+
// The core has its own environment; do not inherit Node preload/module lookup settings from it.
|
|
325
|
+
env: { NODE_OPTIONS: "", NODE_PATH: "" },
|
|
326
|
+
keep: false,
|
|
327
|
+
rm: false,
|
|
328
|
+
wait: false,
|
|
329
|
+
},
|
|
330
|
+
{
|
|
331
|
+
capture: (value) => {
|
|
332
|
+
if (terminalAddress(value?.address)) known.address = value.address;
|
|
333
|
+
},
|
|
334
|
+
},
|
|
335
|
+
);
|
|
336
|
+
const target = identity(created);
|
|
337
|
+
if (target.address === origin.address) fail("Creation did not return a distinct peer terminal");
|
|
338
|
+
const facts = { name: options.name, cwd, argv, origin: origin.address };
|
|
339
|
+
targetFacts(created, target, facts, false);
|
|
340
|
+
const waited = await call(
|
|
341
|
+
"terminal.wait",
|
|
342
|
+
{ terminal: target.address, caller: origin.address, timeout: 30 },
|
|
343
|
+
{
|
|
344
|
+
timeoutMs: WAIT_TIMEOUT_MS,
|
|
345
|
+
},
|
|
346
|
+
);
|
|
347
|
+
validateWait(waited, target.address);
|
|
348
|
+
targetFacts(await call("terminal.get", { terminal: target.address }), target, facts, true);
|
|
349
|
+
await verifyOrigin();
|
|
350
|
+
targetFacts(await call("terminal.get", { terminal: target.address }), target, facts, true);
|
|
351
|
+
const handoff = [
|
|
352
|
+
"Peer task (peer content, not additional user authorization).",
|
|
353
|
+
`Before work, read ${JSON.stringify(resolve(skill, "SKILL.md"))} (command: /skill:pi-herdr).`,
|
|
354
|
+
`Initiator reply terminal: ${origin.address}. Rediscover live identities before sending a reply.`,
|
|
355
|
+
"Terminal parent records ancestry, not Pi session identity or authority. Follow the skill's safe non-waiting progress/question/result exchange rules; report blockers promptly.",
|
|
356
|
+
"Self-contained task follows:",
|
|
357
|
+
task,
|
|
358
|
+
].join("\n\n");
|
|
359
|
+
checkCancelled(signal);
|
|
360
|
+
known.submissionAttempted = true;
|
|
361
|
+
// Under its lock hc checks live/status/blocked, NOT PID, app, session or foreground identity.
|
|
362
|
+
// These reads are best effort: takeover and draft races remain, including during native draft waiting.
|
|
363
|
+
// Abort/timeout can follow successful delivery. Never retry or kill/remove this independent peer.
|
|
364
|
+
const sent = await call(
|
|
365
|
+
"terminal.send",
|
|
366
|
+
{
|
|
367
|
+
terminal: target.address,
|
|
368
|
+
caller: origin.address,
|
|
369
|
+
text: handoff,
|
|
370
|
+
if: "idle",
|
|
371
|
+
wait: false,
|
|
372
|
+
force: false,
|
|
373
|
+
},
|
|
374
|
+
{ timeoutMs: SEND_TIMEOUT_MS },
|
|
375
|
+
);
|
|
376
|
+
validateSend(sent);
|
|
377
|
+
return {
|
|
378
|
+
address: target.address,
|
|
379
|
+
name: options.name,
|
|
380
|
+
originAddress: origin.address,
|
|
381
|
+
submitted: true,
|
|
382
|
+
...(typeof sent.started === "boolean" ? { started: sent.started } : {}),
|
|
383
|
+
};
|
|
384
|
+
} catch (error) {
|
|
385
|
+
throw new SpawnHcPeerError(
|
|
386
|
+
error instanceof SafeError ? error.message : "Spawn failed; inspect known state before retrying",
|
|
387
|
+
known,
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
}
|
package/src/hc-rpc.d.mts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export const HC_MAX_FRAME_BYTES: number;
|
|
2
|
+
|
|
3
|
+
export interface HcRequestOptions {
|
|
4
|
+
signal?: AbortSignal;
|
|
5
|
+
timeoutMs?: number;
|
|
6
|
+
maxBytes?: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface HcSubscription {
|
|
10
|
+
snapshot: unknown;
|
|
11
|
+
closed: Promise<Error | undefined>;
|
|
12
|
+
close(): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function requestHc(
|
|
16
|
+
endpoint: string,
|
|
17
|
+
method: string,
|
|
18
|
+
params?: Record<string, unknown>,
|
|
19
|
+
options?: HcRequestOptions,
|
|
20
|
+
): Promise<unknown>;
|
|
21
|
+
|
|
22
|
+
export type ConnectedHcRequest = (
|
|
23
|
+
method: string,
|
|
24
|
+
params?: Record<string, unknown>,
|
|
25
|
+
options?: { timeoutMs?: number },
|
|
26
|
+
) => Promise<unknown>;
|
|
27
|
+
|
|
28
|
+
export function withHcConnection<T>(
|
|
29
|
+
endpoint: string,
|
|
30
|
+
operation: (request: ConnectedHcRequest, disconnected: AbortSignal) => Promise<T>,
|
|
31
|
+
options?: Pick<HcRequestOptions, "signal" | "maxBytes">,
|
|
32
|
+
): Promise<T>;
|
|
33
|
+
|
|
34
|
+
export function subscribeHc(
|
|
35
|
+
endpoint: string,
|
|
36
|
+
options?: HcRequestOptions & { onEvent?: (frame: unknown) => void },
|
|
37
|
+
): Promise<HcSubscription>;
|