@howaboua/pi-shepherdr 0.2.22 → 0.2.24
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 +16 -18
- package/README.md +79 -58
- package/biome.json +1 -1
- package/index.ts +7 -3
- package/package.json +14 -9
- package/src/agents-discovery.ts +42 -27
- package/src/agents-focus.ts +2 -2
- package/src/agents-reply.ts +1 -1
- package/src/agents-spawn.ts +143 -137
- package/src/agents-tool.ts +3 -3
- package/src/agents-work.ts +33 -9
- package/src/attachment-notes.ts +14 -2
- package/src/attachment-protocol.ts +21 -4
- package/src/attachment-routing.ts +1 -1
- package/src/attachment-target.ts +5 -2
- package/src/attachment.ts +2 -3
- package/src/board/host.ts +2 -2
- package/src/board/membership.ts +1 -1
- package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
- package/src/{control-panel.ts → control-panel/index.ts} +4 -4
- package/src/{control-panel-items.ts → control-panel/items.ts} +3 -3
- package/src/{control-panel-view.ts → control-panel/view.ts} +3 -3
- package/src/controller.ts +6 -3
- package/src/fleet/index.ts +384 -0
- package/src/fleet/inspection.ts +141 -0
- package/src/fleet/machine.ts +52 -0
- package/src/fleet/monitor.ts +71 -0
- package/src/fleet/persistence.ts +42 -0
- package/src/fleet/reconnect.ts +75 -0
- package/src/fleet/setup.ts +92 -0
- package/src/launch.ts +14 -2
- package/src/messages/attachments.ts +39 -0
- package/src/messages/attribution.ts +75 -0
- package/src/messages/event-details.ts +69 -0
- package/src/messages/events.ts +189 -0
- package/src/messages/focus.ts +38 -0
- package/src/messages/guidance.ts +83 -0
- package/src/messages/render.ts +89 -0
- package/src/messages/voice-announcements.ts +79 -0
- package/src/monitor-extension-messages.ts +14 -1
- package/src/monitor.ts +4 -2
- package/src/peer-inbox.ts +2 -2
- package/src/profile-prompt.ts +32 -0
- package/src/profiles.ts +5 -25
- package/src/remote/client.ts +127 -0
- package/src/remote/context-relay.ts +84 -0
- package/src/remote/deployment.ts +179 -0
- package/src/remote/focus-channels.ts +89 -0
- package/src/remote/transport.ts +369 -0
- package/src/settlement/collector.ts +122 -0
- package/src/settlement/delivery.ts +144 -0
- package/src/{settlement.ts → settlement/index.ts} +23 -233
- package/src/shared-context-host.ts +33 -11
- package/src/shared-context.ts +10 -4
- package/src/spawn-context.ts +20 -17
- package/src/voice-handoff.ts +1 -1
- package/src/worker-role.ts +83 -0
- package/src/worker-service.ts +74 -89
- package/src/fleet.ts +0 -702
- package/src/messages.ts +0 -629
- package/src/remote-client.ts +0 -751
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type ExtensionAPI,
|
|
3
|
+
getMarkdownTheme,
|
|
4
|
+
} from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
|
|
6
|
+
import {
|
|
7
|
+
AGENT_EVENT_MESSAGE_TYPE,
|
|
8
|
+
type AgentEventDetails,
|
|
9
|
+
eventDetails,
|
|
10
|
+
} from "./event-details.js";
|
|
11
|
+
|
|
12
|
+
export function registerAgentEventRenderer(pi: ExtensionAPI): void {
|
|
13
|
+
pi.registerMessageRenderer<AgentEventDetails>(
|
|
14
|
+
AGENT_EVENT_MESSAGE_TYPE,
|
|
15
|
+
(message, { expanded, outputPad }, theme) => {
|
|
16
|
+
const details = eventDetails(message.details);
|
|
17
|
+
if (!details) {
|
|
18
|
+
const box = new Box(outputPad, 1, (value) =>
|
|
19
|
+
theme.bg("customMessageBg", value),
|
|
20
|
+
);
|
|
21
|
+
box.addChild(
|
|
22
|
+
new Text(
|
|
23
|
+
typeof message.content === "string"
|
|
24
|
+
? message.content
|
|
25
|
+
: "Herdr agent event unavailable",
|
|
26
|
+
0,
|
|
27
|
+
0,
|
|
28
|
+
),
|
|
29
|
+
);
|
|
30
|
+
return box;
|
|
31
|
+
}
|
|
32
|
+
const blocked = details?.state === "blocked";
|
|
33
|
+
const failed = details?.state === "failed";
|
|
34
|
+
const notification = details.state === "extension-message";
|
|
35
|
+
const agentIdentity = details?.name
|
|
36
|
+
? `${details.name} (${details.paneId})`
|
|
37
|
+
: (details?.paneId ?? "unknown");
|
|
38
|
+
const identity = `${details.machineLabel ?? details.machine} / ${agentIdentity}`;
|
|
39
|
+
const title = theme.fg(
|
|
40
|
+
blocked || failed ? "error" : "success",
|
|
41
|
+
`Herdr agent ${identity} · ${notification ? "extension message pending" : blocked ? "blocked" : failed ? "failed" : "finished"}`,
|
|
42
|
+
);
|
|
43
|
+
const location = [details?.workspace, details?.tab]
|
|
44
|
+
.filter(Boolean)
|
|
45
|
+
.join(" / ");
|
|
46
|
+
const metadata = [location, details?.cwd].filter(Boolean).join(" · ");
|
|
47
|
+
const box = new Box(outputPad, 1, (value) =>
|
|
48
|
+
theme.bg("customMessageBg", value),
|
|
49
|
+
);
|
|
50
|
+
box.addChild(new Text(title, 0, 0));
|
|
51
|
+
if (metadata) box.addChild(new Text(theme.fg("dim", metadata), 0, 0));
|
|
52
|
+
if (blocked || notification) {
|
|
53
|
+
box.addChild(new Spacer(1));
|
|
54
|
+
box.addChild(
|
|
55
|
+
new Text(
|
|
56
|
+
theme.fg(
|
|
57
|
+
"warning",
|
|
58
|
+
details?.blockedOn ??
|
|
59
|
+
(notification
|
|
60
|
+
? "Extension message pending"
|
|
61
|
+
: "Agent needs input or approval"),
|
|
62
|
+
),
|
|
63
|
+
0,
|
|
64
|
+
0,
|
|
65
|
+
),
|
|
66
|
+
);
|
|
67
|
+
if (details.extensionMessages && expanded) {
|
|
68
|
+
for (const message of details.extensionMessages) {
|
|
69
|
+
box.addChild(new Spacer(1));
|
|
70
|
+
box.addChild(
|
|
71
|
+
new Markdown(message.message, 0, 0, getMarkdownTheme()),
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (expanded && details?.task) {
|
|
77
|
+
box.addChild(new Spacer(1));
|
|
78
|
+
box.addChild(new Text(theme.fg("muted", "Task"), 0, 0));
|
|
79
|
+
box.addChild(new Markdown(details.task, 0, 0, getMarkdownTheme()));
|
|
80
|
+
}
|
|
81
|
+
if (details?.response) {
|
|
82
|
+
box.addChild(new Spacer(1));
|
|
83
|
+
box.addChild(new Text(theme.fg("muted", "Response"), 0, 0));
|
|
84
|
+
box.addChild(new Markdown(details.response, 0, 0, getMarkdownTheme()));
|
|
85
|
+
}
|
|
86
|
+
return box;
|
|
87
|
+
},
|
|
88
|
+
);
|
|
89
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { PeerMessage } from "../types.js";
|
|
3
|
+
import type { AgentEventDetails } from "./event-details.js";
|
|
4
|
+
|
|
5
|
+
const REALTIME_VOICE_PROMPT_CHANNEL =
|
|
6
|
+
"@howaboua/pi-codex-conversion/realtime-voice-prompt/v1";
|
|
7
|
+
const MAX_REALTIME_VOICE_PROMPT_BYTES = 8 * 1_024;
|
|
8
|
+
|
|
9
|
+
function boundedVoicePrompt(prompt: string): string {
|
|
10
|
+
const bytes = new TextEncoder().encode(prompt);
|
|
11
|
+
if (bytes.byteLength <= MAX_REALTIME_VOICE_PROMPT_BYTES) return prompt;
|
|
12
|
+
return new TextDecoder()
|
|
13
|
+
.decode(bytes.subarray(0, MAX_REALTIME_VOICE_PROMPT_BYTES), {
|
|
14
|
+
stream: true,
|
|
15
|
+
})
|
|
16
|
+
.trimEnd();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function agentVoicePrompt(details: AgentEventDetails): string {
|
|
20
|
+
const lines = [
|
|
21
|
+
`Worker: ${details.machineLabel ?? details.machine} / ${details.name?.trim() || "unnamed"}`,
|
|
22
|
+
`State: ${details.state}`,
|
|
23
|
+
];
|
|
24
|
+
if (details.task?.trim()) lines.push(`Task:\n${details.task.trim()}`);
|
|
25
|
+
let instruction: string;
|
|
26
|
+
if (details.state === "blocked" || details.state === "extension-message") {
|
|
27
|
+
instruction =
|
|
28
|
+
details.state === "extension-message"
|
|
29
|
+
? "Briefly tell the user what this worker reports."
|
|
30
|
+
: "Briefly tell the user why this monitored worker is blocked and what attention may be required.";
|
|
31
|
+
if (details.blockedOn?.trim())
|
|
32
|
+
lines.push(`Reason:\n${details.blockedOn.trim()}`);
|
|
33
|
+
if (details.extensionMessages)
|
|
34
|
+
lines.push(
|
|
35
|
+
...details.extensionMessages.map((message) => message.message),
|
|
36
|
+
);
|
|
37
|
+
} else {
|
|
38
|
+
instruction =
|
|
39
|
+
details.state === "failed"
|
|
40
|
+
? "Briefly tell the user that this monitored worker failed and include useful detail from its report."
|
|
41
|
+
: "Briefly tell the user what this monitored worker found or completed; do not merely announce that it finished.";
|
|
42
|
+
if (details.response?.trim())
|
|
43
|
+
lines.push(`Report:\n${details.response.trim()}`);
|
|
44
|
+
}
|
|
45
|
+
return boundedVoicePrompt(`${instruction}\n\n${lines.join("\n\n")}`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function announceAgentEvent(
|
|
49
|
+
pi: ExtensionAPI,
|
|
50
|
+
candidateId: string,
|
|
51
|
+
prompt: string,
|
|
52
|
+
): void {
|
|
53
|
+
const id =
|
|
54
|
+
new TextEncoder().encode(candidateId).byteLength <= 160
|
|
55
|
+
? candidateId
|
|
56
|
+
: "pi-shepherdr:worker";
|
|
57
|
+
pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: true, prompt });
|
|
58
|
+
pi.events.emit(REALTIME_VOICE_PROMPT_CHANNEL, { id, active: false, prompt });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function announcePeerMessage(
|
|
62
|
+
pi: ExtensionAPI,
|
|
63
|
+
message: PeerMessage,
|
|
64
|
+
): void {
|
|
65
|
+
const source = Object.fromEntries(
|
|
66
|
+
Array.from(
|
|
67
|
+
message.sender.matchAll(/ ([a-z_]+)="([^"]*)"/g),
|
|
68
|
+
([, key, value]) => [key, value],
|
|
69
|
+
),
|
|
70
|
+
);
|
|
71
|
+
if (source["kind"] !== "message" || message.text.startsWith("/")) return;
|
|
72
|
+
announceAgentEvent(
|
|
73
|
+
pi,
|
|
74
|
+
`pi-shepherdr:${source["host"] ?? "local"}:${source["pane"] ?? "peer"}`,
|
|
75
|
+
boundedVoicePrompt(
|
|
76
|
+
`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()}`,
|
|
77
|
+
),
|
|
78
|
+
);
|
|
79
|
+
}
|
|
@@ -9,6 +9,8 @@ import type { ExtensionMessage, MonitoredAgent, PaneInfo } from "./types.js";
|
|
|
9
9
|
|
|
10
10
|
interface MonitorExtensionMessagesOptions {
|
|
11
11
|
client: HerdrConnection;
|
|
12
|
+
machine: string;
|
|
13
|
+
machineLabel: () => string;
|
|
12
14
|
reader: AssistantReader;
|
|
13
15
|
state: MonitorState;
|
|
14
16
|
notify: (
|
|
@@ -176,8 +178,19 @@ export class MonitorExtensionMessages {
|
|
|
176
178
|
private warning(error: unknown): void {
|
|
177
179
|
if (this.warned) return;
|
|
178
180
|
this.warned = true;
|
|
181
|
+
const label = this.options.machineLabel();
|
|
182
|
+
const machine =
|
|
183
|
+
label === this.options.machine
|
|
184
|
+
? label
|
|
185
|
+
: `${label} (${this.options.machine})`;
|
|
186
|
+
const detail =
|
|
187
|
+
error instanceof Error && "code" in error && error.code === "EPIPE"
|
|
188
|
+
? "the connection closed"
|
|
189
|
+
: error instanceof Error
|
|
190
|
+
? error.message
|
|
191
|
+
: String(error);
|
|
179
192
|
this.context?.ui.notify(
|
|
180
|
-
`Worker
|
|
193
|
+
`Worker notices unavailable on ${machine}: ${detail}. Open /herdr → Status to reconnect. Then use agents read to check worker messages.`,
|
|
181
194
|
"warning",
|
|
182
195
|
);
|
|
183
196
|
}
|
package/src/monitor.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type {
|
|
|
5
5
|
import { isSettledStatus } from "./activity.js";
|
|
6
6
|
import { getSnapshot } from "./herdr.js";
|
|
7
7
|
import { type HerdrConnection, isDispatchRejected } from "./herdr-client.js";
|
|
8
|
-
import { injectAgentEvent } from "./messages.js";
|
|
8
|
+
import { injectAgentEvent } from "./messages/events.js";
|
|
9
9
|
import { parseMonitorEvent } from "./monitor-event.js";
|
|
10
10
|
import { MonitorEvents } from "./monitor-events.js";
|
|
11
11
|
import { MonitorExtensionMessages } from "./monitor-extension-messages.js";
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
type ClaimedSettlement,
|
|
16
16
|
SettlementReporter,
|
|
17
17
|
type SettlementRequest,
|
|
18
|
-
} from "./settlement.js";
|
|
18
|
+
} from "./settlement/index.js";
|
|
19
19
|
import type {
|
|
20
20
|
ExtensionReply,
|
|
21
21
|
HerdrEvent,
|
|
@@ -61,6 +61,8 @@ export class AgentMonitor {
|
|
|
61
61
|
const reader = options.reader ?? new SessionReader();
|
|
62
62
|
this.extensionMessages = new MonitorExtensionMessages({
|
|
63
63
|
client: this.client,
|
|
64
|
+
machine: this.machine,
|
|
65
|
+
machineLabel: options.machineLabel,
|
|
64
66
|
reader,
|
|
65
67
|
state: this.state,
|
|
66
68
|
notify: (ctx, record, agent, message) => {
|
package/src/peer-inbox.ts
CHANGED
|
@@ -8,10 +8,10 @@ import type {
|
|
|
8
8
|
import { acceptFocus, readFocus } from "./agents-focus.js";
|
|
9
9
|
import { sendPolicyMessage } from "./delivery.js";
|
|
10
10
|
import { dispatchExtensionReply } from "./extension-reply.js";
|
|
11
|
-
import type { AgentFleet } from "./fleet.js";
|
|
11
|
+
import type { AgentFleet } from "./fleet/index.js";
|
|
12
12
|
import { getCurrentPane } from "./herdr.js";
|
|
13
13
|
import { HerdrClient } from "./herdr-client.js";
|
|
14
|
-
import { announcePeerMessage } from "./messages.js";
|
|
14
|
+
import { announcePeerMessage } from "./messages/voice-announcements.js";
|
|
15
15
|
import { acceptFocusChannel } from "./peer-channel.js";
|
|
16
16
|
import type { createPeerCommands } from "./peer-commands.js";
|
|
17
17
|
import {
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
export const PROFILE_PROMPT_FLAG = "shepherdr-profile-prompt";
|
|
4
|
+
const SECTION = "shepherdr_profile";
|
|
5
|
+
|
|
6
|
+
export function registerProfilePrompt(pi: ExtensionAPI): void {
|
|
7
|
+
pi.registerFlag(PROFILE_PROMPT_FLAG, {
|
|
8
|
+
type: "string",
|
|
9
|
+
description: "JSON-encoded worker profile prompt",
|
|
10
|
+
});
|
|
11
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
12
|
+
const encoded = pi.getFlag(PROFILE_PROMPT_FLAG);
|
|
13
|
+
if (encoded === undefined) return;
|
|
14
|
+
let prompt: unknown;
|
|
15
|
+
try {
|
|
16
|
+
prompt = JSON.parse(String(encoded));
|
|
17
|
+
if (typeof prompt !== "string") throw new Error("Expected a string");
|
|
18
|
+
} catch (cause) {
|
|
19
|
+
await ctx.abort();
|
|
20
|
+
throw new Error("Worker profile prompt is invalid; respawn the worker", {
|
|
21
|
+
cause,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
// Custom sections follow shared project context. Never relocate foreign addenda.
|
|
25
|
+
const options = event.systemPromptOptions;
|
|
26
|
+
if (options.forceSystemPrompt !== undefined) {
|
|
27
|
+
options.forceSystemPrompt += `\n\n<${SECTION}>\n${prompt}\n</${SECTION}>`;
|
|
28
|
+
} else {
|
|
29
|
+
options.sections[SECTION] = prompt;
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|
package/src/profiles.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
import { homedir } from "node:os";
|
|
14
14
|
import { join, resolve } from "node:path";
|
|
15
15
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
16
|
+
import { PROFILE_PROMPT_FLAG } from "./profile-prompt.js";
|
|
16
17
|
|
|
17
18
|
const PROFILE_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
18
19
|
const AGENT_DIRECTORY =
|
|
@@ -33,7 +34,6 @@ export interface AgentProfile {
|
|
|
33
34
|
piArgs: string[];
|
|
34
35
|
prepare?: string;
|
|
35
36
|
prompt?: string;
|
|
36
|
-
promptPath?: string;
|
|
37
37
|
shareContext?: boolean;
|
|
38
38
|
thinking: string;
|
|
39
39
|
}
|
|
@@ -165,7 +165,6 @@ async function readProfile(
|
|
|
165
165
|
...(resolvedPromptPath
|
|
166
166
|
? {
|
|
167
167
|
prompt: await readFile(resolvedPromptPath, "utf8"),
|
|
168
|
-
promptPath: resolvedPromptPath,
|
|
169
168
|
}
|
|
170
169
|
: {}),
|
|
171
170
|
...(prepare ? { prepare } : {}),
|
|
@@ -261,37 +260,18 @@ export async function loadAgentProfiles(): Promise<Map<string, AgentProfile>> {
|
|
|
261
260
|
return profiles;
|
|
262
261
|
}
|
|
263
262
|
|
|
264
|
-
function promptArgument(
|
|
265
|
-
profile: AgentProfile,
|
|
266
|
-
targetLocal: boolean,
|
|
267
|
-
): string | undefined {
|
|
268
|
-
if (
|
|
269
|
-
targetLocal &&
|
|
270
|
-
profile.promptPath &&
|
|
271
|
-
![...profile.promptPath].some((character) => /\p{Cc}/u.test(character))
|
|
272
|
-
) {
|
|
273
|
-
return profile.promptPath;
|
|
274
|
-
}
|
|
275
|
-
return profile.prompt
|
|
276
|
-
?.replace(/\p{Cc}+/gu, " ")
|
|
277
|
-
.replace(/\s+/gu, " ")
|
|
278
|
-
.trim();
|
|
279
|
-
}
|
|
280
|
-
|
|
281
263
|
export function profileAgentArgs(
|
|
282
264
|
profile: AgentProfile,
|
|
283
|
-
options: {
|
|
265
|
+
options: { includePrompt?: boolean } = {},
|
|
284
266
|
): string[] {
|
|
285
|
-
const prompt =
|
|
286
|
-
options.includePrompt === false
|
|
287
|
-
? undefined
|
|
288
|
-
: promptArgument(profile, options.targetLocal !== false);
|
|
267
|
+
const prompt = options.includePrompt === false ? undefined : profile.prompt;
|
|
289
268
|
return [
|
|
290
269
|
"--model",
|
|
291
270
|
profile.model,
|
|
292
271
|
"--thinking",
|
|
293
272
|
profile.thinking,
|
|
294
|
-
|
|
273
|
+
// JSON keeps newlines/control characters out of argv without altering role text.
|
|
274
|
+
...(prompt ? [`--${PROFILE_PROMPT_FLAG}`, JSON.stringify(prompt)] : []),
|
|
295
275
|
...profile.piArgs,
|
|
296
276
|
];
|
|
297
277
|
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type { HerdrConnection } from "../herdr-client.js";
|
|
2
|
+
import type { SshMachine } from "../machine-catalog.js";
|
|
3
|
+
import type { AssistantReader } from "../session-reader.js";
|
|
4
|
+
import type {
|
|
5
|
+
LatestAssistant,
|
|
6
|
+
PaneInfo,
|
|
7
|
+
PeerDelivery,
|
|
8
|
+
PeerMessage,
|
|
9
|
+
SessionView,
|
|
10
|
+
} from "../types.js";
|
|
11
|
+
import { connectRemoteBridge } from "./deployment.js";
|
|
12
|
+
import { readPeerCommands } from "./shepherdr-peer.mjs";
|
|
13
|
+
import { RemoteTransport } from "./transport.js";
|
|
14
|
+
|
|
15
|
+
/** Operation-specific RPC shapes and responses; transport owns all live resources. */
|
|
16
|
+
export class RemoteHerdrClient
|
|
17
|
+
extends RemoteTransport
|
|
18
|
+
implements HerdrConnection, AssistantReader
|
|
19
|
+
{
|
|
20
|
+
static async connect(
|
|
21
|
+
config: SshMachine,
|
|
22
|
+
onClose: (error: Error) => void,
|
|
23
|
+
): Promise<RemoteHerdrClient> {
|
|
24
|
+
const child = await connectRemoteBridge(config);
|
|
25
|
+
const client = new RemoteHerdrClient(child, onClose);
|
|
26
|
+
try {
|
|
27
|
+
await client.ready();
|
|
28
|
+
return client;
|
|
29
|
+
} catch (error) {
|
|
30
|
+
client.close();
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async request<T>(
|
|
36
|
+
method: string,
|
|
37
|
+
params: object = {},
|
|
38
|
+
timeoutMs = 10_000,
|
|
39
|
+
): Promise<T> {
|
|
40
|
+
return (await this.call(
|
|
41
|
+
{ op: "request", method, params, timeoutMs },
|
|
42
|
+
timeoutMs + 1_000,
|
|
43
|
+
)) as T;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async replyExtension(
|
|
47
|
+
agent: PaneInfo,
|
|
48
|
+
reply: import("../types.js").ExtensionReply,
|
|
49
|
+
): Promise<string> {
|
|
50
|
+
const result = await this.call(
|
|
51
|
+
{ op: "extension-reply", agent, reply },
|
|
52
|
+
60_000,
|
|
53
|
+
);
|
|
54
|
+
if (typeof result !== "string")
|
|
55
|
+
throw new Error(
|
|
56
|
+
"Invalid extension reply receipt; inspect the target before retrying",
|
|
57
|
+
);
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async commands(
|
|
62
|
+
agent: PaneInfo,
|
|
63
|
+
): Promise<import("../types.js").PeerCommand[]> {
|
|
64
|
+
const result = await this.call({ op: "commands", agent }, 26_000);
|
|
65
|
+
return readPeerCommands(result);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async sendMessage(
|
|
69
|
+
agent: PaneInfo,
|
|
70
|
+
message: PeerMessage,
|
|
71
|
+
): Promise<PeerDelivery> {
|
|
72
|
+
const result = await this.call(
|
|
73
|
+
{ op: "message", agent, message },
|
|
74
|
+
message.text.trim() === "/quit" ? 0 : 26_000,
|
|
75
|
+
);
|
|
76
|
+
if (
|
|
77
|
+
!result ||
|
|
78
|
+
typeof result !== "object" ||
|
|
79
|
+
!("command" in result) ||
|
|
80
|
+
typeof result.command !== "boolean"
|
|
81
|
+
)
|
|
82
|
+
throw new Error(
|
|
83
|
+
"Invalid peer acknowledgement; inspect the target before retrying",
|
|
84
|
+
);
|
|
85
|
+
return { command: result.command };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async machineIdentity(): Promise<import("../types.js").MachineIdentity> {
|
|
89
|
+
const result = await this.call({ op: "identity" });
|
|
90
|
+
if (
|
|
91
|
+
!result ||
|
|
92
|
+
typeof result !== "object" ||
|
|
93
|
+
!("host" in result) ||
|
|
94
|
+
typeof result.host !== "string" ||
|
|
95
|
+
!("session" in result) ||
|
|
96
|
+
typeof result.session !== "string"
|
|
97
|
+
)
|
|
98
|
+
throw new Error("Could not identify remote Herdr session");
|
|
99
|
+
return { host: result.host, session: result.session };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
focus(
|
|
103
|
+
agent: PaneInfo,
|
|
104
|
+
request: import("../types.js").FocusRequest,
|
|
105
|
+
): Promise<unknown> {
|
|
106
|
+
return this.call({ op: "focus", agent, request }, 60_000);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async latest(path?: string): Promise<LatestAssistant | undefined> {
|
|
110
|
+
return (await this.view(path)).assistant;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async view(path?: string): Promise<SessionView> {
|
|
114
|
+
return (await this.call({ op: "view", path })) as SessionView;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async keybindings(): Promise<Record<string, unknown>> {
|
|
118
|
+
return (await this.call({ op: "keybindings" })) as Record<string, unknown>;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async directory(
|
|
122
|
+
value: string | undefined,
|
|
123
|
+
fallback: string,
|
|
124
|
+
): Promise<string> {
|
|
125
|
+
return (await this.call({ op: "directory", value, fallback })) as string;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
/** Owns relay handlers and incoming cancellation; transport shutdown aborts the whole relay. */
|
|
4
|
+
export class ContextRelay {
|
|
5
|
+
private contextHandler:
|
|
6
|
+
| ((request: unknown, signal: AbortSignal) => Promise<unknown>)
|
|
7
|
+
| undefined;
|
|
8
|
+
private readonly incomingContext = new Map<string, AbortController>();
|
|
9
|
+
private relayPath: string | undefined;
|
|
10
|
+
private readonly child: ChildProcessWithoutNullStreams;
|
|
11
|
+
private readonly closed: () => boolean;
|
|
12
|
+
private readonly maxFrameBytes: number;
|
|
13
|
+
constructor(
|
|
14
|
+
child: ChildProcessWithoutNullStreams,
|
|
15
|
+
closed: () => boolean,
|
|
16
|
+
maxFrameBytes: number,
|
|
17
|
+
) {
|
|
18
|
+
this.child = child;
|
|
19
|
+
this.closed = closed;
|
|
20
|
+
this.maxFrameBytes = maxFrameBytes;
|
|
21
|
+
}
|
|
22
|
+
async start(
|
|
23
|
+
threadId: string,
|
|
24
|
+
routeId: string,
|
|
25
|
+
handler: (request: unknown, signal: AbortSignal) => Promise<unknown>,
|
|
26
|
+
call: (message: Record<string, unknown>) => Promise<unknown>,
|
|
27
|
+
): Promise<void> {
|
|
28
|
+
this.contextHandler = handler;
|
|
29
|
+
const path = await call({ op: "context_relay", threadId, routeId });
|
|
30
|
+
if (typeof path !== "string")
|
|
31
|
+
throw new Error("Invalid shared context relay path");
|
|
32
|
+
this.relayPath = path;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
path(): string {
|
|
36
|
+
if (!this.relayPath)
|
|
37
|
+
throw new Error(
|
|
38
|
+
"Shared context relay is unavailable; open /herdr → Status to retry",
|
|
39
|
+
);
|
|
40
|
+
return this.relayPath;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
consume(id: string, value: Record<string, unknown>): boolean {
|
|
44
|
+
if (value["type"] === "context_cancel") {
|
|
45
|
+
this.incomingContext.get(id)?.abort();
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
if (value["type"] === "context_request") {
|
|
49
|
+
const controller = new AbortController();
|
|
50
|
+
this.incomingContext.set(id, controller);
|
|
51
|
+
const reply = (data: object) => {
|
|
52
|
+
if (this.closed() || controller.signal.aborted) return;
|
|
53
|
+
let frame = `${JSON.stringify({ op: "context_reply", id, ...data })}\n`;
|
|
54
|
+
if (Buffer.byteLength(frame) > this.maxFrameBytes)
|
|
55
|
+
frame = `${JSON.stringify({ op: "context_reply", id, ok: false, error: "Shared context response is too large" })}\n`;
|
|
56
|
+
this.child.stdin.write(frame);
|
|
57
|
+
};
|
|
58
|
+
void Promise.resolve()
|
|
59
|
+
.then(() => {
|
|
60
|
+
if (!this.contextHandler)
|
|
61
|
+
throw new Error("Shared context controller is unavailable");
|
|
62
|
+
controller.signal.throwIfAborted();
|
|
63
|
+
return this.contextHandler(value["request"], controller.signal);
|
|
64
|
+
})
|
|
65
|
+
.then(
|
|
66
|
+
(result) => reply({ ok: true, result }),
|
|
67
|
+
(error: unknown) =>
|
|
68
|
+
reply({
|
|
69
|
+
ok: false,
|
|
70
|
+
error: error instanceof Error ? error.message : String(error),
|
|
71
|
+
}),
|
|
72
|
+
)
|
|
73
|
+
.finally(() => {
|
|
74
|
+
this.incomingContext.delete(id);
|
|
75
|
+
});
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
abortAll() {
|
|
81
|
+
for (const controller of this.incomingContext.values()) controller.abort();
|
|
82
|
+
this.incomingContext.clear();
|
|
83
|
+
}
|
|
84
|
+
}
|