@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
package/src/hc-rpc.mjs
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import net from "node:net";
|
|
2
|
+
|
|
3
|
+
export const HC_MAX_FRAME_BYTES = 2 * 1024 * 1024;
|
|
4
|
+
const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
5
|
+
|
|
6
|
+
function response(frame, id = 1) {
|
|
7
|
+
if (!record(frame) || frame.jsonrpc !== "2.0" || frame.id !== id) throw new Error("Invalid hc RPC response");
|
|
8
|
+
if (Object.hasOwn(frame, "error")) {
|
|
9
|
+
const kind = frame.error?.data?.kind;
|
|
10
|
+
const suffix = typeof kind === "string" && /^[a-z_]{1,40}$/u.test(kind) ? ` (${kind})` : "";
|
|
11
|
+
// Native messages can contain task text or argv. Publish only the stable error kind.
|
|
12
|
+
throw new Error(`hc RPC rejected${suffix}; inspect the terminal before retrying`);
|
|
13
|
+
}
|
|
14
|
+
if (!Object.hasOwn(frame, "result")) throw new Error("Missing hc RPC result");
|
|
15
|
+
return frame.result;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function connect(endpoint, { signal, timeoutMs, maxBytes, onFrame }) {
|
|
19
|
+
if (typeof endpoint !== "string" || !endpoint.trim()) throw new Error("Missing inherited hc endpoint");
|
|
20
|
+
if (signal?.aborted) throw new Error("hc operation cancelled; remote changes may have occurred");
|
|
21
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || !Number.isFinite(timeoutMs) || timeoutMs <= 0)
|
|
22
|
+
throw new Error("Invalid hc connection limits");
|
|
23
|
+
const socket = net.createConnection(endpoint);
|
|
24
|
+
let ending = false;
|
|
25
|
+
let connected = false;
|
|
26
|
+
socket.once("connect", () => {
|
|
27
|
+
connected = true;
|
|
28
|
+
});
|
|
29
|
+
let reason;
|
|
30
|
+
let pending = "";
|
|
31
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
32
|
+
let resolveClosed;
|
|
33
|
+
const closed = new Promise((resolve) => {
|
|
34
|
+
resolveClosed = resolve;
|
|
35
|
+
});
|
|
36
|
+
const stop = (error) => {
|
|
37
|
+
if (ending) return;
|
|
38
|
+
ending = true;
|
|
39
|
+
reason = error;
|
|
40
|
+
socket.destroy();
|
|
41
|
+
};
|
|
42
|
+
const abort = () => stop(new Error("hc operation cancelled; remote changes may have occurred"));
|
|
43
|
+
const timer = setTimeout(() => stop(new Error("hc connection timed out; outcome may be ambiguous")), timeoutMs);
|
|
44
|
+
timer.unref?.();
|
|
45
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
46
|
+
socket.on("error", () => stop(new Error("hc socket failed; outcome may be ambiguous")));
|
|
47
|
+
socket.on("timeout", () => stop(new Error("hc subscription heartbeat timed out")));
|
|
48
|
+
socket.on("data", (chunk) => {
|
|
49
|
+
if (ending) return;
|
|
50
|
+
try {
|
|
51
|
+
pending += decoder.decode(chunk, { stream: true });
|
|
52
|
+
let newline = pending.indexOf("\n");
|
|
53
|
+
while (newline >= 0 && !ending) {
|
|
54
|
+
const line = pending.slice(0, newline);
|
|
55
|
+
pending = pending.slice(newline + 1);
|
|
56
|
+
if (Buffer.byteLength(line) > maxBytes) throw new Error("hc frame exceeded the limit");
|
|
57
|
+
if (!line.trim()) throw new Error("Empty hc frame");
|
|
58
|
+
let frame;
|
|
59
|
+
try {
|
|
60
|
+
frame = JSON.parse(line);
|
|
61
|
+
} catch {
|
|
62
|
+
throw new Error("Invalid hc JSON frame");
|
|
63
|
+
}
|
|
64
|
+
onFrame(frame);
|
|
65
|
+
newline = pending.indexOf("\n");
|
|
66
|
+
}
|
|
67
|
+
if (Buffer.byteLength(pending) > maxBytes) throw new Error("hc frame exceeded the limit");
|
|
68
|
+
} catch (error) {
|
|
69
|
+
stop(error instanceof Error ? error : new Error("Invalid hc frame"));
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
socket.once("end", () => stop(new Error("hc socket ended")));
|
|
73
|
+
socket.once("close", () => {
|
|
74
|
+
ending = true;
|
|
75
|
+
clearTimeout(timer);
|
|
76
|
+
signal?.removeEventListener("abort", abort);
|
|
77
|
+
socket.removeAllListeners("data");
|
|
78
|
+
resolveClosed(reason);
|
|
79
|
+
});
|
|
80
|
+
return {
|
|
81
|
+
closed,
|
|
82
|
+
send(method, params, id = 1) {
|
|
83
|
+
let line;
|
|
84
|
+
try {
|
|
85
|
+
line = `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`;
|
|
86
|
+
} catch {
|
|
87
|
+
stop(new Error("Invalid hc request"));
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (Buffer.byteLength(line) > maxBytes) {
|
|
91
|
+
stop(new Error("hc request exceeded the limit"));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const write = () => {
|
|
95
|
+
if (!ending) socket.write(line);
|
|
96
|
+
};
|
|
97
|
+
if (connected) write();
|
|
98
|
+
else socket.once("connect", write);
|
|
99
|
+
},
|
|
100
|
+
established() {
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
},
|
|
103
|
+
subscribed() {
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
socket.setTimeout(45_000);
|
|
106
|
+
},
|
|
107
|
+
async close() {
|
|
108
|
+
stop();
|
|
109
|
+
await closed;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** One bounded RPC on its own socket; closing it never rolls back a remote mutation. */
|
|
115
|
+
export function requestHc(
|
|
116
|
+
endpoint,
|
|
117
|
+
method,
|
|
118
|
+
params = {},
|
|
119
|
+
{ signal, timeoutMs = 5000, maxBytes = HC_MAX_FRAME_BYTES } = {},
|
|
120
|
+
) {
|
|
121
|
+
return new Promise((resolve, reject) => {
|
|
122
|
+
let settled = false;
|
|
123
|
+
const connection = connect(endpoint, {
|
|
124
|
+
signal,
|
|
125
|
+
timeoutMs,
|
|
126
|
+
maxBytes,
|
|
127
|
+
onFrame(frame) {
|
|
128
|
+
const result = response(frame);
|
|
129
|
+
settled = true;
|
|
130
|
+
void connection.close().then(() => resolve(result));
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
void connection.closed.then((error) => {
|
|
134
|
+
if (!settled) reject(error ?? new Error("hc connection closed before acknowledgement"));
|
|
135
|
+
});
|
|
136
|
+
connection.send(method, params);
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Bind one operation to one core connection. A closed connection is never reopened. */
|
|
141
|
+
export async function withHcConnection(endpoint, operation, { signal, maxBytes = HC_MAX_FRAME_BYTES } = {}) {
|
|
142
|
+
let nextId = 0;
|
|
143
|
+
let closed = false;
|
|
144
|
+
let pending;
|
|
145
|
+
const connection = connect(endpoint, {
|
|
146
|
+
signal,
|
|
147
|
+
timeoutMs: 5000,
|
|
148
|
+
maxBytes,
|
|
149
|
+
onFrame(frame) {
|
|
150
|
+
if (!pending) throw new Error("Unexpected hc RPC response");
|
|
151
|
+
const result = response(frame, pending.id);
|
|
152
|
+
connection.established();
|
|
153
|
+
const received = pending;
|
|
154
|
+
pending = undefined;
|
|
155
|
+
clearTimeout(received.timer);
|
|
156
|
+
received.resolve(result);
|
|
157
|
+
},
|
|
158
|
+
});
|
|
159
|
+
const disconnected = new AbortController();
|
|
160
|
+
void connection.closed.then((error) => {
|
|
161
|
+
closed = true;
|
|
162
|
+
disconnected.abort();
|
|
163
|
+
if (!pending) return;
|
|
164
|
+
clearTimeout(pending.timer);
|
|
165
|
+
pending.reject(error ?? new Error("hc connection closed before acknowledgement"));
|
|
166
|
+
pending = undefined;
|
|
167
|
+
});
|
|
168
|
+
function request(method, params = {}, { timeoutMs = 5000 } = {}) {
|
|
169
|
+
if (closed || signal?.aborted || pending) throw new Error("hc connection is not available");
|
|
170
|
+
return new Promise((resolve, reject) => {
|
|
171
|
+
const id = ++nextId;
|
|
172
|
+
const timer = setTimeout(() => void connection.close(), timeoutMs);
|
|
173
|
+
timer.unref?.();
|
|
174
|
+
pending = { id, resolve, reject, timer };
|
|
175
|
+
connection.send(method, params, id);
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
return await operation(request, disconnected.signal);
|
|
180
|
+
} finally {
|
|
181
|
+
await connection.close();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Plain subscriptions own their socket; use separate requestHc calls for authoritative reads. */
|
|
186
|
+
export function subscribeHc(endpoint, { signal, onEvent, timeoutMs = 5000, maxBytes = HC_MAX_FRAME_BYTES } = {}) {
|
|
187
|
+
return new Promise((resolve, reject) => {
|
|
188
|
+
let acknowledged = false;
|
|
189
|
+
const connection = connect(endpoint, {
|
|
190
|
+
signal,
|
|
191
|
+
timeoutMs,
|
|
192
|
+
maxBytes,
|
|
193
|
+
onFrame(frame) {
|
|
194
|
+
if (!acknowledged) {
|
|
195
|
+
const snapshot = response(frame);
|
|
196
|
+
acknowledged = true;
|
|
197
|
+
connection.subscribed();
|
|
198
|
+
resolve({ snapshot, closed: connection.closed, close: () => connection.close() });
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (!record(frame) || frame.jsonrpc !== "2.0" || typeof frame.method !== "string" || !record(frame.params))
|
|
202
|
+
throw new Error("Invalid hc notification");
|
|
203
|
+
onEvent?.(frame);
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
void connection.closed.then((error) => {
|
|
207
|
+
if (!acknowledged) reject(error ?? new Error("hc subscription closed before acknowledgement"));
|
|
208
|
+
});
|
|
209
|
+
connection.send("events.subscribe", {});
|
|
210
|
+
});
|
|
211
|
+
}
|
package/src/hc-widget.ts
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
|
|
2
|
+
import {
|
|
3
|
+
type HerdrWidgetRow,
|
|
4
|
+
type HerdrWidgetSnapshot,
|
|
5
|
+
type HerdrWidgetState,
|
|
6
|
+
MAX_HERDR_WIDGET_AGENTS,
|
|
7
|
+
} from "./herdr-widget.js";
|
|
8
|
+
|
|
9
|
+
/** Public terminal facts only; no legacy pane/session identity is synthesized. */
|
|
10
|
+
export interface HcTerminal {
|
|
11
|
+
address: string;
|
|
12
|
+
created_ms: number;
|
|
13
|
+
argv: readonly string[];
|
|
14
|
+
cwd: string;
|
|
15
|
+
state: "live" | "finished";
|
|
16
|
+
labels: Readonly<Record<string, string>>;
|
|
17
|
+
name?: string | null;
|
|
18
|
+
parent?: string | null;
|
|
19
|
+
status?: { state: string; app?: string } | null;
|
|
20
|
+
reported: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const STATE_ORDER: Record<HerdrWidgetState, number> = {
|
|
24
|
+
error: -1,
|
|
25
|
+
blocked: 0,
|
|
26
|
+
done: 1,
|
|
27
|
+
working: 2,
|
|
28
|
+
idle: 3,
|
|
29
|
+
unknown: 4,
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
33
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function stringArray(value: unknown): value is string[] {
|
|
37
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function optionalString(value: unknown): value is string | null | undefined {
|
|
41
|
+
return value === undefined || value === null || typeof value === "string";
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Validate the public fields used here, without changing or retaining opaque payloads. */
|
|
45
|
+
export function parseHcTerminal(value: unknown): HcTerminal | undefined {
|
|
46
|
+
if (!isRecord(value)) return undefined;
|
|
47
|
+
if (
|
|
48
|
+
typeof value.address !== "string" ||
|
|
49
|
+
!safeDisplay(value.address) ||
|
|
50
|
+
typeof value.created_ms !== "number" ||
|
|
51
|
+
!Number.isSafeInteger(value.created_ms) ||
|
|
52
|
+
value.created_ms < 0 ||
|
|
53
|
+
!stringArray(value.argv) ||
|
|
54
|
+
typeof value.cwd !== "string" ||
|
|
55
|
+
(value.state !== "live" && value.state !== "finished") ||
|
|
56
|
+
!isRecord(value.labels) ||
|
|
57
|
+
!Object.values(value.labels).every((label) => typeof label === "string") ||
|
|
58
|
+
!optionalString(value.name) ||
|
|
59
|
+
!optionalString(value.parent) ||
|
|
60
|
+
(value.reported !== undefined && typeof value.reported !== "boolean")
|
|
61
|
+
) {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
let status: HcTerminal["status"];
|
|
65
|
+
if (value.status === null || value.status === undefined) {
|
|
66
|
+
status = value.status;
|
|
67
|
+
} else {
|
|
68
|
+
if (
|
|
69
|
+
!isRecord(value.status) ||
|
|
70
|
+
typeof value.status.state !== "string" ||
|
|
71
|
+
(value.status.app !== undefined && typeof value.status.app !== "string")
|
|
72
|
+
) {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
// Titles, messages, and secondary OSC records are not widget content.
|
|
76
|
+
status = {
|
|
77
|
+
state: value.status.state,
|
|
78
|
+
...(value.status.app === undefined ? {} : { app: value.status.app }),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
address: value.address,
|
|
83
|
+
created_ms: value.created_ms,
|
|
84
|
+
argv: [...value.argv],
|
|
85
|
+
cwd: value.cwd,
|
|
86
|
+
state: value.state,
|
|
87
|
+
labels: { ...value.labels } as Record<string, string>,
|
|
88
|
+
name: value.name,
|
|
89
|
+
parent: value.parent,
|
|
90
|
+
status,
|
|
91
|
+
reported: value.reported ?? false,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Reject an invalid authoritative snapshot rather than reviving a partial identity graph. */
|
|
96
|
+
export function parseHcTerminals(value: unknown): HcTerminal[] {
|
|
97
|
+
if (!Array.isArray(value)) throw new Error("hc returned an invalid terminal list");
|
|
98
|
+
return value.map((record: unknown) => {
|
|
99
|
+
const terminal = parseHcTerminal(record);
|
|
100
|
+
if (!terminal) throw new Error("hc returned an invalid terminal record");
|
|
101
|
+
return terminal;
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function safeDisplay(value: string | null | undefined): string | undefined {
|
|
106
|
+
if (value === undefined || value === null) return undefined;
|
|
107
|
+
const safe = sanitizeTerminalText(value).trim();
|
|
108
|
+
return safe || undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
interface DisplayTerminal {
|
|
112
|
+
terminal: HcTerminal;
|
|
113
|
+
address: string;
|
|
114
|
+
parent?: string;
|
|
115
|
+
name?: string;
|
|
116
|
+
app?: string;
|
|
117
|
+
cwd?: string;
|
|
118
|
+
state: HerdrWidgetState;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function displayTerminal(terminal: HcTerminal): DisplayTerminal | undefined {
|
|
122
|
+
const address = safeDisplay(terminal.address);
|
|
123
|
+
const parent = safeDisplay(terminal.parent);
|
|
124
|
+
const name = safeDisplay(terminal.name);
|
|
125
|
+
const app = safeDisplay(terminal.status?.app);
|
|
126
|
+
const cwd = safeDisplay(terminal.cwd);
|
|
127
|
+
const word = terminal.status?.state;
|
|
128
|
+
// Exact public words determine state; sanitizing an unknown word must not turn it into a known state.
|
|
129
|
+
const state = word && Object.hasOwn(STATE_ORDER, word) ? (word as HerdrWidgetState) : "unknown";
|
|
130
|
+
return address ? { terminal, address, parent, name, app, cwd, state } : undefined;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function terminalSpace(terminal: DisplayTerminal): string {
|
|
134
|
+
// Public mirror addresses are already localized by hc, including parent refs.
|
|
135
|
+
// Never strip a parent prefix or guess a namespace from its child's address.
|
|
136
|
+
const machine = terminal.address.includes("/") ? terminal.address.split("/")[0] : undefined;
|
|
137
|
+
const fallback = machine || "local";
|
|
138
|
+
const cwd = terminal.cwd;
|
|
139
|
+
if (!cwd || /^[a-z]:[\\/]*$/iu.test(cwd)) return fallback;
|
|
140
|
+
return (
|
|
141
|
+
cwd
|
|
142
|
+
.replace(/[\\/]+$/u, "")
|
|
143
|
+
.split(/[\\/]/u)
|
|
144
|
+
.at(-1) || fallback
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function originDisplay(origin: DisplayTerminal): string {
|
|
149
|
+
const label = origin.name ?? origin.app;
|
|
150
|
+
return label ? `${label}/${origin.address}` : origin.address;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Pure projection of a complete public snapshot. Ancestry belongs to terminals,
|
|
155
|
+
* survives kept-program replacement, and never identifies a Pi session/program.
|
|
156
|
+
*/
|
|
157
|
+
export function createHcWidgetSnapshot(
|
|
158
|
+
terminals: readonly HcTerminal[],
|
|
159
|
+
currentAddress: string,
|
|
160
|
+
): HerdrWidgetSnapshot | undefined {
|
|
161
|
+
// Sanitize all presentation fields before filtering, path splitting, or sorting.
|
|
162
|
+
// Raw addresses remain separate: sanitization must not create identity matches.
|
|
163
|
+
const displayed = terminals.flatMap((terminal) => {
|
|
164
|
+
const display = displayTerminal(terminal);
|
|
165
|
+
return display ? [display] : [];
|
|
166
|
+
});
|
|
167
|
+
const addressCounts = new Map<string, number>();
|
|
168
|
+
const displayCounts = new Map<string, number>();
|
|
169
|
+
for (const entry of displayed) {
|
|
170
|
+
addressCounts.set(entry.terminal.address, (addressCounts.get(entry.terminal.address) ?? 0) + 1);
|
|
171
|
+
displayCounts.set(entry.address, (displayCounts.get(entry.address) ?? 0) + 1);
|
|
172
|
+
}
|
|
173
|
+
const ambiguous = new Set<string>();
|
|
174
|
+
const graph = new Map<string, DisplayTerminal>();
|
|
175
|
+
for (const entry of displayed) {
|
|
176
|
+
if (addressCounts.get(entry.terminal.address) !== 1 || displayCounts.get(entry.address) !== 1) {
|
|
177
|
+
ambiguous.add(entry.terminal.address);
|
|
178
|
+
} else {
|
|
179
|
+
graph.set(entry.terminal.address, entry);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const validity = new Map<string, boolean>();
|
|
184
|
+
const validAncestry = (address: string): boolean => {
|
|
185
|
+
const path: string[] = [];
|
|
186
|
+
const visited = new Set<string>();
|
|
187
|
+
let next: string | null | undefined = address;
|
|
188
|
+
let valid = true;
|
|
189
|
+
while (next !== undefined && next !== null) {
|
|
190
|
+
const cached = validity.get(next);
|
|
191
|
+
if (cached !== undefined) {
|
|
192
|
+
valid = cached;
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
if (ambiguous.has(next) || visited.has(next)) {
|
|
196
|
+
valid = false;
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
visited.add(next);
|
|
200
|
+
path.push(next);
|
|
201
|
+
next = graph.get(next)?.terminal.parent;
|
|
202
|
+
}
|
|
203
|
+
for (const identity of path) validity.set(identity, valid);
|
|
204
|
+
return valid;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const current = graph.get(currentAddress);
|
|
208
|
+
const currentOrigin = current && validAncestry(currentAddress) ? current.terminal.parent : undefined;
|
|
209
|
+
const rows: HerdrWidgetRow[] = [];
|
|
210
|
+
// Resolve from the full graph, including self, finished/unreported terminals,
|
|
211
|
+
// and parents that will not fit within the five visible rows.
|
|
212
|
+
for (const entry of graph.values()) {
|
|
213
|
+
const terminal = entry.terminal;
|
|
214
|
+
if (terminal.address === currentAddress || terminal.state !== "live" || !terminal.reported || !entry.app) continue;
|
|
215
|
+
const labels: string[] = [];
|
|
216
|
+
if (entry.parent && terminal.parent && validAncestry(terminal.address)) {
|
|
217
|
+
const origin = graph.get(terminal.parent);
|
|
218
|
+
const label = origin ? (origin === current ? "you" : originDisplay(origin)) : `${entry.parent} (unavailable)`;
|
|
219
|
+
labels.push(`terminal spawned by ${label}`);
|
|
220
|
+
}
|
|
221
|
+
if (currentOrigin === terminal.address) labels.push("spawned your terminal");
|
|
222
|
+
rows.push({
|
|
223
|
+
agent: entry.name ?? entry.app,
|
|
224
|
+
pane: entry.address,
|
|
225
|
+
paneId: entry.address,
|
|
226
|
+
space: terminalSpace(entry),
|
|
227
|
+
state: entry.state,
|
|
228
|
+
stateLabel: entry.state,
|
|
229
|
+
...(labels.length > 0 ? { relation: labels.join("; ") } : {}),
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
rows.sort(
|
|
233
|
+
(left, right) =>
|
|
234
|
+
STATE_ORDER[left.state] - STATE_ORDER[right.state] ||
|
|
235
|
+
left.agent.localeCompare(right.agent) ||
|
|
236
|
+
left.pane.localeCompare(right.pane) ||
|
|
237
|
+
left.paneId.localeCompare(right.paneId),
|
|
238
|
+
);
|
|
239
|
+
if (rows.length === 0) return undefined;
|
|
240
|
+
const visible = rows.slice(0, MAX_HERDR_WIDGET_AGENTS).map((row) => Object.freeze(row));
|
|
241
|
+
return Object.freeze({
|
|
242
|
+
totalAgents: rows.length,
|
|
243
|
+
hiddenAgents: rows.length - visible.length,
|
|
244
|
+
rows: Object.freeze(visible),
|
|
245
|
+
});
|
|
246
|
+
}
|
package/src/herdr-agent-state.ts
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
herdrMetadataSnapshotsEqual,
|
|
11
11
|
} from "./herdr-metadata.js";
|
|
12
12
|
import { createHerdrWidgetObserver, type HerdrWidgetObserver } from "./herdr-observer.js";
|
|
13
|
+
import { claimHerdrRuntime } from "./herdr-runtime-claim.js";
|
|
13
14
|
|
|
14
15
|
import { createHerdrSettingsController, type HerdrSettingsOptions } from "./herdr-settings-controller.js";
|
|
15
16
|
|
|
@@ -68,7 +69,7 @@ function readEnvironment(environment: NodeJS.ProcessEnv = process.env): HerdrEnv
|
|
|
68
69
|
const socketPath = environment.HERDR_SOCKET_PATH;
|
|
69
70
|
const paneId = environment.HERDR_PANE_ID;
|
|
70
71
|
return {
|
|
71
|
-
enabled: environment.HERDR_ENV === "1" && !!socketPath && !!paneId,
|
|
72
|
+
enabled: environment.HERDR_ENV === "1" && !!socketPath?.trim() && !!paneId?.trim(),
|
|
72
73
|
paneId: paneId ?? "",
|
|
73
74
|
socketEndpoint: resolveSocketEndpoint(socketPath),
|
|
74
75
|
};
|
|
@@ -89,6 +90,8 @@ export function createHerdrAgentStateExtension(options: HerdrAgentStateOptions =
|
|
|
89
90
|
|
|
90
91
|
return function herdrAgentState(pi: ExtensionAPI): void {
|
|
91
92
|
if (!environment.enabled) return;
|
|
93
|
+
let releaseClaim = claimHerdrRuntime(pi);
|
|
94
|
+
if (!releaseClaim) return;
|
|
92
95
|
const widget = createHerdrSettingsController(pi, widgetObserver, options);
|
|
93
96
|
|
|
94
97
|
let sessionGeneration = 0;
|
|
@@ -298,9 +301,9 @@ export function createHerdrAgentStateExtension(options: HerdrAgentStateOptions =
|
|
|
298
301
|
return rootSession && ctx.sessionManager === activeSession;
|
|
299
302
|
}
|
|
300
303
|
|
|
301
|
-
function publishMetadata(ctx: ExtensionContext): void {
|
|
304
|
+
function publishMetadata(ctx: ExtensionContext, force = false): void {
|
|
302
305
|
if (!owns(ctx)) return;
|
|
303
|
-
queueMetadata(readMetadataSnapshot(ctx));
|
|
306
|
+
queueMetadata(readMetadataSnapshot(ctx), force);
|
|
304
307
|
}
|
|
305
308
|
|
|
306
309
|
function desiredState(): { state: AgentState; message?: string } {
|
|
@@ -332,6 +335,8 @@ export function createHerdrAgentStateExtension(options: HerdrAgentStateOptions =
|
|
|
332
335
|
});
|
|
333
336
|
|
|
334
337
|
pi.on("session_start", async (event, ctx) => {
|
|
338
|
+
releaseClaim ??= claimHerdrRuntime(pi);
|
|
339
|
+
if (!releaseClaim) return;
|
|
335
340
|
const generation = ++sessionGeneration;
|
|
336
341
|
const replaced = new DOMException("Herdr session replaced", "AbortError");
|
|
337
342
|
sessionController.abort(replaced);
|
|
@@ -359,7 +364,6 @@ export function createHerdrAgentStateExtension(options: HerdrAgentStateOptions =
|
|
|
359
364
|
|
|
360
365
|
updateSessionRef(ctx);
|
|
361
366
|
const sessionReport = reportSession(event.reason);
|
|
362
|
-
publishMetadata(ctx);
|
|
363
367
|
await Promise.all([sessionReport, widgetStart]);
|
|
364
368
|
if (
|
|
365
369
|
generation !== sessionGeneration ||
|
|
@@ -369,6 +373,10 @@ export function createHerdrAgentStateExtension(options: HerdrAgentStateOptions =
|
|
|
369
373
|
) {
|
|
370
374
|
return;
|
|
371
375
|
}
|
|
376
|
+
// Session-only changes do not guarantee a Herdr event. Refresh the existing
|
|
377
|
+
// TTL metadata after the identity report, even if another event sent it
|
|
378
|
+
// during startup, so observers re-read the new session before showing edges.
|
|
379
|
+
publishMetadata(ctx, true);
|
|
372
380
|
agentActive = !ctx.isIdle();
|
|
373
381
|
publishState(true);
|
|
374
382
|
});
|
|
@@ -404,6 +412,8 @@ export function createHerdrAgentStateExtension(options: HerdrAgentStateOptions =
|
|
|
404
412
|
return;
|
|
405
413
|
}
|
|
406
414
|
|
|
415
|
+
releaseClaim?.();
|
|
416
|
+
releaseClaim = undefined;
|
|
407
417
|
const session = ctx.sessionManager;
|
|
408
418
|
const task = (async () => {
|
|
409
419
|
const shouldClearMetadata = rootSession;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { createHcIntegration } from "./hc-integration.js";
|
|
3
|
+
import type { HcEnvironment } from "./hc-observer.js";
|
|
4
|
+
import herdrAgentState from "./herdr-agent-state.js";
|
|
5
|
+
|
|
6
|
+
export type IntegrationBackend = { kind: "hc"; environment: HcEnvironment } | { kind: "herdr" } | { kind: "disabled" };
|
|
7
|
+
|
|
8
|
+
/** A partial inherited hc identity must never fall back to a different legacy endpoint. */
|
|
9
|
+
export function selectIntegrationBackend(env: NodeJS.ProcessEnv = process.env): IntegrationBackend {
|
|
10
|
+
const terminal = env.HC_TERMINAL_ID;
|
|
11
|
+
const endpoint = env.HC_TERMINAL_SOCKET;
|
|
12
|
+
if (terminal === undefined && endpoint === undefined) return { kind: "herdr" };
|
|
13
|
+
const controls = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
14
|
+
if (
|
|
15
|
+
!terminal?.trim() ||
|
|
16
|
+
terminal !== terminal.trim() ||
|
|
17
|
+
[...terminal].length > 256 ||
|
|
18
|
+
controls.test(terminal) ||
|
|
19
|
+
!endpoint ||
|
|
20
|
+
!endpoint.trim() ||
|
|
21
|
+
endpoint.length > 4096 ||
|
|
22
|
+
controls.test(endpoint)
|
|
23
|
+
)
|
|
24
|
+
return { kind: "disabled" };
|
|
25
|
+
return { kind: "hc", environment: { terminalId: terminal, socketEndpoint: endpoint } };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export default function herdrIntegration(pi: ExtensionAPI): void {
|
|
29
|
+
const backend = selectIntegrationBackend();
|
|
30
|
+
if (backend.kind === "hc") createHcIntegration({ environment: backend.environment })(pi);
|
|
31
|
+
else if (backend.kind === "herdr") herdrAgentState(pi);
|
|
32
|
+
}
|
package/src/herdr-menu.ts
CHANGED
|
@@ -2,21 +2,26 @@ import type { MenuDefinition } from "@narumitw/pi-tui-kit";
|
|
|
2
2
|
|
|
3
3
|
export function createHerdrMenu(options: {
|
|
4
4
|
settingsPath: string;
|
|
5
|
+
backend?: "herdr" | "hc";
|
|
5
6
|
isEnabled(): boolean;
|
|
6
7
|
toggle(signal: AbortSignal): Promise<boolean>;
|
|
7
8
|
}): MenuDefinition<undefined, "main" | "status" | "help", "toggle"> {
|
|
9
|
+
const hc = options.backend === "hc";
|
|
10
|
+
const label = hc ? "hc" : "Herdr";
|
|
8
11
|
return {
|
|
9
12
|
start: "main",
|
|
10
13
|
screens: {
|
|
11
14
|
// One setting stays on the main menu, matching /tool rather than adding a submenu.
|
|
12
15
|
main: () => ({
|
|
13
16
|
kind: "actions",
|
|
14
|
-
title:
|
|
17
|
+
title: label,
|
|
15
18
|
items: [
|
|
16
19
|
{
|
|
17
20
|
id: "widget",
|
|
18
21
|
label: `Agent widget: ${options.isEnabled() ? "On" : "Off"}`,
|
|
19
|
-
description:
|
|
22
|
+
description: hc
|
|
23
|
+
? "Show or hide reporting agents across the connected hc core and machines"
|
|
24
|
+
: "Show or hide agents across all workspaces above the editor",
|
|
20
25
|
action: "toggle",
|
|
21
26
|
},
|
|
22
27
|
{ id: "status", label: "Status", to: "status" },
|
|
@@ -27,18 +32,24 @@ export function createHerdrMenu(options: {
|
|
|
27
32
|
}),
|
|
28
33
|
status: () => ({
|
|
29
34
|
kind: "detail",
|
|
30
|
-
title:
|
|
35
|
+
title: `${label} Status`,
|
|
31
36
|
lines: [
|
|
32
37
|
`Agent widget setting: ${options.isEnabled() ? "on" : "off"}`,
|
|
33
38
|
"The widget appears only in TUI mode with recognized sibling agents.",
|
|
34
|
-
|
|
39
|
+
hc
|
|
40
|
+
? "Scope: the connected hc core and its connected machines."
|
|
41
|
+
: "Scope: all workspaces in the connected Herdr session.",
|
|
42
|
+
hc
|
|
43
|
+
? "Pi owns native OSC 7501 lifecycle reports; this setting changes only the widget."
|
|
44
|
+
: "Lifecycle and metadata reporting are independent of this setting.",
|
|
45
|
+
...(hc ? ["Spawn annotations describe terminal ancestry, not Pi session identity or authority."] : []),
|
|
35
46
|
`User settings file: ${options.settingsPath}`,
|
|
36
47
|
],
|
|
37
48
|
hint: "back",
|
|
38
49
|
}),
|
|
39
50
|
help: () => ({
|
|
40
51
|
kind: "detail",
|
|
41
|
-
title:
|
|
52
|
+
title: `${label} Help`,
|
|
42
53
|
lines: [
|
|
43
54
|
"Toggle Agent widget from /herdr. Changes are saved immediately; closing does not undo them.",
|
|
44
55
|
"Manual pi-herdr.json changes apply after /reload or the next session start.",
|