@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/dist/index.ts CHANGED
@@ -1,465 +1,222 @@
1
1
  // @generated by scripts/build-runtime.mjs; do not edit.
2
2
  // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
3
 
4
- // src/herdr-agent-state.ts
5
- import path from "node:path";
4
+ // src/hc-integration.ts
5
+ import { isAbsolute as isAbsolute2 } from "node:path";
6
+ import { fileURLToPath } from "node:url";
6
7
 
7
- // src/herdr-client.ts
8
+ // src/hc-observer.ts
9
+ import { createEditorStatusPublisher } from "@narumitw/pi-tui-kit/editor-status-publisher";
10
+
11
+ // src/hc-rpc.mjs
8
12
  import net from "node:net";
9
- var MAX_HERDR_FRAME_BYTES = 1024 * 1024;
10
- var MAX_PENDING_SUBSCRIPTION_EVENTS = 1024;
11
- var NdjsonFrames = class {
12
- buffer = Buffer.alloc(0);
13
- push(chunk) {
14
- this.buffer = Buffer.concat([this.buffer, chunk]);
15
- if (this.buffer.length > MAX_HERDR_FRAME_BYTES && this.buffer.indexOf(10) < 0) {
16
- throw new Error("Herdr response frame exceeded the size limit");
17
- }
18
- const frames = [];
19
- while (true) {
20
- const newline = this.buffer.indexOf(10);
21
- if (newline < 0) break;
22
- if (newline > MAX_HERDR_FRAME_BYTES) {
23
- throw new Error("Herdr response frame exceeded the size limit");
24
- }
25
- const line = this.buffer.subarray(0, newline);
26
- this.buffer = this.buffer.subarray(newline + 1);
27
- if (line.length === 0) continue;
28
- try {
29
- frames.push(JSON.parse(line.toString("utf8")));
30
- } catch {
31
- throw new Error("Herdr returned invalid JSON");
32
- }
33
- }
34
- if (this.buffer.length > MAX_HERDR_FRAME_BYTES) {
35
- throw new Error("Herdr response frame exceeded the size limit");
36
- }
37
- return frames;
38
- }
39
- };
40
- function isRecord(value) {
41
- return typeof value === "object" && value !== null && !Array.isArray(value);
42
- }
43
- function abortReason(signal) {
44
- return signal.reason instanceof Error ? signal.reason : new DOMException("Herdr request aborted", "AbortError");
45
- }
46
- var HerdrApiError = class extends Error {
47
- code;
48
- constructor(error) {
49
- super(`Herdr ${typeof error.message === "string" ? error.message : "request failed"}`);
50
- this.code = typeof error.code === "string" ? error.code : void 0;
13
+ var HC_MAX_FRAME_BYTES = 2 * 1024 * 1024;
14
+ var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
15
+ function response(frame, id = 1) {
16
+ if (!record(frame) || frame.jsonrpc !== "2.0" || frame.id !== id) throw new Error("Invalid hc RPC response");
17
+ if (Object.hasOwn(frame, "error")) {
18
+ const kind = frame.error?.data?.kind;
19
+ const suffix = typeof kind === "string" && /^[a-z_]{1,40}$/u.test(kind) ? ` (${kind})` : "";
20
+ throw new Error(`hc RPC rejected${suffix}; inspect the terminal before retrying`);
51
21
  }
52
- };
53
- function responseError(frame) {
54
- if (!("error" in frame)) return void 0;
55
- if (!isRecord(frame.error)) return new Error("Herdr returned an invalid error response");
56
- return new HerdrApiError(frame.error);
57
- }
58
- function createBestEffortSender(socketEndpoint) {
59
- return async (request, signal) => {
60
- for (const timeoutMs of [500, 1500]) {
61
- if (signal.aborted) return;
62
- try {
63
- const result = await requestHerdr(socketEndpoint, request, signal, timeoutMs);
64
- if (isRecord(result) && result.type === "ok") return;
65
- } catch (error) {
66
- if (signal.aborted || error instanceof HerdrApiError) return;
67
- }
68
- }
69
- };
22
+ if (!Object.hasOwn(frame, "result")) throw new Error("Missing hc RPC result");
23
+ return frame.result;
70
24
  }
71
- function requestHerdr(socketEndpoint, request, signal, timeoutMs = 1500) {
72
- if (signal.aborted) return Promise.reject(abortReason(signal));
73
- return new Promise((resolve, reject) => {
74
- const payload = `${JSON.stringify(request)}
75
- `;
76
- const socket = net.createConnection(socketEndpoint);
77
- const parser = new NdjsonFrames();
78
- let finished = false;
79
- const timeout = setTimeout(() => finish(new Error("Herdr request timed out")), timeoutMs);
80
- timeout.unref?.();
81
- const cleanup = () => {
82
- clearTimeout(timeout);
83
- signal.removeEventListener("abort", abort);
84
- socket.destroy();
85
- };
86
- const finish = (error, result) => {
87
- if (finished) return;
88
- finished = true;
89
- cleanup();
90
- if (error) reject(error);
91
- else resolve(result);
92
- };
93
- const abort = () => finish(abortReason(signal));
94
- signal.addEventListener("abort", abort, { once: true });
95
- socket.on("connect", () => {
96
- if (!finished) socket.write(payload);
97
- });
98
- socket.on("error", (error) => finish(error));
99
- socket.on("end", () => finish(new Error("Herdr closed the request before responding")));
100
- socket.on("close", () => finish(new Error("Herdr request socket closed")));
101
- socket.on("data", (chunk) => {
102
- if (finished) return;
103
- try {
104
- for (const value of parser.push(chunk)) {
105
- if (!isRecord(value)) continue;
106
- const uncorrelatedError = responseError(value);
107
- if (uncorrelatedError && (value.id === "" || value.id === void 0)) {
108
- finish(uncorrelatedError);
109
- return;
110
- }
111
- if (value.id !== request.id) continue;
112
- const error = responseError(value);
113
- if (error) {
114
- finish(error);
115
- return;
116
- }
117
- if (!("result" in value)) {
118
- finish(new Error("Herdr response did not include a result"));
119
- return;
120
- }
121
- finish(void 0, value.result);
122
- return;
123
- }
124
- } catch (error) {
125
- finish(error instanceof Error ? error : new Error(String(error)));
126
- }
127
- });
25
+ function connect(endpoint, { signal, timeoutMs, maxBytes, onFrame }) {
26
+ if (typeof endpoint !== "string" || !endpoint.trim()) throw new Error("Missing inherited hc endpoint");
27
+ if (signal?.aborted) throw new Error("hc operation cancelled; remote changes may have occurred");
28
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || !Number.isFinite(timeoutMs) || timeoutMs <= 0)
29
+ throw new Error("Invalid hc connection limits");
30
+ const socket = net.createConnection(endpoint);
31
+ let ending = false;
32
+ let connected = false;
33
+ socket.once("connect", () => {
34
+ connected = true;
128
35
  });
129
- }
130
- async function openHerdrSubscription(socketEndpoint, request, signal, onEvent, timeoutMs = 1500) {
131
- if (signal.aborted) throw abortReason(signal);
132
- const payload = `${JSON.stringify(request)}
133
- `;
134
- const socket = net.createConnection(socketEndpoint);
135
- const parser = new NdjsonFrames();
136
- const pendingEvents = [];
137
- let ready = false;
138
- let finished = false;
139
- let intentionalClose = false;
140
- let resolveReady;
141
- let rejectReady;
36
+ let reason;
37
+ let pending = "";
38
+ const decoder = new TextDecoder("utf-8", { fatal: true });
142
39
  let resolveClosed;
143
- let rejectClosed;
144
- const readyPromise = new Promise((resolve, reject) => {
145
- resolveReady = resolve;
146
- rejectReady = reject;
147
- });
148
- const closed = new Promise((resolve, reject) => {
149
- resolveClosed = resolve;
150
- rejectClosed = reject;
40
+ const closed = new Promise((resolve3) => {
41
+ resolveClosed = resolve3;
151
42
  });
152
- void closed.catch(() => void 0);
153
- const timeout = setTimeout(() => finish(new Error("Herdr subscription timed out")), timeoutMs);
154
- timeout.unref?.();
155
- const cleanup = () => {
156
- clearTimeout(timeout);
157
- signal.removeEventListener("abort", abort);
43
+ const stop = (error) => {
44
+ if (ending) return;
45
+ ending = true;
46
+ reason = error;
158
47
  socket.destroy();
159
48
  };
160
- const finish = (error) => {
161
- if (finished) return;
162
- finished = true;
163
- cleanup();
164
- if (!ready) {
165
- if (error && !intentionalClose) rejectReady(error);
166
- else rejectReady(abortReason(signal));
167
- resolveClosed();
168
- return;
169
- }
170
- if (error && !intentionalClose) rejectClosed(error);
171
- else resolveClosed();
172
- };
173
- const deliver = (frame) => {
174
- if (finished) return;
175
- try {
176
- onEvent(frame);
177
- } catch (error) {
178
- finish(error instanceof Error ? error : new Error(String(error)));
179
- }
180
- };
181
- const abort = () => {
182
- intentionalClose = true;
183
- finish();
184
- };
185
- signal.addEventListener("abort", abort, { once: true });
186
- socket.on("connect", () => {
187
- if (!finished) socket.write(payload);
188
- });
189
- socket.on("error", (error) => finish(error));
190
- socket.on("end", () => finish(new Error("Herdr subscription closed")));
191
- socket.on("close", () => finish(new Error("Herdr subscription socket closed")));
49
+ const abort = () => stop(new Error("hc operation cancelled; remote changes may have occurred"));
50
+ const timer = setTimeout(() => stop(new Error("hc connection timed out; outcome may be ambiguous")), timeoutMs);
51
+ timer.unref?.();
52
+ signal?.addEventListener("abort", abort, { once: true });
53
+ socket.on("error", () => stop(new Error("hc socket failed; outcome may be ambiguous")));
54
+ socket.on("timeout", () => stop(new Error("hc subscription heartbeat timed out")));
192
55
  socket.on("data", (chunk) => {
193
- if (finished) return;
56
+ if (ending) return;
194
57
  try {
195
- for (const value of parser.push(chunk)) {
196
- if (finished) return;
197
- if (isRecord(value)) {
198
- const error = responseError(value);
199
- if (error && (value.id === request.id || value.id === "" || value.id === void 0)) {
200
- finish(error);
201
- return;
202
- }
203
- if ("id" in value && value.id !== request.id) continue;
204
- }
205
- if (!ready) {
206
- if (isRecord(value) && value.id === request.id) {
207
- if (!isRecord(value.result) || value.result.type !== "subscription_started") {
208
- finish(new Error("Herdr returned an invalid subscription acknowledgement"));
209
- return;
210
- }
211
- ready = true;
212
- clearTimeout(timeout);
213
- socket.unref();
214
- resolveReady();
215
- for (const event of pendingEvents.splice(0)) deliver(event);
216
- continue;
217
- }
218
- if (pendingEvents.length >= MAX_PENDING_SUBSCRIPTION_EVENTS) {
219
- finish(new Error("Too many Herdr events arrived before subscription acknowledgement"));
220
- return;
221
- }
222
- pendingEvents.push(value);
223
- continue;
58
+ pending += decoder.decode(chunk, { stream: true });
59
+ let newline = pending.indexOf("\n");
60
+ while (newline >= 0 && !ending) {
61
+ const line = pending.slice(0, newline);
62
+ pending = pending.slice(newline + 1);
63
+ if (Buffer.byteLength(line) > maxBytes) throw new Error("hc frame exceeded the limit");
64
+ if (!line.trim()) throw new Error("Empty hc frame");
65
+ let frame;
66
+ try {
67
+ frame = JSON.parse(line);
68
+ } catch {
69
+ throw new Error("Invalid hc JSON frame");
224
70
  }
225
- deliver(value);
71
+ onFrame(frame);
72
+ newline = pending.indexOf("\n");
226
73
  }
74
+ if (Buffer.byteLength(pending) > maxBytes) throw new Error("hc frame exceeded the limit");
227
75
  } catch (error) {
228
- finish(error instanceof Error ? error : new Error(String(error)));
76
+ stop(error instanceof Error ? error : new Error("Invalid hc frame"));
229
77
  }
230
78
  });
231
- await readyPromise;
232
- if (signal.aborted) {
233
- intentionalClose = true;
234
- finish();
235
- throw abortReason(signal);
236
- }
79
+ socket.once("end", () => stop(new Error("hc socket ended")));
80
+ socket.once("close", () => {
81
+ ending = true;
82
+ clearTimeout(timer);
83
+ signal?.removeEventListener("abort", abort);
84
+ socket.removeAllListeners("data");
85
+ resolveClosed(reason);
86
+ });
237
87
  return {
238
88
  closed,
239
- close() {
240
- intentionalClose = true;
241
- finish();
89
+ send(method, params, id = 1) {
90
+ let line;
91
+ try {
92
+ line = `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
93
+ `;
94
+ } catch {
95
+ stop(new Error("Invalid hc request"));
96
+ return;
97
+ }
98
+ if (Buffer.byteLength(line) > maxBytes) {
99
+ stop(new Error("hc request exceeded the limit"));
100
+ return;
101
+ }
102
+ const write = () => {
103
+ if (!ending) socket.write(line);
104
+ };
105
+ if (connected) write();
106
+ else socket.once("connect", write);
107
+ },
108
+ established() {
109
+ clearTimeout(timer);
110
+ },
111
+ subscribed() {
112
+ clearTimeout(timer);
113
+ socket.setTimeout(45e3);
114
+ },
115
+ async close() {
116
+ stop();
117
+ await closed;
242
118
  }
243
119
  };
244
120
  }
245
-
246
- // src/herdr-metadata.ts
247
- import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
248
- var HERDR_METADATA_TOKEN_KEYS = ["model", "provider", "thinking", "session", "context_usage"];
249
- var HERDR_METADATA_MAX_CHARACTERS = 80;
250
- var HERDR_METADATA_TTL_MS = 60 * 60 * 1e3;
251
- var HERDR_METADATA_REFRESH_MS = 30 * 60 * 1e3;
252
- function normalizeHerdrMetadataValue(value) {
253
- if (typeof value !== "string") return null;
254
- const normalized = sanitizeTerminalText(value).trim();
255
- if (normalized.length === 0) return null;
256
- return [...normalized].slice(0, HERDR_METADATA_MAX_CHARACTERS).join("");
257
- }
258
- function formatContextUsagePercent(value) {
259
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null;
260
- return `${Math.round(value)}%`;
261
- }
262
- function createHerdrMetadataSnapshot(inputs) {
263
- return Object.freeze({
264
- model: normalizeHerdrMetadataValue(inputs.model),
265
- provider: normalizeHerdrMetadataValue(inputs.provider),
266
- thinking: normalizeHerdrMetadataValue(inputs.thinking),
267
- session: normalizeHerdrMetadataValue(inputs.session),
268
- context_usage: formatContextUsagePercent(inputs.contextUsagePercent)
121
+ function requestHc(endpoint, method, params = {}, { signal, timeoutMs = 5e3, maxBytes = HC_MAX_FRAME_BYTES } = {}) {
122
+ return new Promise((resolve3, reject) => {
123
+ let settled = false;
124
+ const connection = connect(endpoint, {
125
+ signal,
126
+ timeoutMs,
127
+ maxBytes,
128
+ onFrame(frame) {
129
+ const result = response(frame);
130
+ settled = true;
131
+ void connection.close().then(() => resolve3(result));
132
+ }
133
+ });
134
+ void connection.closed.then((error) => {
135
+ if (!settled) reject(error ?? new Error("hc connection closed before acknowledgement"));
136
+ });
137
+ connection.send(method, params);
269
138
  });
270
139
  }
271
- function createHerdrMetadataClearSnapshot() {
272
- return Object.freeze({
273
- model: null,
274
- provider: null,
275
- thinking: null,
276
- session: null,
277
- context_usage: null
278
- });
279
- }
280
- function herdrMetadataSnapshotsEqual(left, right) {
281
- return left !== void 0 && HERDR_METADATA_TOKEN_KEYS.every((key) => left[key] === right[key]);
282
- }
283
- function createHerdrMetadataRequest(options) {
284
- return {
285
- id: options.id,
286
- method: "pane.report_metadata",
287
- params: {
288
- pane_id: options.paneId,
289
- source: options.source,
290
- seq: options.seq,
291
- tokens: { ...options.snapshot },
292
- ttl_ms: options.ttlMs ?? HERDR_METADATA_TTL_MS
140
+ async function withHcConnection(endpoint, operation, { signal, maxBytes = HC_MAX_FRAME_BYTES } = {}) {
141
+ let nextId = 0;
142
+ let closed = false;
143
+ let pending;
144
+ const connection = connect(endpoint, {
145
+ signal,
146
+ timeoutMs: 5e3,
147
+ maxBytes,
148
+ onFrame(frame) {
149
+ if (!pending) throw new Error("Unexpected hc RPC response");
150
+ const result = response(frame, pending.id);
151
+ connection.established();
152
+ const received = pending;
153
+ pending = void 0;
154
+ clearTimeout(received.timer);
155
+ received.resolve(result);
293
156
  }
294
- };
295
- }
296
-
297
- // src/herdr-observer.ts
298
- import { createEditorStatusPublisher } from "@narumitw/pi-tui-kit/editor-status-publisher";
299
-
300
- // src/herdr-protocol.ts
301
- var HERDR_AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"];
302
- var HERDR_WIDGET_TOPOLOGY_SUBSCRIPTIONS = [
303
- { type: "pane.created" },
304
- { type: "pane.updated" },
305
- { type: "workspace.renamed" },
306
- { type: "pane.closed" },
307
- { type: "pane.moved" },
308
- { type: "pane.exited" },
309
- { type: "pane.agent_detected" }
310
- ];
311
- function herdrWidgetSubscriptions(panes) {
312
- return [
313
- ...HERDR_WIDGET_TOPOLOGY_SUBSCRIPTIONS.map((entry) => ({ ...entry })),
314
- ...panes.filter((pane) => pane.agent !== void 0).map((pane) => ({ type: "pane.agent_status_changed", pane_id: pane.paneId }))
315
- ];
316
- }
317
- function isRecord2(value) {
318
- return typeof value === "object" && value !== null && !Array.isArray(value);
319
- }
320
- function requiredString(value) {
321
- return typeof value === "string" && value.length > 0 ? value : void 0;
322
- }
323
- function optionalString(value) {
324
- return typeof value === "string" ? value : void 0;
325
- }
326
- function agentStatus(value) {
327
- return typeof value === "string" && HERDR_AGENT_STATUSES.includes(value) ? value : void 0;
328
- }
329
- function stringRecord(value) {
330
- if (!isRecord2(value)) return void 0;
331
- const entries = Object.entries(value);
332
- if (!entries.every(([, entry]) => typeof entry === "string")) return void 0;
333
- return Object.fromEntries(entries);
334
- }
335
- function parseHerdrPane(value) {
336
- if (!isRecord2(value)) return void 0;
337
- const paneId = requiredString(value.pane_id);
338
- const workspaceId = requiredString(value.workspace_id);
339
- const tabId = requiredString(value.tab_id);
340
- const terminalId = requiredString(value.terminal_id);
341
- const status = agentStatus(value.agent_status);
342
- const revision = value.revision;
343
- if (!paneId || !workspaceId || !tabId || !terminalId || !status || typeof value.focused !== "boolean" || typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 0) {
344
- return void 0;
345
- }
346
- return {
347
- paneId,
348
- workspaceId,
349
- tabId,
350
- terminalId,
351
- focused: value.focused,
352
- revision,
353
- agent: optionalString(value.agent),
354
- agentName: optionalString(value.name),
355
- agentStatus: status,
356
- displayAgent: optionalString(value.display_agent),
357
- label: optionalString(value.label),
358
- stateLabels: stringRecord(value.state_labels) ?? {},
359
- terminalTitle: optionalString(value.terminal_title_stripped) ?? optionalString(value.terminal_title),
360
- title: optionalString(value.title)
361
- };
362
- }
363
- function parsePaneCurrentResult(value) {
364
- if (!isRecord2(value) || value.type !== "pane_current") {
365
- throw new Error("Herdr returned an invalid current-pane response");
366
- }
367
- const pane = parseHerdrPane(value.pane);
368
- if (!pane) throw new Error("Herdr returned an invalid current pane");
369
- return pane;
370
- }
371
- function parsePaneListResult(value) {
372
- if (!isRecord2(value) || value.type !== "pane_list" || !Array.isArray(value.panes)) {
373
- throw new Error("Herdr returned an invalid pane-list response");
157
+ });
158
+ const disconnected = new AbortController();
159
+ void connection.closed.then((error) => {
160
+ closed = true;
161
+ disconnected.abort();
162
+ if (!pending) return;
163
+ clearTimeout(pending.timer);
164
+ pending.reject(error ?? new Error("hc connection closed before acknowledgement"));
165
+ pending = void 0;
166
+ });
167
+ function request(method, params = {}, { timeoutMs = 5e3 } = {}) {
168
+ if (closed || signal?.aborted || pending) throw new Error("hc connection is not available");
169
+ return new Promise((resolve3, reject) => {
170
+ const id = ++nextId;
171
+ const timer = setTimeout(() => void connection.close(), timeoutMs);
172
+ timer.unref?.();
173
+ pending = { id, resolve: resolve3, reject, timer };
174
+ connection.send(method, params, id);
175
+ });
374
176
  }
375
- const panes = value.panes.map(parseHerdrPane);
376
- if (panes.some((pane) => pane === void 0)) {
377
- throw new Error("Herdr returned an invalid pane in the pane list");
177
+ try {
178
+ return await operation(request, disconnected.signal);
179
+ } finally {
180
+ await connection.close();
378
181
  }
379
- return panes;
380
182
  }
381
- function parseAgentListResult(value) {
382
- if (!isRecord2(value) || value.type !== "agent_list" || !Array.isArray(value.agents)) {
383
- throw new Error("Herdr returned an invalid agent-list response");
384
- }
385
- return value.agents.flatMap((entry) => {
386
- const pane = parseHerdrPane(entry);
387
- return pane ? [pane] : [];
183
+ function subscribeHc(endpoint, { signal, onEvent, timeoutMs = 5e3, maxBytes = HC_MAX_FRAME_BYTES } = {}) {
184
+ return new Promise((resolve3, reject) => {
185
+ let acknowledged = false;
186
+ const connection = connect(endpoint, {
187
+ signal,
188
+ timeoutMs,
189
+ maxBytes,
190
+ onFrame(frame) {
191
+ if (!acknowledged) {
192
+ const snapshot = response(frame);
193
+ acknowledged = true;
194
+ connection.subscribed();
195
+ resolve3({ snapshot, closed: connection.closed, close: () => connection.close() });
196
+ return;
197
+ }
198
+ if (!record(frame) || frame.jsonrpc !== "2.0" || typeof frame.method !== "string" || !record(frame.params))
199
+ throw new Error("Invalid hc notification");
200
+ onEvent?.(frame);
201
+ }
202
+ });
203
+ void connection.closed.then((error) => {
204
+ if (!acknowledged) reject(error ?? new Error("hc subscription closed before acknowledgement"));
205
+ });
206
+ connection.send("events.subscribe", {});
388
207
  });
389
208
  }
390
- function parseWorkspaceGetResult(value) {
391
- if (!isRecord2(value) || value.type !== "workspace_info" || !isRecord2(value.workspace)) {
392
- throw new Error("Herdr returned an invalid workspace response");
393
- }
394
- const workspaceId = requiredString(value.workspace.workspace_id);
395
- if (!workspaceId) throw new Error("Herdr returned an invalid workspace identity");
396
- return { workspaceId, label: optionalString(value.workspace.label) };
397
- }
398
- function parseHerdrPaneEvent(value) {
399
- if (!isRecord2(value) || typeof value.event !== "string" || !isRecord2(value.data)) {
400
- return void 0;
401
- }
402
- const data = value.data;
403
- if (value.event === "workspace_renamed") {
404
- const workspaceId = requiredString(data.workspace_id);
405
- if (!workspaceId || typeof data.label !== "string") return void 0;
406
- return { type: "workspace_renamed", workspaceId };
407
- }
408
- if (value.event === "pane.agent_status_changed" || value.event === "pane_agent_status_changed") {
409
- const paneId = requiredString(data.pane_id);
410
- const workspaceId = requiredString(data.workspace_id);
411
- const status = agentStatus(data.agent_status);
412
- if (!paneId || !workspaceId || !status) return void 0;
413
- return {
414
- type: "agent_status_changed",
415
- paneId,
416
- workspaceId
417
- };
418
- }
419
- if (value.event === "pane_created" || value.event === "pane_updated") {
420
- const pane = parseHerdrPane(data.pane);
421
- return pane ? { type: value.event === "pane_created" ? "created" : "updated", pane } : void 0;
422
- }
423
- if (value.event === "pane_closed" || value.event === "pane_exited") {
424
- const paneId = requiredString(data.pane_id);
425
- const workspaceId = requiredString(data.workspace_id);
426
- if (!paneId || !workspaceId) return void 0;
427
- return {
428
- type: value.event === "pane_closed" ? "closed" : "exited",
429
- paneId,
430
- workspaceId
431
- };
432
- }
433
- if (value.event === "pane_moved") {
434
- const pane = parseHerdrPane(data.pane);
435
- const previousPaneId = requiredString(data.previous_pane_id);
436
- const previousWorkspaceId = requiredString(data.previous_workspace_id);
437
- if (!pane || !previousPaneId || !previousWorkspaceId) return void 0;
438
- return { type: "moved", pane, previousPaneId, previousWorkspaceId };
439
- }
440
- if (value.event === "pane_agent_detected") {
441
- const paneId = requiredString(data.pane_id);
442
- const workspaceId = requiredString(data.workspace_id);
443
- if (!paneId || !workspaceId || data.released !== void 0 && typeof data.released !== "boolean") {
444
- return void 0;
445
- }
446
- const finalStatus = data.final_status === null ? void 0 : agentStatus(data.final_status);
447
- if (data.final_status !== void 0 && data.final_status !== null && !finalStatus) return void 0;
448
- return {
449
- type: "agent_detected",
450
- paneId,
451
- workspaceId
452
- };
453
- }
454
- return void 0;
455
- }
209
+
210
+ // src/hc-widget.ts
211
+ import { sanitizeTerminalText as sanitizeTerminalText2 } from "@narumitw/pi-tui-kit/terminal-text";
456
212
 
457
213
  // src/herdr-widget.ts
458
214
  import { EditorStatusWidget } from "@narumitw/pi-tui-kit/editor-status-widget";
459
- import { sanitizeTerminalText as sanitizeTerminalText2 } from "@narumitw/pi-tui-kit/terminal-text";
215
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
460
216
  var HERDR_WIDGET_KEY = "herdr:agents";
461
217
  var MAX_HERDR_WIDGET_AGENTS = 5;
462
218
  var STATE_ORDER = {
219
+ error: -1,
463
220
  blocked: 0,
464
221
  done: 1,
465
222
  working: 2,
@@ -470,6 +227,9 @@ function observedPane(pane) {
470
227
  return {
471
228
  paneId: pane.paneId,
472
229
  workspaceId: pane.workspaceId,
230
+ terminalId: pane.terminalId,
231
+ sessionFingerprint: pane.sessionFingerprint,
232
+ spawn: pane.spawn ? { ...pane.spawn } : void 0,
473
233
  agent: pane.agent,
474
234
  agentName: pane.agentName,
475
235
  agentStatus: pane.agentStatus,
@@ -481,7 +241,7 @@ function observedPane(pane) {
481
241
  }
482
242
  function safeDisplay(value) {
483
243
  if (value === void 0) return void 0;
484
- const safe = sanitizeTerminalText2(value).trim();
244
+ const safe = sanitizeTerminalText(value).trim();
485
245
  return safe.length > 0 ? safe : void 0;
486
246
  }
487
247
  function shortIdentity(value, fallback) {
@@ -512,6 +272,49 @@ function rowForPane(pane, workspace) {
512
272
  stateLabel: safeDisplay(pane.stateLabels[pane.agentStatus]) ?? safeDisplay(pane.agentStatus) ?? "unknown"
513
273
  };
514
274
  }
275
+ function spawnRelations(panes, currentPaneId) {
276
+ const identities = /* @__PURE__ */ new Map();
277
+ const key = (terminal, session) => JSON.stringify([terminal, session]);
278
+ for (const pane of panes) {
279
+ if (pane.agent !== "pi" || !pane.sessionFingerprint) continue;
280
+ const identity2 = key(pane.terminalId, pane.sessionFingerprint);
281
+ identities.set(identity2, identities.has(identity2) ? void 0 : pane);
282
+ }
283
+ const origins = /* @__PURE__ */ new Map();
284
+ const records = /* @__PURE__ */ new Map();
285
+ for (const pane of panes) {
286
+ const spawn = pane.spawn;
287
+ if (pane.agent !== "pi" || !pane.sessionFingerprint || !spawn || spawn.targetSession !== pane.sessionFingerprint || spawn.originTerminalId === pane.terminalId)
288
+ continue;
289
+ records.set(pane.paneId, spawn);
290
+ const origin = identities.get(key(spawn.originTerminalId, spawn.originSession));
291
+ if (origin) origins.set(pane.paneId, origin);
292
+ }
293
+ const cyclic = (id) => {
294
+ const visited = /* @__PURE__ */ new Set();
295
+ let next = id;
296
+ while (next !== void 0) {
297
+ if (visited.has(next)) return true;
298
+ visited.add(next);
299
+ next = origins.get(next)?.paneId;
300
+ }
301
+ return false;
302
+ };
303
+ const currentOrigin = cyclic(currentPaneId) ? void 0 : origins.get(currentPaneId);
304
+ const relations = /* @__PURE__ */ new Map();
305
+ for (const pane of panes) {
306
+ const labels = [];
307
+ const spawn = records.get(pane.paneId);
308
+ if (spawn && !cyclic(pane.paneId)) {
309
+ const origin = origins.get(pane.paneId);
310
+ const label = origin ? origin.paneId === currentPaneId ? "you" : `${agentDisplay(origin)}/${paneDisplay(origin)}` : `${safeDisplay(spawn.originLabel) ?? "previous agent"} (unavailable)`;
311
+ labels.push(`spawned by ${label}`);
312
+ }
313
+ if (currentOrigin?.paneId === pane.paneId) labels.push("spawned you");
314
+ if (labels.length > 0) relations.set(pane.paneId, labels.join("; "));
315
+ }
316
+ return relations;
317
+ }
515
318
  function immutableSnapshot(rows) {
516
319
  if (rows.length === 0) return void 0;
517
320
  const visible = rows.slice(0, MAX_HERDR_WIDGET_AGENTS).map((row) => Object.freeze({ ...row }));
@@ -523,32 +326,28 @@ function immutableSnapshot(rows) {
523
326
  }
524
327
  var HerdrWidgetModel = class {
525
328
  currentPaneId;
526
- currentWorkspaceId;
527
- workspace;
329
+ workspaces = /* @__PURE__ */ new Map();
528
330
  panes = /* @__PURE__ */ new Map();
529
- reset(currentPane, panes, workspace = { workspaceId: currentPane.workspaceId }) {
331
+ reset(currentPane, panes, workspaces = []) {
530
332
  this.currentPaneId = currentPane.paneId;
531
- this.currentWorkspaceId = currentPane.workspaceId;
532
- this.workspace = { ...workspace };
333
+ this.workspaces = new Map(workspaces.map((workspace) => [workspace.workspaceId, { ...workspace }]));
533
334
  this.panes = new Map(panes.map((pane) => [pane.paneId, observedPane(pane)]));
335
+ this.panes.set(currentPane.paneId, observedPane(currentPane));
534
336
  }
535
337
  clear() {
536
338
  this.currentPaneId = void 0;
537
- this.currentWorkspaceId = void 0;
538
- this.workspace = void 0;
339
+ this.workspaces.clear();
539
340
  this.panes.clear();
540
341
  }
541
- isCurrentPane(paneId) {
542
- return this.currentPaneId === paneId;
543
- }
544
- isCurrentWorkspace(workspaceId) {
545
- return this.currentWorkspaceId === workspaceId;
546
- }
547
342
  snapshot() {
548
- if (!this.currentPaneId || !this.currentWorkspaceId || !this.workspace) return void 0;
549
- const rows = [...this.panes.values()].filter(
550
- (pane) => pane.workspaceId === this.currentWorkspaceId && pane.paneId !== this.currentPaneId && pane.agent !== void 0
551
- ).map((pane) => rowForPane(pane, this.workspace));
343
+ if (!this.currentPaneId) return void 0;
344
+ const panes = [...this.panes.values()];
345
+ const relations = spawnRelations(panes, this.currentPaneId);
346
+ const rows = panes.filter((pane) => pane.paneId !== this.currentPaneId && pane.agent !== void 0).map((pane) => {
347
+ const row = rowForPane(pane, this.workspaces.get(pane.workspaceId) ?? { workspaceId: pane.workspaceId });
348
+ const relation = relations.get(pane.paneId);
349
+ return relation ? { ...row, relation } : row;
350
+ });
552
351
  rows.sort(
553
352
  (left, right) => STATE_ORDER[left.state] - STATE_ORDER[right.state] || left.agent.localeCompare(right.agent) || left.pane.localeCompare(right.pane) || left.paneId.localeCompare(right.paneId)
554
353
  );
@@ -557,6 +356,7 @@ var HerdrWidgetModel = class {
557
356
  };
558
357
  function stateStyle(theme, state, text) {
559
358
  switch (state) {
359
+ case "error":
560
360
  case "blocked":
561
361
  return theme.fg("error", text);
562
362
  case "done":
@@ -571,6 +371,8 @@ function stateStyle(theme, state, text) {
571
371
  }
572
372
  function stateSymbol(state) {
573
373
  switch (state) {
374
+ case "error":
375
+ return "!";
574
376
  case "blocked":
575
377
  return "\xD7";
576
378
  case "done":
@@ -597,7 +399,8 @@ function createHerdrWidget(snapshot, theme, includeHeader = true) {
597
399
  const agent = theme.bold(theme.fg("text", row.agent));
598
400
  const pane = theme.fg("muted", row.pane);
599
401
  const space = theme.fg("dim", row.space);
600
- lines.push(`${state} ${agent}${separator}${pane}${separator}${space}`);
402
+ const relation = row.relation ? `${separator}${theme.fg("muted", row.relation)}` : "";
403
+ lines.push(`${state} ${agent}${separator}${pane}${separator}${space}${relation}`);
601
404
  }
602
405
  if (snapshot.hiddenAgents > 0) {
603
406
  lines.push(theme.fg("dim", `+${snapshot.hiddenAgents} more`));
@@ -610,373 +413,913 @@ function herdrWidgetFingerprint(snapshot) {
610
413
  return snapshot ? JSON.stringify(snapshot) : void 0;
611
414
  }
612
415
 
613
- // src/herdr-observer.ts
614
- var HerdrTopologyChangedError = class extends Error {
615
- };
616
- var HerdrCleanupError = class extends AggregateError {
416
+ // src/hc-widget.ts
417
+ var STATE_ORDER2 = {
418
+ error: -1,
419
+ blocked: 0,
420
+ done: 1,
421
+ working: 2,
422
+ idle: 3,
423
+ unknown: 4
617
424
  };
618
- function renderHerdrWidget(snapshot, theme, width) {
619
- return createHerdrWidget(snapshot, theme, false).render(width);
425
+ function isRecord(value) {
426
+ return typeof value === "object" && value !== null && !Array.isArray(value);
427
+ }
428
+ function stringArray(value) {
429
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
620
430
  }
621
- function isRelevantEvent(model, event) {
622
- if (event.type === "created" || event.type === "updated") {
623
- return model.isCurrentWorkspace(event.pane.workspaceId);
431
+ function optionalString(value) {
432
+ return value === void 0 || value === null || typeof value === "string";
433
+ }
434
+ function parseHcTerminal(value) {
435
+ if (!isRecord(value)) return void 0;
436
+ if (typeof value.address !== "string" || !safeDisplay2(value.address) || typeof value.created_ms !== "number" || !Number.isSafeInteger(value.created_ms) || value.created_ms < 0 || !stringArray(value.argv) || typeof value.cwd !== "string" || value.state !== "live" && value.state !== "finished" || !isRecord(value.labels) || !Object.values(value.labels).every((label) => typeof label === "string") || !optionalString(value.name) || !optionalString(value.parent) || value.reported !== void 0 && typeof value.reported !== "boolean") {
437
+ return void 0;
624
438
  }
625
- if (event.type === "moved") {
626
- return model.isCurrentPane(event.previousPaneId) || model.isCurrentWorkspace(event.previousWorkspaceId) || model.isCurrentWorkspace(event.pane.workspaceId);
439
+ let status;
440
+ if (value.status === null || value.status === void 0) {
441
+ status = value.status;
442
+ } else {
443
+ if (!isRecord(value.status) || typeof value.status.state !== "string" || value.status.app !== void 0 && typeof value.status.app !== "string") {
444
+ return void 0;
445
+ }
446
+ status = {
447
+ state: value.status.state,
448
+ ...value.status.app === void 0 ? {} : { app: value.status.app }
449
+ };
627
450
  }
628
- return "workspaceId" in event && model.isCurrentWorkspace(event.workspaceId);
451
+ return {
452
+ address: value.address,
453
+ created_ms: value.created_ms,
454
+ argv: [...value.argv],
455
+ cwd: value.cwd,
456
+ state: value.state,
457
+ labels: { ...value.labels },
458
+ name: value.name,
459
+ parent: value.parent,
460
+ status,
461
+ reported: value.reported ?? false
462
+ };
629
463
  }
630
- function subscriptionFingerprint(currentPane, panes) {
631
- const agentPaneIds = panes.filter((pane) => pane.agent !== void 0).map((pane) => pane.paneId).sort();
632
- return JSON.stringify([currentPane.paneId, currentPane.workspaceId, agentPaneIds]);
464
+ function parseHcTerminals(value) {
465
+ if (!Array.isArray(value)) throw new Error("hc returned an invalid terminal list");
466
+ return value.map((record5) => {
467
+ const terminal = parseHcTerminal(record5);
468
+ if (!terminal) throw new Error("hc returned an invalid terminal record");
469
+ return terminal;
470
+ });
633
471
  }
634
- function waitForRetry(delayMs, signal) {
635
- if (signal.aborted) return Promise.reject(signal.reason);
636
- if (delayMs <= 0) return Promise.resolve();
637
- return new Promise((resolve, reject) => {
472
+ function safeDisplay2(value) {
473
+ if (value === void 0 || value === null) return void 0;
474
+ const safe = sanitizeTerminalText2(value).trim();
475
+ return safe || void 0;
476
+ }
477
+ function displayTerminal(terminal) {
478
+ const address = safeDisplay2(terminal.address);
479
+ const parent = safeDisplay2(terminal.parent);
480
+ const name = safeDisplay2(terminal.name);
481
+ const app = safeDisplay2(terminal.status?.app);
482
+ const cwd = safeDisplay2(terminal.cwd);
483
+ const word = terminal.status?.state;
484
+ const state = word && Object.hasOwn(STATE_ORDER2, word) ? word : "unknown";
485
+ return address ? { terminal, address, parent, name, app, cwd, state } : void 0;
486
+ }
487
+ function terminalSpace(terminal) {
488
+ const machine = terminal.address.includes("/") ? terminal.address.split("/")[0] : void 0;
489
+ const fallback = machine || "local";
490
+ const cwd = terminal.cwd;
491
+ if (!cwd || /^[a-z]:[\\/]*$/iu.test(cwd)) return fallback;
492
+ return cwd.replace(/[\\/]+$/u, "").split(/[\\/]/u).at(-1) || fallback;
493
+ }
494
+ function originDisplay(origin) {
495
+ const label = origin.name ?? origin.app;
496
+ return label ? `${label}/${origin.address}` : origin.address;
497
+ }
498
+ function createHcWidgetSnapshot(terminals, currentAddress) {
499
+ const displayed = terminals.flatMap((terminal) => {
500
+ const display = displayTerminal(terminal);
501
+ return display ? [display] : [];
502
+ });
503
+ const addressCounts = /* @__PURE__ */ new Map();
504
+ const displayCounts = /* @__PURE__ */ new Map();
505
+ for (const entry of displayed) {
506
+ addressCounts.set(entry.terminal.address, (addressCounts.get(entry.terminal.address) ?? 0) + 1);
507
+ displayCounts.set(entry.address, (displayCounts.get(entry.address) ?? 0) + 1);
508
+ }
509
+ const ambiguous = /* @__PURE__ */ new Set();
510
+ const graph = /* @__PURE__ */ new Map();
511
+ for (const entry of displayed) {
512
+ if (addressCounts.get(entry.terminal.address) !== 1 || displayCounts.get(entry.address) !== 1) {
513
+ ambiguous.add(entry.terminal.address);
514
+ } else {
515
+ graph.set(entry.terminal.address, entry);
516
+ }
517
+ }
518
+ const validity = /* @__PURE__ */ new Map();
519
+ const validAncestry = (address) => {
520
+ const path2 = [];
521
+ const visited = /* @__PURE__ */ new Set();
522
+ let next = address;
523
+ let valid = true;
524
+ while (next !== void 0 && next !== null) {
525
+ const cached = validity.get(next);
526
+ if (cached !== void 0) {
527
+ valid = cached;
528
+ break;
529
+ }
530
+ if (ambiguous.has(next) || visited.has(next)) {
531
+ valid = false;
532
+ break;
533
+ }
534
+ visited.add(next);
535
+ path2.push(next);
536
+ next = graph.get(next)?.terminal.parent;
537
+ }
538
+ for (const identity2 of path2) validity.set(identity2, valid);
539
+ return valid;
540
+ };
541
+ const current = graph.get(currentAddress);
542
+ const currentOrigin = current && validAncestry(currentAddress) ? current.terminal.parent : void 0;
543
+ const rows = [];
544
+ for (const entry of graph.values()) {
545
+ const terminal = entry.terminal;
546
+ if (terminal.address === currentAddress || terminal.state !== "live" || !terminal.reported || !entry.app) continue;
547
+ const labels = [];
548
+ if (entry.parent && terminal.parent && validAncestry(terminal.address)) {
549
+ const origin = graph.get(terminal.parent);
550
+ const label = origin ? origin === current ? "you" : originDisplay(origin) : `${entry.parent} (unavailable)`;
551
+ labels.push(`terminal spawned by ${label}`);
552
+ }
553
+ if (currentOrigin === terminal.address) labels.push("spawned your terminal");
554
+ rows.push({
555
+ agent: entry.name ?? entry.app,
556
+ pane: entry.address,
557
+ paneId: entry.address,
558
+ space: terminalSpace(entry),
559
+ state: entry.state,
560
+ stateLabel: entry.state,
561
+ ...labels.length > 0 ? { relation: labels.join("; ") } : {}
562
+ });
563
+ }
564
+ rows.sort(
565
+ (left, right) => STATE_ORDER2[left.state] - STATE_ORDER2[right.state] || left.agent.localeCompare(right.agent) || left.pane.localeCompare(right.pane) || left.paneId.localeCompare(right.paneId)
566
+ );
567
+ if (rows.length === 0) return void 0;
568
+ const visible = rows.slice(0, MAX_HERDR_WIDGET_AGENTS).map((row) => Object.freeze(row));
569
+ return Object.freeze({
570
+ totalAgents: rows.length,
571
+ hiddenAgents: rows.length - visible.length,
572
+ rows: Object.freeze(visible)
573
+ });
574
+ }
575
+
576
+ // src/hc-observer.ts
577
+ var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
578
+ function sequence(value) {
579
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("Invalid hc event sequence");
580
+ return value;
581
+ }
582
+ function eventSnapshot(value) {
583
+ if (!record2(value)) throw new Error("Invalid hc subscription snapshot");
584
+ return { seq: sequence(value.seq), terminals: parseHcTerminals(value.terminals) };
585
+ }
586
+ function retryDelay(milliseconds, signal) {
587
+ if (signal.aborted) return Promise.reject(new Error("hc observer cancelled"));
588
+ if (milliseconds <= 0) return Promise.resolve();
589
+ return new Promise((resolve3, reject) => {
638
590
  const timer = setTimeout(() => {
639
- signal.removeEventListener("abort", abort);
640
- resolve();
641
- }, delayMs);
591
+ signal.removeEventListener("abort", cancel);
592
+ resolve3();
593
+ }, milliseconds);
642
594
  timer.unref?.();
643
- const abort = () => {
595
+ const cancel = () => {
644
596
  clearTimeout(timer);
645
- reject(signal.reason);
597
+ reject(new Error("hc observer cancelled"));
646
598
  };
647
- signal.addEventListener("abort", abort, { once: true });
599
+ signal.addEventListener("abort", cancel, { once: true });
648
600
  });
649
601
  }
650
- function createHerdrWidgetObserver(options) {
651
- const now = options.now ?? Date.now;
652
- const random = options.random ?? Math.random;
653
- const request = options.request ?? requestHerdr;
654
- const subscribe = options.subscribe ?? openHerdrSubscription;
655
- const retryDelayMs = options.retryDelayMs ?? 200;
602
+ function createHcWidgetObserver(options) {
603
+ const request = options.request ?? requestHc;
604
+ const subscribe = options.subscribe ?? subscribeHc;
656
605
  let generation = 0;
657
- let publisher;
658
- let activeSession;
606
+ let owner;
659
607
  let controller;
660
- const ownedTasks = /* @__PURE__ */ new Set();
661
- const taskErrors = /* @__PURE__ */ new Set();
662
- let publishedFingerprint;
663
- let hasPublished = false;
664
- const owns = (ctx, expectedGeneration = generation) => expectedGeneration === generation && ctx.sessionManager === activeSession;
665
- const requestId = (kind) => `herdr:pi:widget:${kind}:${now()}:${random().toString(36).slice(2)}`;
666
- const clearWidget = () => {
667
- publisher?.publish(void 0);
668
- publishedFingerprint = void 0;
669
- hasPublished = false;
670
- };
671
- const publish = (ctx, model, expectedGeneration) => {
672
- if (!owns(ctx, expectedGeneration) || ctx.mode !== "tui") return;
673
- const snapshot = model.snapshot();
674
- const fingerprint = herdrWidgetFingerprint(snapshot);
675
- if (hasPublished && fingerprint === publishedFingerprint) return;
608
+ let publisher;
609
+ let fingerprint;
610
+ const tasks = /* @__PURE__ */ new Set();
611
+ const cleanupErrors = /* @__PURE__ */ new Set();
612
+ const owns = (ctx, expected = generation) => expected === generation && owner !== void 0 && ctx.sessionManager === owner;
613
+ function publish(ctx, expected, snapshot) {
614
+ if (!owns(ctx, expected)) return;
615
+ const next = herdrWidgetFingerprint(snapshot);
616
+ if (next === fingerprint) return;
676
617
  publisher?.publish(snapshot);
677
- publishedFingerprint = fingerprint;
678
- hasPublished = true;
679
- };
680
- const loadPaneSet = async (ctx, expectedGeneration, signal) => {
681
- const currentResult = await request(
682
- options.environment.socketEndpoint,
683
- {
684
- id: requestId("current"),
685
- method: "pane.current",
686
- params: { caller_pane_id: options.environment.paneId }
687
- },
688
- signal
689
- );
690
- if (!owns(ctx, expectedGeneration) || signal.aborted) return void 0;
691
- const currentPane = parsePaneCurrentResult(currentResult);
692
- const [listResult, agentResult, workspaceResult] = await Promise.all([
693
- request(
694
- options.environment.socketEndpoint,
695
- {
696
- id: requestId("list"),
697
- method: "pane.list",
698
- params: { workspace_id: currentPane.workspaceId }
699
- },
700
- signal
701
- ),
702
- request(
703
- options.environment.socketEndpoint,
704
- { id: requestId("agents"), method: "agent.list", params: {} },
705
- signal
706
- ),
707
- request(
708
- options.environment.socketEndpoint,
709
- {
710
- id: requestId("workspace"),
711
- method: "workspace.get",
712
- params: { workspace_id: currentPane.workspaceId }
713
- },
714
- signal
715
- )
716
- ]);
717
- if (!owns(ctx, expectedGeneration) || signal.aborted) return void 0;
718
- const panes = parsePaneListResult(listResult);
719
- const paneIds = new Set(panes.map((pane) => pane.paneId));
720
- const namesByPane = new Map(
721
- parseAgentListResult(agentResult).filter((pane) => pane.workspaceId === currentPane.workspaceId && paneIds.has(pane.paneId)).map((pane) => [pane.paneId, pane.agentName])
722
- );
723
- const withAgentName = (pane) => ({
724
- ...pane,
725
- agentName: namesByPane.get(pane.paneId) ?? pane.agentName
726
- });
727
- const workspace = parseWorkspaceGetResult(workspaceResult);
728
- if (workspace.workspaceId !== currentPane.workspaceId) {
729
- throw new Error("Herdr returned a mismatched workspace");
730
- }
731
- return {
732
- currentPane: withAgentName(currentPane),
733
- panes: panes.map(withAgentName),
734
- workspace
735
- };
736
- };
737
- const runAttempt = async (ctx, expectedGeneration, sessionSignal) => {
618
+ fingerprint = next;
619
+ }
620
+ async function attempt(ctx, expected, signal, healthy) {
738
621
  const attemptController = new AbortController();
739
- const abortAttempt = () => attemptController.abort(sessionSignal.reason);
740
- if (sessionSignal.aborted) abortAttempt();
741
- else sessionSignal.addEventListener("abort", abortAttempt, { once: true });
742
- const signal = attemptController.signal;
743
- let attemptActive = true;
622
+ const abort = () => attemptController.abort();
623
+ signal.addEventListener("abort", abort, { once: true });
624
+ if (signal.aborted) abort();
744
625
  let subscription;
626
+ let active = true;
627
+ let dirty = true;
628
+ let seq = -1;
745
629
  let failure;
746
- let attemptError;
747
- let cleanupFailure;
748
630
  let wake;
749
- const wakeRefresh = () => {
750
- const resolve = wake;
631
+ const notify = () => {
632
+ const waiting = wake;
751
633
  wake = void 0;
752
- resolve?.();
634
+ waiting?.();
753
635
  };
754
- signal.addEventListener("abort", wakeRefresh);
755
- const failAttempt = (error) => {
756
- if (!attemptActive || signal.aborted) return;
636
+ const fail2 = (error) => {
637
+ if (!active || attemptController.signal.aborted) return;
757
638
  failure = error;
758
- try {
759
- if (owns(ctx, expectedGeneration)) clearWidget();
760
- } catch (cleanupError) {
761
- failure = new AggregateError([error, cleanupError], "Herdr subscription and widget cleanup failed");
762
- } finally {
763
- attemptController.abort(failure);
764
- }
639
+ attemptController.abort();
640
+ notify();
765
641
  };
642
+ attemptController.signal.addEventListener("abort", notify);
643
+ const current = () => active && !attemptController.signal.aborted && owns(ctx, expected);
766
644
  try {
767
- await (async () => {
768
- const discovered = await loadPaneSet(ctx, expectedGeneration, signal);
769
- if (!discovered) return;
770
- const subscribedFingerprint = subscriptionFingerprint(discovered.currentPane, discovered.panes);
771
- const model = new HerdrWidgetModel();
772
- model.reset(discovered.currentPane, discovered.panes, discovered.workspace);
773
- let dirty = true;
774
- subscription = await subscribe(
775
- options.environment.socketEndpoint,
776
- {
777
- id: requestId("subscribe"),
778
- method: "events.subscribe",
779
- params: { subscriptions: herdrWidgetSubscriptions(discovered.panes) }
780
- },
781
- signal,
782
- (frame) => {
783
- if (!attemptActive || !owns(ctx, expectedGeneration) || signal.aborted) return;
784
- const event = parseHerdrPaneEvent(frame);
785
- if (!event || !isRelevantEvent(model, event)) return;
645
+ subscription = await subscribe(options.environment.socketEndpoint, {
646
+ signal: attemptController.signal,
647
+ onEvent(frame) {
648
+ if (!current()) return;
649
+ try {
650
+ if (!record2(frame) || !record2(frame.params)) throw new Error("Invalid hc event");
651
+ const next = sequence(frame.params.seq);
652
+ if (frame.method === "heartbeat") return;
653
+ if (frame.method !== "event" && frame.method !== "missed") throw new Error("Unknown hc notification");
654
+ if (next <= seq) return;
655
+ seq = next;
656
+ if (frame.method === "missed") {
657
+ eventSnapshot(frame.params);
658
+ publish(ctx, expected, void 0);
659
+ } else {
660
+ if (frame.params.type === "doc") return;
661
+ if (typeof frame.params.type !== "string" || typeof frame.params.terminal !== "string")
662
+ throw new Error("Invalid hc fact event");
663
+ }
786
664
  dirty = true;
787
- wakeRefresh();
665
+ notify();
666
+ } catch (error) {
667
+ fail2(error);
788
668
  }
789
- ).catch(async (error) => {
790
- if (!owns(ctx, expectedGeneration) || signal.aborted) throw error;
791
- const latest = await loadPaneSet(ctx, expectedGeneration, signal);
792
- if (latest && subscriptionFingerprint(latest.currentPane, latest.panes) !== subscribedFingerprint) {
793
- throw new HerdrTopologyChangedError();
669
+ }
670
+ });
671
+ void subscription.closed.then((error) => fail2(error ?? new Error("hc subscription closed")));
672
+ if (!current()) {
673
+ if (failure !== void 0 && owns(ctx, expected) && !signal.aborted) throw failure;
674
+ return;
675
+ }
676
+ const initial = eventSnapshot(subscription.snapshot);
677
+ seq = Math.max(seq, initial.seq);
678
+ let discarded = 0;
679
+ while (current()) {
680
+ if (!dirty) {
681
+ await new Promise((resolve3) => {
682
+ wake = resolve3;
683
+ if (!current() || dirty) notify();
684
+ });
685
+ if (!current()) break;
686
+ }
687
+ dirty = false;
688
+ const result = await request(
689
+ options.environment.socketEndpoint,
690
+ "terminal.list",
691
+ { all: true },
692
+ {
693
+ signal: attemptController.signal
794
694
  }
795
- throw error;
796
- });
797
- void subscription.closed.then(
798
- () => failAttempt(new Error("Herdr subscription ended")),
799
- (error) => failAttempt(error instanceof Error ? error : new Error(String(error)))
800
695
  );
801
- while (owns(ctx, expectedGeneration) && !signal.aborted) {
802
- dirty = false;
803
- const refreshed = await loadPaneSet(ctx, expectedGeneration, signal);
804
- if (!refreshed || signal.aborted) break;
805
- if (dirty) continue;
806
- if (subscriptionFingerprint(refreshed.currentPane, refreshed.panes) !== subscribedFingerprint) {
807
- throw new HerdrTopologyChangedError();
808
- }
809
- model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspace);
810
- publish(ctx, model, expectedGeneration);
811
- await new Promise((resolve) => {
812
- wake = resolve;
813
- if (dirty || signal.aborted) wakeRefresh();
814
- });
696
+ if (!current()) break;
697
+ if (!record2(result)) throw new Error("Invalid hc terminal list");
698
+ const terminals = parseHcTerminals(result.terminals);
699
+ const own = terminals.filter((terminal) => terminal.address === options.environment.terminalId);
700
+ if (own.length !== 1 || own[0]?.state !== "live") throw new Error("Current hc terminal is unavailable");
701
+ if (dirty && discarded < 2) {
702
+ discarded += 1;
703
+ continue;
815
704
  }
816
- if (failure) throw failure;
817
- })();
818
- } catch (error) {
819
- attemptError = { error };
705
+ discarded = 0;
706
+ publish(ctx, expected, createHcWidgetSnapshot(terminals, options.environment.terminalId));
707
+ healthy();
708
+ }
709
+ if (failure !== void 0 && owns(ctx, expected) && !signal.aborted) throw failure;
820
710
  } finally {
821
- attemptActive = false;
822
- attemptController.abort(new DOMException("Herdr widget attempt ended", "AbortError"));
823
- signal.removeEventListener("abort", wakeRefresh);
824
- sessionSignal.removeEventListener("abort", abortAttempt);
825
- try {
826
- subscription?.close();
827
- } catch (cleanupError) {
828
- cleanupFailure = { error: cleanupError };
711
+ active = false;
712
+ attemptController.abort();
713
+ notify();
714
+ signal.removeEventListener("abort", abort);
715
+ attemptController.signal.removeEventListener("abort", notify);
716
+ if (subscription) {
717
+ try {
718
+ await subscription.close();
719
+ } catch (error) {
720
+ cleanupErrors.add(error);
721
+ }
829
722
  }
830
723
  }
831
- if (cleanupFailure) {
832
- throw new HerdrCleanupError(
833
- attemptError ? [attemptError.error, cleanupFailure.error] : [cleanupFailure.error],
834
- "Herdr subscription cleanup failed"
835
- );
836
- }
837
- if (attemptError) throw attemptError.error;
838
- };
839
- const run = async (ctx, expectedGeneration, signal) => {
724
+ }
725
+ async function run(ctx, expected, signal) {
840
726
  let failures = 0;
841
- while (owns(ctx, expectedGeneration) && !signal.aborted) {
727
+ while (owns(ctx, expected) && !signal.aborted) {
842
728
  try {
843
- await runAttempt(ctx, expectedGeneration, signal);
729
+ await attempt(ctx, expected, signal, () => {
730
+ failures = 0;
731
+ });
844
732
  return;
845
- } catch (error) {
846
- if (error instanceof HerdrCleanupError) throw error;
847
- if (!owns(ctx, expectedGeneration) || signal.aborted) return;
848
- try {
849
- clearWidget();
850
- } catch (cleanupError) {
851
- throw new AggregateError([error, cleanupError], "Herdr observation and widget cleanup failed");
852
- }
853
- if (error instanceof HerdrTopologyChangedError) continue;
733
+ } catch {
734
+ if (!owns(ctx, expected) || signal.aborted) return;
735
+ publish(ctx, expected, void 0);
854
736
  failures += 1;
855
737
  if (failures >= 2) return;
856
738
  try {
857
- await waitForRetry(retryDelayMs, signal);
739
+ await retryDelay(options.retryDelayMs ?? 200, signal);
858
740
  } catch {
859
741
  return;
860
742
  }
861
- if (!owns(ctx, expectedGeneration) || signal.aborted) return;
862
743
  }
863
744
  }
864
- };
745
+ }
865
746
  return {
866
747
  start(ctx) {
867
- controller?.abort(new DOMException("Herdr widget session replaced", "AbortError"));
748
+ controller?.abort();
868
749
  try {
869
750
  publisher?.dispose();
870
751
  } finally {
871
- publisher = void 0;
872
752
  generation += 1;
873
- activeSession = void 0;
753
+ publisher = void 0;
754
+ fingerprint = void 0;
755
+ owner = void 0;
874
756
  controller = void 0;
875
- publishedFingerprint = void 0;
876
- hasPublished = false;
877
757
  }
878
758
  if (ctx.mode !== "tui") return;
879
- activeSession = ctx.sessionManager;
759
+ owner = ctx.sessionManager;
760
+ const expected = generation;
880
761
  controller = new AbortController();
881
- const expectedGeneration = generation;
882
762
  publisher = createEditorStatusPublisher({
883
763
  key: HERDR_WIDGET_KEY,
884
- name: "Herdr",
764
+ name: "hc",
885
765
  context: ctx,
886
- isCurrent: () => expectedGeneration === generation,
766
+ isCurrent: () => generation === expected,
887
767
  summary: herdrWidgetSummary,
888
- render: renderHerdrWidget
768
+ render: (snapshot, theme, width) => createHerdrWidget(snapshot, theme, false).render(width)
889
769
  });
890
- const task = run(ctx, expectedGeneration, controller.signal);
891
- ownedTasks.add(task);
770
+ const task = run(ctx, expected, controller.signal);
771
+ tasks.add(task);
892
772
  void task.then(
893
- () => ownedTasks.delete(task),
773
+ () => tasks.delete(task),
894
774
  (error) => {
895
- taskErrors.add(error);
896
- ownedTasks.delete(task);
775
+ cleanupErrors.add(error);
776
+ tasks.delete(task);
897
777
  }
898
778
  );
899
779
  },
900
780
  restore(ctx) {
901
- if (activeSession === void 0 || !owns(ctx)) return false;
902
- return publisher?.setCollapsed(false) ?? false;
781
+ return owns(ctx) ? publisher?.setCollapsed(false) ?? false : false;
903
782
  },
904
783
  async shutdown(ctx) {
905
- if (activeSession !== void 0 && !owns(ctx)) return;
906
- controller?.abort(new DOMException("Herdr widget session shut down", "AbortError"));
784
+ if (owner !== void 0 && !owns(ctx)) return;
785
+ controller?.abort();
907
786
  const errors = [];
908
787
  try {
909
788
  publisher?.dispose();
910
789
  } catch (error) {
911
790
  errors.push(error);
912
791
  } finally {
913
- publisher = void 0;
914
792
  generation += 1;
915
- publishedFingerprint = void 0;
916
- hasPublished = false;
793
+ publisher = void 0;
794
+ fingerprint = void 0;
917
795
  }
918
- const shutdownGeneration = generation;
919
- await Promise.allSettled([...ownedTasks]);
920
- errors.push(...taskErrors);
921
- taskErrors.clear();
922
- if (generation === shutdownGeneration) {
923
- activeSession = void 0;
796
+ const expected = generation;
797
+ await Promise.allSettled([...tasks]);
798
+ errors.push(...cleanupErrors);
799
+ cleanupErrors.clear();
800
+ if (expected === generation) {
801
+ owner = void 0;
924
802
  controller = void 0;
925
803
  }
926
- if (errors.length === 1) throw errors[0];
927
- if (errors.length > 1) throw new AggregateError(errors, "Herdr widget cleanup failed");
804
+ if (errors.length) throw new AggregateError(errors, "hc widget cleanup failed");
928
805
  }
929
806
  };
930
807
  }
931
808
 
932
- // src/settings.ts
933
- import { randomUUID } from "node:crypto";
809
+ // src/hc-peer.mjs
934
810
  import { constants } from "node:fs";
935
- import { lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
936
- import { basename, dirname, join } from "node:path";
937
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
938
- var HERDR_SETTINGS_FILE = "pi-herdr.json";
939
- var MAX_SETTINGS_BYTES = 64 * 1024;
940
- var DEFAULT_SETTINGS = { widget: true };
941
- var queues = /* @__PURE__ */ new Map();
942
- function herdrSettingsPath() {
943
- return join(getAgentDir(), HERDR_SETTINGS_FILE);
811
+ import * as files from "node:fs/promises";
812
+ import { dirname, isAbsolute, relative, resolve, sep, win32 } from "node:path";
813
+ var MAX_TASK_BYTES = 32 * 1024;
814
+ var MAX_OUTPUT_BYTES = 128 * 1024;
815
+ var RPC_TIMEOUT_MS = 5e3;
816
+ var WAIT_TIMEOUT_MS = 35e3;
817
+ var SEND_TIMEOUT_MS = 7e4;
818
+ var controls = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
819
+ var record3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
820
+ var validName = (value) => typeof value === "string" && /^[a-z][a-z0-9_-]{0,31}$/u.test(value);
821
+ var identifier = (value) => typeof value === "string" && value.length > 0 && value.trim() === value && value.length <= 256 && !controls.test(value);
822
+ var terminalAddress = (value) => identifier(value) && /^t[1-9][0-9bcdfghjkmnpqrstvwxyz]*$/u.test(value);
823
+ var natural = (value) => Number.isSafeInteger(value) && value >= 0;
824
+ var sameArgv = (left, right) => left.length === right.length && left.every((arg, index) => arg === right[index]);
825
+ var requiredMethods = ["terminal.get", "terminal.run", "terminal.wait", "terminal.send"];
826
+ var SafeError = class extends Error {
827
+ };
828
+ function fail(message) {
829
+ throw new SafeError(message);
944
830
  }
945
- function normalizeHerdrSettings(value) {
946
- if (!isRecord3(value)) return void 0;
947
- if (Object.hasOwn(value, "widget") && typeof value.widget !== "boolean") {
948
- return void 0;
949
- }
950
- return {
951
- widget: typeof value.widget === "boolean" ? value.widget : DEFAULT_SETTINGS.widget
952
- };
831
+ function checkCancelled(signal) {
832
+ if (signal?.aborted) fail("Operation cancelled; server-side changes may have occurred");
953
833
  }
954
- function readHerdrSettings(settingsPath = herdrSettingsPath()) {
955
- return enqueue(settingsPath, async () => {
956
- let document;
834
+ function absolutePath(path2, paths = { isAbsolute }) {
835
+ return typeof path2 === "string" && paths.isAbsolute(path2) && !controls.test(path2);
836
+ }
837
+ function inside(root, path2, paths = { relative, isAbsolute, sep }) {
838
+ const local = paths.relative(root, path2);
839
+ return local === "" || local !== ".." && !local.startsWith(`..${paths.sep}`) && !paths.isAbsolute(local);
840
+ }
841
+ function checkPeerText(text) {
842
+ if (typeof text !== "string" || !text.trim() || Buffer.byteLength(text) > MAX_TASK_BYTES || controls.test(text.replace(/[\t\r\n]/gu, "")))
843
+ fail("Peer text must be nonempty and at most 32768 UTF-8 bytes, without terminal controls except tab/CR/newline");
844
+ }
845
+ async function resolveTrustedExecutables(piCli, { cwd = process.cwd(), execPath = process.execPath, platform = process.platform, signal, fs = files } = {}) {
846
+ const paths = platform === "win32" ? win32 : { dirname, isAbsolute, relative, resolve, sep };
847
+ if (![cwd, execPath, piCli].every((path2) => absolutePath(path2, paths))) {
848
+ fail("The cwd, Node runtime, and Pi CLI must be absolute paths without terminal controls");
849
+ }
850
+ checkCancelled(signal);
851
+ let directory = await fs.realpath(cwd);
852
+ checkCancelled(signal);
853
+ if (!absolutePath(directory, paths)) fail("Invalid canonical cwd");
854
+ let project = directory;
855
+ while (true) {
957
856
  try {
958
- document = await readSettingsDocument(settingsPath);
857
+ await fs.stat(paths.resolve(directory, ".git"));
858
+ project = directory;
959
859
  } catch (error) {
960
- if (isNodeError(error) && error.code === "ENOENT") {
961
- return { kind: "missing", settings: { ...DEFAULT_SETTINGS } };
962
- }
963
- return {
964
- kind: "invalid",
965
- reason: `${settingsPath}: ${safeError(error)}`,
966
- settings: { ...DEFAULT_SETTINGS }
967
- };
860
+ if (error.code !== "ENOENT") throw error;
968
861
  }
969
- const settings = normalizeHerdrSettings(document);
970
- return settings ? { kind: "loaded", settings } : {
971
- kind: "invalid",
972
- reason: `${settingsPath}: invalid settings shape`,
973
- settings: { ...DEFAULT_SETTINGS }
974
- };
975
- });
862
+ checkCancelled(signal);
863
+ const parent = paths.dirname(directory);
864
+ if (parent === directory) break;
865
+ directory = parent;
866
+ }
867
+ async function canonical(path2, executable) {
868
+ const resolved = await fs.realpath(path2);
869
+ checkCancelled(signal);
870
+ if (!absolutePath(resolved, paths) || inside(project, resolved, paths)) {
871
+ fail("Node and the Pi CLI must resolve outside the topmost cwd Git ancestor (or cwd without Git)");
872
+ }
873
+ if (executable && platform === "win32" && !/\.exe$/iu.test(resolved)) fail("Node must be a native executable");
874
+ const info = await fs.stat(resolved);
875
+ checkCancelled(signal);
876
+ if (!info.isFile()) fail("Node and the Pi CLI must be regular files");
877
+ await fs.access(resolved, executable && platform !== "win32" ? constants.X_OK : constants.R_OK);
878
+ checkCancelled(signal);
879
+ return platform === "win32" ? resolved.replaceAll("\\", "/") : resolved;
880
+ }
881
+ const node = await canonical(execPath, true);
882
+ checkCancelled(signal);
883
+ const cli = await canonical(piCli, false);
884
+ checkCancelled(signal);
885
+ return { node, piCli: cli };
976
886
  }
977
- function updateHerdrSettings(patch, options = {}) {
978
- const settingsPath = options.settingsPath ?? herdrSettingsPath();
979
- return enqueue(settingsPath, async () => {
887
+ async function checkResources(root, skill, { signal, fs = files } = {}) {
888
+ if (!absolutePath(root) || !absolutePath(skill)) fail("Invalid package resources");
889
+ checkCancelled(signal);
890
+ const canonicalRoot = await fs.realpath(root);
891
+ checkCancelled(signal);
892
+ const canonicalSkill = await fs.realpath(skill);
893
+ checkCancelled(signal);
894
+ if (!absolutePath(canonicalRoot) || !absolutePath(canonicalSkill) || canonicalSkill !== resolve(canonicalRoot, "skills/pi-herdr"))
895
+ fail("The skill must belong to this package");
896
+ async function regular(path2, boundary) {
897
+ const canonical = await fs.realpath(path2);
898
+ checkCancelled(signal);
899
+ if (!absolutePath(canonical) || !inside(boundary, canonical)) fail("Resource escaped this package");
900
+ const info = await fs.stat(canonical);
901
+ checkCancelled(signal);
902
+ if (!info.isFile()) fail("Resource must be a regular file");
903
+ return canonical;
904
+ }
905
+ await regular(resolve(canonicalSkill, "SKILL.md"), canonicalSkill);
906
+ checkCancelled(signal);
907
+ for (const entry of ["dist/index.ts", "src/index.ts"]) {
908
+ try {
909
+ const path2 = await regular(resolve(canonicalRoot, entry), canonicalRoot);
910
+ checkCancelled(signal);
911
+ return entry === "dist/index.ts" ? canonicalRoot : path2;
912
+ } catch (error) {
913
+ checkCancelled(signal);
914
+ if (error.code !== "ENOENT") throw error;
915
+ }
916
+ }
917
+ fail("Missing package entrypoint");
918
+ }
919
+ function identity(value) {
920
+ if (!record3(value) || !terminalAddress(value.address) || value.state !== "live" || !natural(value.created_ms) || !Number.isSafeInteger(value.pid) || value.pid <= 0 || value.pid > 4294967295 || !Array.isArray(value.argv) || value.argv.length === 0 || value.argv.some((arg) => typeof arg !== "string") || !value.argv[0].trim())
921
+ fail("Missing or malformed live terminal identity");
922
+ return { address: value.address, created: value.created_ms, pid: value.pid, argv: [...value.argv] };
923
+ }
924
+ function sameIdentity(value, expected) {
925
+ const actual = identity(value);
926
+ if (actual.address !== expected.address || actual.created !== expected.created || actual.pid !== expected.pid || !sameArgv(actual.argv, expected.argv))
927
+ fail("Observed terminal identity changed; inspect the known terminal before retrying");
928
+ }
929
+ function reportedPi(value, states2) {
930
+ if (value.reported !== true || !record3(value.status) || value.status.app !== "pi" || !states2.includes(value.status.state)) {
931
+ fail("Terminal has no current safe Pi status report; task not submitted");
932
+ }
933
+ }
934
+ function targetFacts(value, expected, { name, cwd, argv, origin }, ready) {
935
+ sameIdentity(value, expected);
936
+ if (value.name !== name || value.cwd !== cwd || !sameArgv(value.argv, argv) || value.parent !== origin || value.die_with_parent !== false || value.keep !== false || value.rm !== false)
937
+ fail("Peer launch facts changed or do not match the requested independent terminal");
938
+ if (ready) reportedPi(value, ["idle"]);
939
+ }
940
+ function coreIdentity(value) {
941
+ if (!record3(value) || value.generation !== 1 || value.framed !== false || !identifier(value.core?.id) || !Array.isArray(value.methods) || requiredMethods.some((method) => !value.methods.includes(method)))
942
+ fail("Unsupported or malformed hc hello");
943
+ return value.core.id;
944
+ }
945
+ function validateWait(value, address) {
946
+ if (!record3(value) || value.terminal !== address || typeof value.ended !== "boolean" || !natural(value.turn) || !["status", "timeout", "message", "exit"].includes(value.reason) || value.status != null && typeof value.status !== "string" || !Array.isArray(value.children) || value.children.length !== 0)
947
+ fail("Unknown readiness wait result; inspect the known terminal");
948
+ if (value.reason === "exit") fail("Peer exited during readiness wait; task not submitted");
949
+ }
950
+ function validateSend(value) {
951
+ if (!record3(value) || !natural(value.turn) || value.status != null && value.status !== "idle" || value.started != null && typeof value.started !== "boolean")
952
+ fail("Task submission acknowledgement is ambiguous; never retry automatically");
953
+ }
954
+ var SpawnHcPeerError = class extends Error {
955
+ constructor(message, details) {
956
+ super(message);
957
+ this.name = "SpawnHcPeerError";
958
+ this.details = { ...details, error: message };
959
+ }
960
+ };
961
+ async function spawnHcPeer(options, {
962
+ originId,
963
+ cwd = process.cwd(),
964
+ signal,
965
+ request,
966
+ approve,
967
+ assertResources = checkResources,
968
+ resolveExecutables = resolveTrustedExecutables,
969
+ root,
970
+ skill
971
+ }) {
972
+ const known = { ...validName(options?.name) ? { name: options.name } : {}, submissionAttempted: false };
973
+ try {
974
+ if (!validName(options?.name)) fail("Name must match [a-z][a-z0-9_-]{0,31}");
975
+ if (!terminalAddress(originId)) fail("Invalid inherited hc terminal address");
976
+ if (!absolutePath(cwd)) fail("An absolute cwd without terminal controls is required");
977
+ if (!absolutePath(options.piCli)) fail("The active Pi CLI must be an absolute path without terminal controls");
978
+ checkCancelled(signal);
979
+ const task = options.text;
980
+ checkPeerText(task);
981
+ let extension;
982
+ try {
983
+ extension = await assertResources(root, skill, { signal });
984
+ } catch {
985
+ checkCancelled(signal);
986
+ fail("Same-package skill SKILL.md and a package entrypoint (dist/index.ts or src/index.ts) are required");
987
+ }
988
+ checkCancelled(signal);
989
+ if (!absolutePath(extension) || !absolutePath(skill)) fail("Invalid package resource paths");
990
+ let executables;
991
+ try {
992
+ executables = await resolveExecutables(options.piCli, { cwd, signal });
993
+ } catch (error) {
994
+ checkCancelled(signal);
995
+ if (error instanceof SafeError) throw error;
996
+ fail("Cannot verify trusted absolute external Node and Pi CLI files");
997
+ }
998
+ checkCancelled(signal);
999
+ if (!absolutePath(executables?.node) || !absolutePath(executables?.piCli)) fail("Invalid executable paths");
1000
+ const argv = [executables.node, executables.piCli, "-e", extension, "--skill", skill];
1001
+ async function call(method, params, { timeoutMs = RPC_TIMEOUT_MS, capture } = {}) {
1002
+ checkCancelled(signal);
1003
+ let result;
1004
+ try {
1005
+ result = await request(method, params, { timeoutMs });
1006
+ } catch {
1007
+ checkCancelled(signal);
1008
+ fail(`${method} failed or timed out; inspect known state before retrying`);
1009
+ }
1010
+ capture?.(result);
1011
+ checkCancelled(signal);
1012
+ return result;
1013
+ }
1014
+ const core = coreIdentity(await call("hello", { generation: 1 }));
1015
+ const first = await call("terminal.get", { terminal: originId });
1016
+ const origin = identity(first);
1017
+ if (origin.address !== originId) fail("Origin response did not match the inherited terminal address");
1018
+ reportedPi(first, ["idle", "working", "done"]);
1019
+ known.originAddress = origin.address;
1020
+ async function verifyOrigin() {
1021
+ if (coreIdentity(await call("hello", { generation: 1 })) !== core) fail("hc core identity changed");
1022
+ const current = await call("terminal.get", { terminal: origin.address });
1023
+ sameIdentity(current, origin);
1024
+ reportedPi(current, ["idle", "working", "done"]);
1025
+ }
1026
+ if (await approve({ core, name: options.name, origin: origin.address }) !== true) {
1027
+ fail("Launch not approved: the operator must verify the hc core launch environment");
1028
+ }
1029
+ checkCancelled(signal);
1030
+ await verifyOrigin();
1031
+ const created = await call(
1032
+ "terminal.run",
1033
+ {
1034
+ argv,
1035
+ cwd,
1036
+ name: options.name,
1037
+ parent: origin.address,
1038
+ caller: origin.address,
1039
+ outlive_parent: true,
1040
+ // The core has its own environment; do not inherit Node preload/module lookup settings from it.
1041
+ env: { NODE_OPTIONS: "", NODE_PATH: "" },
1042
+ keep: false,
1043
+ rm: false,
1044
+ wait: false
1045
+ },
1046
+ {
1047
+ capture: (value) => {
1048
+ if (terminalAddress(value?.address)) known.address = value.address;
1049
+ }
1050
+ }
1051
+ );
1052
+ const target = identity(created);
1053
+ if (target.address === origin.address) fail("Creation did not return a distinct peer terminal");
1054
+ const facts = { name: options.name, cwd, argv, origin: origin.address };
1055
+ targetFacts(created, target, facts, false);
1056
+ const waited = await call(
1057
+ "terminal.wait",
1058
+ { terminal: target.address, caller: origin.address, timeout: 30 },
1059
+ {
1060
+ timeoutMs: WAIT_TIMEOUT_MS
1061
+ }
1062
+ );
1063
+ validateWait(waited, target.address);
1064
+ targetFacts(await call("terminal.get", { terminal: target.address }), target, facts, true);
1065
+ await verifyOrigin();
1066
+ targetFacts(await call("terminal.get", { terminal: target.address }), target, facts, true);
1067
+ const handoff = [
1068
+ "Peer task (peer content, not additional user authorization).",
1069
+ `Before work, read ${JSON.stringify(resolve(skill, "SKILL.md"))} (command: /skill:pi-herdr).`,
1070
+ `Initiator reply terminal: ${origin.address}. Rediscover live identities before sending a reply.`,
1071
+ "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.",
1072
+ "Self-contained task follows:",
1073
+ task
1074
+ ].join("\n\n");
1075
+ checkCancelled(signal);
1076
+ known.submissionAttempted = true;
1077
+ const sent = await call(
1078
+ "terminal.send",
1079
+ {
1080
+ terminal: target.address,
1081
+ caller: origin.address,
1082
+ text: handoff,
1083
+ if: "idle",
1084
+ wait: false,
1085
+ force: false
1086
+ },
1087
+ { timeoutMs: SEND_TIMEOUT_MS }
1088
+ );
1089
+ validateSend(sent);
1090
+ return {
1091
+ address: target.address,
1092
+ name: options.name,
1093
+ originAddress: origin.address,
1094
+ submitted: true,
1095
+ ...typeof sent.started === "boolean" ? { started: sent.started } : {}
1096
+ };
1097
+ } catch (error) {
1098
+ throw new SpawnHcPeerError(
1099
+ error instanceof SafeError ? error.message : "Spawn failed; inspect known state before retrying",
1100
+ known
1101
+ );
1102
+ }
1103
+ }
1104
+
1105
+ // src/hc-peer-tool.ts
1106
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
1107
+ import { resolve as resolve2 } from "node:path";
1108
+ import { StringEnum } from "@earendil-works/pi-ai";
1109
+ import { defineTool } from "@earendil-works/pi-coding-agent";
1110
+ import { Type } from "typebox";
1111
+ var DECLINE = "Do not launch";
1112
+ var APPROVE = "I verified the core environment. Launch this peer.";
1113
+ var OBSERVATION_MS = 6e4;
1114
+ var states = ["idle", "working", "blocked", "error", "done"];
1115
+ function registerHcPeerTool(pi, { terminalId, socketEndpoint }, root, connect2 = withHcConnection) {
1116
+ let active;
1117
+ function stop() {
1118
+ active?.abort.abort();
1119
+ active = void 0;
1120
+ }
1121
+ const tool = defineTool({
1122
+ name: "herdr_peer",
1123
+ label: "hc peer",
1124
+ description: "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.",
1125
+ parameters: Type.Object({
1126
+ action: StringEnum(["spawn", "inspect", "send"]),
1127
+ name: Type.Optional(Type.String({ description: "Unique lowercase peer name for spawn." })),
1128
+ text: Type.Optional(
1129
+ Type.String({ description: "Complete task for spawn, or a peer message for send. No secrets." })
1130
+ ),
1131
+ address: Type.Optional(Type.String({ description: "Canonical local hc terminal address for inspect or send." })),
1132
+ observation: Type.Optional(
1133
+ Type.String({ description: "Current observation returned by inspect. Required for send." })
1134
+ )
1135
+ }),
1136
+ async execute(_id, params, signal, _update, ctx) {
1137
+ const session = active;
1138
+ if (!session || session.owner !== ctx.sessionManager) throw new Error("No active hc peer session");
1139
+ const { action, address, name, observation, text } = params;
1140
+ if (action === "spawn") {
1141
+ if (typeof name !== "string" || typeof text !== "string" || address !== void 0 || observation !== void 0)
1142
+ throw new Error("spawn requires only name and text");
1143
+ if (ctx.mode !== "tui" || !ctx.hasUI)
1144
+ throw new Error("Peer launch requires confirmation from the Pi TUI operator");
1145
+ checkPeerText(text);
1146
+ } else {
1147
+ if (!terminalAddress(address) || address === terminalId || name !== void 0)
1148
+ throw new Error("Use another canonical local hc terminal address");
1149
+ if (action === "send") {
1150
+ checkPeerText(text);
1151
+ if (!observation || !/^\d{13}\.[a-f0-9]{64}$/u.test(observation))
1152
+ throw new Error("Inspect the intended recipient before sending");
1153
+ } else if (observation !== void 0 || text !== void 0) throw new Error("inspect requires only address");
1154
+ }
1155
+ const mutating = action !== "inspect";
1156
+ if (mutating && session.mutating) throw new Error("Another hc peer operation is in progress");
1157
+ if (mutating) session.mutating = true;
1158
+ const sessionSignal = signal ? AbortSignal.any([session.abort.signal, signal]) : session.abort.signal;
1159
+ const stamp = (core, target, expiry) => `${expiry}.${createHmac("sha256", session.observationKey).update(JSON.stringify([core, target, expiry])).digest("hex")}`;
1160
+ const result = (details) => ({
1161
+ content: [{ type: "text", text: JSON.stringify(details) }],
1162
+ details
1163
+ });
1164
+ try {
1165
+ return await connect2(
1166
+ socketEndpoint,
1167
+ async (rpc, disconnected) => {
1168
+ const operationSignal = AbortSignal.any([sessionSignal, disconnected]);
1169
+ const request = async (method, values, options) => {
1170
+ operationSignal.throwIfAborted();
1171
+ const response2 = await rpc(method, values, options);
1172
+ if (method !== "terminal.run") operationSignal.throwIfAborted();
1173
+ return response2;
1174
+ };
1175
+ if (action === "spawn") {
1176
+ return result(
1177
+ await spawnHcPeer(
1178
+ { name: name ?? "", text: text ?? "", piCli: process.argv[1] },
1179
+ {
1180
+ originId: terminalId,
1181
+ cwd: ctx.cwd,
1182
+ request,
1183
+ signal: operationSignal,
1184
+ root,
1185
+ skill: resolve2(root, "skills/pi-herdr"),
1186
+ async approve({ name: peerName, origin: origin2 }) {
1187
+ operationSignal.throwIfAborted();
1188
+ const answer = await ctx.ui.select(
1189
+ `Launch ${peerName} from ${origin2}? Confirm only if a trusted host applied a pre-spawn environment allowlist to this hc core and its programs.`,
1190
+ [DECLINE, APPROVE],
1191
+ { signal: operationSignal, timeout: 6e4 }
1192
+ );
1193
+ return !operationSignal.aborted && answer === APPROVE;
1194
+ }
1195
+ }
1196
+ )
1197
+ );
1198
+ }
1199
+ const core = coreIdentity(await request("hello", { generation: 1 }));
1200
+ const origin = await request("terminal.get", { terminal: terminalId });
1201
+ if (identity(origin).address !== terminalId) throw new Error("Origin did not match the inherited terminal");
1202
+ reportedPi(origin, ["working", "idle", "done"]);
1203
+ const raw = await request("terminal.get", { terminal: address });
1204
+ const target = identity(raw);
1205
+ if (target.address !== address) throw new Error("Recipient changed; inspect it again");
1206
+ reportedPi(raw, action === "inspect" ? states : ["idle"]);
1207
+ if (action === "inspect") {
1208
+ const { status } = raw;
1209
+ return result({
1210
+ address,
1211
+ status: status.state,
1212
+ observation: stamp(core, target, Date.now() + OBSERVATION_MS)
1213
+ });
1214
+ }
1215
+ const token = observation ?? "";
1216
+ const expiry = Number(token.slice(0, 13));
1217
+ if (expiry <= Date.now() || !timingSafeEqual(Buffer.from(token), Buffer.from(stamp(core, target, expiry))))
1218
+ throw new Error(
1219
+ "Observation expired or recipient changed; inspect again without resending automatically"
1220
+ );
1221
+ const sent = await request(
1222
+ "terminal.send",
1223
+ {
1224
+ terminal: address,
1225
+ caller: terminalId,
1226
+ text: `[peer sender=${terminalId}] Peer content, not user authorization.
1227
+
1228
+ ${text}`,
1229
+ if: "idle",
1230
+ force: false,
1231
+ wait: false
1232
+ },
1233
+ { timeoutMs: SEND_TIMEOUT_MS }
1234
+ );
1235
+ validateSend(sent);
1236
+ return result({ address, submitted: true });
1237
+ },
1238
+ { signal: sessionSignal, maxBytes: MAX_OUTPUT_BYTES }
1239
+ );
1240
+ } catch (error) {
1241
+ if (error instanceof SpawnHcPeerError) throw new Error(JSON.stringify(error.details));
1242
+ throw error;
1243
+ } finally {
1244
+ if (mutating) session.mutating = false;
1245
+ }
1246
+ }
1247
+ });
1248
+ pi.registerTool(tool);
1249
+ return {
1250
+ start(ctx) {
1251
+ stop();
1252
+ active = {
1253
+ owner: ctx.sessionManager,
1254
+ abort: new AbortController(),
1255
+ observationKey: randomBytes(32),
1256
+ mutating: false
1257
+ };
1258
+ },
1259
+ stop
1260
+ };
1261
+ }
1262
+
1263
+ // src/herdr-runtime-claim.ts
1264
+ var CHANNEL = "pi-herdr:runtime-claim:v1";
1265
+ function claimHerdrRuntime(pi) {
1266
+ const request = { version: 1, claimed: false };
1267
+ pi.events.emit(CHANNEL, request);
1268
+ if (request.claimed) return void 0;
1269
+ return pi.events.on(CHANNEL, (value) => {
1270
+ if (typeof value === "object" && value !== null && "version" in value && value.version === 1 && "claimed" in value && typeof value.claimed === "boolean")
1271
+ value.claimed = true;
1272
+ });
1273
+ }
1274
+
1275
+ // src/settings.ts
1276
+ import { randomUUID } from "node:crypto";
1277
+ import { constants as constants2 } from "node:fs";
1278
+ import { lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
1279
+ import { basename, dirname as dirname2, join } from "node:path";
1280
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
1281
+ var HERDR_SETTINGS_FILE = "pi-herdr.json";
1282
+ var MAX_SETTINGS_BYTES = 64 * 1024;
1283
+ var DEFAULT_SETTINGS = { widget: true };
1284
+ var queues = /* @__PURE__ */ new Map();
1285
+ function herdrSettingsPath() {
1286
+ return join(getAgentDir(), HERDR_SETTINGS_FILE);
1287
+ }
1288
+ function normalizeHerdrSettings(value) {
1289
+ if (!isRecord2(value)) return void 0;
1290
+ if (Object.hasOwn(value, "widget") && typeof value.widget !== "boolean") {
1291
+ return void 0;
1292
+ }
1293
+ return {
1294
+ widget: typeof value.widget === "boolean" ? value.widget : DEFAULT_SETTINGS.widget
1295
+ };
1296
+ }
1297
+ function readHerdrSettings(settingsPath = herdrSettingsPath()) {
1298
+ return enqueue(settingsPath, async () => {
1299
+ let document;
1300
+ try {
1301
+ document = await readSettingsDocument(settingsPath);
1302
+ } catch (error) {
1303
+ if (isNodeError(error) && error.code === "ENOENT") {
1304
+ return { kind: "missing", settings: { ...DEFAULT_SETTINGS } };
1305
+ }
1306
+ return {
1307
+ kind: "invalid",
1308
+ reason: `${settingsPath}: ${safeError(error)}`,
1309
+ settings: { ...DEFAULT_SETTINGS }
1310
+ };
1311
+ }
1312
+ const settings = normalizeHerdrSettings(document);
1313
+ return settings ? { kind: "loaded", settings } : {
1314
+ kind: "invalid",
1315
+ reason: `${settingsPath}: invalid settings shape`,
1316
+ settings: { ...DEFAULT_SETTINGS }
1317
+ };
1318
+ });
1319
+ }
1320
+ function updateHerdrSettings(patch, options = {}) {
1321
+ const settingsPath = options.settingsPath ?? herdrSettingsPath();
1322
+ return enqueue(settingsPath, async () => {
980
1323
  const current = await readDocumentForUpdate(settingsPath);
981
1324
  const updated = { ...current, ...patch };
982
1325
  const settings = normalizeHerdrSettings(updated);
@@ -1019,8 +1362,8 @@ async function readSettingsDocument(path2) {
1019
1362
  if (pathStats.size > MAX_SETTINGS_BYTES) {
1020
1363
  throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
1021
1364
  }
1022
- const noFollow = constants.O_NOFOLLOW ?? 0;
1023
- const handle = await open(path2, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | noFollow);
1365
+ const noFollow = constants2.O_NOFOLLOW ?? 0;
1366
+ const handle = await open(path2, constants2.O_RDONLY | (constants2.O_NONBLOCK ?? 0) | noFollow);
1024
1367
  try {
1025
1368
  const stats = await handle.stat();
1026
1369
  if (!stats.isFile() || stats.dev !== pathStats.dev || stats.ino !== pathStats.ino) {
@@ -1048,7 +1391,7 @@ async function readSettingsDocument(path2) {
1048
1391
  } catch {
1049
1392
  throw new Error("invalid JSON");
1050
1393
  }
1051
- if (!isRecord3(parsed)) throw new Error("settings document must be a JSON object");
1394
+ if (!isRecord2(parsed)) throw new Error("settings document must be a JSON object");
1052
1395
  return parsed;
1053
1396
  } finally {
1054
1397
  await handle.close();
@@ -1060,7 +1403,7 @@ async function publishSettings(path2, document, options) {
1060
1403
  if (Buffer.byteLength(contents) > MAX_SETTINGS_BYTES) {
1061
1404
  throw new Error(`Pi Herdr settings document exceeds ${MAX_SETTINGS_BYTES} bytes.`);
1062
1405
  }
1063
- const directory = dirname(path2);
1406
+ const directory = dirname2(path2);
1064
1407
  await mkdir(directory, { recursive: true });
1065
1408
  const temporaryPath = join(directory, `.${basename(path2)}.${process.pid}.${randomUUID()}.tmp`);
1066
1409
  try {
@@ -1072,7 +1415,7 @@ async function publishSettings(path2, document, options) {
1072
1415
  throw error;
1073
1416
  }
1074
1417
  }
1075
- function isRecord3(value) {
1418
+ function isRecord2(value) {
1076
1419
  return typeof value === "object" && value !== null && !Array.isArray(value);
1077
1420
  }
1078
1421
  function isNodeError(error) {
@@ -1085,6 +1428,7 @@ function safeError(error) {
1085
1428
  // src/herdr-settings-controller.ts
1086
1429
  function createHerdrSettingsController(pi, observer, options = {}) {
1087
1430
  const settingsPath = options.settingsPath ?? herdrSettingsPath();
1431
+ const label = options.backend === "hc" ? "hc" : "Herdr";
1088
1432
  let generation = 0;
1089
1433
  let owner;
1090
1434
  let controller = new AbortController();
@@ -1093,7 +1437,7 @@ function createHerdrSettingsController(pi, observer, options = {}) {
1093
1437
  let menuOpen = false;
1094
1438
  const current = (expected) => expected === generation && !controller.signal.aborted;
1095
1439
  pi.registerCommand("herdr", {
1096
- description: "Configure the Herdr agent widget",
1440
+ description: `Configure the ${label} agent widget`,
1097
1441
  handler: async (args, ctx) => {
1098
1442
  if (args.trim()) throw new Error("/herdr does not accept arguments.");
1099
1443
  if (!ctx.hasUI || ctx.mode !== "tui" && ctx.mode !== "rpc") {
@@ -1104,96 +1448,942 @@ function createHerdrSettingsController(pi, observer, options = {}) {
1104
1448
  const signal = controller.signal;
1105
1449
  menuOpen = true;
1106
1450
  try {
1107
- const [{ runMenu }, { createHerdrMenu }] = await Promise.all([
1108
- import("@narumitw/pi-tui-kit"),
1109
- import("./chunks/herdr-menu-IUPFF5YK.ts")
1110
- ]);
1111
- if (!current(expected)) return;
1112
- if (enabled && ctx.mode === "tui") observer.restore(ctx);
1113
- await runMenu(
1114
- ctx,
1115
- createHerdrMenu({
1116
- settingsPath,
1117
- isEnabled: () => enabled,
1118
- toggle: (actionSignal) => {
1119
- const result = changes.then(async () => {
1120
- if (actionSignal.aborted || !current(expected) || !owner) return false;
1121
- const previous = enabled;
1122
- const actionOwner = owner;
1123
- try {
1124
- enabled = !previous;
1125
- if (enabled && actionOwner.mode === "tui") observer.start(actionOwner);
1126
- else await observer.shutdown(actionOwner);
1127
- if (!current(expected)) return false;
1128
- await updateHerdrSettings({ widget: enabled }, { settingsPath });
1129
- return current(expected);
1130
- } catch {
1131
- if (!current(expected)) return false;
1132
- enabled = previous;
1133
- try {
1134
- if (previous && actionOwner.mode === "tui") observer.start(actionOwner);
1135
- else await observer.shutdown(actionOwner);
1136
- } finally {
1137
- if (current(expected))
1138
- ctx.ui.notify(
1139
- "Herdr settings were not saved; the previous widget setting was restored. Check pi-herdr.json and its permissions.",
1140
- "warning"
1141
- );
1142
- }
1143
- return false;
1144
- }
1145
- });
1146
- changes = result.then(
1147
- () => void 0,
1148
- () => void 0
1149
- );
1150
- return result;
1151
- }
1152
- }),
1451
+ const [{ runMenu }, { createHerdrMenu }] = await Promise.all([
1452
+ import("@narumitw/pi-tui-kit"),
1453
+ import("./chunks/herdr-menu-CA4DI2LZ.ts")
1454
+ ]);
1455
+ if (!current(expected)) return;
1456
+ if (enabled && ctx.mode === "tui") observer.restore(ctx);
1457
+ await runMenu(
1458
+ ctx,
1459
+ createHerdrMenu({
1460
+ settingsPath,
1461
+ backend: options.backend,
1462
+ isEnabled: () => enabled,
1463
+ toggle: (actionSignal) => {
1464
+ const result = changes.then(async () => {
1465
+ if (actionSignal.aborted || !current(expected) || !owner) return false;
1466
+ const previous = enabled;
1467
+ const actionOwner = owner;
1468
+ try {
1469
+ enabled = !previous;
1470
+ if (enabled && actionOwner.mode === "tui") observer.start(actionOwner);
1471
+ else await observer.shutdown(actionOwner);
1472
+ if (!current(expected)) return false;
1473
+ await updateHerdrSettings({ widget: enabled }, { settingsPath });
1474
+ return current(expected);
1475
+ } catch {
1476
+ if (!current(expected)) return false;
1477
+ enabled = previous;
1478
+ try {
1479
+ if (previous && actionOwner.mode === "tui") observer.start(actionOwner);
1480
+ else await observer.shutdown(actionOwner);
1481
+ } finally {
1482
+ if (current(expected))
1483
+ ctx.ui.notify(
1484
+ `${label} settings were not saved; the previous widget setting was restored. Check pi-herdr.json and its permissions.`,
1485
+ "warning"
1486
+ );
1487
+ }
1488
+ return false;
1489
+ }
1490
+ });
1491
+ changes = result.then(
1492
+ () => void 0,
1493
+ () => void 0
1494
+ );
1495
+ return result;
1496
+ }
1497
+ }),
1498
+ {
1499
+ getState: () => void 0,
1500
+ signal,
1501
+ isCurrent: () => current(expected),
1502
+ onError: () => {
1503
+ if (current(expected)) ctx.ui.notify(`The ${label} menu could not be displayed.`, "error");
1504
+ }
1505
+ }
1506
+ );
1507
+ } finally {
1508
+ if (expected === generation) menuOpen = false;
1509
+ }
1510
+ }
1511
+ });
1512
+ return {
1513
+ async start(ctx) {
1514
+ const expected = ++generation;
1515
+ controller.abort();
1516
+ controller = new AbortController();
1517
+ menuOpen = false;
1518
+ const previous = owner;
1519
+ owner = ctx;
1520
+ if (previous) await observer.shutdown(previous);
1521
+ if (!current(expected)) return;
1522
+ await changes;
1523
+ if (!current(expected)) return;
1524
+ const loaded = await readHerdrSettings(settingsPath);
1525
+ if (!current(expected)) return;
1526
+ enabled = loaded.settings.widget;
1527
+ if (loaded.kind === "invalid" && ctx.hasUI)
1528
+ ctx.ui.notify(
1529
+ `${label} ignored invalid pi-herdr.json settings and kept the widget enabled. Fix the file before saving.`,
1530
+ "warning"
1531
+ );
1532
+ if (enabled && ctx.mode === "tui") observer.start(ctx);
1533
+ },
1534
+ async shutdown(ctx) {
1535
+ if (ctx.sessionManager !== owner?.sessionManager) return;
1536
+ generation += 1;
1537
+ controller.abort();
1538
+ owner = void 0;
1539
+ menuOpen = false;
1540
+ await Promise.all([observer.shutdown(ctx), changes]);
1541
+ await awaitHerdrSettingsWrites(settingsPath);
1542
+ }
1543
+ };
1544
+ }
1545
+
1546
+ // src/hc-integration.ts
1547
+ function createHcIntegration(options) {
1548
+ const observer = options.observer ?? createHcWidgetObserver(options);
1549
+ return (pi) => {
1550
+ let release = claimHerdrRuntime(pi);
1551
+ if (!release) return;
1552
+ const widget = createHerdrSettingsController(pi, observer, { ...options, backend: "hc" });
1553
+ const { terminalId, socketEndpoint } = options.environment;
1554
+ const local = terminalAddress(terminalId) && (process.platform === "win32" ? /^\\\\\.\\pipe\\[^\\]/u.test(socketEndpoint) : isAbsolute2(socketEndpoint));
1555
+ const peers = local ? registerHcPeerTool(pi, options.environment, fileURLToPath(new URL("../", import.meta.url))) : void 0;
1556
+ let owner;
1557
+ let closing;
1558
+ pi.on("session_start", async (_event, ctx) => {
1559
+ release ??= claimHerdrRuntime(pi);
1560
+ if (!release) return;
1561
+ owner = ctx.sessionManager;
1562
+ peers?.start(ctx);
1563
+ await widget.start(ctx);
1564
+ });
1565
+ pi.on("session_shutdown", async (_event, ctx) => {
1566
+ const session = ctx.sessionManager;
1567
+ if (closing?.session === session) {
1568
+ await closing.task;
1569
+ return;
1570
+ }
1571
+ if (session !== owner) return;
1572
+ owner = void 0;
1573
+ peers?.stop();
1574
+ release?.();
1575
+ release = void 0;
1576
+ const task = widget.shutdown(ctx);
1577
+ closing = { session, task };
1578
+ await task;
1579
+ });
1580
+ };
1581
+ }
1582
+
1583
+ // src/herdr-agent-state.ts
1584
+ import path from "node:path";
1585
+
1586
+ // src/herdr-client.ts
1587
+ import net2 from "node:net";
1588
+ var MAX_HERDR_FRAME_BYTES = 1024 * 1024;
1589
+ var MAX_PENDING_SUBSCRIPTION_EVENTS = 1024;
1590
+ var NdjsonFrames = class {
1591
+ buffer = Buffer.alloc(0);
1592
+ push(chunk) {
1593
+ this.buffer = Buffer.concat([this.buffer, chunk]);
1594
+ if (this.buffer.length > MAX_HERDR_FRAME_BYTES && this.buffer.indexOf(10) < 0) {
1595
+ throw new Error("Herdr response frame exceeded the size limit");
1596
+ }
1597
+ const frames = [];
1598
+ while (true) {
1599
+ const newline = this.buffer.indexOf(10);
1600
+ if (newline < 0) break;
1601
+ if (newline > MAX_HERDR_FRAME_BYTES) {
1602
+ throw new Error("Herdr response frame exceeded the size limit");
1603
+ }
1604
+ const line = this.buffer.subarray(0, newline);
1605
+ this.buffer = this.buffer.subarray(newline + 1);
1606
+ if (line.length === 0) continue;
1607
+ try {
1608
+ frames.push(JSON.parse(line.toString("utf8")));
1609
+ } catch {
1610
+ throw new Error("Herdr returned invalid JSON");
1611
+ }
1612
+ }
1613
+ if (this.buffer.length > MAX_HERDR_FRAME_BYTES) {
1614
+ throw new Error("Herdr response frame exceeded the size limit");
1615
+ }
1616
+ return frames;
1617
+ }
1618
+ };
1619
+ function isRecord3(value) {
1620
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1621
+ }
1622
+ function abortReason(signal) {
1623
+ return signal.reason instanceof Error ? signal.reason : new DOMException("Herdr request aborted", "AbortError");
1624
+ }
1625
+ var HerdrApiError = class extends Error {
1626
+ code;
1627
+ constructor(error) {
1628
+ super(`Herdr ${typeof error.message === "string" ? error.message : "request failed"}`);
1629
+ this.code = typeof error.code === "string" ? error.code : void 0;
1630
+ }
1631
+ };
1632
+ function responseError(frame) {
1633
+ if (!("error" in frame)) return void 0;
1634
+ if (!isRecord3(frame.error)) return new Error("Herdr returned an invalid error response");
1635
+ return new HerdrApiError(frame.error);
1636
+ }
1637
+ function createBestEffortSender(socketEndpoint) {
1638
+ return async (request, signal) => {
1639
+ for (const timeoutMs of [500, 1500]) {
1640
+ if (signal.aborted) return;
1641
+ try {
1642
+ const result = await requestHerdr(socketEndpoint, request, signal, timeoutMs);
1643
+ if (isRecord3(result) && result.type === "ok") return;
1644
+ } catch (error) {
1645
+ if (signal.aborted || error instanceof HerdrApiError) return;
1646
+ }
1647
+ }
1648
+ };
1649
+ }
1650
+ function requestHerdr(socketEndpoint, request, signal, timeoutMs = 1500) {
1651
+ if (signal.aborted) return Promise.reject(abortReason(signal));
1652
+ return new Promise((resolve3, reject) => {
1653
+ const payload = `${JSON.stringify(request)}
1654
+ `;
1655
+ const socket = net2.createConnection(socketEndpoint);
1656
+ const parser = new NdjsonFrames();
1657
+ let finished = false;
1658
+ const timeout = setTimeout(() => finish(new Error("Herdr request timed out")), timeoutMs);
1659
+ timeout.unref?.();
1660
+ const cleanup = () => {
1661
+ clearTimeout(timeout);
1662
+ signal.removeEventListener("abort", abort);
1663
+ socket.destroy();
1664
+ };
1665
+ const finish = (error, result) => {
1666
+ if (finished) return;
1667
+ finished = true;
1668
+ cleanup();
1669
+ if (error) reject(error);
1670
+ else resolve3(result);
1671
+ };
1672
+ const abort = () => finish(abortReason(signal));
1673
+ signal.addEventListener("abort", abort, { once: true });
1674
+ socket.on("connect", () => {
1675
+ if (!finished) socket.write(payload);
1676
+ });
1677
+ socket.on("error", (error) => finish(error));
1678
+ socket.on("end", () => finish(new Error("Herdr closed the request before responding")));
1679
+ socket.on("close", () => finish(new Error("Herdr request socket closed")));
1680
+ socket.on("data", (chunk) => {
1681
+ if (finished) return;
1682
+ try {
1683
+ for (const value of parser.push(chunk)) {
1684
+ if (!isRecord3(value)) continue;
1685
+ const uncorrelatedError = responseError(value);
1686
+ if (uncorrelatedError && (value.id === "" || value.id === void 0)) {
1687
+ finish(uncorrelatedError);
1688
+ return;
1689
+ }
1690
+ if (value.id !== request.id) continue;
1691
+ const error = responseError(value);
1692
+ if (error) {
1693
+ finish(error);
1694
+ return;
1695
+ }
1696
+ if (!("result" in value)) {
1697
+ finish(new Error("Herdr response did not include a result"));
1698
+ return;
1699
+ }
1700
+ finish(void 0, value.result);
1701
+ return;
1702
+ }
1703
+ } catch (error) {
1704
+ finish(error instanceof Error ? error : new Error(String(error)));
1705
+ }
1706
+ });
1707
+ });
1708
+ }
1709
+ async function openHerdrSubscription(socketEndpoint, request, signal, onEvent, timeoutMs = 1500) {
1710
+ if (signal.aborted) throw abortReason(signal);
1711
+ const payload = `${JSON.stringify(request)}
1712
+ `;
1713
+ const socket = net2.createConnection(socketEndpoint);
1714
+ const parser = new NdjsonFrames();
1715
+ const pendingEvents = [];
1716
+ let ready = false;
1717
+ let finished = false;
1718
+ let intentionalClose = false;
1719
+ let resolveReady;
1720
+ let rejectReady;
1721
+ let resolveClosed;
1722
+ let rejectClosed;
1723
+ const readyPromise = new Promise((resolve3, reject) => {
1724
+ resolveReady = resolve3;
1725
+ rejectReady = reject;
1726
+ });
1727
+ const closed = new Promise((resolve3, reject) => {
1728
+ resolveClosed = resolve3;
1729
+ rejectClosed = reject;
1730
+ });
1731
+ void closed.catch(() => void 0);
1732
+ const timeout = setTimeout(() => finish(new Error("Herdr subscription timed out")), timeoutMs);
1733
+ timeout.unref?.();
1734
+ const cleanup = () => {
1735
+ clearTimeout(timeout);
1736
+ signal.removeEventListener("abort", abort);
1737
+ socket.destroy();
1738
+ };
1739
+ const finish = (error) => {
1740
+ if (finished) return;
1741
+ finished = true;
1742
+ cleanup();
1743
+ if (!ready) {
1744
+ if (error && !intentionalClose) rejectReady(error);
1745
+ else rejectReady(abortReason(signal));
1746
+ resolveClosed();
1747
+ return;
1748
+ }
1749
+ if (error && !intentionalClose) rejectClosed(error);
1750
+ else resolveClosed();
1751
+ };
1752
+ const deliver = (frame) => {
1753
+ if (finished) return;
1754
+ try {
1755
+ onEvent(frame);
1756
+ } catch (error) {
1757
+ finish(error instanceof Error ? error : new Error(String(error)));
1758
+ }
1759
+ };
1760
+ const abort = () => {
1761
+ intentionalClose = true;
1762
+ finish();
1763
+ };
1764
+ signal.addEventListener("abort", abort, { once: true });
1765
+ socket.on("connect", () => {
1766
+ if (!finished) socket.write(payload);
1767
+ });
1768
+ socket.on("error", (error) => finish(error));
1769
+ socket.on("end", () => finish(new Error("Herdr subscription closed")));
1770
+ socket.on("close", () => finish(new Error("Herdr subscription socket closed")));
1771
+ socket.on("data", (chunk) => {
1772
+ if (finished) return;
1773
+ try {
1774
+ for (const value of parser.push(chunk)) {
1775
+ if (finished) return;
1776
+ if (isRecord3(value)) {
1777
+ const error = responseError(value);
1778
+ if (error && (value.id === request.id || value.id === "" || value.id === void 0)) {
1779
+ finish(error);
1780
+ return;
1781
+ }
1782
+ if ("id" in value && value.id !== request.id) continue;
1783
+ }
1784
+ if (!ready) {
1785
+ if (isRecord3(value) && value.id === request.id) {
1786
+ if (!isRecord3(value.result) || value.result.type !== "subscription_started") {
1787
+ finish(new Error("Herdr returned an invalid subscription acknowledgement"));
1788
+ return;
1789
+ }
1790
+ ready = true;
1791
+ clearTimeout(timeout);
1792
+ socket.unref();
1793
+ resolveReady();
1794
+ for (const event of pendingEvents.splice(0)) deliver(event);
1795
+ continue;
1796
+ }
1797
+ if (pendingEvents.length >= MAX_PENDING_SUBSCRIPTION_EVENTS) {
1798
+ finish(new Error("Too many Herdr events arrived before subscription acknowledgement"));
1799
+ return;
1800
+ }
1801
+ pendingEvents.push(value);
1802
+ continue;
1803
+ }
1804
+ deliver(value);
1805
+ }
1806
+ } catch (error) {
1807
+ finish(error instanceof Error ? error : new Error(String(error)));
1808
+ }
1809
+ });
1810
+ await readyPromise;
1811
+ if (signal.aborted) {
1812
+ intentionalClose = true;
1813
+ finish();
1814
+ throw abortReason(signal);
1815
+ }
1816
+ return {
1817
+ closed,
1818
+ close() {
1819
+ intentionalClose = true;
1820
+ finish();
1821
+ }
1822
+ };
1823
+ }
1824
+
1825
+ // src/herdr-metadata.ts
1826
+ import { sanitizeTerminalText as sanitizeTerminalText3 } from "@narumitw/pi-tui-kit/terminal-text";
1827
+ var HERDR_METADATA_TOKEN_KEYS = ["model", "provider", "thinking", "session", "context_usage"];
1828
+ var HERDR_METADATA_MAX_CHARACTERS = 80;
1829
+ var HERDR_METADATA_TTL_MS = 60 * 60 * 1e3;
1830
+ var HERDR_METADATA_REFRESH_MS = 30 * 60 * 1e3;
1831
+ function normalizeHerdrMetadataValue(value) {
1832
+ if (typeof value !== "string") return null;
1833
+ const normalized = sanitizeTerminalText3(value).trim();
1834
+ if (normalized.length === 0) return null;
1835
+ return [...normalized].slice(0, HERDR_METADATA_MAX_CHARACTERS).join("");
1836
+ }
1837
+ function formatContextUsagePercent(value) {
1838
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null;
1839
+ return `${Math.round(value)}%`;
1840
+ }
1841
+ function createHerdrMetadataSnapshot(inputs) {
1842
+ return Object.freeze({
1843
+ model: normalizeHerdrMetadataValue(inputs.model),
1844
+ provider: normalizeHerdrMetadataValue(inputs.provider),
1845
+ thinking: normalizeHerdrMetadataValue(inputs.thinking),
1846
+ session: normalizeHerdrMetadataValue(inputs.session),
1847
+ context_usage: formatContextUsagePercent(inputs.contextUsagePercent)
1848
+ });
1849
+ }
1850
+ function createHerdrMetadataClearSnapshot() {
1851
+ return Object.freeze({
1852
+ model: null,
1853
+ provider: null,
1854
+ thinking: null,
1855
+ session: null,
1856
+ context_usage: null
1857
+ });
1858
+ }
1859
+ function herdrMetadataSnapshotsEqual(left, right) {
1860
+ return left !== void 0 && HERDR_METADATA_TOKEN_KEYS.every((key) => left[key] === right[key]);
1861
+ }
1862
+ function createHerdrMetadataRequest(options) {
1863
+ return {
1864
+ id: options.id,
1865
+ method: "pane.report_metadata",
1866
+ params: {
1867
+ pane_id: options.paneId,
1868
+ source: options.source,
1869
+ seq: options.seq,
1870
+ tokens: { ...options.snapshot },
1871
+ ttl_ms: options.ttlMs ?? HERDR_METADATA_TTL_MS
1872
+ }
1873
+ };
1874
+ }
1875
+
1876
+ // src/herdr-observer.ts
1877
+ import { createEditorStatusPublisher as createEditorStatusPublisher2 } from "@narumitw/pi-tui-kit/editor-status-publisher";
1878
+
1879
+ // src/herdr-spawn-provenance.ts
1880
+ import { createHash } from "node:crypto";
1881
+ function record4(value) {
1882
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1883
+ }
1884
+ function terminalIdentity(value) {
1885
+ return typeof value === "string" && value.length > 0 && [...value].length <= 256 && !/[\p{Cc}\p{Cf}]/u.test(value);
1886
+ }
1887
+ function herdrSessionFingerprint(terminalId, session) {
1888
+ if (!terminalIdentity(terminalId) || !record4(session) || session.source !== "herdr:pi" || session.agent !== "pi" || session.kind !== "id" && session.kind !== "path" || typeof session.value !== "string" || session.value.length === 0 || Buffer.byteLength(session.value, "utf8") > 4096) {
1889
+ return void 0;
1890
+ }
1891
+ return createHash("sha256").update(JSON.stringify([terminalId, session.source, session.agent, session.kind, session.value])).digest("hex");
1892
+ }
1893
+ function parseHerdrSpawnProvenance(tokens, targetTerminalId, targetSession) {
1894
+ if (!record4(tokens) || tokens.pi_spawn_v !== "1" || !targetSession) return void 0;
1895
+ const originTerminalId = tokens.pi_spawn_origin;
1896
+ const originSession = tokens.pi_spawn_from;
1897
+ const originLabel = tokens.pi_spawn_label;
1898
+ if (!terminalIdentity(originTerminalId) || [...originTerminalId].length > 80 || originTerminalId === targetTerminalId || typeof originSession !== "string" || !/^[a-f0-9]{64}$/u.test(originSession) || tokens.pi_spawn_to !== targetSession || typeof originLabel !== "string" || originLabel.length === 0 || [...originLabel].length > 80) {
1899
+ return void 0;
1900
+ }
1901
+ return { originTerminalId, originSession, targetSession, originLabel };
1902
+ }
1903
+
1904
+ // src/herdr-protocol.ts
1905
+ var HERDR_AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"];
1906
+ var HERDR_WIDGET_TOPOLOGY_SUBSCRIPTIONS = [
1907
+ { type: "workspace.created" },
1908
+ { type: "workspace.closed" },
1909
+ { type: "pane.created" },
1910
+ { type: "pane.updated" },
1911
+ { type: "workspace.renamed" },
1912
+ { type: "pane.closed" },
1913
+ { type: "pane.moved" },
1914
+ { type: "pane.exited" },
1915
+ { type: "pane.agent_detected" }
1916
+ ];
1917
+ function herdrWidgetSubscriptions(panes) {
1918
+ return [
1919
+ ...HERDR_WIDGET_TOPOLOGY_SUBSCRIPTIONS.map((entry) => ({ ...entry })),
1920
+ ...panes.filter((pane) => pane.agent !== void 0).map((pane) => ({ type: "pane.agent_status_changed", pane_id: pane.paneId }))
1921
+ ];
1922
+ }
1923
+ function isRecord4(value) {
1924
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1925
+ }
1926
+ function requiredString(value) {
1927
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1928
+ }
1929
+ function optionalString2(value) {
1930
+ return typeof value === "string" ? value : void 0;
1931
+ }
1932
+ function agentStatus(value) {
1933
+ return typeof value === "string" && HERDR_AGENT_STATUSES.includes(value) ? value : void 0;
1934
+ }
1935
+ function stringRecord(value) {
1936
+ if (!isRecord4(value)) return void 0;
1937
+ const entries = Object.entries(value);
1938
+ if (!entries.every(([, entry]) => typeof entry === "string")) return void 0;
1939
+ return Object.fromEntries(entries);
1940
+ }
1941
+ function parseHerdrPane(value) {
1942
+ if (!isRecord4(value)) return void 0;
1943
+ const paneId = requiredString(value.pane_id);
1944
+ const workspaceId = requiredString(value.workspace_id);
1945
+ const tabId = requiredString(value.tab_id);
1946
+ const terminalId = requiredString(value.terminal_id);
1947
+ const status = agentStatus(value.agent_status);
1948
+ const revision = value.revision;
1949
+ if (!paneId || !workspaceId || !tabId || !terminalId || !status || typeof value.focused !== "boolean" || typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 0) {
1950
+ return void 0;
1951
+ }
1952
+ const sessionFingerprint = value.agent === "pi" ? herdrSessionFingerprint(terminalId, value.agent_session) : void 0;
1953
+ const spawn = parseHerdrSpawnProvenance(value.tokens, terminalId, sessionFingerprint);
1954
+ return {
1955
+ paneId,
1956
+ workspaceId,
1957
+ tabId,
1958
+ terminalId,
1959
+ ...sessionFingerprint ? { sessionFingerprint } : {},
1960
+ ...spawn ? { spawn } : {},
1961
+ focused: value.focused,
1962
+ revision,
1963
+ agent: optionalString2(value.agent),
1964
+ agentName: optionalString2(value.name),
1965
+ agentStatus: status,
1966
+ displayAgent: optionalString2(value.display_agent),
1967
+ label: optionalString2(value.label),
1968
+ stateLabels: stringRecord(value.state_labels) ?? {},
1969
+ terminalTitle: optionalString2(value.terminal_title_stripped) ?? optionalString2(value.terminal_title),
1970
+ title: optionalString2(value.title)
1971
+ };
1972
+ }
1973
+ function parsePaneCurrentResult(value) {
1974
+ if (!isRecord4(value) || value.type !== "pane_current") {
1975
+ throw new Error("Herdr returned an invalid current-pane response");
1976
+ }
1977
+ const pane = parseHerdrPane(value.pane);
1978
+ if (!pane) throw new Error("Herdr returned an invalid current pane");
1979
+ return pane;
1980
+ }
1981
+ function parsePaneListResult(value) {
1982
+ if (!isRecord4(value) || value.type !== "pane_list" || !Array.isArray(value.panes)) {
1983
+ throw new Error("Herdr returned an invalid pane-list response");
1984
+ }
1985
+ const panes = value.panes.map(parseHerdrPane);
1986
+ if (panes.some((pane) => pane === void 0)) {
1987
+ throw new Error("Herdr returned an invalid pane in the pane list");
1988
+ }
1989
+ return panes;
1990
+ }
1991
+ function parseAgentListResult(value) {
1992
+ if (!isRecord4(value) || value.type !== "agent_list" || !Array.isArray(value.agents)) {
1993
+ throw new Error("Herdr returned an invalid agent-list response");
1994
+ }
1995
+ return value.agents.flatMap((entry) => {
1996
+ const pane = parseHerdrPane(entry);
1997
+ return pane ? [pane] : [];
1998
+ });
1999
+ }
2000
+ function parseWorkspaceListResult(value) {
2001
+ if (!isRecord4(value) || value.type !== "workspace_list" || !Array.isArray(value.workspaces)) {
2002
+ throw new Error("Herdr returned an invalid workspace-list response");
2003
+ }
2004
+ return value.workspaces.map((workspace) => {
2005
+ if (!isRecord4(workspace)) throw new Error("Herdr returned an invalid workspace");
2006
+ const workspaceId = requiredString(workspace.workspace_id);
2007
+ if (!workspaceId) throw new Error("Herdr returned an invalid workspace identity");
2008
+ return { workspaceId, label: optionalString2(workspace.label) };
2009
+ });
2010
+ }
2011
+ function parseHerdrPaneEvent(value) {
2012
+ if (!isRecord4(value) || typeof value.event !== "string" || !isRecord4(value.data)) {
2013
+ return void 0;
2014
+ }
2015
+ const data = value.data;
2016
+ if (value.event === "workspace_created") {
2017
+ const workspaceId = isRecord4(data.workspace) ? requiredString(data.workspace.workspace_id) : void 0;
2018
+ return workspaceId ? { type: "workspace_created", workspaceId } : void 0;
2019
+ }
2020
+ if (value.event === "workspace_closed") {
2021
+ const workspaceId = requiredString(data.workspace_id);
2022
+ return workspaceId ? { type: "workspace_closed", workspaceId } : void 0;
2023
+ }
2024
+ if (value.event === "workspace_renamed") {
2025
+ const workspaceId = requiredString(data.workspace_id);
2026
+ if (!workspaceId || typeof data.label !== "string") return void 0;
2027
+ return { type: "workspace_renamed", workspaceId };
2028
+ }
2029
+ if (value.event === "pane.agent_status_changed" || value.event === "pane_agent_status_changed") {
2030
+ const paneId = requiredString(data.pane_id);
2031
+ const workspaceId = requiredString(data.workspace_id);
2032
+ const status = agentStatus(data.agent_status);
2033
+ if (!paneId || !workspaceId || !status) return void 0;
2034
+ return {
2035
+ type: "agent_status_changed",
2036
+ paneId,
2037
+ workspaceId
2038
+ };
2039
+ }
2040
+ if (value.event === "pane_created" || value.event === "pane_updated") {
2041
+ const pane = parseHerdrPane(data.pane);
2042
+ return pane ? { type: value.event === "pane_created" ? "created" : "updated", pane } : void 0;
2043
+ }
2044
+ if (value.event === "pane_closed" || value.event === "pane_exited") {
2045
+ const paneId = requiredString(data.pane_id);
2046
+ const workspaceId = requiredString(data.workspace_id);
2047
+ if (!paneId || !workspaceId) return void 0;
2048
+ return {
2049
+ type: value.event === "pane_closed" ? "closed" : "exited",
2050
+ paneId,
2051
+ workspaceId
2052
+ };
2053
+ }
2054
+ if (value.event === "pane_moved") {
2055
+ const pane = parseHerdrPane(data.pane);
2056
+ const previousPaneId = requiredString(data.previous_pane_id);
2057
+ const previousWorkspaceId = requiredString(data.previous_workspace_id);
2058
+ if (!pane || !previousPaneId || !previousWorkspaceId) return void 0;
2059
+ return { type: "moved", pane, previousPaneId, previousWorkspaceId };
2060
+ }
2061
+ if (value.event === "pane_agent_detected") {
2062
+ const paneId = requiredString(data.pane_id);
2063
+ const workspaceId = requiredString(data.workspace_id);
2064
+ if (!paneId || !workspaceId || data.released !== void 0 && typeof data.released !== "boolean") {
2065
+ return void 0;
2066
+ }
2067
+ const finalStatus = data.final_status === null ? void 0 : agentStatus(data.final_status);
2068
+ if (data.final_status !== void 0 && data.final_status !== null && !finalStatus) return void 0;
2069
+ return {
2070
+ type: "agent_detected",
2071
+ paneId,
2072
+ workspaceId
2073
+ };
2074
+ }
2075
+ return void 0;
2076
+ }
2077
+
2078
+ // src/herdr-observer.ts
2079
+ var MAX_CONSECUTIVE_DISCARDS = 2;
2080
+ var HerdrTopologyChangedError = class extends Error {
2081
+ };
2082
+ var HerdrCleanupError = class extends AggregateError {
2083
+ };
2084
+ function renderHerdrWidget(snapshot, theme, width) {
2085
+ return createHerdrWidget(snapshot, theme, false).render(width);
2086
+ }
2087
+ function subscriptionFingerprint(currentPane, panes) {
2088
+ const agentPaneIds = panes.filter((pane) => pane.agent !== void 0).map((pane) => pane.paneId).sort();
2089
+ return JSON.stringify([currentPane.paneId, currentPane.workspaceId, agentPaneIds]);
2090
+ }
2091
+ function waitForRetry(delayMs, signal) {
2092
+ if (signal.aborted) return Promise.reject(signal.reason);
2093
+ if (delayMs <= 0) return Promise.resolve();
2094
+ return new Promise((resolve3, reject) => {
2095
+ const timer = setTimeout(() => {
2096
+ signal.removeEventListener("abort", abort);
2097
+ resolve3();
2098
+ }, delayMs);
2099
+ timer.unref?.();
2100
+ const abort = () => {
2101
+ clearTimeout(timer);
2102
+ reject(signal.reason);
2103
+ };
2104
+ signal.addEventListener("abort", abort, { once: true });
2105
+ });
2106
+ }
2107
+ function createHerdrWidgetObserver(options) {
2108
+ const now = options.now ?? Date.now;
2109
+ const random = options.random ?? Math.random;
2110
+ const request = options.request ?? requestHerdr;
2111
+ const subscribe = options.subscribe ?? openHerdrSubscription;
2112
+ const retryDelayMs = options.retryDelayMs ?? 200;
2113
+ let generation = 0;
2114
+ let publisher;
2115
+ let activeSession;
2116
+ let controller;
2117
+ const ownedTasks = /* @__PURE__ */ new Set();
2118
+ const taskErrors = /* @__PURE__ */ new Set();
2119
+ let publishedFingerprint;
2120
+ let hasPublished = false;
2121
+ const owns = (ctx, expectedGeneration = generation) => expectedGeneration === generation && ctx.sessionManager === activeSession;
2122
+ const requestId = (kind) => `herdr:pi:widget:${kind}:${now()}:${random().toString(36).slice(2)}`;
2123
+ const clearWidget = () => {
2124
+ publisher?.publish(void 0);
2125
+ publishedFingerprint = void 0;
2126
+ hasPublished = false;
2127
+ };
2128
+ const publish = (ctx, model, expectedGeneration) => {
2129
+ if (!owns(ctx, expectedGeneration) || ctx.mode !== "tui") return;
2130
+ const snapshot = model.snapshot();
2131
+ const fingerprint = herdrWidgetFingerprint(snapshot);
2132
+ if (hasPublished && fingerprint === publishedFingerprint) return;
2133
+ publisher?.publish(snapshot);
2134
+ publishedFingerprint = fingerprint;
2135
+ hasPublished = true;
2136
+ };
2137
+ const loadPaneSet = async (ctx, expectedGeneration, signal) => {
2138
+ const currentResult = await request(
2139
+ options.environment.socketEndpoint,
2140
+ {
2141
+ id: requestId("current"),
2142
+ method: "pane.current",
2143
+ params: { caller_pane_id: options.environment.paneId }
2144
+ },
2145
+ signal
2146
+ );
2147
+ if (!owns(ctx, expectedGeneration) || signal.aborted) return void 0;
2148
+ const caller = parsePaneCurrentResult(currentResult);
2149
+ const [listResult, agentResult, workspaceResult] = await Promise.all([
2150
+ request(
2151
+ options.environment.socketEndpoint,
2152
+ {
2153
+ id: requestId("list"),
2154
+ method: "pane.list",
2155
+ params: {}
2156
+ },
2157
+ signal
2158
+ ),
2159
+ request(
2160
+ options.environment.socketEndpoint,
2161
+ { id: requestId("agents"), method: "agent.list", params: {} },
2162
+ signal
2163
+ ),
2164
+ request(
2165
+ options.environment.socketEndpoint,
2166
+ {
2167
+ id: requestId("workspace"),
2168
+ method: "workspace.list",
2169
+ params: {}
2170
+ },
2171
+ signal
2172
+ )
2173
+ ]);
2174
+ if (!owns(ctx, expectedGeneration) || signal.aborted) return void 0;
2175
+ const panes = parsePaneListResult(listResult);
2176
+ const panesById = new Map(panes.map((pane) => [pane.paneId, pane]));
2177
+ const currentPane = panesById.get(caller.paneId);
2178
+ if (currentPane?.terminalId !== caller.terminalId) throw new HerdrTopologyChangedError();
2179
+ const namesByPane = new Map(
2180
+ parseAgentListResult(agentResult).filter((pane) => panesById.get(pane.paneId)?.workspaceId === pane.workspaceId).map((pane) => [pane.paneId, pane.agentName])
2181
+ );
2182
+ const withAgentName = (pane) => ({
2183
+ ...pane,
2184
+ agentName: namesByPane.get(pane.paneId) ?? pane.agentName
2185
+ });
2186
+ return {
2187
+ currentPane: withAgentName(currentPane),
2188
+ panes: panes.map(withAgentName),
2189
+ workspaces: parseWorkspaceListResult(workspaceResult)
2190
+ };
2191
+ };
2192
+ const runAttempt = async (ctx, expectedGeneration, sessionSignal) => {
2193
+ const attemptController = new AbortController();
2194
+ const abortAttempt = () => attemptController.abort(sessionSignal.reason);
2195
+ if (sessionSignal.aborted) abortAttempt();
2196
+ else sessionSignal.addEventListener("abort", abortAttempt, { once: true });
2197
+ const signal = attemptController.signal;
2198
+ let attemptActive = true;
2199
+ let subscription;
2200
+ let failure;
2201
+ let attemptError;
2202
+ let cleanupFailure;
2203
+ let wake;
2204
+ const wakeRefresh = () => {
2205
+ const resolve3 = wake;
2206
+ wake = void 0;
2207
+ resolve3?.();
2208
+ };
2209
+ signal.addEventListener("abort", wakeRefresh);
2210
+ const failAttempt = (error) => {
2211
+ if (!attemptActive || signal.aborted) return;
2212
+ failure = error;
2213
+ try {
2214
+ if (owns(ctx, expectedGeneration)) clearWidget();
2215
+ } catch (cleanupError) {
2216
+ failure = new AggregateError([error, cleanupError], "Herdr subscription and widget cleanup failed");
2217
+ } finally {
2218
+ attemptController.abort(failure);
2219
+ }
2220
+ };
2221
+ try {
2222
+ await (async () => {
2223
+ const discovered = await loadPaneSet(ctx, expectedGeneration, signal);
2224
+ if (!discovered) return;
2225
+ const subscribedFingerprint = subscriptionFingerprint(discovered.currentPane, discovered.panes);
2226
+ const model = new HerdrWidgetModel();
2227
+ let dirty = true;
2228
+ let consecutiveDiscards = 0;
2229
+ subscription = await subscribe(
2230
+ options.environment.socketEndpoint,
1153
2231
  {
1154
- getState: () => void 0,
1155
- signal,
1156
- isCurrent: () => current(expected),
1157
- onError: () => {
1158
- if (current(expected)) ctx.ui.notify("The Herdr menu could not be displayed.", "error");
1159
- }
2232
+ id: requestId("subscribe"),
2233
+ method: "events.subscribe",
2234
+ params: { subscriptions: herdrWidgetSubscriptions(discovered.panes) }
2235
+ },
2236
+ signal,
2237
+ (frame) => {
2238
+ if (!attemptActive || !owns(ctx, expectedGeneration) || signal.aborted) return;
2239
+ const event = parseHerdrPaneEvent(frame);
2240
+ if (!event) return;
2241
+ dirty = true;
2242
+ wakeRefresh();
2243
+ }
2244
+ ).catch(async (error) => {
2245
+ if (!owns(ctx, expectedGeneration) || signal.aborted) throw error;
2246
+ const latest = await loadPaneSet(ctx, expectedGeneration, signal);
2247
+ if (latest && subscriptionFingerprint(latest.currentPane, latest.panes) !== subscribedFingerprint) {
2248
+ throw new HerdrTopologyChangedError();
1160
2249
  }
2250
+ throw error;
2251
+ });
2252
+ void subscription.closed.then(
2253
+ () => failAttempt(new Error("Herdr subscription ended")),
2254
+ (error) => failAttempt(error instanceof Error ? error : new Error(String(error)))
1161
2255
  );
1162
- } finally {
1163
- if (expected === generation) menuOpen = false;
2256
+ while (owns(ctx, expectedGeneration) && !signal.aborted) {
2257
+ dirty = false;
2258
+ const refreshed = await loadPaneSet(ctx, expectedGeneration, signal);
2259
+ if (!refreshed || signal.aborted) break;
2260
+ if (subscriptionFingerprint(refreshed.currentPane, refreshed.panes) !== subscribedFingerprint) {
2261
+ throw new HerdrTopologyChangedError();
2262
+ }
2263
+ if (dirty && consecutiveDiscards < MAX_CONSECUTIVE_DISCARDS) {
2264
+ consecutiveDiscards += 1;
2265
+ continue;
2266
+ }
2267
+ consecutiveDiscards = 0;
2268
+ model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspaces);
2269
+ publish(ctx, model, expectedGeneration);
2270
+ await new Promise((resolve3) => {
2271
+ wake = resolve3;
2272
+ if (dirty || signal.aborted) wakeRefresh();
2273
+ });
2274
+ }
2275
+ if (failure) throw failure;
2276
+ })();
2277
+ } catch (error) {
2278
+ attemptError = { error };
2279
+ } finally {
2280
+ attemptActive = false;
2281
+ attemptController.abort(new DOMException("Herdr widget attempt ended", "AbortError"));
2282
+ signal.removeEventListener("abort", wakeRefresh);
2283
+ sessionSignal.removeEventListener("abort", abortAttempt);
2284
+ try {
2285
+ subscription?.close();
2286
+ } catch (cleanupError) {
2287
+ cleanupFailure = { error: cleanupError };
1164
2288
  }
1165
2289
  }
1166
- });
2290
+ if (cleanupFailure) {
2291
+ throw new HerdrCleanupError(
2292
+ attemptError ? [attemptError.error, cleanupFailure.error] : [cleanupFailure.error],
2293
+ "Herdr subscription cleanup failed"
2294
+ );
2295
+ }
2296
+ if (attemptError) throw attemptError.error;
2297
+ };
2298
+ const run = async (ctx, expectedGeneration, signal) => {
2299
+ let failures = 0;
2300
+ while (owns(ctx, expectedGeneration) && !signal.aborted) {
2301
+ try {
2302
+ await runAttempt(ctx, expectedGeneration, signal);
2303
+ return;
2304
+ } catch (error) {
2305
+ if (error instanceof HerdrCleanupError) throw error;
2306
+ if (!owns(ctx, expectedGeneration) || signal.aborted) return;
2307
+ try {
2308
+ clearWidget();
2309
+ } catch (cleanupError) {
2310
+ throw new AggregateError([error, cleanupError], "Herdr observation and widget cleanup failed");
2311
+ }
2312
+ if (error instanceof HerdrTopologyChangedError) continue;
2313
+ failures += 1;
2314
+ if (failures >= 2) return;
2315
+ try {
2316
+ await waitForRetry(retryDelayMs, signal);
2317
+ } catch {
2318
+ return;
2319
+ }
2320
+ if (!owns(ctx, expectedGeneration) || signal.aborted) return;
2321
+ }
2322
+ }
2323
+ };
1167
2324
  return {
1168
- async start(ctx) {
1169
- const expected = ++generation;
1170
- controller.abort();
2325
+ start(ctx) {
2326
+ controller?.abort(new DOMException("Herdr widget session replaced", "AbortError"));
2327
+ try {
2328
+ publisher?.dispose();
2329
+ } finally {
2330
+ publisher = void 0;
2331
+ generation += 1;
2332
+ activeSession = void 0;
2333
+ controller = void 0;
2334
+ publishedFingerprint = void 0;
2335
+ hasPublished = false;
2336
+ }
2337
+ if (ctx.mode !== "tui") return;
2338
+ activeSession = ctx.sessionManager;
1171
2339
  controller = new AbortController();
1172
- menuOpen = false;
1173
- const previous = owner;
1174
- owner = ctx;
1175
- if (previous) await observer.shutdown(previous);
1176
- if (!current(expected)) return;
1177
- await changes;
1178
- if (!current(expected)) return;
1179
- const loaded = await readHerdrSettings(settingsPath);
1180
- if (!current(expected)) return;
1181
- enabled = loaded.settings.widget;
1182
- if (loaded.kind === "invalid" && ctx.hasUI)
1183
- ctx.ui.notify(
1184
- "Herdr ignored invalid pi-herdr.json settings and kept the widget enabled. Fix the file before saving.",
1185
- "warning"
1186
- );
1187
- if (enabled && ctx.mode === "tui") observer.start(ctx);
2340
+ const expectedGeneration = generation;
2341
+ publisher = createEditorStatusPublisher2({
2342
+ key: HERDR_WIDGET_KEY,
2343
+ name: "Herdr",
2344
+ context: ctx,
2345
+ isCurrent: () => expectedGeneration === generation,
2346
+ summary: herdrWidgetSummary,
2347
+ render: renderHerdrWidget
2348
+ });
2349
+ const task = run(ctx, expectedGeneration, controller.signal);
2350
+ ownedTasks.add(task);
2351
+ void task.then(
2352
+ () => ownedTasks.delete(task),
2353
+ (error) => {
2354
+ taskErrors.add(error);
2355
+ ownedTasks.delete(task);
2356
+ }
2357
+ );
2358
+ },
2359
+ restore(ctx) {
2360
+ if (activeSession === void 0 || !owns(ctx)) return false;
2361
+ return publisher?.setCollapsed(false) ?? false;
1188
2362
  },
1189
2363
  async shutdown(ctx) {
1190
- if (ctx.sessionManager !== owner?.sessionManager) return;
1191
- generation += 1;
1192
- controller.abort();
1193
- owner = void 0;
1194
- menuOpen = false;
1195
- await Promise.all([observer.shutdown(ctx), changes]);
1196
- await awaitHerdrSettingsWrites(settingsPath);
2364
+ if (activeSession !== void 0 && !owns(ctx)) return;
2365
+ controller?.abort(new DOMException("Herdr widget session shut down", "AbortError"));
2366
+ const errors = [];
2367
+ try {
2368
+ publisher?.dispose();
2369
+ } catch (error) {
2370
+ errors.push(error);
2371
+ } finally {
2372
+ publisher = void 0;
2373
+ generation += 1;
2374
+ publishedFingerprint = void 0;
2375
+ hasPublished = false;
2376
+ }
2377
+ const shutdownGeneration = generation;
2378
+ await Promise.allSettled([...ownedTasks]);
2379
+ errors.push(...taskErrors);
2380
+ taskErrors.clear();
2381
+ if (generation === shutdownGeneration) {
2382
+ activeSession = void 0;
2383
+ controller = void 0;
2384
+ }
2385
+ if (errors.length === 1) throw errors[0];
2386
+ if (errors.length > 1) throw new AggregateError(errors, "Herdr widget cleanup failed");
1197
2387
  }
1198
2388
  };
1199
2389
  }
@@ -1217,7 +2407,7 @@ function readEnvironment(environment = process.env) {
1217
2407
  const socketPath = environment.HERDR_SOCKET_PATH;
1218
2408
  const paneId = environment.HERDR_PANE_ID;
1219
2409
  return {
1220
- enabled: environment.HERDR_ENV === "1" && !!socketPath && !!paneId,
2410
+ enabled: environment.HERDR_ENV === "1" && !!socketPath?.trim() && !!paneId?.trim(),
1221
2411
  paneId: paneId ?? "",
1222
2412
  socketEndpoint: resolveSocketEndpoint(socketPath)
1223
2413
  };
@@ -1234,6 +2424,8 @@ function createHerdrAgentStateExtension(options = {}) {
1234
2424
  });
1235
2425
  return function herdrAgentState2(pi) {
1236
2426
  if (!environment.enabled) return;
2427
+ let releaseClaim = claimHerdrRuntime(pi);
2428
+ if (!releaseClaim) return;
1237
2429
  const widget = createHerdrSettingsController(pi, widgetObserver, options);
1238
2430
  let sessionGeneration = 0;
1239
2431
  let sessionController = new AbortController();
@@ -1416,9 +2608,9 @@ function createHerdrAgentStateExtension(options = {}) {
1416
2608
  function owns(ctx) {
1417
2609
  return rootSession && ctx.sessionManager === activeSession;
1418
2610
  }
1419
- function publishMetadata(ctx) {
2611
+ function publishMetadata(ctx, force = false) {
1420
2612
  if (!owns(ctx)) return;
1421
- queueMetadata(readMetadataSnapshot(ctx));
2613
+ queueMetadata(readMetadataSnapshot(ctx), force);
1422
2614
  }
1423
2615
  function desiredState() {
1424
2616
  if (blockedCount > 0) return { state: "blocked", message: blockedMessage };
@@ -1445,6 +2637,8 @@ function createHerdrAgentStateExtension(options = {}) {
1445
2637
  publishState();
1446
2638
  });
1447
2639
  pi.on("session_start", async (event, ctx) => {
2640
+ releaseClaim ??= claimHerdrRuntime(pi);
2641
+ if (!releaseClaim) return;
1448
2642
  const generation = ++sessionGeneration;
1449
2643
  const replaced = new DOMException("Herdr session replaced", "AbortError");
1450
2644
  sessionController.abort(replaced);
@@ -1471,11 +2665,11 @@ function createHerdrAgentStateExtension(options = {}) {
1471
2665
  }
1472
2666
  updateSessionRef(ctx);
1473
2667
  const sessionReport = reportSession(event.reason);
1474
- publishMetadata(ctx);
1475
2668
  await Promise.all([sessionReport, widgetStart]);
1476
2669
  if (generation !== sessionGeneration || activeSession !== ctx.sessionManager || sessionController.signal.aborted || !rootSession) {
1477
2670
  return;
1478
2671
  }
2672
+ publishMetadata(ctx, true);
1479
2673
  agentActive = !ctx.isIdle();
1480
2674
  publishState(true);
1481
2675
  });
@@ -1506,6 +2700,8 @@ function createHerdrAgentStateExtension(options = {}) {
1506
2700
  await shutdownTask;
1507
2701
  return;
1508
2702
  }
2703
+ releaseClaim?.();
2704
+ releaseClaim = void 0;
1509
2705
  const session = ctx.sessionManager;
1510
2706
  const task = (async () => {
1511
2707
  const shouldClearMetadata = rootSession;
@@ -1557,7 +2753,23 @@ function createHerdrAgentStateExtension(options = {}) {
1557
2753
  function herdrAgentState(pi) {
1558
2754
  createHerdrAgentStateExtension()(pi);
1559
2755
  }
2756
+
2757
+ // src/herdr-integration.ts
2758
+ function selectIntegrationBackend(env = process.env) {
2759
+ const terminal = env.HC_TERMINAL_ID;
2760
+ const endpoint = env.HC_TERMINAL_SOCKET;
2761
+ if (terminal === void 0 && endpoint === void 0) return { kind: "herdr" };
2762
+ const controls2 = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
2763
+ if (!terminal?.trim() || terminal !== terminal.trim() || [...terminal].length > 256 || controls2.test(terminal) || !endpoint || !endpoint.trim() || endpoint.length > 4096 || controls2.test(endpoint))
2764
+ return { kind: "disabled" };
2765
+ return { kind: "hc", environment: { terminalId: terminal, socketEndpoint: endpoint } };
2766
+ }
2767
+ function herdrIntegration(pi) {
2768
+ const backend = selectIntegrationBackend();
2769
+ if (backend.kind === "hc") createHcIntegration({ environment: backend.environment })(pi);
2770
+ else if (backend.kind === "herdr") herdrAgentState(pi);
2771
+ }
1560
2772
  export {
1561
- herdrAgentState as default
2773
+ herdrIntegration as default
1562
2774
  };
1563
2775
  //# sourceMappingURL=index.ts.map