@narumitw/pi-herdr 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +84 -29
- package/dist/chunks/{herdr-menu-H74GELLE.ts → herdr-menu-CA4DI2LZ.ts} +10 -7
- package/dist/chunks/herdr-menu-CA4DI2LZ.ts.map +7 -0
- package/dist/index.ts +1999 -781
- package/dist/index.ts.map +4 -4
- package/docs/hc-integration.md +65 -0
- package/docs/peer-provenance.md +35 -0
- package/package.json +15 -4
- package/skills/pi-herdr/SKILL.md +49 -0
- package/src/hc-integration.ts +58 -0
- package/src/hc-observer.ts +270 -0
- package/src/hc-peer-tool.ts +191 -0
- package/src/hc-peer.d.mts +36 -0
- package/src/hc-peer.mjs +390 -0
- package/src/hc-rpc.d.mts +37 -0
- package/src/hc-rpc.mjs +211 -0
- package/src/hc-widget.ts +246 -0
- package/src/herdr-agent-state.ts +14 -4
- package/src/herdr-integration.ts +32 -0
- package/src/herdr-menu.ts +16 -6
- package/src/herdr-observer.ts +4 -1
- package/src/herdr-protocol.ts +13 -0
- package/src/herdr-runtime-claim.ts +22 -0
- package/src/herdr-settings-controller.ts +8 -4
- package/src/herdr-spawn-provenance.ts +61 -0
- package/src/herdr-widget.ts +84 -7
- package/src/index.ts +1 -1
- package/dist/chunks/herdr-menu-H74GELLE.ts.map +0 -7
package/dist/index.ts
CHANGED
|
@@ -1,478 +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/
|
|
5
|
-
import
|
|
4
|
+
// src/hc-integration.ts
|
|
5
|
+
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
6
7
|
|
|
7
|
-
// src/
|
|
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
|
|
10
|
-
var
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
|
|
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
|
|
72
|
-
if (
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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
|
-
|
|
131
|
-
|
|
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
|
-
|
|
144
|
-
|
|
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
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
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 (
|
|
56
|
+
if (ending) return;
|
|
194
57
|
try {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
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
|
-
|
|
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
|
-
|
|
76
|
+
stop(error instanceof Error ? error : new Error("Invalid hc frame"));
|
|
229
77
|
}
|
|
230
78
|
});
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
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
|
-
|
|
240
|
-
|
|
241
|
-
|
|
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
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
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
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
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: "workspace.created" },
|
|
304
|
-
{ type: "workspace.closed" },
|
|
305
|
-
{ type: "pane.created" },
|
|
306
|
-
{ type: "pane.updated" },
|
|
307
|
-
{ type: "workspace.renamed" },
|
|
308
|
-
{ type: "pane.closed" },
|
|
309
|
-
{ type: "pane.moved" },
|
|
310
|
-
{ type: "pane.exited" },
|
|
311
|
-
{ type: "pane.agent_detected" }
|
|
312
|
-
];
|
|
313
|
-
function herdrWidgetSubscriptions(panes) {
|
|
314
|
-
return [
|
|
315
|
-
...HERDR_WIDGET_TOPOLOGY_SUBSCRIPTIONS.map((entry) => ({ ...entry })),
|
|
316
|
-
...panes.filter((pane) => pane.agent !== void 0).map((pane) => ({ type: "pane.agent_status_changed", pane_id: pane.paneId }))
|
|
317
|
-
];
|
|
318
|
-
}
|
|
319
|
-
function isRecord2(value) {
|
|
320
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
321
|
-
}
|
|
322
|
-
function requiredString(value) {
|
|
323
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
324
|
-
}
|
|
325
|
-
function optionalString(value) {
|
|
326
|
-
return typeof value === "string" ? value : void 0;
|
|
327
|
-
}
|
|
328
|
-
function agentStatus(value) {
|
|
329
|
-
return typeof value === "string" && HERDR_AGENT_STATUSES.includes(value) ? value : void 0;
|
|
330
|
-
}
|
|
331
|
-
function stringRecord(value) {
|
|
332
|
-
if (!isRecord2(value)) return void 0;
|
|
333
|
-
const entries = Object.entries(value);
|
|
334
|
-
if (!entries.every(([, entry]) => typeof entry === "string")) return void 0;
|
|
335
|
-
return Object.fromEntries(entries);
|
|
336
|
-
}
|
|
337
|
-
function parseHerdrPane(value) {
|
|
338
|
-
if (!isRecord2(value)) return void 0;
|
|
339
|
-
const paneId = requiredString(value.pane_id);
|
|
340
|
-
const workspaceId = requiredString(value.workspace_id);
|
|
341
|
-
const tabId = requiredString(value.tab_id);
|
|
342
|
-
const terminalId = requiredString(value.terminal_id);
|
|
343
|
-
const status = agentStatus(value.agent_status);
|
|
344
|
-
const revision = value.revision;
|
|
345
|
-
if (!paneId || !workspaceId || !tabId || !terminalId || !status || typeof value.focused !== "boolean" || typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 0) {
|
|
346
|
-
return void 0;
|
|
347
|
-
}
|
|
348
|
-
return {
|
|
349
|
-
paneId,
|
|
350
|
-
workspaceId,
|
|
351
|
-
tabId,
|
|
352
|
-
terminalId,
|
|
353
|
-
focused: value.focused,
|
|
354
|
-
revision,
|
|
355
|
-
agent: optionalString(value.agent),
|
|
356
|
-
agentName: optionalString(value.name),
|
|
357
|
-
agentStatus: status,
|
|
358
|
-
displayAgent: optionalString(value.display_agent),
|
|
359
|
-
label: optionalString(value.label),
|
|
360
|
-
stateLabels: stringRecord(value.state_labels) ?? {},
|
|
361
|
-
terminalTitle: optionalString(value.terminal_title_stripped) ?? optionalString(value.terminal_title),
|
|
362
|
-
title: optionalString(value.title)
|
|
363
|
-
};
|
|
364
|
-
}
|
|
365
|
-
function parsePaneCurrentResult(value) {
|
|
366
|
-
if (!isRecord2(value) || value.type !== "pane_current") {
|
|
367
|
-
throw new Error("Herdr returned an invalid current-pane response");
|
|
368
|
-
}
|
|
369
|
-
const pane = parseHerdrPane(value.pane);
|
|
370
|
-
if (!pane) throw new Error("Herdr returned an invalid current pane");
|
|
371
|
-
return pane;
|
|
372
|
-
}
|
|
373
|
-
function parsePaneListResult(value) {
|
|
374
|
-
if (!isRecord2(value) || value.type !== "pane_list" || !Array.isArray(value.panes)) {
|
|
375
|
-
throw new Error("Herdr returned an invalid pane-list response");
|
|
376
|
-
}
|
|
377
|
-
const panes = value.panes.map(parseHerdrPane);
|
|
378
|
-
if (panes.some((pane) => pane === void 0)) {
|
|
379
|
-
throw new Error("Herdr returned an invalid pane in the pane list");
|
|
380
|
-
}
|
|
381
|
-
return panes;
|
|
382
|
-
}
|
|
383
|
-
function parseAgentListResult(value) {
|
|
384
|
-
if (!isRecord2(value) || value.type !== "agent_list" || !Array.isArray(value.agents)) {
|
|
385
|
-
throw new Error("Herdr returned an invalid agent-list response");
|
|
386
|
-
}
|
|
387
|
-
return value.agents.flatMap((entry) => {
|
|
388
|
-
const pane = parseHerdrPane(entry);
|
|
389
|
-
return pane ? [pane] : [];
|
|
390
157
|
});
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
if (!workspaceId) throw new Error("Herdr returned an invalid workspace identity");
|
|
400
|
-
return { workspaceId, label: optionalString(workspace.label) };
|
|
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;
|
|
401
166
|
});
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
}
|
|
412
|
-
if (value.event === "workspace_closed") {
|
|
413
|
-
const workspaceId = requiredString(data.workspace_id);
|
|
414
|
-
return workspaceId ? { type: "workspace_closed", workspaceId } : void 0;
|
|
415
|
-
}
|
|
416
|
-
if (value.event === "workspace_renamed") {
|
|
417
|
-
const workspaceId = requiredString(data.workspace_id);
|
|
418
|
-
if (!workspaceId || typeof data.label !== "string") return void 0;
|
|
419
|
-
return { type: "workspace_renamed", workspaceId };
|
|
420
|
-
}
|
|
421
|
-
if (value.event === "pane.agent_status_changed" || value.event === "pane_agent_status_changed") {
|
|
422
|
-
const paneId = requiredString(data.pane_id);
|
|
423
|
-
const workspaceId = requiredString(data.workspace_id);
|
|
424
|
-
const status = agentStatus(data.agent_status);
|
|
425
|
-
if (!paneId || !workspaceId || !status) return void 0;
|
|
426
|
-
return {
|
|
427
|
-
type: "agent_status_changed",
|
|
428
|
-
paneId,
|
|
429
|
-
workspaceId
|
|
430
|
-
};
|
|
431
|
-
}
|
|
432
|
-
if (value.event === "pane_created" || value.event === "pane_updated") {
|
|
433
|
-
const pane = parseHerdrPane(data.pane);
|
|
434
|
-
return pane ? { type: value.event === "pane_created" ? "created" : "updated", pane } : void 0;
|
|
435
|
-
}
|
|
436
|
-
if (value.event === "pane_closed" || value.event === "pane_exited") {
|
|
437
|
-
const paneId = requiredString(data.pane_id);
|
|
438
|
-
const workspaceId = requiredString(data.workspace_id);
|
|
439
|
-
if (!paneId || !workspaceId) return void 0;
|
|
440
|
-
return {
|
|
441
|
-
type: value.event === "pane_closed" ? "closed" : "exited",
|
|
442
|
-
paneId,
|
|
443
|
-
workspaceId
|
|
444
|
-
};
|
|
445
|
-
}
|
|
446
|
-
if (value.event === "pane_moved") {
|
|
447
|
-
const pane = parseHerdrPane(data.pane);
|
|
448
|
-
const previousPaneId = requiredString(data.previous_pane_id);
|
|
449
|
-
const previousWorkspaceId = requiredString(data.previous_workspace_id);
|
|
450
|
-
if (!pane || !previousPaneId || !previousWorkspaceId) return void 0;
|
|
451
|
-
return { type: "moved", pane, previousPaneId, previousWorkspaceId };
|
|
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
|
+
});
|
|
452
176
|
}
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
return void 0;
|
|
458
|
-
}
|
|
459
|
-
const finalStatus = data.final_status === null ? void 0 : agentStatus(data.final_status);
|
|
460
|
-
if (data.final_status !== void 0 && data.final_status !== null && !finalStatus) return void 0;
|
|
461
|
-
return {
|
|
462
|
-
type: "agent_detected",
|
|
463
|
-
paneId,
|
|
464
|
-
workspaceId
|
|
465
|
-
};
|
|
177
|
+
try {
|
|
178
|
+
return await operation(request, disconnected.signal);
|
|
179
|
+
} finally {
|
|
180
|
+
await connection.close();
|
|
466
181
|
}
|
|
467
|
-
return void 0;
|
|
468
182
|
}
|
|
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", {});
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// src/hc-widget.ts
|
|
211
|
+
import { sanitizeTerminalText as sanitizeTerminalText2 } from "@narumitw/pi-tui-kit/terminal-text";
|
|
469
212
|
|
|
470
213
|
// src/herdr-widget.ts
|
|
471
214
|
import { EditorStatusWidget } from "@narumitw/pi-tui-kit/editor-status-widget";
|
|
472
|
-
import { sanitizeTerminalText
|
|
215
|
+
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
|
|
473
216
|
var HERDR_WIDGET_KEY = "herdr:agents";
|
|
474
217
|
var MAX_HERDR_WIDGET_AGENTS = 5;
|
|
475
218
|
var STATE_ORDER = {
|
|
219
|
+
error: -1,
|
|
476
220
|
blocked: 0,
|
|
477
221
|
done: 1,
|
|
478
222
|
working: 2,
|
|
@@ -483,6 +227,9 @@ function observedPane(pane) {
|
|
|
483
227
|
return {
|
|
484
228
|
paneId: pane.paneId,
|
|
485
229
|
workspaceId: pane.workspaceId,
|
|
230
|
+
terminalId: pane.terminalId,
|
|
231
|
+
sessionFingerprint: pane.sessionFingerprint,
|
|
232
|
+
spawn: pane.spawn ? { ...pane.spawn } : void 0,
|
|
486
233
|
agent: pane.agent,
|
|
487
234
|
agentName: pane.agentName,
|
|
488
235
|
agentStatus: pane.agentStatus,
|
|
@@ -494,7 +241,7 @@ function observedPane(pane) {
|
|
|
494
241
|
}
|
|
495
242
|
function safeDisplay(value) {
|
|
496
243
|
if (value === void 0) return void 0;
|
|
497
|
-
const safe =
|
|
244
|
+
const safe = sanitizeTerminalText(value).trim();
|
|
498
245
|
return safe.length > 0 ? safe : void 0;
|
|
499
246
|
}
|
|
500
247
|
function shortIdentity(value, fallback) {
|
|
@@ -525,6 +272,49 @@ function rowForPane(pane, workspace) {
|
|
|
525
272
|
stateLabel: safeDisplay(pane.stateLabels[pane.agentStatus]) ?? safeDisplay(pane.agentStatus) ?? "unknown"
|
|
526
273
|
};
|
|
527
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
|
+
}
|
|
528
318
|
function immutableSnapshot(rows) {
|
|
529
319
|
if (rows.length === 0) return void 0;
|
|
530
320
|
const visible = rows.slice(0, MAX_HERDR_WIDGET_AGENTS).map((row) => Object.freeze({ ...row }));
|
|
@@ -542,6 +332,7 @@ var HerdrWidgetModel = class {
|
|
|
542
332
|
this.currentPaneId = currentPane.paneId;
|
|
543
333
|
this.workspaces = new Map(workspaces.map((workspace) => [workspace.workspaceId, { ...workspace }]));
|
|
544
334
|
this.panes = new Map(panes.map((pane) => [pane.paneId, observedPane(pane)]));
|
|
335
|
+
this.panes.set(currentPane.paneId, observedPane(currentPane));
|
|
545
336
|
}
|
|
546
337
|
clear() {
|
|
547
338
|
this.currentPaneId = void 0;
|
|
@@ -550,7 +341,13 @@ var HerdrWidgetModel = class {
|
|
|
550
341
|
}
|
|
551
342
|
snapshot() {
|
|
552
343
|
if (!this.currentPaneId) return void 0;
|
|
553
|
-
const
|
|
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
|
+
});
|
|
554
351
|
rows.sort(
|
|
555
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)
|
|
556
353
|
);
|
|
@@ -559,6 +356,7 @@ var HerdrWidgetModel = class {
|
|
|
559
356
|
};
|
|
560
357
|
function stateStyle(theme, state, text) {
|
|
561
358
|
switch (state) {
|
|
359
|
+
case "error":
|
|
562
360
|
case "blocked":
|
|
563
361
|
return theme.fg("error", text);
|
|
564
362
|
case "done":
|
|
@@ -573,6 +371,8 @@ function stateStyle(theme, state, text) {
|
|
|
573
371
|
}
|
|
574
372
|
function stateSymbol(state) {
|
|
575
373
|
switch (state) {
|
|
374
|
+
case "error":
|
|
375
|
+
return "!";
|
|
576
376
|
case "blocked":
|
|
577
377
|
return "\xD7";
|
|
578
378
|
case "done":
|
|
@@ -599,7 +399,8 @@ function createHerdrWidget(snapshot, theme, includeHeader = true) {
|
|
|
599
399
|
const agent = theme.bold(theme.fg("text", row.agent));
|
|
600
400
|
const pane = theme.fg("muted", row.pane);
|
|
601
401
|
const space = theme.fg("dim", row.space);
|
|
602
|
-
|
|
402
|
+
const relation = row.relation ? `${separator}${theme.fg("muted", row.relation)}` : "";
|
|
403
|
+
lines.push(`${state} ${agent}${separator}${pane}${separator}${space}${relation}`);
|
|
603
404
|
}
|
|
604
405
|
if (snapshot.hiddenAgents > 0) {
|
|
605
406
|
lines.push(theme.fg("dim", `+${snapshot.hiddenAgents} more`));
|
|
@@ -612,332 +413,880 @@ function herdrWidgetFingerprint(snapshot) {
|
|
|
612
413
|
return snapshot ? JSON.stringify(snapshot) : void 0;
|
|
613
414
|
}
|
|
614
415
|
|
|
615
|
-
// src/
|
|
616
|
-
var
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
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
|
|
620
424
|
};
|
|
621
|
-
function
|
|
622
|
-
return
|
|
425
|
+
function isRecord(value) {
|
|
426
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
623
427
|
}
|
|
624
|
-
function
|
|
625
|
-
|
|
626
|
-
return JSON.stringify([currentPane.paneId, currentPane.workspaceId, agentPaneIds]);
|
|
428
|
+
function stringArray(value) {
|
|
429
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
627
430
|
}
|
|
628
|
-
function
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
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;
|
|
438
|
+
}
|
|
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 }
|
|
640
449
|
};
|
|
641
|
-
|
|
450
|
+
}
|
|
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
|
+
};
|
|
463
|
+
}
|
|
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;
|
|
642
470
|
});
|
|
643
471
|
}
|
|
644
|
-
function
|
|
645
|
-
|
|
646
|
-
const
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
const
|
|
655
|
-
const
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
const
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
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;
|
|
673
540
|
};
|
|
674
|
-
const
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
),
|
|
696
|
-
request(
|
|
697
|
-
options.environment.socketEndpoint,
|
|
698
|
-
{ id: requestId("agents"), method: "agent.list", params: {} },
|
|
699
|
-
signal
|
|
700
|
-
),
|
|
701
|
-
request(
|
|
702
|
-
options.environment.socketEndpoint,
|
|
703
|
-
{
|
|
704
|
-
id: requestId("workspace"),
|
|
705
|
-
method: "workspace.list",
|
|
706
|
-
params: {}
|
|
707
|
-
},
|
|
708
|
-
signal
|
|
709
|
-
)
|
|
710
|
-
]);
|
|
711
|
-
if (!owns(ctx, expectedGeneration) || signal.aborted) return void 0;
|
|
712
|
-
const panes = parsePaneListResult(listResult);
|
|
713
|
-
const panesById = new Map(panes.map((pane) => [pane.paneId, pane]));
|
|
714
|
-
const namesByPane = new Map(
|
|
715
|
-
parseAgentListResult(agentResult).filter((pane) => panesById.get(pane.paneId)?.workspaceId === pane.workspaceId).map((pane) => [pane.paneId, pane.agentName])
|
|
716
|
-
);
|
|
717
|
-
const withAgentName = (pane) => ({
|
|
718
|
-
...pane,
|
|
719
|
-
agentName: namesByPane.get(pane.paneId) ?? pane.agentName
|
|
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("; ") } : {}
|
|
720
562
|
});
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
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) => {
|
|
590
|
+
const timer = setTimeout(() => {
|
|
591
|
+
signal.removeEventListener("abort", cancel);
|
|
592
|
+
resolve3();
|
|
593
|
+
}, milliseconds);
|
|
594
|
+
timer.unref?.();
|
|
595
|
+
const cancel = () => {
|
|
596
|
+
clearTimeout(timer);
|
|
597
|
+
reject(new Error("hc observer cancelled"));
|
|
725
598
|
};
|
|
726
|
-
|
|
727
|
-
|
|
599
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
function createHcWidgetObserver(options) {
|
|
603
|
+
const request = options.request ?? requestHc;
|
|
604
|
+
const subscribe = options.subscribe ?? subscribeHc;
|
|
605
|
+
let generation = 0;
|
|
606
|
+
let owner;
|
|
607
|
+
let controller;
|
|
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;
|
|
617
|
+
publisher?.publish(snapshot);
|
|
618
|
+
fingerprint = next;
|
|
619
|
+
}
|
|
620
|
+
async function attempt(ctx, expected, signal, healthy) {
|
|
728
621
|
const attemptController = new AbortController();
|
|
729
|
-
const
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
const signal = attemptController.signal;
|
|
733
|
-
let attemptActive = true;
|
|
622
|
+
const abort = () => attemptController.abort();
|
|
623
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
624
|
+
if (signal.aborted) abort();
|
|
734
625
|
let subscription;
|
|
626
|
+
let active = true;
|
|
627
|
+
let dirty = true;
|
|
628
|
+
let seq = -1;
|
|
735
629
|
let failure;
|
|
736
|
-
let attemptError;
|
|
737
|
-
let cleanupFailure;
|
|
738
630
|
let wake;
|
|
739
|
-
const
|
|
740
|
-
const
|
|
631
|
+
const notify = () => {
|
|
632
|
+
const waiting = wake;
|
|
741
633
|
wake = void 0;
|
|
742
|
-
|
|
634
|
+
waiting?.();
|
|
743
635
|
};
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
if (!attemptActive || signal.aborted) return;
|
|
636
|
+
const fail2 = (error) => {
|
|
637
|
+
if (!active || attemptController.signal.aborted) return;
|
|
747
638
|
failure = error;
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
} catch (cleanupError) {
|
|
751
|
-
failure = new AggregateError([error, cleanupError], "Herdr subscription and widget cleanup failed");
|
|
752
|
-
} finally {
|
|
753
|
-
attemptController.abort(failure);
|
|
754
|
-
}
|
|
639
|
+
attemptController.abort();
|
|
640
|
+
notify();
|
|
755
641
|
};
|
|
642
|
+
attemptController.signal.addEventListener("abort", notify);
|
|
643
|
+
const current = () => active && !attemptController.signal.aborted && owns(ctx, expected);
|
|
756
644
|
try {
|
|
757
|
-
await (
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
method
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
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
|
+
}
|
|
776
664
|
dirty = true;
|
|
777
|
-
|
|
665
|
+
notify();
|
|
666
|
+
} catch (error) {
|
|
667
|
+
fail2(error);
|
|
778
668
|
}
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
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
|
|
784
694
|
}
|
|
785
|
-
throw error;
|
|
786
|
-
});
|
|
787
|
-
void subscription.closed.then(
|
|
788
|
-
() => failAttempt(new Error("Herdr subscription ended")),
|
|
789
|
-
(error) => failAttempt(error instanceof Error ? error : new Error(String(error)))
|
|
790
695
|
);
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
consecutiveDiscards += 1;
|
|
800
|
-
continue;
|
|
801
|
-
}
|
|
802
|
-
consecutiveDiscards = 0;
|
|
803
|
-
model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspaces);
|
|
804
|
-
publish(ctx, model, expectedGeneration);
|
|
805
|
-
await new Promise((resolve) => {
|
|
806
|
-
wake = resolve;
|
|
807
|
-
if (dirty || signal.aborted) wakeRefresh();
|
|
808
|
-
});
|
|
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;
|
|
809
704
|
}
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
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;
|
|
814
710
|
} finally {
|
|
815
|
-
|
|
816
|
-
attemptController.abort(
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
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
|
+
}
|
|
823
722
|
}
|
|
824
723
|
}
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
attemptError ? [attemptError.error, cleanupFailure.error] : [cleanupFailure.error],
|
|
828
|
-
"Herdr subscription cleanup failed"
|
|
829
|
-
);
|
|
830
|
-
}
|
|
831
|
-
if (attemptError) throw attemptError.error;
|
|
832
|
-
};
|
|
833
|
-
const run = async (ctx, expectedGeneration, signal) => {
|
|
724
|
+
}
|
|
725
|
+
async function run(ctx, expected, signal) {
|
|
834
726
|
let failures = 0;
|
|
835
|
-
while (owns(ctx,
|
|
727
|
+
while (owns(ctx, expected) && !signal.aborted) {
|
|
836
728
|
try {
|
|
837
|
-
await
|
|
729
|
+
await attempt(ctx, expected, signal, () => {
|
|
730
|
+
failures = 0;
|
|
731
|
+
});
|
|
838
732
|
return;
|
|
839
|
-
} catch
|
|
840
|
-
if (
|
|
841
|
-
|
|
842
|
-
try {
|
|
843
|
-
clearWidget();
|
|
844
|
-
} catch (cleanupError) {
|
|
845
|
-
throw new AggregateError([error, cleanupError], "Herdr observation and widget cleanup failed");
|
|
846
|
-
}
|
|
847
|
-
if (error instanceof HerdrTopologyChangedError) continue;
|
|
733
|
+
} catch {
|
|
734
|
+
if (!owns(ctx, expected) || signal.aborted) return;
|
|
735
|
+
publish(ctx, expected, void 0);
|
|
848
736
|
failures += 1;
|
|
849
737
|
if (failures >= 2) return;
|
|
850
738
|
try {
|
|
851
|
-
await
|
|
739
|
+
await retryDelay(options.retryDelayMs ?? 200, signal);
|
|
852
740
|
} catch {
|
|
853
741
|
return;
|
|
854
742
|
}
|
|
855
|
-
if (!owns(ctx, expectedGeneration) || signal.aborted) return;
|
|
856
743
|
}
|
|
857
744
|
}
|
|
858
|
-
}
|
|
745
|
+
}
|
|
859
746
|
return {
|
|
860
747
|
start(ctx) {
|
|
861
|
-
controller?.abort(
|
|
748
|
+
controller?.abort();
|
|
862
749
|
try {
|
|
863
750
|
publisher?.dispose();
|
|
864
751
|
} finally {
|
|
865
|
-
publisher = void 0;
|
|
866
752
|
generation += 1;
|
|
867
|
-
|
|
753
|
+
publisher = void 0;
|
|
754
|
+
fingerprint = void 0;
|
|
755
|
+
owner = void 0;
|
|
868
756
|
controller = void 0;
|
|
869
|
-
publishedFingerprint = void 0;
|
|
870
|
-
hasPublished = false;
|
|
871
757
|
}
|
|
872
758
|
if (ctx.mode !== "tui") return;
|
|
873
|
-
|
|
759
|
+
owner = ctx.sessionManager;
|
|
760
|
+
const expected = generation;
|
|
874
761
|
controller = new AbortController();
|
|
875
|
-
const expectedGeneration = generation;
|
|
876
762
|
publisher = createEditorStatusPublisher({
|
|
877
763
|
key: HERDR_WIDGET_KEY,
|
|
878
|
-
name: "
|
|
764
|
+
name: "hc",
|
|
879
765
|
context: ctx,
|
|
880
|
-
isCurrent: () =>
|
|
766
|
+
isCurrent: () => generation === expected,
|
|
881
767
|
summary: herdrWidgetSummary,
|
|
882
|
-
render:
|
|
768
|
+
render: (snapshot, theme, width) => createHerdrWidget(snapshot, theme, false).render(width)
|
|
883
769
|
});
|
|
884
|
-
const task = run(ctx,
|
|
885
|
-
|
|
770
|
+
const task = run(ctx, expected, controller.signal);
|
|
771
|
+
tasks.add(task);
|
|
886
772
|
void task.then(
|
|
887
|
-
() =>
|
|
773
|
+
() => tasks.delete(task),
|
|
888
774
|
(error) => {
|
|
889
|
-
|
|
890
|
-
|
|
775
|
+
cleanupErrors.add(error);
|
|
776
|
+
tasks.delete(task);
|
|
891
777
|
}
|
|
892
778
|
);
|
|
893
779
|
},
|
|
894
780
|
restore(ctx) {
|
|
895
|
-
|
|
896
|
-
return publisher?.setCollapsed(false) ?? false;
|
|
781
|
+
return owns(ctx) ? publisher?.setCollapsed(false) ?? false : false;
|
|
897
782
|
},
|
|
898
783
|
async shutdown(ctx) {
|
|
899
|
-
if (
|
|
900
|
-
controller?.abort(
|
|
784
|
+
if (owner !== void 0 && !owns(ctx)) return;
|
|
785
|
+
controller?.abort();
|
|
901
786
|
const errors = [];
|
|
902
787
|
try {
|
|
903
788
|
publisher?.dispose();
|
|
904
789
|
} catch (error) {
|
|
905
790
|
errors.push(error);
|
|
906
791
|
} finally {
|
|
907
|
-
publisher = void 0;
|
|
908
792
|
generation += 1;
|
|
909
|
-
|
|
910
|
-
|
|
793
|
+
publisher = void 0;
|
|
794
|
+
fingerprint = void 0;
|
|
911
795
|
}
|
|
912
|
-
const
|
|
913
|
-
await Promise.allSettled([...
|
|
914
|
-
errors.push(...
|
|
915
|
-
|
|
916
|
-
if (
|
|
917
|
-
|
|
796
|
+
const expected = generation;
|
|
797
|
+
await Promise.allSettled([...tasks]);
|
|
798
|
+
errors.push(...cleanupErrors);
|
|
799
|
+
cleanupErrors.clear();
|
|
800
|
+
if (expected === generation) {
|
|
801
|
+
owner = void 0;
|
|
918
802
|
controller = void 0;
|
|
919
803
|
}
|
|
920
|
-
if (errors.length
|
|
921
|
-
if (errors.length > 1) throw new AggregateError(errors, "Herdr widget cleanup failed");
|
|
804
|
+
if (errors.length) throw new AggregateError(errors, "hc widget cleanup failed");
|
|
922
805
|
}
|
|
923
806
|
};
|
|
924
807
|
}
|
|
925
808
|
|
|
926
|
-
// src/
|
|
927
|
-
import { randomUUID } from "node:crypto";
|
|
809
|
+
// src/hc-peer.mjs
|
|
928
810
|
import { constants } from "node:fs";
|
|
929
|
-
import
|
|
930
|
-
import {
|
|
931
|
-
|
|
932
|
-
var
|
|
933
|
-
var
|
|
934
|
-
var
|
|
935
|
-
var
|
|
936
|
-
|
|
937
|
-
|
|
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);
|
|
830
|
+
}
|
|
831
|
+
function checkCancelled(signal) {
|
|
832
|
+
if (signal?.aborted) fail("Operation cancelled; server-side changes may have occurred");
|
|
833
|
+
}
|
|
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) {
|
|
856
|
+
try {
|
|
857
|
+
await fs.stat(paths.resolve(directory, ".git"));
|
|
858
|
+
project = directory;
|
|
859
|
+
} catch (error) {
|
|
860
|
+
if (error.code !== "ENOENT") throw error;
|
|
861
|
+
}
|
|
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 };
|
|
886
|
+
}
|
|
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);
|
|
938
1287
|
}
|
|
939
1288
|
function normalizeHerdrSettings(value) {
|
|
940
|
-
if (!
|
|
1289
|
+
if (!isRecord2(value)) return void 0;
|
|
941
1290
|
if (Object.hasOwn(value, "widget") && typeof value.widget !== "boolean") {
|
|
942
1291
|
return void 0;
|
|
943
1292
|
}
|
|
@@ -1013,8 +1362,8 @@ async function readSettingsDocument(path2) {
|
|
|
1013
1362
|
if (pathStats.size > MAX_SETTINGS_BYTES) {
|
|
1014
1363
|
throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
|
|
1015
1364
|
}
|
|
1016
|
-
const noFollow =
|
|
1017
|
-
const handle = await open(path2,
|
|
1365
|
+
const noFollow = constants2.O_NOFOLLOW ?? 0;
|
|
1366
|
+
const handle = await open(path2, constants2.O_RDONLY | (constants2.O_NONBLOCK ?? 0) | noFollow);
|
|
1018
1367
|
try {
|
|
1019
1368
|
const stats = await handle.stat();
|
|
1020
1369
|
if (!stats.isFile() || stats.dev !== pathStats.dev || stats.ino !== pathStats.ino) {
|
|
@@ -1042,7 +1391,7 @@ async function readSettingsDocument(path2) {
|
|
|
1042
1391
|
} catch {
|
|
1043
1392
|
throw new Error("invalid JSON");
|
|
1044
1393
|
}
|
|
1045
|
-
if (!
|
|
1394
|
+
if (!isRecord2(parsed)) throw new Error("settings document must be a JSON object");
|
|
1046
1395
|
return parsed;
|
|
1047
1396
|
} finally {
|
|
1048
1397
|
await handle.close();
|
|
@@ -1054,7 +1403,7 @@ async function publishSettings(path2, document, options) {
|
|
|
1054
1403
|
if (Buffer.byteLength(contents) > MAX_SETTINGS_BYTES) {
|
|
1055
1404
|
throw new Error(`Pi Herdr settings document exceeds ${MAX_SETTINGS_BYTES} bytes.`);
|
|
1056
1405
|
}
|
|
1057
|
-
const directory =
|
|
1406
|
+
const directory = dirname2(path2);
|
|
1058
1407
|
await mkdir(directory, { recursive: true });
|
|
1059
1408
|
const temporaryPath = join(directory, `.${basename(path2)}.${process.pid}.${randomUUID()}.tmp`);
|
|
1060
1409
|
try {
|
|
@@ -1066,7 +1415,7 @@ async function publishSettings(path2, document, options) {
|
|
|
1066
1415
|
throw error;
|
|
1067
1416
|
}
|
|
1068
1417
|
}
|
|
1069
|
-
function
|
|
1418
|
+
function isRecord2(value) {
|
|
1070
1419
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1071
1420
|
}
|
|
1072
1421
|
function isNodeError(error) {
|
|
@@ -1079,6 +1428,7 @@ function safeError(error) {
|
|
|
1079
1428
|
// src/herdr-settings-controller.ts
|
|
1080
1429
|
function createHerdrSettingsController(pi, observer, options = {}) {
|
|
1081
1430
|
const settingsPath = options.settingsPath ?? herdrSettingsPath();
|
|
1431
|
+
const label = options.backend === "hc" ? "hc" : "Herdr";
|
|
1082
1432
|
let generation = 0;
|
|
1083
1433
|
let owner;
|
|
1084
1434
|
let controller = new AbortController();
|
|
@@ -1087,7 +1437,7 @@ function createHerdrSettingsController(pi, observer, options = {}) {
|
|
|
1087
1437
|
let menuOpen = false;
|
|
1088
1438
|
const current = (expected) => expected === generation && !controller.signal.aborted;
|
|
1089
1439
|
pi.registerCommand("herdr", {
|
|
1090
|
-
description:
|
|
1440
|
+
description: `Configure the ${label} agent widget`,
|
|
1091
1441
|
handler: async (args, ctx) => {
|
|
1092
1442
|
if (args.trim()) throw new Error("/herdr does not accept arguments.");
|
|
1093
1443
|
if (!ctx.hasUI || ctx.mode !== "tui" && ctx.mode !== "rpc") {
|
|
@@ -1098,96 +1448,942 @@ function createHerdrSettingsController(pi, observer, options = {}) {
|
|
|
1098
1448
|
const signal = controller.signal;
|
|
1099
1449
|
menuOpen = true;
|
|
1100
1450
|
try {
|
|
1101
|
-
const [{ runMenu }, { createHerdrMenu }] = await Promise.all([
|
|
1102
|
-
import("@narumitw/pi-tui-kit"),
|
|
1103
|
-
import("./chunks/herdr-menu-
|
|
1104
|
-
]);
|
|
1105
|
-
if (!current(expected)) return;
|
|
1106
|
-
if (enabled && ctx.mode === "tui") observer.restore(ctx);
|
|
1107
|
-
await runMenu(
|
|
1108
|
-
ctx,
|
|
1109
|
-
createHerdrMenu({
|
|
1110
|
-
settingsPath,
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
const
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
() => void 0
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
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,
|
|
1147
2231
|
{
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
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();
|
|
1154
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)))
|
|
1155
2255
|
);
|
|
1156
|
-
|
|
1157
|
-
|
|
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 };
|
|
1158
2288
|
}
|
|
1159
2289
|
}
|
|
1160
|
-
|
|
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
|
+
};
|
|
1161
2324
|
return {
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
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;
|
|
1165
2339
|
controller = new AbortController();
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
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;
|
|
1182
2362
|
},
|
|
1183
2363
|
async shutdown(ctx) {
|
|
1184
|
-
if (
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
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");
|
|
1191
2387
|
}
|
|
1192
2388
|
};
|
|
1193
2389
|
}
|
|
@@ -1211,7 +2407,7 @@ function readEnvironment(environment = process.env) {
|
|
|
1211
2407
|
const socketPath = environment.HERDR_SOCKET_PATH;
|
|
1212
2408
|
const paneId = environment.HERDR_PANE_ID;
|
|
1213
2409
|
return {
|
|
1214
|
-
enabled: environment.HERDR_ENV === "1" && !!socketPath && !!paneId,
|
|
2410
|
+
enabled: environment.HERDR_ENV === "1" && !!socketPath?.trim() && !!paneId?.trim(),
|
|
1215
2411
|
paneId: paneId ?? "",
|
|
1216
2412
|
socketEndpoint: resolveSocketEndpoint(socketPath)
|
|
1217
2413
|
};
|
|
@@ -1228,6 +2424,8 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1228
2424
|
});
|
|
1229
2425
|
return function herdrAgentState2(pi) {
|
|
1230
2426
|
if (!environment.enabled) return;
|
|
2427
|
+
let releaseClaim = claimHerdrRuntime(pi);
|
|
2428
|
+
if (!releaseClaim) return;
|
|
1231
2429
|
const widget = createHerdrSettingsController(pi, widgetObserver, options);
|
|
1232
2430
|
let sessionGeneration = 0;
|
|
1233
2431
|
let sessionController = new AbortController();
|
|
@@ -1410,9 +2608,9 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1410
2608
|
function owns(ctx) {
|
|
1411
2609
|
return rootSession && ctx.sessionManager === activeSession;
|
|
1412
2610
|
}
|
|
1413
|
-
function publishMetadata(ctx) {
|
|
2611
|
+
function publishMetadata(ctx, force = false) {
|
|
1414
2612
|
if (!owns(ctx)) return;
|
|
1415
|
-
queueMetadata(readMetadataSnapshot(ctx));
|
|
2613
|
+
queueMetadata(readMetadataSnapshot(ctx), force);
|
|
1416
2614
|
}
|
|
1417
2615
|
function desiredState() {
|
|
1418
2616
|
if (blockedCount > 0) return { state: "blocked", message: blockedMessage };
|
|
@@ -1439,6 +2637,8 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1439
2637
|
publishState();
|
|
1440
2638
|
});
|
|
1441
2639
|
pi.on("session_start", async (event, ctx) => {
|
|
2640
|
+
releaseClaim ??= claimHerdrRuntime(pi);
|
|
2641
|
+
if (!releaseClaim) return;
|
|
1442
2642
|
const generation = ++sessionGeneration;
|
|
1443
2643
|
const replaced = new DOMException("Herdr session replaced", "AbortError");
|
|
1444
2644
|
sessionController.abort(replaced);
|
|
@@ -1465,11 +2665,11 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1465
2665
|
}
|
|
1466
2666
|
updateSessionRef(ctx);
|
|
1467
2667
|
const sessionReport = reportSession(event.reason);
|
|
1468
|
-
publishMetadata(ctx);
|
|
1469
2668
|
await Promise.all([sessionReport, widgetStart]);
|
|
1470
2669
|
if (generation !== sessionGeneration || activeSession !== ctx.sessionManager || sessionController.signal.aborted || !rootSession) {
|
|
1471
2670
|
return;
|
|
1472
2671
|
}
|
|
2672
|
+
publishMetadata(ctx, true);
|
|
1473
2673
|
agentActive = !ctx.isIdle();
|
|
1474
2674
|
publishState(true);
|
|
1475
2675
|
});
|
|
@@ -1500,6 +2700,8 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1500
2700
|
await shutdownTask;
|
|
1501
2701
|
return;
|
|
1502
2702
|
}
|
|
2703
|
+
releaseClaim?.();
|
|
2704
|
+
releaseClaim = void 0;
|
|
1503
2705
|
const session = ctx.sessionManager;
|
|
1504
2706
|
const task = (async () => {
|
|
1505
2707
|
const shouldClearMetadata = rootSession;
|
|
@@ -1551,7 +2753,23 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1551
2753
|
function herdrAgentState(pi) {
|
|
1552
2754
|
createHerdrAgentStateExtension()(pi);
|
|
1553
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
|
+
}
|
|
1554
2772
|
export {
|
|
1555
|
-
|
|
2773
|
+
herdrIntegration as default
|
|
1556
2774
|
};
|
|
1557
2775
|
//# sourceMappingURL=index.ts.map
|