@howaboua/pi-shepherdr 0.2.6 → 0.2.7
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 +12 -0
- package/README.md +11 -1
- package/index.ts +3 -1
- package/package.json +6 -6
- package/src/agents-spawn.ts +35 -24
- package/src/agents-tool.ts +15 -9
- package/src/delivery.ts +14 -3
- package/src/fleet.ts +66 -10
- package/src/herdr-client.ts +17 -0
- package/src/launch.ts +19 -8
- package/src/messages.ts +30 -4
- package/src/peer-inbox.ts +10 -0
- package/src/remote/shepherdr-context.mjs +260 -0
- package/src/remote/shepherdr-peer.mjs +1 -1
- package/src/remote/shepherdr.mjs +94 -4
- package/src/remote-client.ts +123 -21
- package/src/shared-context.ts +283 -0
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
// @howaboua/pi-shepherdr managed bridge
|
|
2
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
3
|
+
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
4
|
+
import { createConnection, createServer } from "node:net";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { readReceiver } from "./shepherdr-peer.mjs";
|
|
8
|
+
|
|
9
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
10
|
+
const TIMEOUT = 35_000;
|
|
11
|
+
|
|
12
|
+
function contextDirectory() {
|
|
13
|
+
return join(
|
|
14
|
+
process.env["PI_CODING_AGENT_DIR"] || join(homedir(), ".pi", "agent"),
|
|
15
|
+
"shepherdr",
|
|
16
|
+
"context",
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** @param {string} threadId @param {string} routeId */
|
|
21
|
+
export function relayContextPath(threadId, routeId) {
|
|
22
|
+
if (typeof threadId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(threadId))
|
|
23
|
+
throw new Error("Invalid context thread ID");
|
|
24
|
+
if (typeof routeId !== "string" || !/^[a-f0-9]{32}$/.test(routeId))
|
|
25
|
+
throw new Error("Invalid context route ID");
|
|
26
|
+
return join(contextDirectory(), `relay-${routeId}-${threadId}.json`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {string} sessionFile */
|
|
30
|
+
export function sessionContextPath(sessionFile) {
|
|
31
|
+
return `${sessionFile}.shepherdr-context.json`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param {unknown} error @param {string} code */
|
|
35
|
+
function hasCode(error, code) {
|
|
36
|
+
return error instanceof Error && "code" in error && error.code === code;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Local authenticated RPC; SSH helpers relay over their existing connection.
|
|
40
|
+
* @param {string} path @param {unknown} request @param {AbortSignal} [signal]
|
|
41
|
+
* @returns {Promise<unknown>} */
|
|
42
|
+
export async function requestContext(path, request, signal) {
|
|
43
|
+
signal?.throwIfAborted();
|
|
44
|
+
let descriptor;
|
|
45
|
+
try {
|
|
46
|
+
descriptor = JSON.parse(await readReceiver(path));
|
|
47
|
+
} catch (error) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
"Shared context owner is unavailable; resume it and reconnect its machine",
|
|
50
|
+
{ cause: error },
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
if (
|
|
54
|
+
descriptor.protocol !== 1 ||
|
|
55
|
+
!Number.isInteger(descriptor.port) ||
|
|
56
|
+
descriptor.port < 1 ||
|
|
57
|
+
descriptor.port > 65535 ||
|
|
58
|
+
typeof descriptor.token !== "string" ||
|
|
59
|
+
!/^[a-f0-9]{64}$/.test(descriptor.token)
|
|
60
|
+
)
|
|
61
|
+
throw new Error("Invalid shared context receiver");
|
|
62
|
+
const id = randomUUID();
|
|
63
|
+
const frame = `${JSON.stringify({ protocol: 1, id, token: descriptor.token, request })}\n`;
|
|
64
|
+
if (Buffer.byteLength(frame) > MAX_BYTES)
|
|
65
|
+
throw new Error("Shared context request is too large");
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
let attempted = false;
|
|
68
|
+
let settled = false;
|
|
69
|
+
let buffer = "";
|
|
70
|
+
const socket = createConnection({
|
|
71
|
+
host: "127.0.0.1",
|
|
72
|
+
port: descriptor.port,
|
|
73
|
+
});
|
|
74
|
+
/** @param {Error} [error] @param {unknown} [result] */
|
|
75
|
+
const finish = (error, result) => {
|
|
76
|
+
if (settled) return;
|
|
77
|
+
settled = true;
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
signal?.removeEventListener("abort", failed);
|
|
80
|
+
socket.destroy();
|
|
81
|
+
if (error) reject(error);
|
|
82
|
+
else resolve(result);
|
|
83
|
+
};
|
|
84
|
+
const failed = () =>
|
|
85
|
+
finish(
|
|
86
|
+
new Error(
|
|
87
|
+
attempted
|
|
88
|
+
? "Shared context response was lost; a write may have completed. Reread the note before retrying"
|
|
89
|
+
: "Shared context owner is unavailable; resume it and reconnect its machine",
|
|
90
|
+
),
|
|
91
|
+
);
|
|
92
|
+
const timer = setTimeout(failed, TIMEOUT);
|
|
93
|
+
timer.unref();
|
|
94
|
+
signal?.addEventListener("abort", failed, { once: true });
|
|
95
|
+
if (signal?.aborted) {
|
|
96
|
+
failed();
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
socket.setEncoding("utf8");
|
|
100
|
+
socket.on("error", failed);
|
|
101
|
+
socket.on("close", failed);
|
|
102
|
+
socket.on("connect", () => {
|
|
103
|
+
attempted = true;
|
|
104
|
+
socket.write(frame);
|
|
105
|
+
});
|
|
106
|
+
socket.on("data", (chunk) => {
|
|
107
|
+
buffer += chunk;
|
|
108
|
+
if (Buffer.byteLength(buffer) > MAX_BYTES) {
|
|
109
|
+
failed();
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const newline = buffer.indexOf("\n");
|
|
113
|
+
if (newline < 0) return;
|
|
114
|
+
try {
|
|
115
|
+
const value = JSON.parse(buffer.slice(0, newline));
|
|
116
|
+
if (value.protocol !== 1 || value.id !== id) {
|
|
117
|
+
failed();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (value.ok === true) finish(undefined, value.result);
|
|
121
|
+
else if (value.ok === false && typeof value.error === "string")
|
|
122
|
+
finish(new Error(value.error));
|
|
123
|
+
else failed();
|
|
124
|
+
} catch {
|
|
125
|
+
failed();
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** @param {string} path @param {(request: unknown, signal: AbortSignal) => Promise<unknown>} handle */
|
|
132
|
+
export async function listenContext(path, handle) {
|
|
133
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
134
|
+
try {
|
|
135
|
+
const previous = JSON.parse(await readFile(path, "utf8"));
|
|
136
|
+
if (Number.isInteger(previous.pid)) {
|
|
137
|
+
let alive = true;
|
|
138
|
+
try {
|
|
139
|
+
process.kill(previous.pid, 0);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (hasCode(error, "ESRCH")) alive = false;
|
|
142
|
+
else throw error;
|
|
143
|
+
}
|
|
144
|
+
if (alive)
|
|
145
|
+
throw new Error(
|
|
146
|
+
"This shared context session is already open; close its other live owner first",
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
} catch (error) {
|
|
150
|
+
if (!hasCode(error, "ENOENT")) throw error;
|
|
151
|
+
}
|
|
152
|
+
const token = randomBytes(32).toString("hex");
|
|
153
|
+
const sockets = new Set();
|
|
154
|
+
const server = createServer((socket) => {
|
|
155
|
+
sockets.add(socket);
|
|
156
|
+
const controller = new AbortController();
|
|
157
|
+
let buffer = "";
|
|
158
|
+
let received = false;
|
|
159
|
+
socket.setEncoding("utf8");
|
|
160
|
+
socket.setTimeout(TIMEOUT, () => socket.destroy());
|
|
161
|
+
socket.on("error", () => socket.destroy());
|
|
162
|
+
socket.on("close", () => {
|
|
163
|
+
sockets.delete(socket);
|
|
164
|
+
controller.abort();
|
|
165
|
+
});
|
|
166
|
+
socket.on("data", (chunk) => {
|
|
167
|
+
if (received) return;
|
|
168
|
+
buffer += chunk;
|
|
169
|
+
if (Buffer.byteLength(buffer) > MAX_BYTES) {
|
|
170
|
+
socket.destroy();
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const newline = buffer.indexOf("\n");
|
|
174
|
+
if (newline < 0) return;
|
|
175
|
+
received = true;
|
|
176
|
+
let value;
|
|
177
|
+
try {
|
|
178
|
+
value = JSON.parse(buffer.slice(0, newline));
|
|
179
|
+
} catch {
|
|
180
|
+
socket.destroy();
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (
|
|
184
|
+
value?.protocol !== 1 ||
|
|
185
|
+
value.token !== token ||
|
|
186
|
+
typeof value.id !== "string"
|
|
187
|
+
) {
|
|
188
|
+
socket.destroy();
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
/** @param {object} data */
|
|
192
|
+
const reply = (data) => {
|
|
193
|
+
const frame = `${JSON.stringify({ protocol: 1, id: value.id, ...data })}\n`;
|
|
194
|
+
if (Buffer.byteLength(frame) > MAX_BYTES)
|
|
195
|
+
socket.end(
|
|
196
|
+
`${JSON.stringify({ protocol: 1, id: value.id, ok: false, error: "Shared context response is too large" })}\n`,
|
|
197
|
+
);
|
|
198
|
+
else socket.end(frame);
|
|
199
|
+
};
|
|
200
|
+
void Promise.resolve()
|
|
201
|
+
.then(() => handle(value.request, controller.signal))
|
|
202
|
+
.then(
|
|
203
|
+
(result) => reply({ ok: true, result }),
|
|
204
|
+
(error) =>
|
|
205
|
+
reply({
|
|
206
|
+
ok: false,
|
|
207
|
+
error: error instanceof Error ? error.message : String(error),
|
|
208
|
+
}),
|
|
209
|
+
);
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
server.maxConnections = 16;
|
|
213
|
+
const temporary = `${path}.${token}.tmp`;
|
|
214
|
+
let closed = false;
|
|
215
|
+
const close = async () => {
|
|
216
|
+
if (closed) return;
|
|
217
|
+
closed = true;
|
|
218
|
+
for (const socket of sockets) socket.destroy();
|
|
219
|
+
await new Promise((resolve) => server.close(resolve));
|
|
220
|
+
try {
|
|
221
|
+
if (JSON.parse(await readFile(path, "utf8")).token === token)
|
|
222
|
+
await unlink(path);
|
|
223
|
+
} catch (error) {
|
|
224
|
+
if (!hasCode(error, "ENOENT")) throw error;
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
try {
|
|
228
|
+
await new Promise((resolve, reject) => {
|
|
229
|
+
server.once("error", reject);
|
|
230
|
+
server.listen(0, "127.0.0.1", () => {
|
|
231
|
+
server.removeListener("error", reject);
|
|
232
|
+
resolve(undefined);
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
const address = server.address();
|
|
236
|
+
if (!address || typeof address === "string")
|
|
237
|
+
throw new Error("Shared context receiver has no address");
|
|
238
|
+
await writeFile(
|
|
239
|
+
temporary,
|
|
240
|
+
JSON.stringify({
|
|
241
|
+
protocol: 1,
|
|
242
|
+
port: address.port,
|
|
243
|
+
token,
|
|
244
|
+
pid: process.pid,
|
|
245
|
+
}),
|
|
246
|
+
{ flag: "wx", mode: 0o600 },
|
|
247
|
+
);
|
|
248
|
+
await rename(temporary, path);
|
|
249
|
+
server.on("error", () => {
|
|
250
|
+
for (const socket of sockets) socket.destroy();
|
|
251
|
+
});
|
|
252
|
+
return close;
|
|
253
|
+
} catch (error) {
|
|
254
|
+
await unlink(temporary).catch((failure) => {
|
|
255
|
+
if (failure.code !== "ENOENT") throw failure;
|
|
256
|
+
});
|
|
257
|
+
await close();
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
}
|
package/src/remote/shepherdr.mjs
CHANGED
|
@@ -3,12 +3,57 @@ import { readFile, stat } from "node:fs/promises";
|
|
|
3
3
|
import { createConnection } from "node:net";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { join, resolve } from "node:path";
|
|
6
|
+
import {
|
|
7
|
+
listenContext,
|
|
8
|
+
relayContextPath,
|
|
9
|
+
requestContext,
|
|
10
|
+
} from "./shepherdr-context.mjs";
|
|
6
11
|
import { sendPeerMessage } from "./shepherdr-peer.mjs";
|
|
7
12
|
import { readSessionView } from "./shepherdr-session.mjs";
|
|
8
13
|
|
|
9
|
-
const BRIDGE_VERSION =
|
|
14
|
+
const BRIDGE_VERSION = 11;
|
|
10
15
|
const MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
|
11
16
|
const subscriptions = new Map();
|
|
17
|
+
const contextRelays = new Map();
|
|
18
|
+
const contextRequests = new Map();
|
|
19
|
+
const contextCalls = new Map();
|
|
20
|
+
|
|
21
|
+
function requestController(request, signal) {
|
|
22
|
+
signal.throwIfAborted();
|
|
23
|
+
const id = crypto.randomUUID();
|
|
24
|
+
return new Promise((resolve, reject) => {
|
|
25
|
+
const finish = (error, result) => {
|
|
26
|
+
if (!contextRequests.delete(id)) return;
|
|
27
|
+
clearTimeout(timer);
|
|
28
|
+
signal.removeEventListener("abort", abort);
|
|
29
|
+
if (error) reject(error);
|
|
30
|
+
else resolve(result);
|
|
31
|
+
};
|
|
32
|
+
const abort = () => {
|
|
33
|
+
send({ type: "context_cancel", id });
|
|
34
|
+
finish(
|
|
35
|
+
new Error(
|
|
36
|
+
"Shared context request cancelled; a write may have completed. Reread before retrying",
|
|
37
|
+
),
|
|
38
|
+
);
|
|
39
|
+
};
|
|
40
|
+
const timer = setTimeout(() => {
|
|
41
|
+
send({ type: "context_cancel", id });
|
|
42
|
+
finish(
|
|
43
|
+
new Error(
|
|
44
|
+
"Shared context controller did not reply; a write may have completed. Reread before retrying",
|
|
45
|
+
),
|
|
46
|
+
);
|
|
47
|
+
}, 35_000);
|
|
48
|
+
timer.unref();
|
|
49
|
+
contextRequests.set(id, {
|
|
50
|
+
resolve: (result) => finish(undefined, result),
|
|
51
|
+
reject: (error) => finish(error),
|
|
52
|
+
});
|
|
53
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
54
|
+
send({ type: "context_request", id, request });
|
|
55
|
+
});
|
|
56
|
+
}
|
|
12
57
|
|
|
13
58
|
function argument(name) {
|
|
14
59
|
const index = process.argv.indexOf(`--${name}`);
|
|
@@ -276,6 +321,25 @@ async function handle(message) {
|
|
|
276
321
|
if (message.op === "message") {
|
|
277
322
|
return sendPeerMessage(request, message.agent, message.message);
|
|
278
323
|
}
|
|
324
|
+
if (message.op === "context") {
|
|
325
|
+
const controller = new AbortController();
|
|
326
|
+
contextCalls.set(message.id, controller);
|
|
327
|
+
try {
|
|
328
|
+
return await requestContext(
|
|
329
|
+
message.path,
|
|
330
|
+
message.request,
|
|
331
|
+
controller.signal,
|
|
332
|
+
);
|
|
333
|
+
} finally {
|
|
334
|
+
contextCalls.delete(message.id);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (message.op === "context_relay") {
|
|
338
|
+
const path = relayContextPath(message.threadId, message.routeId);
|
|
339
|
+
if (!contextRelays.has(path))
|
|
340
|
+
contextRelays.set(path, await listenContext(path, requestController));
|
|
341
|
+
return path;
|
|
342
|
+
}
|
|
279
343
|
if (message.op === "subscribe") {
|
|
280
344
|
await subscribe(message.id, message.subscriptions ?? []);
|
|
281
345
|
return { subscribed: true };
|
|
@@ -313,6 +377,25 @@ process.stdin.on("data", (chunk) => {
|
|
|
313
377
|
send({ id: "invalid", ok: false, error: serializableError(error) });
|
|
314
378
|
continue;
|
|
315
379
|
}
|
|
380
|
+
if (message?.op === "context_cancel") {
|
|
381
|
+
contextCalls.get(message.id)?.abort();
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
if (message?.op === "context_reply") {
|
|
385
|
+
const pending = contextRequests.get(message.id);
|
|
386
|
+
if (pending) {
|
|
387
|
+
if (message.ok === true) pending.resolve(message.result);
|
|
388
|
+
else
|
|
389
|
+
pending.reject(
|
|
390
|
+
new Error(
|
|
391
|
+
typeof message.error === "string"
|
|
392
|
+
? message.error
|
|
393
|
+
: "Shared context controller failed",
|
|
394
|
+
),
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
316
399
|
void handle(message).then(
|
|
317
400
|
(result) => send({ id: message.id, ok: true, result }),
|
|
318
401
|
(error) =>
|
|
@@ -321,11 +404,18 @@ process.stdin.on("data", (chunk) => {
|
|
|
321
404
|
}
|
|
322
405
|
});
|
|
323
406
|
|
|
324
|
-
|
|
407
|
+
async function shutdown() {
|
|
408
|
+
for (const close of subscriptions.values()) close();
|
|
409
|
+
for (const controller of contextCalls.values()) controller.abort();
|
|
410
|
+
await Promise.allSettled([...contextRelays.values()].map((close) => close()));
|
|
411
|
+
process.exit();
|
|
412
|
+
}
|
|
413
|
+
process.stdin.on("end", () => {
|
|
414
|
+
void shutdown();
|
|
415
|
+
});
|
|
325
416
|
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
326
417
|
process.on(signal, () => {
|
|
327
|
-
|
|
328
|
-
process.exit();
|
|
418
|
+
void shutdown();
|
|
329
419
|
});
|
|
330
420
|
}
|
|
331
421
|
|
package/src/remote-client.ts
CHANGED
|
@@ -14,10 +14,11 @@ import type {
|
|
|
14
14
|
SessionView,
|
|
15
15
|
} from "./types.js";
|
|
16
16
|
|
|
17
|
-
const BRIDGE_VERSION =
|
|
17
|
+
const BRIDGE_VERSION = 11;
|
|
18
18
|
const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
|
|
19
19
|
const REMOTE_PEER_HELPER = "~/.pi/agent/shepherdr-peer.mjs";
|
|
20
20
|
const REMOTE_SESSION_HELPER = "~/.pi/agent/shepherdr-session.mjs";
|
|
21
|
+
const REMOTE_CONTEXT_HELPER = "~/.pi/agent/shepherdr-context.mjs";
|
|
21
22
|
const MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
|
22
23
|
const MAX_DIAGNOSTIC_BYTES = 8 * 1024;
|
|
23
24
|
const DEPLOY_TIMEOUT_MS = 20_000;
|
|
@@ -59,6 +60,7 @@ interface PendingCall {
|
|
|
59
60
|
reject: (error: Error) => void;
|
|
60
61
|
resolve: (value: unknown) => void;
|
|
61
62
|
timer: NodeJS.Timeout;
|
|
63
|
+
cleanup?: () => void;
|
|
62
64
|
}
|
|
63
65
|
|
|
64
66
|
interface SubscriptionCallbacks {
|
|
@@ -160,6 +162,11 @@ async function deploy(
|
|
|
160
162
|
}
|
|
161
163
|
|
|
162
164
|
export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
|
|
165
|
+
private contextHandler:
|
|
166
|
+
| ((request: unknown, signal: AbortSignal) => Promise<unknown>)
|
|
167
|
+
| undefined;
|
|
168
|
+
private readonly incomingContext = new Map<string, AbortController>();
|
|
169
|
+
private relayPath: string | undefined;
|
|
163
170
|
private readonly child: ChildProcessWithoutNullStreams;
|
|
164
171
|
private closed = false;
|
|
165
172
|
private diagnostics = "";
|
|
@@ -194,21 +201,30 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
|
|
|
194
201
|
config: SshMachine,
|
|
195
202
|
onClose: (error: Error) => void,
|
|
196
203
|
): Promise<RemoteHerdrClient> {
|
|
197
|
-
const [source, peerSource, sessionSource] =
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
readFile(
|
|
202
|
-
fileURLToPath(new URL("./remote/shepherdr-peer.mjs", import.meta.url)),
|
|
203
|
-
),
|
|
204
|
-
readFile(
|
|
205
|
-
fileURLToPath(
|
|
206
|
-
new URL("./remote/shepherdr-session.mjs", import.meta.url),
|
|
204
|
+
const [source, peerSource, sessionSource, contextSource] =
|
|
205
|
+
await Promise.all([
|
|
206
|
+
readFile(
|
|
207
|
+
fileURLToPath(new URL("./remote/shepherdr.mjs", import.meta.url)),
|
|
207
208
|
),
|
|
208
|
-
|
|
209
|
-
|
|
209
|
+
readFile(
|
|
210
|
+
fileURLToPath(
|
|
211
|
+
new URL("./remote/shepherdr-peer.mjs", import.meta.url),
|
|
212
|
+
),
|
|
213
|
+
),
|
|
214
|
+
readFile(
|
|
215
|
+
fileURLToPath(
|
|
216
|
+
new URL("./remote/shepherdr-session.mjs", import.meta.url),
|
|
217
|
+
),
|
|
218
|
+
),
|
|
219
|
+
readFile(
|
|
220
|
+
fileURLToPath(
|
|
221
|
+
new URL("./remote/shepherdr-context.mjs", import.meta.url),
|
|
222
|
+
),
|
|
223
|
+
),
|
|
224
|
+
]);
|
|
210
225
|
await deploy(config, peerSource, REMOTE_PEER_HELPER);
|
|
211
226
|
await deploy(config, sessionSource, REMOTE_SESSION_HELPER);
|
|
227
|
+
await deploy(config, contextSource, REMOTE_CONTEXT_HELPER);
|
|
212
228
|
await deploy(config, source, REMOTE_HELPER);
|
|
213
229
|
const child = spawnConnector(config, remoteCommand(config));
|
|
214
230
|
const client = new RemoteHerdrClient(child, onClose);
|
|
@@ -232,6 +248,35 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
|
|
|
232
248
|
)) as T;
|
|
233
249
|
}
|
|
234
250
|
|
|
251
|
+
async requestContext(
|
|
252
|
+
path: string,
|
|
253
|
+
request: unknown,
|
|
254
|
+
signal?: AbortSignal,
|
|
255
|
+
): Promise<unknown> {
|
|
256
|
+
signal?.throwIfAborted();
|
|
257
|
+
return this.call({ op: "context", path, request }, 36_000, signal);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async startContextRelay(
|
|
261
|
+
threadId: string,
|
|
262
|
+
routeId: string,
|
|
263
|
+
handler: (request: unknown, signal: AbortSignal) => Promise<unknown>,
|
|
264
|
+
): Promise<void> {
|
|
265
|
+
this.contextHandler = handler;
|
|
266
|
+
const path = await this.call({ op: "context_relay", threadId, routeId });
|
|
267
|
+
if (typeof path !== "string")
|
|
268
|
+
throw new Error("Invalid shared context relay path");
|
|
269
|
+
this.relayPath = path;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
contextRelayPath(): string {
|
|
273
|
+
if (!this.relayPath)
|
|
274
|
+
throw new Error(
|
|
275
|
+
"Shared context relay is unavailable; run /herdr connect to retry",
|
|
276
|
+
);
|
|
277
|
+
return this.relayPath;
|
|
278
|
+
}
|
|
279
|
+
|
|
235
280
|
async sendMessage(
|
|
236
281
|
agent: PaneInfo,
|
|
237
282
|
message: PeerMessage,
|
|
@@ -329,7 +374,9 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
|
|
|
329
374
|
private call(
|
|
330
375
|
message: Record<string, unknown>,
|
|
331
376
|
timeoutMs = 10_000,
|
|
377
|
+
signal?: AbortSignal,
|
|
332
378
|
): Promise<unknown> {
|
|
379
|
+
signal?.throwIfAborted();
|
|
333
380
|
if (this.closed)
|
|
334
381
|
return Promise.reject(
|
|
335
382
|
new Error("remote Shepherdr bridge is unavailable"),
|
|
@@ -337,21 +384,37 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
|
|
|
337
384
|
const id = typeof message["id"] === "string" ? message["id"] : randomUUID();
|
|
338
385
|
return new Promise((resolve, reject) => {
|
|
339
386
|
const timer = setTimeout(() => {
|
|
340
|
-
|
|
341
|
-
|
|
387
|
+
const error = new Error(
|
|
388
|
+
`remote Shepherdr ${String(message["op"])} timed out`,
|
|
342
389
|
);
|
|
390
|
+
if (message["op"] === "context_relay") this.rejectPending(id, error);
|
|
391
|
+
else this.disconnected(error);
|
|
343
392
|
}, timeoutMs);
|
|
344
393
|
timer.unref();
|
|
345
|
-
|
|
394
|
+
const abort = () => {
|
|
395
|
+
if (!this.pending.has(id)) return;
|
|
396
|
+
this.rejectPending(
|
|
397
|
+
id,
|
|
398
|
+
new Error(
|
|
399
|
+
"Shared context request cancelled; a write may have completed. Reread the note before retrying",
|
|
400
|
+
),
|
|
401
|
+
);
|
|
402
|
+
this.child.stdin.write(
|
|
403
|
+
`${JSON.stringify({ op: "context_cancel", id })}\n`,
|
|
404
|
+
);
|
|
405
|
+
};
|
|
406
|
+
this.pending.set(id, {
|
|
407
|
+
resolve,
|
|
408
|
+
reject,
|
|
409
|
+
timer,
|
|
410
|
+
cleanup: () => signal?.removeEventListener("abort", abort),
|
|
411
|
+
});
|
|
412
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
346
413
|
this.child.stdin.write(
|
|
347
414
|
`${JSON.stringify({ ...message, id })}\n`,
|
|
348
415
|
(error) => {
|
|
349
416
|
if (!error) return;
|
|
350
|
-
|
|
351
|
-
if (!pending) return;
|
|
352
|
-
this.pending.delete(id);
|
|
353
|
-
clearTimeout(pending.timer);
|
|
354
|
-
pending.reject(error);
|
|
417
|
+
this.rejectPending(id, error);
|
|
355
418
|
},
|
|
356
419
|
);
|
|
357
420
|
});
|
|
@@ -407,6 +470,40 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
|
|
|
407
470
|
}
|
|
408
471
|
const id = value["id"];
|
|
409
472
|
if (typeof id !== "string") continue;
|
|
473
|
+
if (value["type"] === "context_cancel") {
|
|
474
|
+
this.incomingContext.get(id)?.abort();
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
if (value["type"] === "context_request") {
|
|
478
|
+
const controller = new AbortController();
|
|
479
|
+
this.incomingContext.set(id, controller);
|
|
480
|
+
const reply = (data: object) => {
|
|
481
|
+
if (this.closed || controller.signal.aborted) return;
|
|
482
|
+
let frame = `${JSON.stringify({ op: "context_reply", id, ...data })}\n`;
|
|
483
|
+
if (Buffer.byteLength(frame) > MAX_FRAME_BYTES)
|
|
484
|
+
frame = `${JSON.stringify({ op: "context_reply", id, ok: false, error: "Shared context response is too large" })}\n`;
|
|
485
|
+
this.child.stdin.write(frame);
|
|
486
|
+
};
|
|
487
|
+
void Promise.resolve()
|
|
488
|
+
.then(() => {
|
|
489
|
+
if (!this.contextHandler)
|
|
490
|
+
throw new Error("Shared context controller is unavailable");
|
|
491
|
+
controller.signal.throwIfAborted();
|
|
492
|
+
return this.contextHandler(value["request"], controller.signal);
|
|
493
|
+
})
|
|
494
|
+
.then(
|
|
495
|
+
(result) => reply({ ok: true, result }),
|
|
496
|
+
(error: unknown) =>
|
|
497
|
+
reply({
|
|
498
|
+
ok: false,
|
|
499
|
+
error: error instanceof Error ? error.message : String(error),
|
|
500
|
+
}),
|
|
501
|
+
)
|
|
502
|
+
.finally(() => {
|
|
503
|
+
this.incomingContext.delete(id);
|
|
504
|
+
});
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
410
507
|
if (value["ok"] === true) this.resolvePending(id, value["result"]);
|
|
411
508
|
else {
|
|
412
509
|
const detail = value["error"] as BridgeError | undefined;
|
|
@@ -428,6 +525,7 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
|
|
|
428
525
|
if (!pending) return;
|
|
429
526
|
this.pending.delete(id);
|
|
430
527
|
clearTimeout(pending.timer);
|
|
528
|
+
pending.cleanup?.();
|
|
431
529
|
pending.resolve(value);
|
|
432
530
|
}
|
|
433
531
|
|
|
@@ -436,6 +534,7 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
|
|
|
436
534
|
if (!pending) return;
|
|
437
535
|
this.pending.delete(id);
|
|
438
536
|
clearTimeout(pending.timer);
|
|
537
|
+
pending.cleanup?.();
|
|
439
538
|
pending.reject(error);
|
|
440
539
|
}
|
|
441
540
|
|
|
@@ -447,8 +546,11 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
|
|
|
447
546
|
}
|
|
448
547
|
|
|
449
548
|
private failPending(error: Error, notify: boolean): void {
|
|
549
|
+
for (const controller of this.incomingContext.values()) controller.abort();
|
|
550
|
+
this.incomingContext.clear();
|
|
450
551
|
for (const pending of this.pending.values()) {
|
|
451
552
|
clearTimeout(pending.timer);
|
|
553
|
+
pending.cleanup?.();
|
|
452
554
|
pending.reject(error);
|
|
453
555
|
}
|
|
454
556
|
this.pending.clear();
|