@howaboua/pi-shepherdr 0.2.27 → 0.2.28-core.12.1.gda85fa2e8a0f
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/README.md +48 -48
- package/index.ts +7 -1
- package/package.json +2 -9
- package/src/agent-identity.ts +3 -3
- package/src/agents-contract.ts +10 -14
- package/src/agents-discovery.ts +34 -54
- package/src/agents-focus.ts +23 -35
- package/src/agents-spawn.ts +24 -23
- package/src/agents-tool.ts +4 -19
- package/src/agents-work.ts +4 -3
- package/src/attachment-notes.ts +8 -7
- package/src/attachment-protocol.ts +3 -2
- package/src/attachment-routing.ts +1 -1
- package/src/attachment-target.ts +10 -18
- package/src/attachment.ts +14 -9
- package/src/board/discovery.ts +67 -0
- package/src/board/host.ts +93 -63
- package/src/board/membership.ts +16 -11
- package/src/board/records.ts +185 -0
- package/src/close-idle.ts +2 -9
- package/src/context-briefing.ts +230 -0
- package/src/context-routing.ts +1 -1
- package/src/control-panel/index.ts +2 -4
- package/src/control-panel/items.ts +1 -11
- package/src/control-panel/view.ts +3 -9
- package/src/controller.ts +50 -63
- package/src/core/AGENTS.md +7 -4
- package/src/core/admission-broker.mjs +235 -0
- package/src/core/admission-endpoint.ts +180 -0
- package/src/core/admission-owner.mjs +52 -0
- package/src/core/admission-startup.ts +130 -0
- package/src/core/admission.ts +181 -0
- package/src/core/agents.ts +102 -0
- package/src/core/backend.ts +110 -84
- package/src/core/client.ts +16 -0
- package/src/core/focus-channel-helper.mjs +6 -27
- package/src/core/focus-channel-wire.mjs +9 -6
- package/src/core/focus-channel.ts +5 -3
- package/src/core/focus-window.ts +15 -4
- package/src/core/helper-bootstrap.mjs +70 -0
- package/src/core/helper-context.mjs +98 -0
- package/src/core/helper-core.mjs +121 -0
- package/src/core/machines.ts +30 -0
- package/src/core/registration.ts +7 -2
- package/src/core/remote-endpoint.ts +80 -74
- package/src/core/remote-helper.ts +330 -0
- package/src/core/remote-reader.ts +3 -42
- package/src/core/remote-service.mjs +239 -0
- package/src/core/remote-transport.ts +290 -0
- package/src/core/spawn.ts +20 -20
- package/src/core/terminal-peer.mjs +57 -0
- package/src/core/terminal.ts +4 -2
- package/src/delivery.ts +39 -0
- package/src/fleet/catalog.ts +16 -58
- package/src/fleet/connection.ts +9 -18
- package/src/fleet/index.ts +38 -76
- package/src/fleet/inspection.ts +9 -22
- package/src/fleet/machine.ts +28 -12
- package/src/fleet/monitor.ts +8 -29
- package/src/fleet/persistence.ts +2 -2
- package/src/fleet/reconnect.ts +5 -3
- package/src/fleet/setup.ts +6 -16
- package/src/launch-contract.ts +0 -3
- package/src/launch-location.ts +4 -132
- package/src/launch.ts +18 -144
- package/src/messages/attachments.ts +1 -1
- package/src/messages/attribution.ts +9 -14
- package/src/messages/events.ts +5 -9
- package/src/messages/focus.ts +2 -7
- package/src/messages/guidance.ts +2 -43
- package/src/messages/peer-sharing.ts +133 -0
- package/src/monitor-events.ts +14 -43
- package/src/monitor-extension-messages.ts +5 -6
- package/src/monitor-record.ts +4 -0
- package/src/monitor-state.ts +1 -101
- package/src/monitor.ts +38 -66
- package/src/notes-discovery.ts +67 -0
- package/src/peer-inbox.ts +21 -27
- package/src/remote/context-relay.ts +25 -10
- package/src/remote/notes-reader.mjs +67 -0
- package/src/remote/shepherdr-channel.mjs +1 -1
- package/src/remote/shepherdr-checkpoints.mjs +49 -102
- package/src/remote/shepherdr-context.mjs +1 -1
- package/src/remote/shepherdr-peer.mjs +19 -24
- package/src/remote/shepherdr-session.mjs +18 -7
- package/src/saved-context.ts +62 -0
- package/src/settlement/collector.ts +29 -9
- package/src/settlement/index.ts +35 -6
- package/src/shared-context-host.ts +27 -33
- package/src/shared-context.ts +44 -15
- package/src/spawn-context.ts +11 -3
- package/src/spawn-ownership.ts +1 -1
- package/src/ssh-setup.ts +40 -73
- package/src/types.ts +4 -8
- package/src/voice-handoff.ts +1 -1
- package/src/widget.ts +7 -2
- package/src/worker-ownership.ts +2 -8
- package/src/worker-service.ts +6 -14
- package/src/core/context-relay.mjs +0 -111
- package/src/core/remote-exec.ts +0 -122
- package/src/core/remote-helper.mjs +0 -244
- package/src/core/remote-relay.ts +0 -191
- package/src/core/request.ts +0 -124
- package/src/herdr-client.ts +0 -364
- package/src/herdr.ts +0 -268
- package/src/machine-catalog.ts +0 -83
- package/src/monitor-event.ts +0 -84
- package/src/remote/client.ts +0 -127
- package/src/remote/deployment.ts +0 -179
- package/src/remote/focus-channels.ts +0 -89
- package/src/remote/shepherdr.mjs +0 -504
- package/src/remote/transport.ts +0 -369
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises";
|
|
2
|
+
import { homedir, hostname } from "node:os";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
const NOTES_UNAVAILABLE =
|
|
6
|
+
"Saved Notes reads are unavailable. Install Notes Compaction or Agent Comms alongside Shepherdr on the controller, then reload Pi. Other agent operations remain available.";
|
|
7
|
+
|
|
8
|
+
/** Operations that need the selected Core's filesystem or authenticated Pi peers. */
|
|
9
|
+
export async function serve(input, send, fail) {
|
|
10
|
+
const [
|
|
11
|
+
{ localCore },
|
|
12
|
+
peer,
|
|
13
|
+
session,
|
|
14
|
+
watch,
|
|
15
|
+
context,
|
|
16
|
+
{ helperContext },
|
|
17
|
+
pi,
|
|
18
|
+
{ terminalPeer },
|
|
19
|
+
] = await Promise.all([
|
|
20
|
+
import(input.modules.core),
|
|
21
|
+
import(input.modules.peer),
|
|
22
|
+
import(input.modules.session),
|
|
23
|
+
import(input.modules.watch),
|
|
24
|
+
import(input.modules.context),
|
|
25
|
+
import(input.modules.contextHost),
|
|
26
|
+
import(input.modules.pi),
|
|
27
|
+
import(input.modules.terminal),
|
|
28
|
+
]);
|
|
29
|
+
const core = localCore(process.env.HC_TERMINAL_SOCKET);
|
|
30
|
+
const terminals = terminalPeer((method, params) =>
|
|
31
|
+
core.request(method, params),
|
|
32
|
+
);
|
|
33
|
+
const subscriptions = new Map();
|
|
34
|
+
const relay = helperContext(context, send);
|
|
35
|
+
let savedSession;
|
|
36
|
+
let savedSessionIndex;
|
|
37
|
+
let closed = false;
|
|
38
|
+
const close = async () => {
|
|
39
|
+
if (closed) return;
|
|
40
|
+
closed = true;
|
|
41
|
+
for (const subscription of subscriptions.values()) subscription();
|
|
42
|
+
subscriptions.clear();
|
|
43
|
+
core.close();
|
|
44
|
+
await relay.close();
|
|
45
|
+
};
|
|
46
|
+
try {
|
|
47
|
+
const hello = await core.request("hello");
|
|
48
|
+
if (
|
|
49
|
+
hello.core.id !== input.coreId ||
|
|
50
|
+
(process.env.HC_SESSION ?? "default") !== input.session
|
|
51
|
+
)
|
|
52
|
+
throw new Error(
|
|
53
|
+
"Remote Core identity changed; refresh machines before retrying",
|
|
54
|
+
);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
await close();
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
const local = (terminal) =>
|
|
60
|
+
typeof terminal.address === "string" && !terminal.address.includes("/");
|
|
61
|
+
const localEvent = (event) => {
|
|
62
|
+
if (event.method === "snapshot" || event.method === "missed")
|
|
63
|
+
return { ...event, terminals: event.terminals.filter(local) };
|
|
64
|
+
if (
|
|
65
|
+
event.method === "event" &&
|
|
66
|
+
(!event.event.terminal || event.event.terminal.includes("/"))
|
|
67
|
+
)
|
|
68
|
+
return;
|
|
69
|
+
return event;
|
|
70
|
+
};
|
|
71
|
+
async function list() {
|
|
72
|
+
// The local snapshot never fans out to, or silently omits, slow remote Cores.
|
|
73
|
+
let terminals;
|
|
74
|
+
const subscription = core.subscribe(
|
|
75
|
+
{},
|
|
76
|
+
(event) => {
|
|
77
|
+
if (event.method === "snapshot")
|
|
78
|
+
terminals = event.terminals.filter(local);
|
|
79
|
+
},
|
|
80
|
+
() => {},
|
|
81
|
+
);
|
|
82
|
+
try {
|
|
83
|
+
await subscription.ready;
|
|
84
|
+
return { terminals };
|
|
85
|
+
} finally {
|
|
86
|
+
subscription.close();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async function handle(message) {
|
|
90
|
+
switch (message.op) {
|
|
91
|
+
case "core":
|
|
92
|
+
return message.method === "terminal.list"
|
|
93
|
+
? list()
|
|
94
|
+
: core.request(message.method, message.params);
|
|
95
|
+
case "identity":
|
|
96
|
+
return { host: hostname(), session: input.coreId };
|
|
97
|
+
case "pi-executable":
|
|
98
|
+
return pi.piExecutable(message.cwd);
|
|
99
|
+
case "message":
|
|
100
|
+
return peer.sendPeerMessage(terminals, message.agent, message.message);
|
|
101
|
+
case "focus":
|
|
102
|
+
return peer.sendPeerFocus(terminals, message.agent, message.focus);
|
|
103
|
+
case "commands":
|
|
104
|
+
return peer.sendPeerCommands(terminals, message.agent);
|
|
105
|
+
case "reply":
|
|
106
|
+
return peer.sendPeerExtensionReply(
|
|
107
|
+
terminals,
|
|
108
|
+
message.agent,
|
|
109
|
+
message.reply,
|
|
110
|
+
);
|
|
111
|
+
case "context":
|
|
112
|
+
return relay.request(message.id, (signal) =>
|
|
113
|
+
context.requestContext(message.path, message.request, signal),
|
|
114
|
+
);
|
|
115
|
+
case "saved_session":
|
|
116
|
+
return relay.request(message.id, async (signal) => {
|
|
117
|
+
if (!input.modules.savedSession) throw new Error(NOTES_UNAVAILABLE);
|
|
118
|
+
if (
|
|
119
|
+
typeof message.path !== "string" ||
|
|
120
|
+
typeof message.history !== "boolean"
|
|
121
|
+
)
|
|
122
|
+
throw new Error("Invalid saved session location");
|
|
123
|
+
const reader = await (savedSession ??= import(
|
|
124
|
+
input.modules.savedSession
|
|
125
|
+
));
|
|
126
|
+
const result = await reader.readSavedNotesSession(
|
|
127
|
+
message.path,
|
|
128
|
+
signal,
|
|
129
|
+
message.history,
|
|
130
|
+
);
|
|
131
|
+
if (Buffer.byteLength(JSON.stringify(result)) > 7 * 1024 * 1024)
|
|
132
|
+
throw new Error(
|
|
133
|
+
"Saved session is too large to transfer; open it on its machine to read it",
|
|
134
|
+
);
|
|
135
|
+
return result;
|
|
136
|
+
});
|
|
137
|
+
case "find_saved_sessions":
|
|
138
|
+
return relay.request(message.id, async (signal) => {
|
|
139
|
+
if (!input.modules.savedSessionIndex)
|
|
140
|
+
throw new Error(NOTES_UNAVAILABLE);
|
|
141
|
+
if (typeof message.threadId !== "string")
|
|
142
|
+
throw new Error("Invalid saved session identity");
|
|
143
|
+
const index = await (savedSessionIndex ??= import(
|
|
144
|
+
input.modules.savedSessionIndex
|
|
145
|
+
));
|
|
146
|
+
const result = await index.findSavedNotesSessions(
|
|
147
|
+
message.threadId,
|
|
148
|
+
undefined,
|
|
149
|
+
signal,
|
|
150
|
+
);
|
|
151
|
+
if (Buffer.byteLength(JSON.stringify(result)) > 7 * 1024 * 1024)
|
|
152
|
+
throw new Error(
|
|
153
|
+
"Saved session lookup is too large to transfer; open the session on its machine",
|
|
154
|
+
);
|
|
155
|
+
return result;
|
|
156
|
+
});
|
|
157
|
+
case "context_relay":
|
|
158
|
+
return relay.start(message.threadId, message.routeId);
|
|
159
|
+
case "view":
|
|
160
|
+
return session.readSessionView(message.path);
|
|
161
|
+
case "directory": {
|
|
162
|
+
const expand = (value) =>
|
|
163
|
+
value === "~"
|
|
164
|
+
? homedir()
|
|
165
|
+
: value.startsWith("~/")
|
|
166
|
+
? resolve(homedir(), value.slice(2))
|
|
167
|
+
: value;
|
|
168
|
+
const path = resolve(
|
|
169
|
+
expand(message.fallback),
|
|
170
|
+
expand(message.value?.trim() || "."),
|
|
171
|
+
);
|
|
172
|
+
if (!(await stat(path)).isDirectory())
|
|
173
|
+
throw new Error("Remote working directory is not a directory");
|
|
174
|
+
return path;
|
|
175
|
+
}
|
|
176
|
+
case "subscribe": {
|
|
177
|
+
const subscription = core.subscribe(
|
|
178
|
+
message.filter ?? {},
|
|
179
|
+
(event) => {
|
|
180
|
+
const value = localEvent(event);
|
|
181
|
+
if (value) send({ subscription: message.id, event: value });
|
|
182
|
+
},
|
|
183
|
+
fail,
|
|
184
|
+
);
|
|
185
|
+
subscriptions.set(message.id, subscription.close);
|
|
186
|
+
await subscription.ready;
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
case "watch": {
|
|
190
|
+
const stop = watch.watchSessions(
|
|
191
|
+
message.paths,
|
|
192
|
+
(path) => send({ subscription: message.id, path }),
|
|
193
|
+
fail,
|
|
194
|
+
);
|
|
195
|
+
subscriptions.set(message.id, stop);
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
case "unsubscribe":
|
|
199
|
+
subscriptions.get(message.subscription)?.();
|
|
200
|
+
subscriptions.delete(message.subscription);
|
|
201
|
+
return true;
|
|
202
|
+
default:
|
|
203
|
+
throw new Error("Unknown remote operation");
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
close,
|
|
208
|
+
receive(message) {
|
|
209
|
+
if (closed) return;
|
|
210
|
+
if (
|
|
211
|
+
!message ||
|
|
212
|
+
typeof message.id !== "string" ||
|
|
213
|
+
typeof message.op !== "string"
|
|
214
|
+
)
|
|
215
|
+
throw new Error("Invalid remote request");
|
|
216
|
+
if (relay.consume(message)) return;
|
|
217
|
+
void handle(message)
|
|
218
|
+
.then(
|
|
219
|
+
(result) => {
|
|
220
|
+
if (!closed) send({ id: message.id, ok: true, result });
|
|
221
|
+
},
|
|
222
|
+
(error) => {
|
|
223
|
+
if (!closed)
|
|
224
|
+
send({
|
|
225
|
+
id: message.id,
|
|
226
|
+
ok: false,
|
|
227
|
+
error: {
|
|
228
|
+
message: error.message,
|
|
229
|
+
code: error.code,
|
|
230
|
+
kind: error.kind,
|
|
231
|
+
hint: error.hint,
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
},
|
|
235
|
+
)
|
|
236
|
+
.catch(fail);
|
|
237
|
+
},
|
|
238
|
+
};
|
|
239
|
+
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { ContextRelay } from "../remote/context-relay.js";
|
|
3
|
+
import type {
|
|
4
|
+
CoreRequestOptions,
|
|
5
|
+
CoreSubscribeOptions,
|
|
6
|
+
CoreSubscription,
|
|
7
|
+
} from "./client.js";
|
|
8
|
+
import type { CoreMachine } from "./machines.js";
|
|
9
|
+
import {
|
|
10
|
+
type CoreNotification,
|
|
11
|
+
type CoreObject,
|
|
12
|
+
notification,
|
|
13
|
+
object,
|
|
14
|
+
snapshot,
|
|
15
|
+
} from "./protocol.js";
|
|
16
|
+
import { openRemoteHelper, type RemoteHelper } from "./remote-helper.js";
|
|
17
|
+
|
|
18
|
+
interface Pending {
|
|
19
|
+
resolve(value: unknown): void;
|
|
20
|
+
reject(error: Error): void;
|
|
21
|
+
timer: NodeJS.Timeout | undefined;
|
|
22
|
+
cleanup(): void;
|
|
23
|
+
}
|
|
24
|
+
interface Subscription {
|
|
25
|
+
receive(message: CoreObject): void;
|
|
26
|
+
close(error?: Error): void;
|
|
27
|
+
}
|
|
28
|
+
const relayOwners = new Map<string, CoreRemoteTransport>();
|
|
29
|
+
|
|
30
|
+
/** One owner for helper lifetime, requests, subscriptions and reverse context calls. */
|
|
31
|
+
export class CoreRemoteTransport {
|
|
32
|
+
private readonly lifetime = new AbortController();
|
|
33
|
+
private readonly starting: Promise<RemoteHelper>;
|
|
34
|
+
private helper: RemoteHelper | undefined;
|
|
35
|
+
private readonly pending = new Map<string, Pending>();
|
|
36
|
+
private readonly subscriptions = new Map<string, Subscription>();
|
|
37
|
+
private readonly relay: ContextRelay;
|
|
38
|
+
private ended: Error | undefined;
|
|
39
|
+
private closing: Promise<void> | undefined;
|
|
40
|
+
private route: string | undefined;
|
|
41
|
+
private relayFailure: ((error: Error) => void) | undefined;
|
|
42
|
+
private readonly socketPath: string;
|
|
43
|
+
private readonly machine: CoreMachine;
|
|
44
|
+
constructor(socketPath: string, machine: CoreMachine) {
|
|
45
|
+
this.socketPath = socketPath;
|
|
46
|
+
this.machine = machine;
|
|
47
|
+
this.relay = new ContextRelay(
|
|
48
|
+
(message) => this.send(message),
|
|
49
|
+
() => !!this.ended,
|
|
50
|
+
8 * 1024 * 1024,
|
|
51
|
+
(error) => {
|
|
52
|
+
void this.close(error);
|
|
53
|
+
},
|
|
54
|
+
);
|
|
55
|
+
this.starting = openRemoteHelper(
|
|
56
|
+
socketPath,
|
|
57
|
+
machine,
|
|
58
|
+
(message) => this.receive(message),
|
|
59
|
+
(error) => {
|
|
60
|
+
void this.close(error);
|
|
61
|
+
},
|
|
62
|
+
this.lifetime.signal,
|
|
63
|
+
);
|
|
64
|
+
void this.starting.then(
|
|
65
|
+
(helper) => {
|
|
66
|
+
this.helper = helper;
|
|
67
|
+
},
|
|
68
|
+
(error: unknown) => {
|
|
69
|
+
void this.close(
|
|
70
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
71
|
+
);
|
|
72
|
+
},
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
async call(
|
|
76
|
+
message: CoreObject,
|
|
77
|
+
options: CoreRequestOptions = {},
|
|
78
|
+
): Promise<unknown> {
|
|
79
|
+
options.signal?.throwIfAborted();
|
|
80
|
+
if (this.ended) throw this.ended;
|
|
81
|
+
const id = typeof message["id"] === "string" ? message["id"] : randomUUID();
|
|
82
|
+
return new Promise((resolve, reject) => {
|
|
83
|
+
const cancel = (reason: string) => {
|
|
84
|
+
this.finish(
|
|
85
|
+
id,
|
|
86
|
+
new Error(
|
|
87
|
+
`Remote request ${reason}; it may already have completed. Inspect the target before retrying`,
|
|
88
|
+
),
|
|
89
|
+
);
|
|
90
|
+
try {
|
|
91
|
+
if (!this.ended && this.helper)
|
|
92
|
+
this.send({ op: "context_cancel", id });
|
|
93
|
+
} catch (error) {
|
|
94
|
+
void this.close(
|
|
95
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
const abort = () => cancel("cancelled");
|
|
100
|
+
const timeout = options.timeoutMs ?? 30_000;
|
|
101
|
+
const timer =
|
|
102
|
+
timeout === 0
|
|
103
|
+
? undefined
|
|
104
|
+
: setTimeout(() => cancel("timed out"), timeout);
|
|
105
|
+
this.pending.set(id, {
|
|
106
|
+
resolve,
|
|
107
|
+
reject,
|
|
108
|
+
timer,
|
|
109
|
+
cleanup: () => options.signal?.removeEventListener("abort", abort),
|
|
110
|
+
});
|
|
111
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
112
|
+
void this.starting
|
|
113
|
+
.then(() => {
|
|
114
|
+
if (this.pending.has(id)) this.send({ ...message, id });
|
|
115
|
+
})
|
|
116
|
+
.catch((error: unknown) =>
|
|
117
|
+
this.finish(
|
|
118
|
+
id,
|
|
119
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
120
|
+
),
|
|
121
|
+
);
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
private send(message: CoreObject): void {
|
|
125
|
+
if (this.ended || !this.helper)
|
|
126
|
+
throw this.ended ?? new Error("Remote connection is not ready");
|
|
127
|
+
this.helper.send(message);
|
|
128
|
+
}
|
|
129
|
+
private finish(id: string, error?: Error, result?: unknown): void {
|
|
130
|
+
const pending = this.pending.get(id);
|
|
131
|
+
if (!pending) return;
|
|
132
|
+
this.pending.delete(id);
|
|
133
|
+
clearTimeout(pending.timer);
|
|
134
|
+
pending.cleanup();
|
|
135
|
+
if (error) pending.reject(error);
|
|
136
|
+
else pending.resolve(result);
|
|
137
|
+
}
|
|
138
|
+
private receive(message: CoreObject): void {
|
|
139
|
+
if (this.ended) return;
|
|
140
|
+
if (typeof message["subscription"] === "string") {
|
|
141
|
+
this.subscriptions.get(message["subscription"])?.receive(message);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const id = message["id"];
|
|
145
|
+
if (typeof id !== "string")
|
|
146
|
+
throw new Error("Remote response has no request identity");
|
|
147
|
+
if (this.relay.consume(id, message)) return;
|
|
148
|
+
if (message["ok"] === true) this.finish(id, undefined, message["result"]);
|
|
149
|
+
else {
|
|
150
|
+
const detail = object(message["error"]);
|
|
151
|
+
const error = new Error(
|
|
152
|
+
typeof detail["message"] === "string"
|
|
153
|
+
? detail["message"]
|
|
154
|
+
: "Remote request failed",
|
|
155
|
+
);
|
|
156
|
+
for (const key of ["code", "kind", "hint"])
|
|
157
|
+
if (typeof detail[key] === "string")
|
|
158
|
+
Object.assign(error, { [key]: detail[key] });
|
|
159
|
+
this.finish(id, error);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async subscribe(
|
|
163
|
+
filter: CoreObject,
|
|
164
|
+
onEvent: (event: CoreNotification) => void,
|
|
165
|
+
options: CoreSubscribeOptions = {},
|
|
166
|
+
): Promise<CoreSubscription> {
|
|
167
|
+
let resolveClosed: (error?: Error) => void = () => {};
|
|
168
|
+
const closed = new Promise<Error | undefined>((resolve) => {
|
|
169
|
+
resolveClosed = resolve;
|
|
170
|
+
});
|
|
171
|
+
const close = await this.listen(
|
|
172
|
+
{ op: "subscribe", filter },
|
|
173
|
+
(message) => {
|
|
174
|
+
const event = object(message["event"]);
|
|
175
|
+
if (
|
|
176
|
+
!["snapshot", "missed", "event", "heartbeat"].includes(
|
|
177
|
+
String(event["method"]),
|
|
178
|
+
)
|
|
179
|
+
)
|
|
180
|
+
throw new Error("Invalid remote event");
|
|
181
|
+
onEvent(
|
|
182
|
+
event["method"] === "snapshot"
|
|
183
|
+
? { method: "snapshot", ...snapshot(event) }
|
|
184
|
+
: notification({
|
|
185
|
+
jsonrpc: "2.0",
|
|
186
|
+
method: event["method"],
|
|
187
|
+
params: event["method"] === "event" ? event["event"] : event,
|
|
188
|
+
}),
|
|
189
|
+
);
|
|
190
|
+
},
|
|
191
|
+
resolveClosed,
|
|
192
|
+
options,
|
|
193
|
+
);
|
|
194
|
+
return { closed, close };
|
|
195
|
+
}
|
|
196
|
+
async watch(
|
|
197
|
+
paths: string[],
|
|
198
|
+
onChange: (path: string) => void,
|
|
199
|
+
onError: (error: Error) => void,
|
|
200
|
+
signal: AbortSignal,
|
|
201
|
+
): Promise<() => void> {
|
|
202
|
+
return this.listen(
|
|
203
|
+
{ op: "watch", paths },
|
|
204
|
+
(message) => {
|
|
205
|
+
const path = message["path"];
|
|
206
|
+
if (typeof path !== "string" || !paths.includes(path))
|
|
207
|
+
throw new Error("Invalid remote session change");
|
|
208
|
+
onChange(path);
|
|
209
|
+
},
|
|
210
|
+
(error) => {
|
|
211
|
+
if (error && !signal.aborted) onError(error);
|
|
212
|
+
},
|
|
213
|
+
{ signal },
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
private async listen(
|
|
217
|
+
message: CoreObject,
|
|
218
|
+
receive: Subscription["receive"],
|
|
219
|
+
onClose: Subscription["close"],
|
|
220
|
+
options: CoreRequestOptions,
|
|
221
|
+
): Promise<() => void> {
|
|
222
|
+
options.signal?.throwIfAborted();
|
|
223
|
+
const id = randomUUID();
|
|
224
|
+
const close = (error?: Error) => {
|
|
225
|
+
if (!this.subscriptions.delete(id)) return;
|
|
226
|
+
options.signal?.removeEventListener("abort", abort);
|
|
227
|
+
onClose(error);
|
|
228
|
+
if (!this.ended)
|
|
229
|
+
void this.call({ op: "unsubscribe", subscription: id }).catch(() => {});
|
|
230
|
+
};
|
|
231
|
+
const abort = () => close();
|
|
232
|
+
this.subscriptions.set(id, { receive, close });
|
|
233
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
234
|
+
try {
|
|
235
|
+
await this.call({ ...message, id }, options);
|
|
236
|
+
options.signal?.throwIfAborted();
|
|
237
|
+
return () => close();
|
|
238
|
+
} catch (error) {
|
|
239
|
+
close(error instanceof Error ? error : new Error(String(error)));
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
async startContextRelay(
|
|
244
|
+
threadId: string,
|
|
245
|
+
handler: (request: unknown, signal: AbortSignal) => Promise<unknown>,
|
|
246
|
+
onFailure: (error: Error) => void,
|
|
247
|
+
): Promise<void> {
|
|
248
|
+
const route = JSON.stringify([this.socketPath, this.machine.id, threadId]);
|
|
249
|
+
const previous = relayOwners.get(route);
|
|
250
|
+
if (previous && previous !== this) await previous.close();
|
|
251
|
+
if (this.ended) throw this.ended;
|
|
252
|
+
this.route = route;
|
|
253
|
+
this.relayFailure = onFailure;
|
|
254
|
+
relayOwners.set(route, this);
|
|
255
|
+
await this.relay.start(
|
|
256
|
+
threadId,
|
|
257
|
+
createHash("sha256").update(this.machine.id).digest("hex").slice(0, 32),
|
|
258
|
+
handler,
|
|
259
|
+
(message) => this.call(message),
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
contextRelayPath(): string {
|
|
263
|
+
if (this.ended) throw this.ended;
|
|
264
|
+
return this.relay.path();
|
|
265
|
+
}
|
|
266
|
+
close(error?: Error): Promise<void> {
|
|
267
|
+
if (this.closing) return this.closing;
|
|
268
|
+
if (this.ended) return Promise.resolve();
|
|
269
|
+
this.ended = error ?? new Error("Remote connection closed");
|
|
270
|
+
// Abort startup promptly; its owner still awaits any accepted terminal.run
|
|
271
|
+
// and cleans that terminal before the replacement route may start.
|
|
272
|
+
if (!this.helper) this.lifetime.abort();
|
|
273
|
+
this.relay.abortAll();
|
|
274
|
+
for (const id of this.pending.keys()) this.finish(id, this.ended);
|
|
275
|
+
for (const subscription of [...this.subscriptions.values()])
|
|
276
|
+
subscription.close(this.ended);
|
|
277
|
+
this.closing = this.starting
|
|
278
|
+
.then(
|
|
279
|
+
(helper) => helper.close(),
|
|
280
|
+
() => {},
|
|
281
|
+
)
|
|
282
|
+
.finally(() => {
|
|
283
|
+
this.lifetime.abort();
|
|
284
|
+
if (this.route && relayOwners.get(this.route) === this)
|
|
285
|
+
relayOwners.delete(this.route);
|
|
286
|
+
});
|
|
287
|
+
if (error) this.relayFailure?.(error);
|
|
288
|
+
return this.closing;
|
|
289
|
+
}
|
|
290
|
+
}
|
package/src/core/spawn.ts
CHANGED
|
@@ -1,28 +1,24 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import {
|
|
3
|
-
RolledBackAgentLaunchError,
|
|
4
3
|
type StartAgentParams,
|
|
5
4
|
type StartedAgent,
|
|
6
5
|
UnstartedAgentLaunchError,
|
|
7
6
|
} from "../launch-contract.js";
|
|
7
|
+
import { rollbackCreatedLocation } from "../launch-location.js";
|
|
8
8
|
import type { CoreConnection } from "./backend.js";
|
|
9
9
|
import { piExecutable } from "./pi-executable.mjs";
|
|
10
10
|
import { object } from "./protocol.js";
|
|
11
11
|
import { RemoteCoreEndpoint } from "./remote-endpoint.js";
|
|
12
|
-
import { remoteExec } from "./remote-exec.js";
|
|
13
12
|
import { terminalPane, terminalSnapshot } from "./terminal.js";
|
|
14
13
|
|
|
15
14
|
export async function startCoreAgent(
|
|
16
15
|
client: CoreConnection,
|
|
17
16
|
params: StartAgentParams,
|
|
18
17
|
cwd: string,
|
|
19
|
-
_label: string,
|
|
20
18
|
args: string[],
|
|
19
|
+
signal?: AbortSignal,
|
|
21
20
|
): Promise<StartedAgent> {
|
|
22
|
-
|
|
23
|
-
throw new Error(
|
|
24
|
-
"Core cannot launch a program inside an existing terminal without terminal input. Use terminal placement for a background worker or new_tab/new_workspace for a Herdr window location.",
|
|
25
|
-
);
|
|
21
|
+
signal?.throwIfAborted();
|
|
26
22
|
const labels: Record<string, string> = {};
|
|
27
23
|
if (params.placement === "new_tab") {
|
|
28
24
|
const snapshot = terminalSnapshot(
|
|
@@ -49,13 +45,14 @@ export async function startCoreAgent(
|
|
|
49
45
|
}
|
|
50
46
|
const executable =
|
|
51
47
|
client.core instanceof RemoteCoreEndpoint
|
|
52
|
-
? await
|
|
48
|
+
? await client.core.call({
|
|
53
49
|
op: "pi-executable",
|
|
54
50
|
cwd,
|
|
55
51
|
})
|
|
56
52
|
: await piExecutable(cwd);
|
|
57
53
|
if (typeof executable !== "string" || !executable)
|
|
58
54
|
throw new Error("Could not resolve Pi on the target machine");
|
|
55
|
+
signal?.throwIfAborted();
|
|
59
56
|
const result = object(
|
|
60
57
|
await client.core.request("terminal.run", {
|
|
61
58
|
argv: [executable, ...args],
|
|
@@ -74,28 +71,26 @@ export async function startCoreAgent(
|
|
|
74
71
|
throw new Error(
|
|
75
72
|
"Core launch returned no local terminal address; inspect Core terminals before retrying",
|
|
76
73
|
);
|
|
77
|
-
const cleanup = {
|
|
74
|
+
const cleanup = { id: terminal };
|
|
78
75
|
try {
|
|
76
|
+
signal?.throwIfAborted();
|
|
79
77
|
await client.core.request("terminal.label", {
|
|
80
78
|
terminal,
|
|
81
79
|
labels: { "pi.shepherdr.name": params.name },
|
|
82
80
|
});
|
|
83
|
-
const agent = await waitReady(client, terminal);
|
|
81
|
+
const agent = await waitReady(client, terminal, signal);
|
|
82
|
+
signal?.throwIfAborted();
|
|
84
83
|
return { agent, id: terminal, cleanup };
|
|
85
84
|
} catch (error) {
|
|
86
|
-
|
|
87
|
-
await client.request(cleanup.method, { id: cleanup.id });
|
|
88
|
-
} catch (cleanupError) {
|
|
89
|
-
throw new Error(
|
|
90
|
-
`${String(error)}; cleanup failed: ${String(cleanupError)}`,
|
|
91
|
-
{ cause: error },
|
|
92
|
-
);
|
|
93
|
-
}
|
|
94
|
-
throw new RolledBackAgentLaunchError(error);
|
|
85
|
+
return rollbackCreatedLocation(client, cleanup, error);
|
|
95
86
|
}
|
|
96
87
|
}
|
|
97
88
|
|
|
98
|
-
async function waitReady(
|
|
89
|
+
async function waitReady(
|
|
90
|
+
client: CoreConnection,
|
|
91
|
+
terminal: string,
|
|
92
|
+
signal?: AbortSignal,
|
|
93
|
+
) {
|
|
99
94
|
const abort = new AbortController();
|
|
100
95
|
let chain = Promise.resolve();
|
|
101
96
|
let resolve!: (agent: ReturnType<typeof terminalPane>) => void;
|
|
@@ -104,6 +99,10 @@ async function waitReady(client: CoreConnection, terminal: string) {
|
|
|
104
99
|
resolve = yes;
|
|
105
100
|
reject = no;
|
|
106
101
|
});
|
|
102
|
+
const cancelled = () =>
|
|
103
|
+
reject(signal?.reason ?? new Error("Agent launch cancelled"));
|
|
104
|
+
signal?.addEventListener("abort", cancelled, { once: true });
|
|
105
|
+
if (signal?.aborted) cancelled();
|
|
107
106
|
const inspect = (value: unknown) => {
|
|
108
107
|
const record = object(value);
|
|
109
108
|
if (record["state"] !== "live")
|
|
@@ -172,6 +171,7 @@ async function waitReady(client: CoreConnection, terminal: string) {
|
|
|
172
171
|
return agent;
|
|
173
172
|
} finally {
|
|
174
173
|
clearTimeout(timer);
|
|
174
|
+
signal?.removeEventListener("abort", cancelled);
|
|
175
175
|
abort.abort();
|
|
176
176
|
}
|
|
177
177
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** @typedef {Pick<import('../types.js').PaneInfo, 'pane_id' | 'terminal_id' | 'agent' | 'agent_session'>} PeerTerminal */
|
|
2
|
+
/** @typedef {{terminal:(address:string)=>Promise<PeerTerminal>,closeTerminal:(address:string)=>Promise<void>}} TerminalPeer */
|
|
3
|
+
|
|
4
|
+
/** Native terminal identity and lifecycle shared by local and bundled peer delivery.
|
|
5
|
+
* @param {(method:string,params:Record<string,unknown>)=>Promise<unknown>} request
|
|
6
|
+
* @returns {TerminalPeer}
|
|
7
|
+
*/
|
|
8
|
+
export function terminalPeer(request) {
|
|
9
|
+
/** @param {string} address */
|
|
10
|
+
async function get(address) {
|
|
11
|
+
if (!/^t[1-9][0-9bcdfghjkmnpqrstvwxyz]*$/.test(address))
|
|
12
|
+
throw new Error("Use an exact terminal address from this machine");
|
|
13
|
+
const value = await request("terminal.get", { terminal: address });
|
|
14
|
+
if (
|
|
15
|
+
!value ||
|
|
16
|
+
typeof value !== "object" ||
|
|
17
|
+
!("address" in value) ||
|
|
18
|
+
value.address !== address ||
|
|
19
|
+
!("state" in value)
|
|
20
|
+
)
|
|
21
|
+
throw new Error("Terminal identity changed; resolve the target again");
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
async terminal(address) {
|
|
26
|
+
const record = await get(address);
|
|
27
|
+
const labels = "labels" in record ? record.labels : undefined;
|
|
28
|
+
const path =
|
|
29
|
+
labels && typeof labels === "object" && "pi.session_file" in labels
|
|
30
|
+
? labels["pi.session_file"]
|
|
31
|
+
: undefined;
|
|
32
|
+
return {
|
|
33
|
+
pane_id: address,
|
|
34
|
+
terminal_id: address,
|
|
35
|
+
agent: typeof path === "string" && path ? "pi" : null,
|
|
36
|
+
...(typeof path === "string" && path
|
|
37
|
+
? {
|
|
38
|
+
agent_session: {
|
|
39
|
+
agent: "pi",
|
|
40
|
+
kind: /** @type {const} */ ("path"),
|
|
41
|
+
source: "pi.session_file",
|
|
42
|
+
value: path,
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
: {}),
|
|
46
|
+
};
|
|
47
|
+
},
|
|
48
|
+
async closeTerminal(address) {
|
|
49
|
+
const record = await get(address);
|
|
50
|
+
if (record.state === "live")
|
|
51
|
+
await request("terminal.kill", { terminal: address });
|
|
52
|
+
else if (record.state !== "finished")
|
|
53
|
+
throw new Error("Terminal state is unknown; inspect it before cleanup");
|
|
54
|
+
await request("terminal.rm", { terminal: address });
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|