@howaboua/pi-shepherdr 0.2.5 → 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 +20 -0
- package/README.md +14 -2
- package/index.ts +3 -1
- package/package.json +6 -6
- package/src/agents-answer.ts +108 -0
- package/src/agents-contract.ts +18 -1
- package/src/agents-discovery.ts +211 -0
- package/src/agents-spawn.ts +179 -0
- package/src/agents-tool.ts +24 -202
- package/src/agents-work.ts +194 -0
- package/src/ask-answer.ts +54 -2
- 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 +39 -7
- package/src/monitor.ts +2 -1
- 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-session.mjs +294 -0
- package/src/remote/shepherdr.mjs +98 -236
- package/src/remote-client.ts +126 -17
- package/src/session-reader.ts +58 -0
- package/src/settlement.ts +19 -1
- package/src/shared-context.ts +283 -0
- package/src/types.ts +6 -0
- package/src/agents-operations.ts +0 -413
package/src/fleet.ts
CHANGED
|
@@ -27,6 +27,7 @@ interface Runtime {
|
|
|
27
27
|
attempting?: boolean;
|
|
28
28
|
client?: HerdrConnection;
|
|
29
29
|
config?: SshMachine;
|
|
30
|
+
contextRelayError?: string;
|
|
30
31
|
local: boolean;
|
|
31
32
|
monitor?: AgentMonitor;
|
|
32
33
|
monitoringIssue?: MonitoringIssue;
|
|
@@ -106,6 +107,22 @@ function groupSaved(values: unknown[]): Map<string, unknown[]> {
|
|
|
106
107
|
}
|
|
107
108
|
|
|
108
109
|
export class AgentFleet {
|
|
110
|
+
private contextRelay:
|
|
111
|
+
| ((
|
|
112
|
+
ctx: ExtensionContext,
|
|
113
|
+
request: unknown,
|
|
114
|
+
signal: AbortSignal,
|
|
115
|
+
) => Promise<unknown>)
|
|
116
|
+
| undefined;
|
|
117
|
+
setContextRelay(
|
|
118
|
+
handler: (
|
|
119
|
+
ctx: ExtensionContext,
|
|
120
|
+
request: unknown,
|
|
121
|
+
signal: AbortSignal,
|
|
122
|
+
) => Promise<unknown>,
|
|
123
|
+
): void {
|
|
124
|
+
this.contextRelay = handler;
|
|
125
|
+
}
|
|
109
126
|
private context: ExtensionContext | undefined;
|
|
110
127
|
private generation = 0;
|
|
111
128
|
private readonly pi: ExtensionAPI;
|
|
@@ -342,11 +359,14 @@ export class AgentFleet {
|
|
|
342
359
|
const runtime = this.runtimes.get(target);
|
|
343
360
|
if (!runtime)
|
|
344
361
|
throw new Error(`unknown Herdr machine ${JSON.stringify(target)}`);
|
|
345
|
-
if (
|
|
362
|
+
if (
|
|
363
|
+
runtime.status === "connected" &&
|
|
364
|
+
(runtime.monitoringIssue || runtime.contextRelayError)
|
|
365
|
+
) {
|
|
346
366
|
if (runtime.attempting)
|
|
347
|
-
return `Already retrying
|
|
348
|
-
void this.
|
|
349
|
-
return `Retrying
|
|
367
|
+
return `Already retrying connection setup on ${target}`;
|
|
368
|
+
void this.retrySetup(target, runtime);
|
|
369
|
+
return `Retrying connection setup on ${target}`;
|
|
350
370
|
}
|
|
351
371
|
if (runtime.local) {
|
|
352
372
|
return `${target} is the local machine and is already connected`;
|
|
@@ -364,11 +384,10 @@ export class AgentFleet {
|
|
|
364
384
|
const retries = [...this.runtimes.entries()].filter(
|
|
365
385
|
([, runtime]) =>
|
|
366
386
|
runtime.status === "connected" &&
|
|
367
|
-
runtime.monitoringIssue &&
|
|
387
|
+
(runtime.monitoringIssue || runtime.contextRelayError) &&
|
|
368
388
|
!runtime.attempting,
|
|
369
389
|
);
|
|
370
|
-
for (const [name, runtime] of retries)
|
|
371
|
-
void this.retryMonitoring(name, runtime);
|
|
390
|
+
for (const [name, runtime] of retries) void this.retrySetup(name, runtime);
|
|
372
391
|
const names = [...this.runtimes.entries()]
|
|
373
392
|
.filter(
|
|
374
393
|
([, runtime]) =>
|
|
@@ -383,7 +402,7 @@ export class AgentFleet {
|
|
|
383
402
|
if (names.length > 0 || retries.length > 0) {
|
|
384
403
|
return [
|
|
385
404
|
retries.length > 0
|
|
386
|
-
? `Retrying
|
|
405
|
+
? `Retrying connection setup on ${retries.map(([name]) => name).join(", ")}`
|
|
387
406
|
: "",
|
|
388
407
|
names.length > 0 ? `Connecting to ${names.join(", ")}` : "",
|
|
389
408
|
]
|
|
@@ -473,14 +492,49 @@ export class AgentFleet {
|
|
|
473
492
|
});
|
|
474
493
|
}
|
|
475
494
|
|
|
476
|
-
private async
|
|
495
|
+
private async prepareContextRelay(
|
|
496
|
+
name: string,
|
|
497
|
+
runtime: Runtime,
|
|
498
|
+
client: RemoteHerdrClient,
|
|
499
|
+
ctx: ExtensionContext,
|
|
500
|
+
): Promise<void> {
|
|
501
|
+
if (!this.contextRelay) return;
|
|
502
|
+
try {
|
|
503
|
+
await client.startContextRelay(
|
|
504
|
+
ctx.sessionManager.getSessionId(),
|
|
505
|
+
name,
|
|
506
|
+
(request, signal) => this.contextRelay!(ctx, request, signal),
|
|
507
|
+
);
|
|
508
|
+
if (this.context !== ctx || this.runtimes.get(name) !== runtime) return;
|
|
509
|
+
delete runtime.contextRelayError;
|
|
510
|
+
} catch (error) {
|
|
511
|
+
if (this.context !== ctx || this.runtimes.get(name) !== runtime) return;
|
|
512
|
+
runtime.contextRelayError = errorMessage(error);
|
|
513
|
+
ctx.ui.notify(
|
|
514
|
+
`Context sharing unavailable on ${name}: ${runtime.contextRelayError}\nRun /herdr connect ${name} to retry sharing.`,
|
|
515
|
+
"warning",
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
private async retrySetup(name: string, runtime: Runtime): Promise<void> {
|
|
477
521
|
const monitor = runtime.monitor;
|
|
478
522
|
const ctx = this.context;
|
|
479
523
|
const generation = this.generation;
|
|
480
524
|
if (!monitor || !ctx || runtime.attempting) return;
|
|
481
525
|
runtime.attempting = true;
|
|
482
526
|
try {
|
|
483
|
-
|
|
527
|
+
if (
|
|
528
|
+
runtime.contextRelayError &&
|
|
529
|
+
runtime.client instanceof RemoteHerdrClient
|
|
530
|
+
)
|
|
531
|
+
await this.prepareContextRelay(name, runtime, runtime.client, ctx);
|
|
532
|
+
if (
|
|
533
|
+
this.isCurrent(generation, ctx) &&
|
|
534
|
+
this.runtimes.get(name) === runtime &&
|
|
535
|
+
runtime.monitoringIssue
|
|
536
|
+
)
|
|
537
|
+
await monitor.retryMonitoring();
|
|
484
538
|
} catch (error) {
|
|
485
539
|
if (
|
|
486
540
|
this.isCurrent(generation, ctx) &&
|
|
@@ -526,6 +580,7 @@ export class AgentFleet {
|
|
|
526
580
|
if (runtime.client === client)
|
|
527
581
|
this.disconnected(name, runtime, error.message);
|
|
528
582
|
});
|
|
583
|
+
await this.prepareContextRelay(name, runtime, client, ctx);
|
|
529
584
|
if (
|
|
530
585
|
!this.isCurrent(generation, ctx) ||
|
|
531
586
|
this.runtimes.get(name) !== runtime
|
|
@@ -596,6 +651,7 @@ export class AgentFleet {
|
|
|
596
651
|
runtime.monitor?.deactivate();
|
|
597
652
|
if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
|
|
598
653
|
delete runtime.client;
|
|
654
|
+
delete runtime.contextRelayError;
|
|
599
655
|
delete runtime.monitoringIssue;
|
|
600
656
|
runtime.status = "unavailable";
|
|
601
657
|
delete runtime.attempting;
|
package/src/herdr-client.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createConnection } from "node:net";
|
|
2
|
+
import { requestContext } from "./remote/shepherdr-context.mjs";
|
|
2
3
|
import { sendPeerMessage } from "./remote/shepherdr-peer.mjs";
|
|
3
4
|
import type {
|
|
4
5
|
HerdrEvent,
|
|
@@ -55,6 +56,12 @@ export function isHerdrErrorCode(error: unknown, code: string): boolean {
|
|
|
55
56
|
}
|
|
56
57
|
|
|
57
58
|
export interface HerdrConnection {
|
|
59
|
+
requestContext(
|
|
60
|
+
path: string,
|
|
61
|
+
request: unknown,
|
|
62
|
+
signal?: AbortSignal,
|
|
63
|
+
): Promise<unknown>;
|
|
64
|
+
contextRelayPath(): string;
|
|
58
65
|
request<T>(method: string, params?: object, timeoutMs?: number): Promise<T>;
|
|
59
66
|
sendMessage(agent: PaneInfo, message: PeerMessage): Promise<PeerDelivery>;
|
|
60
67
|
subscribe(
|
|
@@ -67,6 +74,16 @@ export interface HerdrConnection {
|
|
|
67
74
|
|
|
68
75
|
export class HerdrClient implements HerdrConnection {
|
|
69
76
|
readonly socketPath: string;
|
|
77
|
+
requestContext(
|
|
78
|
+
path: string,
|
|
79
|
+
request: unknown,
|
|
80
|
+
signal?: AbortSignal,
|
|
81
|
+
): Promise<unknown> {
|
|
82
|
+
return requestContext(path, request, signal);
|
|
83
|
+
}
|
|
84
|
+
contextRelayPath(): string {
|
|
85
|
+
throw new Error("Local context routes use the controller session");
|
|
86
|
+
}
|
|
70
87
|
|
|
71
88
|
constructor(socketPath = process.env["HERDR_SOCKET_PATH"]) {
|
|
72
89
|
if (!socketPath) {
|
package/src/launch.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { stat } from "node:fs/promises";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
|
+
import { parseArgs } from "@earendil-works/pi-coding-agent";
|
|
3
4
|
import {
|
|
4
5
|
getAgent,
|
|
5
6
|
getPane,
|
|
6
7
|
getSnapshot,
|
|
7
8
|
parsePaneInfo,
|
|
8
9
|
resolveWorkspace,
|
|
10
|
+
sessionPath,
|
|
9
11
|
} from "./herdr.js";
|
|
10
12
|
import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
|
|
11
13
|
import type { PaneInfo } from "./types.js";
|
|
@@ -208,6 +210,12 @@ export async function startAgent(
|
|
|
208
210
|
throw new Error("name must match [a-z][a-z0-9_-]{0,31}");
|
|
209
211
|
}
|
|
210
212
|
const label = params.label?.trim() || name;
|
|
213
|
+
const args = ["--name", label, ...(options.agentArgs ?? [])];
|
|
214
|
+
if (parseArgs(args).noSession) {
|
|
215
|
+
throw new Error(
|
|
216
|
+
"spawn requires a persistent Pi session; remove --no-session from profile pi_args",
|
|
217
|
+
);
|
|
218
|
+
}
|
|
211
219
|
if (params.placement === "pane" && params.cwd) {
|
|
212
220
|
throw new Error(
|
|
213
221
|
"cwd cannot change an existing pane; prepare the pane through Herdr",
|
|
@@ -225,7 +233,7 @@ export async function startAgent(
|
|
|
225
233
|
name,
|
|
226
234
|
kind: "pi",
|
|
227
235
|
pane_id: created.paneId,
|
|
228
|
-
args
|
|
236
|
+
args,
|
|
229
237
|
timeout_ms: 30_000,
|
|
230
238
|
});
|
|
231
239
|
} catch (error) {
|
|
@@ -303,6 +311,7 @@ async function startWhenShellReady(
|
|
|
303
311
|
);
|
|
304
312
|
const terminalId = started.agent.terminal_id;
|
|
305
313
|
const readyDeadline = Date.now() + 30_000;
|
|
314
|
+
let waitingForSession = false;
|
|
306
315
|
while (Date.now() < readyDeadline) {
|
|
307
316
|
let current: PaneInfo;
|
|
308
317
|
try {
|
|
@@ -321,14 +330,14 @@ async function startWhenShellReady(
|
|
|
321
330
|
if (current.agent_status === "blocked") {
|
|
322
331
|
throw new Error(`agent ${name} is blocked during startup`);
|
|
323
332
|
}
|
|
324
|
-
|
|
333
|
+
waitingForSession =
|
|
325
334
|
(current.agent_status === "idle" || current.agent_status === "done") &&
|
|
326
335
|
current.interactive_ready === true &&
|
|
327
|
-
current.agent === "pi"
|
|
328
|
-
) {
|
|
329
|
-
return current;
|
|
330
|
-
|
|
331
|
-
if (
|
|
336
|
+
current.agent === "pi";
|
|
337
|
+
if (waitingForSession) {
|
|
338
|
+
if (sessionPath(current)) return current;
|
|
339
|
+
// Herdr can finish launch before Pi reports its persistent session.
|
|
340
|
+
} else if (
|
|
332
341
|
(current.agent_status === "idle" || current.agent_status === "done") &&
|
|
333
342
|
current.launch_pending === false
|
|
334
343
|
) {
|
|
@@ -336,7 +345,9 @@ async function startWhenShellReady(
|
|
|
336
345
|
}
|
|
337
346
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
338
347
|
}
|
|
339
|
-
throw new Error(
|
|
348
|
+
throw new Error(
|
|
349
|
+
`timed out waiting for agent ${name} ${waitingForSession ? "to register its Pi session" : "to become interactive"}`,
|
|
350
|
+
);
|
|
340
351
|
}
|
|
341
352
|
|
|
342
353
|
async function resolveDuringStart(
|
package/src/messages.ts
CHANGED
|
@@ -22,6 +22,8 @@ const AGENT_EVENT_MESSAGE_TYPE = "herdr-agent-event";
|
|
|
22
22
|
const REALTIME_VOICE_PROMPT_CHANNEL =
|
|
23
23
|
"@howaboua/pi-codex-conversion/realtime-voice-prompt/v1";
|
|
24
24
|
const MAX_REALTIME_VOICE_PROMPT_BYTES = 8 * 1_024;
|
|
25
|
+
const DELEGATED_WORKER_GUIDANCE =
|
|
26
|
+
"When finished or blocked from progressing, end with an assistant reply. Use send only for useful mid-run updates while work can continue. Do not watch your parent or use messaging to wait for a reply.";
|
|
25
27
|
|
|
26
28
|
function xml(value: string): string {
|
|
27
29
|
return value
|
|
@@ -85,6 +87,7 @@ export async function attributeAgentPrompt(
|
|
|
85
87
|
return {
|
|
86
88
|
sender: `<herdr_sender ${sourceAttributes(source)} />`,
|
|
87
89
|
text: message,
|
|
90
|
+
...(kind === "task" ? { context: DELEGATED_WORKER_GUIDANCE } : {}),
|
|
88
91
|
};
|
|
89
92
|
}
|
|
90
93
|
|
|
@@ -102,6 +105,14 @@ interface AgentEventOptions {
|
|
|
102
105
|
status: SettledAgentStatus;
|
|
103
106
|
}
|
|
104
107
|
|
|
108
|
+
export function modelAsk(ask: PendingAsk) {
|
|
109
|
+
return {
|
|
110
|
+
ask_id: ask.toolCallId,
|
|
111
|
+
handoff: ask.handoff,
|
|
112
|
+
prompts: ask.prompts,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
105
116
|
interface AgentEventDetails {
|
|
106
117
|
ask?: PendingAsk;
|
|
107
118
|
blockedOn?: string;
|
|
@@ -205,18 +216,37 @@ function agentVoicePrompt(details: AgentEventDetails): string {
|
|
|
205
216
|
|
|
206
217
|
function announceAgentEvent(
|
|
207
218
|
pi: ExtensionAPI,
|
|
208
|
-
|
|
219
|
+
candidateId: string,
|
|
220
|
+
prompt: string,
|
|
209
221
|
): void {
|
|
210
|
-
const candidateId = `pi-shepherdr:${details.machine}:${details.paneId}`;
|
|
211
222
|
const id =
|
|
212
223
|
new TextEncoder().encode(candidateId).byteLength <= 160
|
|
213
224
|
? candidateId
|
|
214
225
|
: "pi-shepherdr:worker";
|
|
215
|
-
const prompt = agentVoicePrompt(details);
|
|
216
226
|
pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: true, prompt });
|
|
217
227
|
pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: false, prompt });
|
|
218
228
|
}
|
|
219
229
|
|
|
230
|
+
export function announcePeerMessage(
|
|
231
|
+
pi: ExtensionAPI,
|
|
232
|
+
message: PeerMessage,
|
|
233
|
+
): void {
|
|
234
|
+
const source = Object.fromEntries(
|
|
235
|
+
Array.from(
|
|
236
|
+
message.sender.matchAll(/ ([a-z_]+)="([^"]*)"/g),
|
|
237
|
+
([, key, value]) => [key, value],
|
|
238
|
+
),
|
|
239
|
+
);
|
|
240
|
+
if (source["kind"] !== "message" || message.text.startsWith("/")) return;
|
|
241
|
+
announceAgentEvent(
|
|
242
|
+
pi,
|
|
243
|
+
`pi-shepherdr:${source["host"] ?? "local"}:${source["pane"] ?? "peer"}`,
|
|
244
|
+
boundedVoicePrompt(
|
|
245
|
+
`Briefly tell the user the useful update from this peer.\n\nPeer: ${source["host"] ?? "local"} / ${source["name"] || source["pane"] || "unnamed"}\n\nUpdate:\n${message.text.trim()}`,
|
|
246
|
+
),
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
|
|
220
250
|
function operatorCommand(operatorPrefix: string, command: string): string {
|
|
221
251
|
return `\`${operatorPrefix} ${command}\``;
|
|
222
252
|
}
|
|
@@ -313,9 +343,7 @@ function agentEvent(options: AgentEventOptions): {
|
|
|
313
343
|
lines.push(`<blocked_on>${xml(blockedMessage)}</blocked_on>`);
|
|
314
344
|
}
|
|
315
345
|
if (blocked && ask) {
|
|
316
|
-
lines.push(
|
|
317
|
-
`<ask>${xml(JSON.stringify({ handoff: ask.handoff, prompts: ask.prompts }))}</ask>`,
|
|
318
|
-
);
|
|
346
|
+
lines.push(`<ask>${xml(JSON.stringify(modelAsk(ask)))}</ask>`);
|
|
319
347
|
}
|
|
320
348
|
if (blocked) {
|
|
321
349
|
lines.push(
|
|
@@ -370,7 +398,11 @@ export function injectAgentEvent(
|
|
|
370
398
|
delivery,
|
|
371
399
|
);
|
|
372
400
|
if (idle) startPreparedIdleTurn(pi, ctx);
|
|
373
|
-
announceAgentEvent(
|
|
401
|
+
announceAgentEvent(
|
|
402
|
+
pi,
|
|
403
|
+
`pi-shepherdr:${message.details.machine}:${message.details.paneId}`,
|
|
404
|
+
agentVoicePrompt(message.details),
|
|
405
|
+
);
|
|
374
406
|
}
|
|
375
407
|
|
|
376
408
|
export function registerAgentEventRenderer(pi: ExtensionAPI): void {
|
package/src/monitor.ts
CHANGED
|
@@ -166,8 +166,9 @@ export class AgentMonitor {
|
|
|
166
166
|
claimWork(
|
|
167
167
|
attempt: WorkAttempt,
|
|
168
168
|
signal: AbortSignal,
|
|
169
|
+
answeringAskId?: string,
|
|
169
170
|
): Promise<ClaimedSettlement> {
|
|
170
|
-
return this.settlements.claim(attempt, signal);
|
|
171
|
+
return this.settlements.claim(attempt, signal, answeringAskId);
|
|
171
172
|
}
|
|
172
173
|
|
|
173
174
|
releaseWorkClaim(attempt: WorkAttempt | undefined, error: unknown): void {
|
package/src/peer-inbox.ts
CHANGED
|
@@ -8,6 +8,7 @@ import type {
|
|
|
8
8
|
import { sendPolicyMessage, startPreparedIdleTurn } from "./delivery.js";
|
|
9
9
|
import { getCurrentPane } from "./herdr.js";
|
|
10
10
|
import { HerdrClient } from "./herdr-client.js";
|
|
11
|
+
import { announcePeerMessage } from "./messages.js";
|
|
11
12
|
import {
|
|
12
13
|
MAX_PEER_FRAME_BYTES,
|
|
13
14
|
peerInboxPath,
|
|
@@ -168,6 +169,15 @@ async function openInbox(
|
|
|
168
169
|
// Appending then claiming the shared kickoff also coalesces arrivals
|
|
169
170
|
// during async preparation, when Pi still reports itself idle.
|
|
170
171
|
if (idle) startPreparedIdleTurn(pi, ctx);
|
|
172
|
+
// Voice failure must not turn accepted delivery into a retry.
|
|
173
|
+
try {
|
|
174
|
+
announcePeerMessage(pi, { sender: request["sender"], text });
|
|
175
|
+
} catch (error) {
|
|
176
|
+
ctx.ui.notify(
|
|
177
|
+
`Peer voice update failed: ${String(error)}`,
|
|
178
|
+
"warning",
|
|
179
|
+
);
|
|
180
|
+
}
|
|
171
181
|
reply({ ok: true, command: false });
|
|
172
182
|
} catch (error) {
|
|
173
183
|
reply({
|
|
@@ -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
|
+
}
|