@howaboua/pi-shepherdr 0.2.0 → 0.2.2
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 +8 -4
- package/index.ts +4 -1
- package/package.json +4 -4
- package/src/agents-contract.ts +1 -3
- package/src/agents-operations.ts +50 -14
- package/src/agents-tool.ts +57 -46
- package/src/delivery.ts +76 -1
- package/src/herdr-client.ts +26 -2
- package/src/machine-catalog.ts +27 -10
- package/src/messages.ts +11 -5
- package/src/monitor-state.ts +22 -1
- package/src/monitor.ts +4 -2
- package/src/peer-inbox.ts +237 -0
- package/src/remote/shepherdr-peer.mjs +225 -0
- package/src/remote/shepherdr.mjs +5 -1
- package/src/remote-client.ts +43 -8
- package/src/types.ts +10 -0
- package/tsconfig.json +7 -1
package/src/machine-catalog.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
2
3
|
import { promisify } from "node:util";
|
|
3
4
|
import { type Static, Type } from "typebox";
|
|
4
5
|
import { Check } from "typebox/value";
|
|
@@ -25,20 +26,36 @@ export type SshMachine = Static<typeof Machine>;
|
|
|
25
26
|
export async function readMachineCatalog(): Promise<
|
|
26
27
|
Record<string, SshMachine>
|
|
27
28
|
> {
|
|
29
|
+
const inheritedBinary = process.env["HERDR_BIN_PATH"]?.trim() || "herdr";
|
|
30
|
+
let binary = inheritedBinary;
|
|
31
|
+
const read = (path: string) =>
|
|
32
|
+
promisify(execFile)(path, ["machine", "list", "--json"], {
|
|
33
|
+
timeout: 10_000,
|
|
34
|
+
maxBuffer: 1024 * 1024,
|
|
35
|
+
encoding: "utf8",
|
|
36
|
+
});
|
|
28
37
|
let stdout: string;
|
|
29
38
|
try {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
+
try {
|
|
40
|
+
({ stdout } = await read(binary));
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (
|
|
43
|
+
!(error instanceof Error) ||
|
|
44
|
+
!("code" in error) ||
|
|
45
|
+
error.code !== "ENOENT" ||
|
|
46
|
+
!isAbsolute(binary) ||
|
|
47
|
+
!binary.endsWith(" (deleted)")
|
|
48
|
+
) {
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
// Linux /proc executable paths can retain this suffix after replacement.
|
|
52
|
+
binary = binary.slice(0, -" (deleted)".length);
|
|
53
|
+
({ stdout } = await read(binary));
|
|
54
|
+
}
|
|
39
55
|
} catch (error) {
|
|
40
56
|
throw new Error(
|
|
41
|
-
`Could not read Herdr machines
|
|
57
|
+
`Could not read Herdr machines${binary !== inheritedBinary ? " after retrying stale HERDR_BIN_PATH" : ""}: ${error instanceof Error ? error.message : String(error)}`,
|
|
58
|
+
{ cause: error },
|
|
42
59
|
);
|
|
43
60
|
}
|
|
44
61
|
let value: unknown;
|
package/src/messages.ts
CHANGED
|
@@ -6,13 +6,14 @@ import {
|
|
|
6
6
|
} from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
|
|
8
8
|
import { activityTask } from "./activity.js";
|
|
9
|
-
import { sendPolicyMessage } from "./delivery.js";
|
|
9
|
+
import { sendPolicyMessage, startPreparedIdleTurn } from "./delivery.js";
|
|
10
10
|
import { getCurrentPane, getSnapshot } from "./herdr.js";
|
|
11
11
|
import type { HerdrConnection } from "./herdr-client.js";
|
|
12
12
|
import type {
|
|
13
13
|
LatestAssistant,
|
|
14
14
|
MonitoredAgent,
|
|
15
15
|
PaneInfo,
|
|
16
|
+
PeerMessage,
|
|
16
17
|
PendingAsk,
|
|
17
18
|
SettledAgentStatus,
|
|
18
19
|
} from "./types.js";
|
|
@@ -63,7 +64,7 @@ export async function attributeAgentPrompt(
|
|
|
63
64
|
client: HerdrConnection,
|
|
64
65
|
message: string,
|
|
65
66
|
kind: "message" | "task",
|
|
66
|
-
): Promise<
|
|
67
|
+
): Promise<PeerMessage> {
|
|
67
68
|
const [pane, snapshot] = await Promise.all([
|
|
68
69
|
getCurrentPane(client),
|
|
69
70
|
getSnapshot(client),
|
|
@@ -81,7 +82,10 @@ export async function attributeAgentPrompt(
|
|
|
81
82
|
...(tab ? { tab } : {}),
|
|
82
83
|
}),
|
|
83
84
|
};
|
|
84
|
-
return
|
|
85
|
+
return {
|
|
86
|
+
sender: `<herdr_sender ${sourceAttributes(source)} />`,
|
|
87
|
+
text: message,
|
|
88
|
+
};
|
|
85
89
|
}
|
|
86
90
|
|
|
87
91
|
interface AgentEventOptions {
|
|
@@ -367,8 +371,9 @@ export function injectAgentEvent(
|
|
|
367
371
|
options: AgentEventOptions,
|
|
368
372
|
): void {
|
|
369
373
|
const message = agentEvent(options);
|
|
370
|
-
const
|
|
371
|
-
|
|
374
|
+
const idle = ctx.isIdle();
|
|
375
|
+
const delivery = idle
|
|
376
|
+
? { triggerTurn: false, deliverAs: "steer" as const }
|
|
372
377
|
: { deliverAs: "steer" as const };
|
|
373
378
|
sendPolicyMessage(
|
|
374
379
|
pi,
|
|
@@ -380,6 +385,7 @@ export function injectAgentEvent(
|
|
|
380
385
|
},
|
|
381
386
|
delivery,
|
|
382
387
|
);
|
|
388
|
+
if (idle) startPreparedIdleTurn(pi, ctx);
|
|
383
389
|
announceAgentEvent(pi, message.details);
|
|
384
390
|
}
|
|
385
391
|
|
package/src/monitor-state.ts
CHANGED
|
@@ -44,9 +44,11 @@ interface StatusResult {
|
|
|
44
44
|
|
|
45
45
|
export class MonitorState {
|
|
46
46
|
private readonly agents = new Map<string, MonitoredAgent>();
|
|
47
|
+
private readonly pendingSubmissions = new Set<string>();
|
|
47
48
|
|
|
48
49
|
restore(values: unknown[], controllingPaneId?: string): number {
|
|
49
50
|
this.agents.clear();
|
|
51
|
+
this.pendingSubmissions.clear();
|
|
50
52
|
let dropped = 0;
|
|
51
53
|
for (const value of values) {
|
|
52
54
|
const record = parseMonitoredAgent(value);
|
|
@@ -133,6 +135,7 @@ export class MonitorState {
|
|
|
133
135
|
attemptId: randomUUID(),
|
|
134
136
|
terminalId: record.terminalId,
|
|
135
137
|
};
|
|
138
|
+
this.pendingSubmissions.add(attempt.attemptId);
|
|
136
139
|
this.agents.set(record.terminalId, {
|
|
137
140
|
...record,
|
|
138
141
|
activity: {
|
|
@@ -146,7 +149,12 @@ export class MonitorState {
|
|
|
146
149
|
return attempt;
|
|
147
150
|
}
|
|
148
151
|
|
|
152
|
+
endSubmission(attempt: WorkAttempt | undefined): void {
|
|
153
|
+
if (attempt) this.pendingSubmissions.delete(attempt.attemptId);
|
|
154
|
+
}
|
|
155
|
+
|
|
149
156
|
acceptWork(attempt: WorkAttempt | undefined): boolean {
|
|
157
|
+
this.endSubmission(attempt);
|
|
150
158
|
const record = attempt ? this.byTerminal(attempt.terminalId) : undefined;
|
|
151
159
|
if (
|
|
152
160
|
!record ||
|
|
@@ -170,6 +178,7 @@ export class MonitorState {
|
|
|
170
178
|
}
|
|
171
179
|
|
|
172
180
|
rejectWork(attempt: WorkAttempt | undefined): boolean {
|
|
181
|
+
this.endSubmission(attempt);
|
|
173
182
|
const record = attempt ? this.byTerminal(attempt.terminalId) : undefined;
|
|
174
183
|
if (
|
|
175
184
|
!record ||
|
|
@@ -188,6 +197,13 @@ export class MonitorState {
|
|
|
188
197
|
applyStatus(paneId: string, status: AgentStatus): StatusResult {
|
|
189
198
|
const record = this.byPane(paneId);
|
|
190
199
|
if (!record) return { changed: false };
|
|
200
|
+
// Submission owns the transaction until its receipt decides whether this
|
|
201
|
+
// is delegated work at all. The caller reconciles after accepting it.
|
|
202
|
+
if (
|
|
203
|
+
record.activity.phase === "submitting" &&
|
|
204
|
+
this.pendingSubmissions.has(record.activity.attemptId)
|
|
205
|
+
)
|
|
206
|
+
return { changed: false };
|
|
191
207
|
if (status === "working") {
|
|
192
208
|
const task = activityTask(record.activity);
|
|
193
209
|
const attemptId =
|
|
@@ -283,7 +299,12 @@ export class MonitorState {
|
|
|
283
299
|
|
|
284
300
|
let activity = record.activity;
|
|
285
301
|
let completion: Omit<CompletionCandidate, "record"> | undefined;
|
|
286
|
-
if (
|
|
302
|
+
if (
|
|
303
|
+
activity.phase === "submitting" &&
|
|
304
|
+
this.pendingSubmissions.has(activity.attemptId)
|
|
305
|
+
) {
|
|
306
|
+
// Keep the rollback state until submission is acknowledged.
|
|
307
|
+
} else if (panel.agent_status === "working") {
|
|
287
308
|
const task = activityTask(activity);
|
|
288
309
|
const attemptId =
|
|
289
310
|
activity.phase === "settled" ? undefined : activity.attemptId;
|
package/src/monitor.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type {
|
|
|
4
4
|
} from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { isSettledStatus } from "./activity.js";
|
|
6
6
|
import { getSnapshot } from "./herdr.js";
|
|
7
|
-
import { type HerdrConnection,
|
|
7
|
+
import { type HerdrConnection, isDispatchRejected } from "./herdr-client.js";
|
|
8
8
|
import { parseMonitorEvent } from "./monitor-event.js";
|
|
9
9
|
import { MonitorEvents } from "./monitor-events.js";
|
|
10
10
|
import { MonitorState, type WorkAttempt } from "./monitor-state.js";
|
|
@@ -190,10 +190,12 @@ export class AgentMonitor {
|
|
|
190
190
|
attempt: WorkAttempt | undefined,
|
|
191
191
|
error: unknown,
|
|
192
192
|
): Promise<void> {
|
|
193
|
-
if (
|
|
193
|
+
if (isDispatchRejected(error)) {
|
|
194
194
|
this.rejectWork(attempt);
|
|
195
195
|
return;
|
|
196
196
|
}
|
|
197
|
+
// An unknown acknowledgement must not leave status processing suspended.
|
|
198
|
+
this.state.endSubmission(attempt);
|
|
197
199
|
try {
|
|
198
200
|
await this.reconcileNow();
|
|
199
201
|
} catch (reconcileError) {
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { createServer, type Socket } from "node:net";
|
|
4
|
+
import type {
|
|
5
|
+
ExtensionAPI,
|
|
6
|
+
ExtensionContext,
|
|
7
|
+
} from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { sendPolicyMessage, startPreparedIdleTurn } from "./delivery.js";
|
|
9
|
+
import { getCurrentPane } from "./herdr.js";
|
|
10
|
+
import { HerdrClient } from "./herdr-client.js";
|
|
11
|
+
import {
|
|
12
|
+
MAX_PEER_FRAME_BYTES,
|
|
13
|
+
peerInboxPath,
|
|
14
|
+
} from "./remote/shepherdr-peer.mjs";
|
|
15
|
+
|
|
16
|
+
export function registerPeerInbox(pi: ExtensionAPI): void {
|
|
17
|
+
let close: (() => Promise<void>) | undefined;
|
|
18
|
+
let running = false;
|
|
19
|
+
pi.on("agent_start", () => {
|
|
20
|
+
running = true;
|
|
21
|
+
});
|
|
22
|
+
pi.on("agent_settled", () => {
|
|
23
|
+
running = false;
|
|
24
|
+
});
|
|
25
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
26
|
+
await close?.();
|
|
27
|
+
close = undefined;
|
|
28
|
+
running = false;
|
|
29
|
+
if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"])
|
|
30
|
+
return;
|
|
31
|
+
close = await openInbox(pi, ctx, () => running);
|
|
32
|
+
});
|
|
33
|
+
pi.on("session_shutdown", async () => {
|
|
34
|
+
await close?.();
|
|
35
|
+
close = undefined;
|
|
36
|
+
running = false;
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function openInbox(
|
|
41
|
+
pi: ExtensionAPI,
|
|
42
|
+
ctx: ExtensionContext,
|
|
43
|
+
isRunning: () => boolean,
|
|
44
|
+
): Promise<() => Promise<void>> {
|
|
45
|
+
const sessionFile = ctx.sessionManager.getSessionFile();
|
|
46
|
+
if (!sessionFile)
|
|
47
|
+
throw new Error("Shepherdr peer delivery requires a saved Pi session");
|
|
48
|
+
const pane = await getCurrentPane(new HerdrClient());
|
|
49
|
+
const token = randomBytes(32).toString("hex");
|
|
50
|
+
const path = peerInboxPath(sessionFile, pane.terminal_id);
|
|
51
|
+
const temporary = `${path}.${token}.tmp`;
|
|
52
|
+
const sockets = new Set<Socket>();
|
|
53
|
+
let active = true;
|
|
54
|
+
const server = createServer((socket) => {
|
|
55
|
+
sockets.add(socket);
|
|
56
|
+
socket.setEncoding("utf8");
|
|
57
|
+
socket.setTimeout(10_000, () => socket.destroy());
|
|
58
|
+
socket.on("error", () => socket.destroy());
|
|
59
|
+
socket.on("close", () => sockets.delete(socket));
|
|
60
|
+
let buffer = "";
|
|
61
|
+
let received = false;
|
|
62
|
+
socket.on("data", (chunk: string) => {
|
|
63
|
+
if (received) return;
|
|
64
|
+
buffer += chunk;
|
|
65
|
+
if (Buffer.byteLength(buffer) > MAX_PEER_FRAME_BYTES) {
|
|
66
|
+
socket.destroy();
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const newline = buffer.indexOf("\n");
|
|
70
|
+
if (newline < 0) return;
|
|
71
|
+
received = true;
|
|
72
|
+
let request: Record<string, unknown>;
|
|
73
|
+
try {
|
|
74
|
+
const value: unknown = JSON.parse(buffer.slice(0, newline));
|
|
75
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
76
|
+
throw new Error("Invalid request");
|
|
77
|
+
request = value as Record<string, unknown>;
|
|
78
|
+
} catch {
|
|
79
|
+
socket.destroy();
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const reply = (value: object) =>
|
|
83
|
+
socket.end(
|
|
84
|
+
`${JSON.stringify({ protocol: 1, id: request["id"], ...value })}\n`,
|
|
85
|
+
);
|
|
86
|
+
if (
|
|
87
|
+
!active ||
|
|
88
|
+
request["protocol"] !== 1 ||
|
|
89
|
+
request["token"] !== token ||
|
|
90
|
+
request["sessionFile"] !== sessionFile ||
|
|
91
|
+
request["terminalId"] !== pane.terminal_id ||
|
|
92
|
+
ctx.sessionManager.getSessionFile() !== sessionFile ||
|
|
93
|
+
typeof request["id"] !== "string" ||
|
|
94
|
+
typeof request["text"] !== "string" ||
|
|
95
|
+
!request["text"].trim() ||
|
|
96
|
+
typeof request["sender"] !== "string" ||
|
|
97
|
+
!/^<herdr_sender [^\n]+ \/>$/.test(request["sender"]) ||
|
|
98
|
+
(request["context"] !== undefined &&
|
|
99
|
+
typeof request["context"] !== "string")
|
|
100
|
+
) {
|
|
101
|
+
reply({
|
|
102
|
+
ok: false,
|
|
103
|
+
rejected: true,
|
|
104
|
+
error: "Peer delivery rejected: stale session or invalid request",
|
|
105
|
+
});
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
let submitted = false;
|
|
109
|
+
try {
|
|
110
|
+
const idle = ctx.isIdle();
|
|
111
|
+
// Manual compaction/tree navigation can be busy without an agent
|
|
112
|
+
// loop to consume steering. Do not acknowledge a stranded message.
|
|
113
|
+
if (!idle && !isRunning()) {
|
|
114
|
+
reply({
|
|
115
|
+
ok: false,
|
|
116
|
+
rejected: true,
|
|
117
|
+
error: "Target is changing context; retry after it settles",
|
|
118
|
+
});
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const text = request["text"];
|
|
122
|
+
const sender = request["context"]
|
|
123
|
+
? `${request["sender"]}\n${request["context"]}`
|
|
124
|
+
: request["sender"];
|
|
125
|
+
if (text.startsWith("/")) {
|
|
126
|
+
// Match only Pi's extension-command boundary, not its argument or
|
|
127
|
+
// skill/template parsers. Extension commands may never start a turn.
|
|
128
|
+
const space = text.indexOf(" ");
|
|
129
|
+
const name = text.slice(1, space < 0 ? undefined : space);
|
|
130
|
+
const command = pi
|
|
131
|
+
.getCommands()
|
|
132
|
+
.some(
|
|
133
|
+
(entry) => entry.source === "extension" && entry.name === name,
|
|
134
|
+
);
|
|
135
|
+
const submit = () => {
|
|
136
|
+
submitted = true;
|
|
137
|
+
sendPolicyMessage(
|
|
138
|
+
pi,
|
|
139
|
+
{
|
|
140
|
+
customType: "herdr-agent-source",
|
|
141
|
+
content: sender,
|
|
142
|
+
display: true,
|
|
143
|
+
},
|
|
144
|
+
{ triggerTurn: false, deliverAs: "steer" },
|
|
145
|
+
);
|
|
146
|
+
pi.sendUserMessage(text, {
|
|
147
|
+
expandPromptTemplates: true,
|
|
148
|
+
deliverAs: "steer",
|
|
149
|
+
});
|
|
150
|
+
};
|
|
151
|
+
if (idle && !command) startPreparedIdleTurn(pi, ctx, submit);
|
|
152
|
+
else submit();
|
|
153
|
+
reply({ ok: true, command });
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
submitted = true;
|
|
157
|
+
sendPolicyMessage(
|
|
158
|
+
pi,
|
|
159
|
+
{
|
|
160
|
+
customType: "herdr-agent-message",
|
|
161
|
+
content: `${sender}\n${text}`,
|
|
162
|
+
display: true,
|
|
163
|
+
},
|
|
164
|
+
idle
|
|
165
|
+
? { triggerTurn: false, deliverAs: "steer" }
|
|
166
|
+
: { deliverAs: "steer" },
|
|
167
|
+
);
|
|
168
|
+
// Appending then claiming the shared kickoff also coalesces arrivals
|
|
169
|
+
// during async preparation, when Pi still reports itself idle.
|
|
170
|
+
if (idle) startPreparedIdleTurn(pi, ctx);
|
|
171
|
+
reply({ ok: true, command: false });
|
|
172
|
+
} catch (error) {
|
|
173
|
+
reply({
|
|
174
|
+
ok: false,
|
|
175
|
+
rejected: !submitted,
|
|
176
|
+
error: `${submitted ? "Peer delivery failed; inspect the target before retrying" : "Peer delivery rejected"}: ${error instanceof Error ? error.message : String(error)}`,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
server.maxConnections = 16;
|
|
182
|
+
const stop = async () => {
|
|
183
|
+
if (!active) return;
|
|
184
|
+
active = false;
|
|
185
|
+
for (const socket of sockets) socket.destroy();
|
|
186
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
187
|
+
try {
|
|
188
|
+
const current: unknown = JSON.parse(await readFile(path, "utf8"));
|
|
189
|
+
if (
|
|
190
|
+
current &&
|
|
191
|
+
typeof current === "object" &&
|
|
192
|
+
"token" in current &&
|
|
193
|
+
current.token === token
|
|
194
|
+
)
|
|
195
|
+
await unlink(path);
|
|
196
|
+
} catch (error) {
|
|
197
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
try {
|
|
201
|
+
await new Promise<void>((resolve, reject) => {
|
|
202
|
+
server.once("error", reject);
|
|
203
|
+
server.listen(0, "127.0.0.1", () => {
|
|
204
|
+
server.removeListener("error", reject);
|
|
205
|
+
resolve();
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
server.on("error", (error) => {
|
|
209
|
+
ctx.ui.notify(
|
|
210
|
+
`Shepherdr peer receiver failed: ${error.message}`,
|
|
211
|
+
"error",
|
|
212
|
+
);
|
|
213
|
+
void stop().catch((failure: unknown) =>
|
|
214
|
+
ctx.ui.notify(String(failure), "error"),
|
|
215
|
+
);
|
|
216
|
+
});
|
|
217
|
+
const address = server.address();
|
|
218
|
+
if (!address || typeof address === "string")
|
|
219
|
+
throw new Error("Shepherdr peer receiver has no address");
|
|
220
|
+
await writeFile(
|
|
221
|
+
temporary,
|
|
222
|
+
JSON.stringify({ protocol: 1, port: address.port, token }),
|
|
223
|
+
{ mode: 0o600, flag: "wx" },
|
|
224
|
+
);
|
|
225
|
+
await rename(temporary, path);
|
|
226
|
+
} catch (error) {
|
|
227
|
+
try {
|
|
228
|
+
await unlink(temporary).catch((failure: NodeJS.ErrnoException) => {
|
|
229
|
+
if (failure.code !== "ENOENT") throw failure;
|
|
230
|
+
});
|
|
231
|
+
} finally {
|
|
232
|
+
await stop();
|
|
233
|
+
}
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
return stop;
|
|
237
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// @howaboua/pi-shepherdr managed bridge
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { watch } from "node:fs";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { createConnection } from "node:net";
|
|
6
|
+
import { basename, dirname } from "node:path";
|
|
7
|
+
|
|
8
|
+
export const MAX_PEER_FRAME_BYTES = 8 * 1024 * 1024;
|
|
9
|
+
|
|
10
|
+
/** @param {string} sessionFile @param {string} terminalId */
|
|
11
|
+
export function peerInboxPath(sessionFile, terminalId) {
|
|
12
|
+
const terminal = createHash("sha256")
|
|
13
|
+
.update(terminalId)
|
|
14
|
+
.digest("hex")
|
|
15
|
+
.slice(0, 16);
|
|
16
|
+
return `${sessionFile}.shepherdr-${terminal}.json`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** @param {string} message @param {boolean} rejected */
|
|
20
|
+
function deliveryError(message, rejected) {
|
|
21
|
+
return Object.assign(new Error(message), {
|
|
22
|
+
code: rejected
|
|
23
|
+
? "SHEPHERDR_DELIVERY_REJECTED"
|
|
24
|
+
: "SHEPHERDR_DELIVERY_UNKNOWN",
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** @param {unknown} error */
|
|
29
|
+
function isMissing(error) {
|
|
30
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @param {string} path @returns {Promise<string>} */
|
|
34
|
+
async function readReceiver(path) {
|
|
35
|
+
try {
|
|
36
|
+
return await readFile(path, "utf8");
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (!isMissing(error)) throw error;
|
|
39
|
+
}
|
|
40
|
+
// Herdr can report Pi ready before all session_start handlers complete.
|
|
41
|
+
// Wait for receiver publication, never retry a submitted message.
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
const watcher = watch(dirname(path));
|
|
44
|
+
let settled = false;
|
|
45
|
+
const finish = () => {
|
|
46
|
+
if (settled) return false;
|
|
47
|
+
settled = true;
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
watcher.close();
|
|
50
|
+
return true;
|
|
51
|
+
};
|
|
52
|
+
/** @param {unknown} error */
|
|
53
|
+
const fail = (error) => {
|
|
54
|
+
if (finish()) reject(error);
|
|
55
|
+
};
|
|
56
|
+
const timer = setTimeout(
|
|
57
|
+
() =>
|
|
58
|
+
fail(
|
|
59
|
+
Object.assign(new Error("Receiver not published"), {
|
|
60
|
+
code: "ENOENT",
|
|
61
|
+
}),
|
|
62
|
+
),
|
|
63
|
+
5_000,
|
|
64
|
+
);
|
|
65
|
+
const read = () => {
|
|
66
|
+
void readFile(path, "utf8").then(
|
|
67
|
+
(value) => {
|
|
68
|
+
if (finish()) resolve(value);
|
|
69
|
+
},
|
|
70
|
+
(error) => {
|
|
71
|
+
if (!isMissing(error)) fail(error);
|
|
72
|
+
},
|
|
73
|
+
);
|
|
74
|
+
};
|
|
75
|
+
watcher.on("error", fail);
|
|
76
|
+
watcher.on("change", (_event, file) => {
|
|
77
|
+
if (file === null || file === basename(path)) read();
|
|
78
|
+
});
|
|
79
|
+
read();
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @param {(method: string, params: object) => Promise<unknown>} request
|
|
85
|
+
* @param {import("../types.js").PaneInfo} expected
|
|
86
|
+
* @param {import("../types.js").PeerMessage} message
|
|
87
|
+
* @returns {Promise<import("../types.js").PeerDelivery>}
|
|
88
|
+
*/
|
|
89
|
+
export async function sendPeerMessage(request, expected, message) {
|
|
90
|
+
const result = await request("agent.get", { target: expected.pane_id });
|
|
91
|
+
const agent =
|
|
92
|
+
result &&
|
|
93
|
+
typeof result === "object" &&
|
|
94
|
+
"agent" in result &&
|
|
95
|
+
result.agent &&
|
|
96
|
+
typeof result.agent === "object"
|
|
97
|
+
? result.agent
|
|
98
|
+
: {};
|
|
99
|
+
const session = "agent_session" in agent ? agent.agent_session : undefined;
|
|
100
|
+
const sessionFile =
|
|
101
|
+
session &&
|
|
102
|
+
typeof session === "object" &&
|
|
103
|
+
"kind" in session &&
|
|
104
|
+
session.kind === "path" &&
|
|
105
|
+
"value" in session &&
|
|
106
|
+
typeof session.value === "string"
|
|
107
|
+
? session.value
|
|
108
|
+
: undefined;
|
|
109
|
+
if (
|
|
110
|
+
!("agent" in agent) ||
|
|
111
|
+
agent.agent !== "pi" ||
|
|
112
|
+
!("terminal_id" in agent) ||
|
|
113
|
+
typeof agent.terminal_id !== "string" ||
|
|
114
|
+
agent.terminal_id !== expected.terminal_id ||
|
|
115
|
+
!sessionFile ||
|
|
116
|
+
(expected.agent_session?.kind === "path" &&
|
|
117
|
+
expected.agent_session.value !== sessionFile)
|
|
118
|
+
) {
|
|
119
|
+
throw deliveryError(
|
|
120
|
+
"Target Pi session changed or is not ready; resolve the target again",
|
|
121
|
+
true,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
if ("agent_status" in agent && agent.agent_status === "blocked") {
|
|
125
|
+
throw deliveryError(
|
|
126
|
+
"Target is blocked; answer its pending question first",
|
|
127
|
+
true,
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
let descriptor;
|
|
131
|
+
try {
|
|
132
|
+
descriptor = JSON.parse(
|
|
133
|
+
await readReceiver(peerInboxPath(sessionFile, agent.terminal_id)),
|
|
134
|
+
);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
throw deliveryError(
|
|
137
|
+
isMissing(error)
|
|
138
|
+
? "Target has no native Shepherdr receiver; update and reload Shepherdr in the target Pi session"
|
|
139
|
+
: `Could not read target Shepherdr receiver: ${error instanceof Error ? error.message : String(error)}`,
|
|
140
|
+
true,
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
if (
|
|
144
|
+
descriptor?.protocol !== 1 ||
|
|
145
|
+
!Number.isInteger(descriptor.port) ||
|
|
146
|
+
descriptor.port < 1 ||
|
|
147
|
+
descriptor.port > 65535 ||
|
|
148
|
+
typeof descriptor.token !== "string" ||
|
|
149
|
+
!/^[a-f0-9]{64}$/.test(descriptor.token)
|
|
150
|
+
) {
|
|
151
|
+
throw deliveryError(
|
|
152
|
+
"Target Shepherdr receiver is invalid; reload the target Pi session",
|
|
153
|
+
true,
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
const id = randomUUID();
|
|
157
|
+
const frame =
|
|
158
|
+
JSON.stringify({
|
|
159
|
+
protocol: 1,
|
|
160
|
+
id,
|
|
161
|
+
token: descriptor.token,
|
|
162
|
+
sessionFile,
|
|
163
|
+
terminalId: agent.terminal_id,
|
|
164
|
+
text: message.text,
|
|
165
|
+
sender: message.sender,
|
|
166
|
+
context: message.context,
|
|
167
|
+
}) + "\n";
|
|
168
|
+
if (Buffer.byteLength(frame) > MAX_PEER_FRAME_BYTES) {
|
|
169
|
+
throw deliveryError("Peer message is too large", true);
|
|
170
|
+
}
|
|
171
|
+
return new Promise((resolve, reject) => {
|
|
172
|
+
let attempted = false;
|
|
173
|
+
let settled = false;
|
|
174
|
+
let buffer = "";
|
|
175
|
+
const socket = createConnection({
|
|
176
|
+
host: "127.0.0.1",
|
|
177
|
+
port: descriptor.port,
|
|
178
|
+
});
|
|
179
|
+
/** @param {unknown} [error] @param {import("../types.js").PeerDelivery} [receipt] */
|
|
180
|
+
const finish = (error, receipt) => {
|
|
181
|
+
if (settled) return;
|
|
182
|
+
settled = true;
|
|
183
|
+
clearTimeout(timer);
|
|
184
|
+
socket.destroy();
|
|
185
|
+
if (error) reject(error);
|
|
186
|
+
else if (receipt) resolve(receipt);
|
|
187
|
+
};
|
|
188
|
+
const failed = () =>
|
|
189
|
+
finish(
|
|
190
|
+
deliveryError(
|
|
191
|
+
attempted
|
|
192
|
+
? "Peer delivery was not acknowledged; inspect the target before retrying"
|
|
193
|
+
: "Target Shepherdr receiver is unavailable; reload the target Pi session",
|
|
194
|
+
!attempted,
|
|
195
|
+
),
|
|
196
|
+
);
|
|
197
|
+
const timer = setTimeout(failed, 10_000);
|
|
198
|
+
timer.unref();
|
|
199
|
+
socket.setEncoding("utf8");
|
|
200
|
+
socket.on("error", failed);
|
|
201
|
+
socket.on("end", failed);
|
|
202
|
+
socket.on("close", failed);
|
|
203
|
+
socket.on("connect", () => {
|
|
204
|
+
attempted = true;
|
|
205
|
+
socket.write(frame);
|
|
206
|
+
});
|
|
207
|
+
socket.on("data", (chunk) => {
|
|
208
|
+
buffer += chunk;
|
|
209
|
+
if (Buffer.byteLength(buffer) > MAX_PEER_FRAME_BYTES) return failed();
|
|
210
|
+
const newline = buffer.indexOf("\n");
|
|
211
|
+
if (newline < 0) return;
|
|
212
|
+
try {
|
|
213
|
+
const reply = JSON.parse(buffer.slice(0, newline));
|
|
214
|
+
if (reply.protocol !== 1 || reply.id !== id) return failed();
|
|
215
|
+
if (reply.ok === true && typeof reply.command === "boolean")
|
|
216
|
+
finish(undefined, { command: reply.command });
|
|
217
|
+
else if (reply.ok === false && typeof reply.error === "string")
|
|
218
|
+
finish(deliveryError(reply.error, reply.rejected === true));
|
|
219
|
+
else failed();
|
|
220
|
+
} catch {
|
|
221
|
+
failed();
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
}
|
package/src/remote/shepherdr.mjs
CHANGED
|
@@ -3,8 +3,9 @@ import { open, readFile, stat } from "node:fs/promises";
|
|
|
3
3
|
import { createConnection } from "node:net";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { sendPeerMessage } from "./shepherdr-peer.mjs";
|
|
6
7
|
|
|
7
|
-
const BRIDGE_VERSION =
|
|
8
|
+
const BRIDGE_VERSION = 6;
|
|
8
9
|
const MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
|
9
10
|
const READ_CHUNK_BYTES = 64 * 1024;
|
|
10
11
|
const subscriptions = new Map();
|
|
@@ -500,6 +501,9 @@ async function handle(message) {
|
|
|
500
501
|
if (message.op === "request") {
|
|
501
502
|
return request(message.method, message.params ?? {}, message.timeoutMs);
|
|
502
503
|
}
|
|
504
|
+
if (message.op === "message") {
|
|
505
|
+
return sendPeerMessage(request, message.agent, message.message);
|
|
506
|
+
}
|
|
503
507
|
if (message.op === "subscribe") {
|
|
504
508
|
await subscribe(message.id, message.subscriptions ?? []);
|
|
505
509
|
return { subscribed: true };
|