@howaboua/pi-shepherdr 0.2.24 → 0.2.25
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 +13 -0
- package/README.md +17 -9
- package/index.ts +2 -0
- package/package.json +5 -5
- package/src/agents-contract.ts +9 -6
- package/src/agents-discovery.ts +41 -15
- package/src/agents-focus.ts +15 -9
- package/src/agents-spawn.ts +22 -6
- package/src/agents-tool.ts +24 -6
- package/src/agents-work.ts +2 -2
- package/src/attachment.ts +2 -0
- package/src/board/host.ts +3 -1
- package/src/close-idle.ts +89 -0
- package/src/control-panel/index.ts +3 -1
- package/src/control-panel/items.ts +14 -2
- package/src/control-panel/view.ts +6 -2
- package/src/controller.ts +11 -2
- package/src/core/AGENTS.md +5 -0
- package/src/core/backend.ts +266 -0
- package/src/core/client.ts +249 -0
- package/src/core/context-relay.mjs +111 -0
- package/src/core/focus-channel-helper.mjs +165 -0
- package/src/core/focus-channel-stream.ts +140 -0
- package/src/core/focus-channel-wire.mjs +160 -0
- package/src/core/focus-channel.ts +213 -0
- package/src/core/focus-window.ts +192 -0
- package/src/core/pi-executable.mjs +34 -0
- package/src/core/protocol.ts +116 -0
- package/src/core/registration.ts +51 -0
- package/src/core/remote-endpoint.ts +119 -0
- package/src/core/remote-exec.ts +122 -0
- package/src/core/remote-helper.mjs +244 -0
- package/src/core/remote-reader.ts +67 -0
- package/src/core/remote-relay.ts +191 -0
- package/src/core/request.ts +124 -0
- package/src/core/spawn.ts +177 -0
- package/src/core/status.ts +68 -0
- package/src/core/terminal.ts +103 -0
- package/src/fleet/catalog.ts +83 -0
- package/src/fleet/connection.ts +111 -0
- package/src/fleet/index.ts +151 -122
- package/src/fleet/inspection.ts +19 -1
- package/src/fleet/machine.ts +3 -0
- package/src/fleet/monitor.ts +18 -4
- package/src/fleet/persistence.ts +26 -3
- package/src/fleet/setup.ts +54 -13
- package/src/herdr.ts +25 -5
- package/src/launch-contract.ts +48 -0
- package/src/launch-location.ts +151 -0
- package/src/launch.ts +30 -183
- package/src/messages/attribution.ts +15 -6
- package/src/messages/events.ts +10 -4
- package/src/messages/focus.ts +11 -2
- package/src/monitor-record.ts +9 -6
- package/src/monitor.ts +31 -0
- package/src/peer-commands.ts +11 -0
- package/src/peer-inbox-delivery.ts +171 -0
- package/src/peer-inbox-focus.ts +113 -0
- package/src/peer-inbox.ts +126 -208
- package/src/remote/deployment.ts +1 -1
- package/src/remote/shepherdr-context.mjs +1 -1
- package/src/remote/shepherdr-peer.mjs +18 -5
- package/src/remote/shepherdr-session.mjs +9 -2
- package/src/remote/shepherdr.mjs +1 -1
- package/src/settlement/collector.ts +2 -2
- package/src/settlement/index.ts +12 -0
- package/src/shared-context-host.ts +7 -3
- package/src/shared-context.ts +34 -2
- package/src/spawn-context.ts +4 -0
- package/src/spawn-ownership.ts +91 -0
- package/src/types.ts +9 -5
- package/src/worker-ownership.ts +92 -0
- package/src/worker-service.ts +12 -81
|
@@ -15,7 +15,17 @@ export function buildPanelItems(
|
|
|
15
15
|
tab: PanelTab,
|
|
16
16
|
draft: SshSetupDraft,
|
|
17
17
|
): SettingItem[] {
|
|
18
|
-
if (tab === "Connections")
|
|
18
|
+
if (tab === "Connections") {
|
|
19
|
+
if (process.env["HC_TERMINAL_SOCKET"])
|
|
20
|
+
return [
|
|
21
|
+
{
|
|
22
|
+
id: "core-machines",
|
|
23
|
+
label: "Manage machines in Herdr or with hc machine add",
|
|
24
|
+
currentValue: "",
|
|
25
|
+
},
|
|
26
|
+
];
|
|
27
|
+
return sshSetupItems(draft);
|
|
28
|
+
}
|
|
19
29
|
if (tab === "Status")
|
|
20
30
|
return [
|
|
21
31
|
{
|
|
@@ -23,7 +33,9 @@ export function buildPanelItems(
|
|
|
23
33
|
label: "Refresh and reconnect",
|
|
24
34
|
currentValue: "Enter",
|
|
25
35
|
values: ["Enter"],
|
|
26
|
-
description:
|
|
36
|
+
description: process.env["HC_TERMINAL_SOCKET"]
|
|
37
|
+
? "Refresh Core machines and retry connections."
|
|
38
|
+
: "Reload Herdr profiles and retry connections.",
|
|
27
39
|
},
|
|
28
40
|
...options.fleet.statuses().map((machine) => ({
|
|
29
41
|
id: `machine:${machine.id}`,
|
|
@@ -150,8 +150,12 @@ export class PanelView {
|
|
|
150
150
|
this.tab === "Settings"
|
|
151
151
|
? ""
|
|
152
152
|
: this.tab === "Connections"
|
|
153
|
-
?
|
|
154
|
-
|
|
153
|
+
? process.env["HC_TERMINAL_SOCKET"]
|
|
154
|
+
? ""
|
|
155
|
+
: "Remote needs Node on SSH PATH and Pi with Herdr integration. Herdr prepares its server before saving."
|
|
156
|
+
: process.env["HC_TERMINAL_SOCKET"]
|
|
157
|
+
? "Select a machine to reconnect."
|
|
158
|
+
: `${this.owners.fleet.isActive() ? "" : "Run Pi inside Herdr. "}Add SSH targets in Connections; select a machine here to reconnect.`,
|
|
155
159
|
).filter((line) => line.trim()),
|
|
156
160
|
"",
|
|
157
161
|
];
|
package/src/controller.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
recordContextBriefing,
|
|
9
9
|
registerContextBriefing,
|
|
10
10
|
} from "@howaboua/pi-agent-board/integration";
|
|
11
|
+
import { closeIdleChildren } from "./close-idle.js";
|
|
11
12
|
import { controlPanelStatus, openControlPanel } from "./control-panel/index.js";
|
|
12
13
|
import { sendPolicyMessage } from "./delivery.js";
|
|
13
14
|
import type { AgentFleet } from "./fleet/index.js";
|
|
@@ -128,7 +129,7 @@ export function registerAgentController(
|
|
|
128
129
|
},
|
|
129
130
|
);
|
|
130
131
|
pi.registerCommand("herdr", {
|
|
131
|
-
description: "Shepherdr settings, status
|
|
132
|
+
description: "Shepherdr settings, status, SSH setup and close-idle",
|
|
132
133
|
handler: async (args, ctx) => {
|
|
133
134
|
if (await peerCommands.handle(args, ctx)) return;
|
|
134
135
|
const commandSignal = sessionLifetime.signal;
|
|
@@ -136,6 +137,11 @@ export function registerAgentController(
|
|
|
136
137
|
const current = () =>
|
|
137
138
|
!commandSignal.aborted &&
|
|
138
139
|
ctx.sessionManager.getSessionId() === commandSessionId;
|
|
140
|
+
if (args.trim() === "close-idle") {
|
|
141
|
+
const result = await closeIdleChildren(fleet, ctx, current);
|
|
142
|
+
if (current()) ctx.ui.notify(result, "info");
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
139
145
|
if (args.trim()) {
|
|
140
146
|
ctx.ui.notify("Open /herdr, then choose a tab.", "warning");
|
|
141
147
|
return;
|
|
@@ -218,7 +224,10 @@ async function activateController(
|
|
|
218
224
|
fleet: AgentFleet,
|
|
219
225
|
ctx: ExtensionContext,
|
|
220
226
|
): Promise<boolean> {
|
|
221
|
-
if (
|
|
227
|
+
if (
|
|
228
|
+
!(process.env["HC_TERMINAL_ID"] && process.env["HC_TERMINAL_SOCKET"]) &&
|
|
229
|
+
(process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"])
|
|
230
|
+
) {
|
|
222
231
|
ctx.ui.notify("Shepherdr requires Pi to run inside Herdr", "error");
|
|
223
232
|
return false;
|
|
224
233
|
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
- Shared `pane_id` is an internal address key here, not a window pane identity. Emit terminal identity; never manufacture layout/focus IDs. Scope remote addresses by permanent Core ID, not session names or mutable machine aliases.
|
|
2
|
+
- Remote subscriptions are invalidations: Core 0.1.14 retains old aliases after rename. Host aggregate lists omit slow machines, so supervision reads the selected Core's own list through the verified helper. An empty startup mirror requires a direct get, not rollback.
|
|
3
|
+
- Remote helper bundling reuses the unchanged native peer/session/context readers. Keep its data-URL relative-import map complete when those helpers gain dependencies; never edit or deploy over the legacy bridge.
|
|
4
|
+
- Closing a plain Core request does not cancel accepted remote execution. Keep remote watches and exec watchdogs bounded; abort local callbacks before releasing their monitor/client owner.
|
|
5
|
+
- Fleet teardown is synchronous. Context relay route ownership spans replacement connections: fence startup behind the previous owner's completed close, including accepted startup, and release route entries after bounded cleanup. Keep relay payload limits aligned in remote-relay.ts and context-relay.mjs; poll batches must fit raw exec/context limits after JSON escaping, not just each request.
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
import type { HerdrConnection } from "../herdr-client.js";
|
|
3
|
+
import { openPeerChannel } from "../remote/shepherdr-channel.mjs";
|
|
4
|
+
import { requestContext } from "../remote/shepherdr-context.mjs";
|
|
5
|
+
import {
|
|
6
|
+
readPeerCommands,
|
|
7
|
+
sendPeerCommands,
|
|
8
|
+
sendPeerExtensionReply,
|
|
9
|
+
sendPeerFocus,
|
|
10
|
+
sendPeerMessage,
|
|
11
|
+
} from "../remote/shepherdr-peer.mjs";
|
|
12
|
+
import type {
|
|
13
|
+
ExtensionReply,
|
|
14
|
+
FocusRequest,
|
|
15
|
+
HerdrEvent,
|
|
16
|
+
PaneInfo,
|
|
17
|
+
PeerChannel,
|
|
18
|
+
PeerMessage,
|
|
19
|
+
} from "../types.js";
|
|
20
|
+
import { CoreClient } from "./client.js";
|
|
21
|
+
import { openCoreFocusChannel } from "./focus-channel.js";
|
|
22
|
+
import { object } from "./protocol.js";
|
|
23
|
+
import { RemoteCoreEndpoint } from "./remote-endpoint.js";
|
|
24
|
+
import { type CoreMachine, remoteExec } from "./remote-exec.js";
|
|
25
|
+
import { CoreRemoteReader } from "./remote-reader.js";
|
|
26
|
+
import { CoreContextRelay } from "./remote-relay.js";
|
|
27
|
+
import { dispatchCoreRequest } from "./request.js";
|
|
28
|
+
|
|
29
|
+
export class CoreConnection implements HerdrConnection {
|
|
30
|
+
private readonly lifetime = new AbortController();
|
|
31
|
+
private readonly focusChannels = new Set<PeerChannel>();
|
|
32
|
+
private relay: CoreContextRelay | undefined;
|
|
33
|
+
private readonly socketPath: string;
|
|
34
|
+
readonly core: CoreClient | RemoteCoreEndpoint;
|
|
35
|
+
readonly remote: CoreMachine | undefined;
|
|
36
|
+
readonly reader: CoreRemoteReader | undefined;
|
|
37
|
+
constructor(
|
|
38
|
+
socketPath = process.env["HC_TERMINAL_SOCKET"],
|
|
39
|
+
remote?: CoreMachine,
|
|
40
|
+
) {
|
|
41
|
+
if (!socketPath)
|
|
42
|
+
throw new Error("Run Pi inside a Core terminal to connect Shepherdr");
|
|
43
|
+
this.remote = remote;
|
|
44
|
+
this.socketPath = socketPath;
|
|
45
|
+
this.core = remote
|
|
46
|
+
? new RemoteCoreEndpoint(socketPath, remote)
|
|
47
|
+
: new CoreClient(socketPath);
|
|
48
|
+
this.reader =
|
|
49
|
+
this.core instanceof RemoteCoreEndpoint
|
|
50
|
+
? new CoreRemoteReader(this.core)
|
|
51
|
+
: undefined;
|
|
52
|
+
}
|
|
53
|
+
close(): void {
|
|
54
|
+
this.lifetime.abort();
|
|
55
|
+
for (const channel of this.focusChannels) channel.close();
|
|
56
|
+
this.focusChannels.clear();
|
|
57
|
+
void this.relay?.close();
|
|
58
|
+
this.core.close();
|
|
59
|
+
}
|
|
60
|
+
async machineIdentity() {
|
|
61
|
+
const hello = object(await this.core.request("hello"));
|
|
62
|
+
const core = object(hello["core"]);
|
|
63
|
+
if (typeof core["id"] !== "string" || !core["id"])
|
|
64
|
+
throw new Error("Core returned no stable identity");
|
|
65
|
+
return {
|
|
66
|
+
host:
|
|
67
|
+
this.remote && typeof core["name"] === "string"
|
|
68
|
+
? core["name"]
|
|
69
|
+
: hostname(),
|
|
70
|
+
session: core["id"],
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
requestContext(path: string, request: unknown, signal?: AbortSignal) {
|
|
74
|
+
if (this.core instanceof RemoteCoreEndpoint)
|
|
75
|
+
return remoteExec(
|
|
76
|
+
this.core.host,
|
|
77
|
+
this.core.machine,
|
|
78
|
+
{ op: "context", path, request },
|
|
79
|
+
signal ? { signal } : {},
|
|
80
|
+
);
|
|
81
|
+
return requestContext(path, request, signal);
|
|
82
|
+
}
|
|
83
|
+
async startContextRelay(
|
|
84
|
+
threadId: string,
|
|
85
|
+
_routeId: string,
|
|
86
|
+
handler: (request: unknown, signal: AbortSignal) => Promise<unknown>,
|
|
87
|
+
onFailure: (error: Error) => void = () => {},
|
|
88
|
+
): Promise<void> {
|
|
89
|
+
if (!this.remote)
|
|
90
|
+
throw new Error("Local context routes use the controller session");
|
|
91
|
+
this.lifetime.signal.throwIfAborted();
|
|
92
|
+
await this.relay?.close();
|
|
93
|
+
this.lifetime.signal.throwIfAborted();
|
|
94
|
+
const relay = new CoreContextRelay(this.socketPath, this.remote);
|
|
95
|
+
this.relay = relay;
|
|
96
|
+
try {
|
|
97
|
+
await relay.start(threadId, handler, onFailure);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
await relay.close();
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
contextRelayPath(): string {
|
|
104
|
+
if (!this.relay)
|
|
105
|
+
throw new Error(
|
|
106
|
+
"Shared context relay is unavailable; open /herdr → Status to retry sharing",
|
|
107
|
+
);
|
|
108
|
+
return this.relay.path();
|
|
109
|
+
}
|
|
110
|
+
async directory(
|
|
111
|
+
value: string | undefined,
|
|
112
|
+
fallback: string,
|
|
113
|
+
): Promise<string> {
|
|
114
|
+
if (!(this.core instanceof RemoteCoreEndpoint))
|
|
115
|
+
throw new Error("Use local directory resolution on the local Core");
|
|
116
|
+
const result = await remoteExec(this.core.host, this.core.machine, {
|
|
117
|
+
op: "directory",
|
|
118
|
+
value,
|
|
119
|
+
fallback,
|
|
120
|
+
});
|
|
121
|
+
if (typeof result !== "string")
|
|
122
|
+
throw new Error("Remote directory returned no path");
|
|
123
|
+
return result;
|
|
124
|
+
}
|
|
125
|
+
async sendMessage(agent: PaneInfo, message: PeerMessage) {
|
|
126
|
+
if (this.core instanceof RemoteCoreEndpoint) {
|
|
127
|
+
const result = object(
|
|
128
|
+
await remoteExec(this.core.host, this.core.machine, {
|
|
129
|
+
op: "message",
|
|
130
|
+
agent,
|
|
131
|
+
message,
|
|
132
|
+
}),
|
|
133
|
+
);
|
|
134
|
+
if (
|
|
135
|
+
typeof result["command"] !== "boolean" ||
|
|
136
|
+
(result["result"] !== undefined && typeof result["result"] !== "string")
|
|
137
|
+
)
|
|
138
|
+
throw new Error(
|
|
139
|
+
"Remote delivery was not acknowledged; inspect the target before retrying",
|
|
140
|
+
);
|
|
141
|
+
return {
|
|
142
|
+
command: result["command"],
|
|
143
|
+
...(typeof result["result"] === "string"
|
|
144
|
+
? { result: result["result"] }
|
|
145
|
+
: {}),
|
|
146
|
+
...(result["commands"] !== undefined
|
|
147
|
+
? { commands: readPeerCommands(result["commands"]) }
|
|
148
|
+
: {}),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
return sendPeerMessage(
|
|
152
|
+
(method, params) => this.request(method, params),
|
|
153
|
+
agent,
|
|
154
|
+
message,
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
async commands(agent: PaneInfo) {
|
|
158
|
+
if (this.core instanceof RemoteCoreEndpoint)
|
|
159
|
+
return readPeerCommands(
|
|
160
|
+
await remoteExec(this.core.host, this.core.machine, {
|
|
161
|
+
op: "commands",
|
|
162
|
+
agent,
|
|
163
|
+
}),
|
|
164
|
+
);
|
|
165
|
+
return sendPeerCommands(
|
|
166
|
+
(method, params) => this.request(method, params),
|
|
167
|
+
agent,
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
async replyExtension(agent: PaneInfo, reply: ExtensionReply) {
|
|
171
|
+
if (this.core instanceof RemoteCoreEndpoint) {
|
|
172
|
+
const result = await remoteExec(this.core.host, this.core.machine, {
|
|
173
|
+
op: "reply",
|
|
174
|
+
agent,
|
|
175
|
+
reply,
|
|
176
|
+
});
|
|
177
|
+
if (typeof result !== "string")
|
|
178
|
+
throw new Error(
|
|
179
|
+
"Remote extension reply was not acknowledged; inspect the target before retrying",
|
|
180
|
+
);
|
|
181
|
+
return result;
|
|
182
|
+
}
|
|
183
|
+
return sendPeerExtensionReply(
|
|
184
|
+
(method, params) => this.request(method, params),
|
|
185
|
+
agent,
|
|
186
|
+
reply,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
focus(agent: PaneInfo, request: FocusRequest): Promise<unknown> {
|
|
190
|
+
if (this.core instanceof RemoteCoreEndpoint)
|
|
191
|
+
return remoteExec(this.core.host, this.core.machine, {
|
|
192
|
+
op: "focus",
|
|
193
|
+
agent,
|
|
194
|
+
focus: request,
|
|
195
|
+
});
|
|
196
|
+
return sendPeerFocus(
|
|
197
|
+
(method, params) => this.request(method, params),
|
|
198
|
+
agent,
|
|
199
|
+
request,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
async openFocusChannel(
|
|
203
|
+
agent: PaneInfo,
|
|
204
|
+
request: FocusRequest,
|
|
205
|
+
): Promise<PeerChannel> {
|
|
206
|
+
this.lifetime.signal.throwIfAborted();
|
|
207
|
+
const channel =
|
|
208
|
+
this.core instanceof RemoteCoreEndpoint
|
|
209
|
+
? await openCoreFocusChannel(
|
|
210
|
+
this.core.host,
|
|
211
|
+
this.socketPath,
|
|
212
|
+
this.core.machine,
|
|
213
|
+
agent,
|
|
214
|
+
request,
|
|
215
|
+
{ signal: this.lifetime.signal },
|
|
216
|
+
)
|
|
217
|
+
: await openPeerChannel(
|
|
218
|
+
(method, params) => this.request(method, params),
|
|
219
|
+
agent,
|
|
220
|
+
request,
|
|
221
|
+
);
|
|
222
|
+
if (this.lifetime.signal.aborted) {
|
|
223
|
+
channel.close();
|
|
224
|
+
this.lifetime.signal.throwIfAborted();
|
|
225
|
+
}
|
|
226
|
+
this.focusChannels.add(channel);
|
|
227
|
+
channel.onClose(() => this.focusChannels.delete(channel));
|
|
228
|
+
return channel;
|
|
229
|
+
}
|
|
230
|
+
async request<T>(
|
|
231
|
+
method: string,
|
|
232
|
+
params: object = {},
|
|
233
|
+
timeoutMs = 30_000,
|
|
234
|
+
): Promise<T> {
|
|
235
|
+
return (await dispatchCoreRequest(
|
|
236
|
+
this.core,
|
|
237
|
+
method,
|
|
238
|
+
object(params),
|
|
239
|
+
timeoutMs,
|
|
240
|
+
)) as T;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async subscribe(
|
|
244
|
+
_subscriptions: object[],
|
|
245
|
+
onEvent: (event: HerdrEvent) => void,
|
|
246
|
+
onDisconnect: (error?: Error) => void,
|
|
247
|
+
signal?: AbortSignal,
|
|
248
|
+
): Promise<() => void> {
|
|
249
|
+
let closed = false;
|
|
250
|
+
const subscription = await this.core.subscribe(
|
|
251
|
+
{},
|
|
252
|
+
(notification) => {
|
|
253
|
+
if (notification.method !== "heartbeat")
|
|
254
|
+
onEvent({ event: "core.reconcile", data: {} });
|
|
255
|
+
},
|
|
256
|
+
{ ...(signal ? { signal } : {}) },
|
|
257
|
+
);
|
|
258
|
+
void subscription.closed.then((error) => {
|
|
259
|
+
if (!closed && !signal?.aborted) onDisconnect(error);
|
|
260
|
+
});
|
|
261
|
+
return () => {
|
|
262
|
+
closed = true;
|
|
263
|
+
subscription.close();
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { Socket } from "node:net";
|
|
2
|
+
import {
|
|
3
|
+
type CoreNotification,
|
|
4
|
+
type CoreObject,
|
|
5
|
+
notification,
|
|
6
|
+
object,
|
|
7
|
+
response,
|
|
8
|
+
snapshot,
|
|
9
|
+
} from "./protocol.js";
|
|
10
|
+
|
|
11
|
+
export interface CoreRequestOptions {
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
/** Includes connection time. Default: 30 seconds. */
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface CoreEventFilter {
|
|
18
|
+
terminal?: string;
|
|
19
|
+
children_of?: string;
|
|
20
|
+
labels?: Record<string, string>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface CoreSubscribeOptions extends CoreRequestOptions {
|
|
24
|
+
/** Maximum silence after the snapshot. Default: 45 seconds (Core heartbeats every 15). */
|
|
25
|
+
idleTimeoutMs?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface CoreSubscription {
|
|
29
|
+
/** Resolves once: undefined for explicit close, otherwise the failure/abort reason. */
|
|
30
|
+
closed: Promise<Error | undefined>;
|
|
31
|
+
close(): void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function timeout(value: number): number {
|
|
35
|
+
if (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
"Core timeout must be a positive integer below 2147483648 ms",
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function failure(value: unknown): Error {
|
|
44
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function timedOut(): Error {
|
|
48
|
+
const error = new Error("Core connection timed out");
|
|
49
|
+
error.name = "TimeoutError";
|
|
50
|
+
return error;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Plain NDJSON only. Core dedicates a connection to events after subscribing. */
|
|
54
|
+
class PlainConnection {
|
|
55
|
+
private readonly socket = new Socket();
|
|
56
|
+
private ended = false;
|
|
57
|
+
private buffer = "";
|
|
58
|
+
private timer: NodeJS.Timeout | undefined;
|
|
59
|
+
private readonly options: CoreRequestOptions;
|
|
60
|
+
private readonly onMessage: (message: CoreObject) => void;
|
|
61
|
+
private readonly onClose: (error: Error | undefined) => void;
|
|
62
|
+
private readonly abort = () => {
|
|
63
|
+
const error = new Error("Core connection cancelled", {
|
|
64
|
+
cause: this.options.signal?.reason,
|
|
65
|
+
});
|
|
66
|
+
error.name = "AbortError";
|
|
67
|
+
this.close(error);
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
constructor(
|
|
71
|
+
options: CoreRequestOptions,
|
|
72
|
+
onMessage: (message: CoreObject) => void,
|
|
73
|
+
onClose: (error: Error | undefined) => void,
|
|
74
|
+
) {
|
|
75
|
+
this.options = options;
|
|
76
|
+
this.onMessage = onMessage;
|
|
77
|
+
this.onClose = onClose;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
start(socketPath: string, payload: string): void {
|
|
81
|
+
this.socket.setEncoding("utf8");
|
|
82
|
+
this.socket.on("data", (chunk: string) => this.receive(chunk));
|
|
83
|
+
this.socket.on("error", (error) => this.close(error));
|
|
84
|
+
this.socket.on("close", () =>
|
|
85
|
+
this.close(new Error("Core connection closed")),
|
|
86
|
+
);
|
|
87
|
+
this.options.signal?.addEventListener("abort", this.abort, { once: true });
|
|
88
|
+
if (this.options.signal?.aborted) return this.abort();
|
|
89
|
+
this.setTimeout(this.options.timeoutMs ?? 30_000);
|
|
90
|
+
try {
|
|
91
|
+
this.socket.connect(socketPath, () => this.socket.write(payload));
|
|
92
|
+
} catch (error) {
|
|
93
|
+
this.close(failure(error));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
setTimeout(ms: number): void {
|
|
98
|
+
if (this.timer) clearTimeout(this.timer);
|
|
99
|
+
this.timer = setTimeout(() => this.close(timedOut()), ms);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
close(error?: Error): void {
|
|
103
|
+
if (this.ended) return;
|
|
104
|
+
this.ended = true;
|
|
105
|
+
if (this.timer) clearTimeout(this.timer);
|
|
106
|
+
this.options.signal?.removeEventListener("abort", this.abort);
|
|
107
|
+
this.socket.destroy();
|
|
108
|
+
this.buffer = "";
|
|
109
|
+
this.onClose(error);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private receive(chunk: string): void {
|
|
113
|
+
if (this.ended) return;
|
|
114
|
+
this.buffer += chunk;
|
|
115
|
+
try {
|
|
116
|
+
let end = this.buffer.indexOf("\n");
|
|
117
|
+
while (end !== -1 && !this.ended) {
|
|
118
|
+
const line = this.buffer.slice(0, end);
|
|
119
|
+
this.buffer = this.buffer.slice(end + 1);
|
|
120
|
+
this.checkSize(line);
|
|
121
|
+
if (line.trim()) this.onMessage(object(JSON.parse(line)));
|
|
122
|
+
end = this.buffer.indexOf("\n");
|
|
123
|
+
}
|
|
124
|
+
this.checkSize(this.buffer);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
this.close(failure(error));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private checkSize(line: string): void {
|
|
131
|
+
// Released file/exec methods can return up to 8 MiB, base64 encoded.
|
|
132
|
+
if (Buffer.byteLength(line) > 32 * 1024 * 1024) {
|
|
133
|
+
throw new Error("Core JSON-RPC message exceeds 32 MiB");
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Connects only to the supplied local endpoint; never starts or reconnects Core.
|
|
140
|
+
* Cancellation/timeouts close the socket, not a rollback of already accepted work.
|
|
141
|
+
*/
|
|
142
|
+
export class CoreClient {
|
|
143
|
+
private readonly connections = new Set<PlainConnection>();
|
|
144
|
+
private ended = false;
|
|
145
|
+
private readonly socketPath: string;
|
|
146
|
+
|
|
147
|
+
constructor(socketPath: string) {
|
|
148
|
+
if (!socketPath) throw new Error("A Core socket path is required");
|
|
149
|
+
this.socketPath = socketPath;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Result payloads stay unknown: callers validate their chosen released API method. */
|
|
153
|
+
request(
|
|
154
|
+
method: string,
|
|
155
|
+
params: CoreObject = {},
|
|
156
|
+
options: CoreRequestOptions = {},
|
|
157
|
+
): Promise<unknown> {
|
|
158
|
+
if (method === "events.subscribe") {
|
|
159
|
+
return Promise.reject(new Error("Use CoreClient.subscribe for events"));
|
|
160
|
+
}
|
|
161
|
+
return new Promise((resolve, reject) => {
|
|
162
|
+
const connection = this.open(
|
|
163
|
+
method,
|
|
164
|
+
params,
|
|
165
|
+
options,
|
|
166
|
+
(message) => {
|
|
167
|
+
const result = response(message);
|
|
168
|
+
resolve(result);
|
|
169
|
+
connection.close();
|
|
170
|
+
},
|
|
171
|
+
(error) => reject(error ?? new Error("Core request closed")),
|
|
172
|
+
);
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The callback receives the initial snapshot before live events. Replace terminal
|
|
178
|
+
* state on snapshot/missed; missed also requires refetching any watched documents.
|
|
179
|
+
* Old events at/below a snapshot are discarded. Sequence gaps are normal with
|
|
180
|
+
* filters, not proof of loss. No replay or continuity is promised across reconnects.
|
|
181
|
+
* Callbacks run synchronously; a thrown error closes the subscription.
|
|
182
|
+
*/
|
|
183
|
+
subscribe(
|
|
184
|
+
filter: CoreEventFilter,
|
|
185
|
+
onNotification: (message: CoreNotification) => void,
|
|
186
|
+
options: CoreSubscribeOptions = {},
|
|
187
|
+
): Promise<CoreSubscription> {
|
|
188
|
+
return new Promise((resolve, reject) => {
|
|
189
|
+
const idleTimeout = timeout(options.idleTimeoutMs ?? 45_000);
|
|
190
|
+
let initial = true;
|
|
191
|
+
let floor = 0;
|
|
192
|
+
let resolveClosed: (error: Error | undefined) => void = () => {};
|
|
193
|
+
const closed = new Promise<Error | undefined>((done) => {
|
|
194
|
+
resolveClosed = done;
|
|
195
|
+
});
|
|
196
|
+
const connection = this.open(
|
|
197
|
+
"events.subscribe",
|
|
198
|
+
{ ...filter },
|
|
199
|
+
options,
|
|
200
|
+
(message) => {
|
|
201
|
+
connection.setTimeout(idleTimeout);
|
|
202
|
+
if (initial) {
|
|
203
|
+
const result = object(response(message));
|
|
204
|
+
if (result["channel"] != null)
|
|
205
|
+
throw new Error("Expected a plain Core subscription");
|
|
206
|
+
const state = snapshot(result);
|
|
207
|
+
floor = state.seq;
|
|
208
|
+
initial = false;
|
|
209
|
+
onNotification({ method: "snapshot", ...state });
|
|
210
|
+
resolve({ closed, close: () => connection.close() });
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const update = notification(message);
|
|
214
|
+
if (update.method === "missed") floor = update.seq;
|
|
215
|
+
if (update.method === "event" && update.event.seq <= floor) return;
|
|
216
|
+
onNotification(update);
|
|
217
|
+
},
|
|
218
|
+
(error) => {
|
|
219
|
+
reject(error ?? new Error("Core subscription closed before ready"));
|
|
220
|
+
resolveClosed(error);
|
|
221
|
+
},
|
|
222
|
+
);
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
close(): void {
|
|
227
|
+
this.ended = true;
|
|
228
|
+
for (const connection of this.connections) connection.close();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private open(
|
|
232
|
+
method: string,
|
|
233
|
+
params: CoreObject,
|
|
234
|
+
options: CoreRequestOptions,
|
|
235
|
+
onMessage: (message: CoreObject) => void,
|
|
236
|
+
onClose: (error: Error | undefined) => void,
|
|
237
|
+
): PlainConnection {
|
|
238
|
+
if (this.ended) throw new Error("Core client is closed");
|
|
239
|
+
timeout(options.timeoutMs ?? 30_000);
|
|
240
|
+
const payload = `${JSON.stringify({ jsonrpc: "2.0", id: 1, method, params })}\n`;
|
|
241
|
+
const connection = new PlainConnection(options, onMessage, (error) => {
|
|
242
|
+
this.connections.delete(connection);
|
|
243
|
+
onClose(error);
|
|
244
|
+
});
|
|
245
|
+
this.connections.add(connection);
|
|
246
|
+
connection.start(this.socketPath, payload);
|
|
247
|
+
return connection;
|
|
248
|
+
}
|
|
249
|
+
}
|