@howaboua/pi-shepherdr 0.2.23 → 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 +20 -18
- package/README.md +80 -69
- package/biome.json +1 -1
- package/index.ts +4 -2
- package/package.json +14 -9
- package/src/agents-contract.ts +9 -6
- package/src/agents-discovery.ts +78 -37
- package/src/agents-focus.ts +17 -11
- package/src/agents-reply.ts +1 -1
- package/src/agents-spawn.ts +24 -8
- package/src/agents-tool.ts +26 -8
- package/src/agents-work.ts +5 -5
- 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 +4 -3
- package/src/board/host.ts +5 -3
- package/src/board/membership.ts +1 -1
- package/src/close-idle.ts +89 -0
- package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
- package/src/{control-panel.ts → control-panel/index.ts} +7 -5
- package/src/{control-panel-items.ts → control-panel/items.ts} +17 -5
- package/src/{control-panel-view.ts → control-panel/view.ts} +9 -5
- package/src/controller.ts +17 -5
- 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 +413 -0
- package/src/fleet/inspection.ts +159 -0
- package/src/fleet/machine.ts +55 -0
- package/src/fleet/monitor.ts +85 -0
- package/src/fleet/persistence.ts +65 -0
- package/src/fleet/reconnect.ts +75 -0
- package/src/fleet/setup.ts +133 -0
- 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/attachments.ts +39 -0
- package/src/messages/attribution.ts +84 -0
- package/src/messages/event-details.ts +69 -0
- package/src/messages/events.ts +195 -0
- package/src/messages/focus.ts +47 -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-record.ts +9 -6
- package/src/monitor.ts +33 -2
- 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 +127 -209
- 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/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/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} +35 -233
- package/src/shared-context-host.ts +40 -14
- package/src/shared-context.ts +44 -6
- package/src/spawn-context.ts +24 -17
- package/src/spawn-ownership.ts +91 -0
- package/src/types.ts +9 -5
- package/src/voice-handoff.ts +1 -1
- package/src/worker-ownership.ts +92 -0
- package/src/worker-service.ts +14 -83
- package/src/fleet.ts +0 -702
- package/src/messages.ts +0 -637
- package/src/remote-client.ts +0 -761
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// End-to-end credit keeps Core's terminal repaint fallback out of this stream.
|
|
2
|
+
const LIMIT = 1024 * 1024;
|
|
3
|
+
const CHUNK = 8192;
|
|
4
|
+
// PeerChannel's 512KiB JSON plus the transport's data envelope.
|
|
5
|
+
const MAX_MESSAGE = 512 * 1024 + 128;
|
|
6
|
+
/**
|
|
7
|
+
* @param {string} nonce
|
|
8
|
+
* @param {(bytes:Buffer)=>void} write
|
|
9
|
+
* @param {(message:unknown)=>void} receive
|
|
10
|
+
* @param {(error:Error)=>void} fail
|
|
11
|
+
* @param {()=>void} [onLive]
|
|
12
|
+
*/
|
|
13
|
+
export function focusWire(nonce, write, receive, fail, onLive) {
|
|
14
|
+
const prefix = `!${nonce}!`;
|
|
15
|
+
let buffer = "";
|
|
16
|
+
let ended = false;
|
|
17
|
+
let heard = Date.now();
|
|
18
|
+
let sent = 0;
|
|
19
|
+
let received = 0;
|
|
20
|
+
let acknowledged = 0;
|
|
21
|
+
let queuedBytes = 0;
|
|
22
|
+
/** @type {Buffer[]} */
|
|
23
|
+
let chunks = [];
|
|
24
|
+
let chunkBytes = 0;
|
|
25
|
+
/** @type {Array<{data:string,end:boolean}>} */
|
|
26
|
+
const queue = [];
|
|
27
|
+
/** @param {object} value */
|
|
28
|
+
const emit = (value) => {
|
|
29
|
+
if (!ended)
|
|
30
|
+
write(
|
|
31
|
+
Buffer.from(
|
|
32
|
+
`${prefix}${Buffer.from(JSON.stringify(value)).toString("base64")}!\n`,
|
|
33
|
+
),
|
|
34
|
+
);
|
|
35
|
+
};
|
|
36
|
+
const flush = () => {
|
|
37
|
+
// Four 8KiB chunks, even after base64 twice, fit below Core's 256KiB credit.
|
|
38
|
+
while (!ended && queue.length && sent - acknowledged < 4) {
|
|
39
|
+
const frame = queue.shift();
|
|
40
|
+
if (!frame) break;
|
|
41
|
+
queuedBytes -= frame.data.length;
|
|
42
|
+
emit({ n: ++sent, ...frame });
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
/** @param {unknown} error */
|
|
46
|
+
const failed = (error) => {
|
|
47
|
+
if (ended) return;
|
|
48
|
+
const reason = error instanceof Error ? error : new Error(String(error));
|
|
49
|
+
// Error control bypasses a full data queue; never hide remote overflow as EOF.
|
|
50
|
+
try {
|
|
51
|
+
emit({ error: reason.message });
|
|
52
|
+
} catch {}
|
|
53
|
+
close();
|
|
54
|
+
fail(reason);
|
|
55
|
+
};
|
|
56
|
+
const timer = setInterval(() => {
|
|
57
|
+
try {
|
|
58
|
+
if (Date.now() - heard > 10_000)
|
|
59
|
+
throw new Error("Focus stream lease expired");
|
|
60
|
+
emit({ ping: true });
|
|
61
|
+
} catch (error) {
|
|
62
|
+
failed(error);
|
|
63
|
+
}
|
|
64
|
+
}, 1000);
|
|
65
|
+
function close() {
|
|
66
|
+
ended = true;
|
|
67
|
+
clearInterval(timer);
|
|
68
|
+
queue.length = 0;
|
|
69
|
+
chunks = [];
|
|
70
|
+
buffer = "";
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
close,
|
|
74
|
+
/** @param {unknown} message */
|
|
75
|
+
send(message) {
|
|
76
|
+
if (ended) throw new Error("Focus stream is closed");
|
|
77
|
+
try {
|
|
78
|
+
const json = JSON.stringify(message);
|
|
79
|
+
if (json === undefined) throw new Error("Focus stream requires JSON");
|
|
80
|
+
const bytes = Buffer.from(json);
|
|
81
|
+
if (bytes.length > MAX_MESSAGE)
|
|
82
|
+
throw new Error("Focus stream message exceeds 512 KiB");
|
|
83
|
+
if (queuedBytes + Math.ceil(bytes.length / 3) * 4 > LIMIT)
|
|
84
|
+
throw new Error("Focus stream output exceeded its buffer");
|
|
85
|
+
for (let at = 0; at < bytes.length; at += CHUNK) {
|
|
86
|
+
const data = bytes.subarray(at, at + CHUNK).toString("base64");
|
|
87
|
+
queuedBytes += data.length;
|
|
88
|
+
queue.push({ data, end: at + CHUNK >= bytes.length });
|
|
89
|
+
}
|
|
90
|
+
flush();
|
|
91
|
+
} catch (error) {
|
|
92
|
+
failed(error);
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
/** @param {Buffer} bytes */
|
|
97
|
+
push(bytes) {
|
|
98
|
+
if (ended) return;
|
|
99
|
+
try {
|
|
100
|
+
buffer += bytes.toString("ascii");
|
|
101
|
+
if (buffer.length > LIMIT)
|
|
102
|
+
throw new Error("Focus stream input exceeded its buffer");
|
|
103
|
+
for (;;) {
|
|
104
|
+
const start = buffer.indexOf(prefix);
|
|
105
|
+
if (start < 0) {
|
|
106
|
+
buffer = buffer.slice(-prefix.length);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const end = buffer.indexOf("!", start + prefix.length);
|
|
110
|
+
if (end < 0) {
|
|
111
|
+
buffer = buffer.slice(start);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const frame = JSON.parse(
|
|
115
|
+
Buffer.from(
|
|
116
|
+
buffer.slice(start + prefix.length, end),
|
|
117
|
+
"base64",
|
|
118
|
+
).toString(),
|
|
119
|
+
);
|
|
120
|
+
buffer = buffer.slice(end + 1);
|
|
121
|
+
heard = Date.now();
|
|
122
|
+
if (typeof frame.error === "string") throw new Error(frame.error);
|
|
123
|
+
if (frame.ping === true) {
|
|
124
|
+
onLive?.();
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (Number.isSafeInteger(frame.ack)) {
|
|
128
|
+
if (frame.ack !== acknowledged + 1 || frame.ack > sent)
|
|
129
|
+
throw new Error("Focus stream acknowledgement is out of order");
|
|
130
|
+
acknowledged = frame.ack;
|
|
131
|
+
flush();
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (
|
|
135
|
+
frame.n !== received + 1 ||
|
|
136
|
+
typeof frame.data !== "string" ||
|
|
137
|
+
frame.data.length > 11000 ||
|
|
138
|
+
typeof frame.end !== "boolean"
|
|
139
|
+
)
|
|
140
|
+
throw new Error("Focus stream data is out of order or invalid");
|
|
141
|
+
const chunk = Buffer.from(frame.data, "base64");
|
|
142
|
+
chunkBytes += chunk.length;
|
|
143
|
+
if (chunkBytes > MAX_MESSAGE)
|
|
144
|
+
throw new Error("Focus stream message exceeds 512 KiB");
|
|
145
|
+
chunks.push(chunk);
|
|
146
|
+
received++;
|
|
147
|
+
if (frame.end) {
|
|
148
|
+
const message = JSON.parse(Buffer.concat(chunks).toString());
|
|
149
|
+
chunks = [];
|
|
150
|
+
chunkBytes = 0;
|
|
151
|
+
receive(message);
|
|
152
|
+
}
|
|
153
|
+
emit({ ack: received });
|
|
154
|
+
}
|
|
155
|
+
} catch (error) {
|
|
156
|
+
failed(error);
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { createBufferedChannel } from "../remote/shepherdr-channel.mjs";
|
|
4
|
+
import type { FocusRequest, PaneInfo, PeerChannel } from "../types.js";
|
|
5
|
+
import type { CoreClient } from "./client.js";
|
|
6
|
+
import { attachCoreTerminal } from "./focus-channel-stream.js";
|
|
7
|
+
import { focusWire } from "./focus-channel-wire.mjs";
|
|
8
|
+
import { object } from "./protocol.js";
|
|
9
|
+
import type { CoreMachine } from "./remote-exec.js";
|
|
10
|
+
|
|
11
|
+
const moduleUrl = (text: string) =>
|
|
12
|
+
`data:text/javascript;base64,${Buffer.from(text).toString("base64")}`;
|
|
13
|
+
async function helperSources() {
|
|
14
|
+
const read = (name: string) =>
|
|
15
|
+
readFile(new URL(name, import.meta.url), "utf8");
|
|
16
|
+
const [helper, wire, channel, peer] = await Promise.all([
|
|
17
|
+
read("./focus-channel-helper.mjs"),
|
|
18
|
+
read("./focus-channel-wire.mjs"),
|
|
19
|
+
read("../remote/shepherdr-channel.mjs"),
|
|
20
|
+
read("../remote/shepherdr-peer.mjs"),
|
|
21
|
+
]);
|
|
22
|
+
return {
|
|
23
|
+
helper,
|
|
24
|
+
modules: {
|
|
25
|
+
wire: moduleUrl(wire),
|
|
26
|
+
channel: moduleUrl(
|
|
27
|
+
channel.replace(
|
|
28
|
+
'"./shepherdr-peer.mjs"',
|
|
29
|
+
JSON.stringify(moduleUrl(peer)),
|
|
30
|
+
),
|
|
31
|
+
),
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Private Core terminal, authenticated native peer admission, no relay agent. */
|
|
37
|
+
export async function openCoreFocusChannel(
|
|
38
|
+
client: CoreClient,
|
|
39
|
+
socketPath: string,
|
|
40
|
+
machine: CoreMachine,
|
|
41
|
+
expected: PaneInfo,
|
|
42
|
+
focus: FocusRequest,
|
|
43
|
+
options: { signal?: AbortSignal } = {},
|
|
44
|
+
): Promise<PeerChannel> {
|
|
45
|
+
if (
|
|
46
|
+
!/^t[0-9a-z]+$/.test(expected.pane_id) ||
|
|
47
|
+
expected.pane_id !== expected.terminal_id ||
|
|
48
|
+
expected.agent_session?.kind !== "path"
|
|
49
|
+
)
|
|
50
|
+
throw new Error(
|
|
51
|
+
"Resolve an exact remote Pi terminal and saved session before focus",
|
|
52
|
+
);
|
|
53
|
+
options.signal?.throwIfAborted();
|
|
54
|
+
const { helper, modules } = await helperSources();
|
|
55
|
+
const nonce = randomBytes(8).toString("hex");
|
|
56
|
+
// Only the wire bootstrap belongs in argv; peer modules and focus data travel
|
|
57
|
+
// over its bounded, credited start frame, below Windows' CreateProcessW limit.
|
|
58
|
+
const argv = [
|
|
59
|
+
"node",
|
|
60
|
+
"--input-type=module",
|
|
61
|
+
"-e",
|
|
62
|
+
helper,
|
|
63
|
+
Buffer.from(JSON.stringify({ nonce, wire: modules.wire })).toString(
|
|
64
|
+
"base64",
|
|
65
|
+
),
|
|
66
|
+
];
|
|
67
|
+
// Worst-case Windows quoting, with room for the resolved Node executable path.
|
|
68
|
+
if (argv.reduce((size, arg) => size + arg.length * 2 + 3, 0) > 30_000)
|
|
69
|
+
throw new Error(
|
|
70
|
+
"Remote focus launcher is too large; update Shepherdr before retrying",
|
|
71
|
+
);
|
|
72
|
+
let terminal: string | undefined;
|
|
73
|
+
let stream: ReturnType<typeof attachCoreTerminal> | undefined;
|
|
74
|
+
let wire: ReturnType<typeof focusWire> | undefined;
|
|
75
|
+
let ended = false;
|
|
76
|
+
let started = false;
|
|
77
|
+
let admitted = false;
|
|
78
|
+
let resolveAdmission: () => void = () => {};
|
|
79
|
+
let rejectAdmission: (error: Error) => void = () => {};
|
|
80
|
+
const admission = new Promise<void>((resolve, reject) => {
|
|
81
|
+
resolveAdmission = resolve;
|
|
82
|
+
rejectAdmission = reject;
|
|
83
|
+
});
|
|
84
|
+
// Startup may fail before we reach await admission.
|
|
85
|
+
void admission.catch(() => {});
|
|
86
|
+
const state = createBufferedChannel(
|
|
87
|
+
(message) => {
|
|
88
|
+
if (!admitted || !wire) throw new Error("Focus channel is not admitted");
|
|
89
|
+
wire.send({ type: "data", message });
|
|
90
|
+
},
|
|
91
|
+
() => stop(new Error("Focus channel closed")),
|
|
92
|
+
);
|
|
93
|
+
const timer = setTimeout(
|
|
94
|
+
() =>
|
|
95
|
+
stop(
|
|
96
|
+
new Error(
|
|
97
|
+
"Remote focus admission timed out; inspect the destination before retrying",
|
|
98
|
+
),
|
|
99
|
+
),
|
|
100
|
+
60_000,
|
|
101
|
+
);
|
|
102
|
+
function stop(error: Error) {
|
|
103
|
+
if (ended) return;
|
|
104
|
+
ended = true;
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
options.signal?.removeEventListener("abort", abort);
|
|
107
|
+
rejectAdmission(error);
|
|
108
|
+
try {
|
|
109
|
+
wire?.send({ type: "close" });
|
|
110
|
+
} catch {}
|
|
111
|
+
wire?.close();
|
|
112
|
+
stream?.close();
|
|
113
|
+
state.fail(error);
|
|
114
|
+
// The remote lease also removes the rm:true terminal if this request cannot reach it.
|
|
115
|
+
if (terminal)
|
|
116
|
+
void client
|
|
117
|
+
.request("terminal.kill", { terminal }, { timeoutMs: 5000 })
|
|
118
|
+
.catch(() => {});
|
|
119
|
+
}
|
|
120
|
+
function abort() {
|
|
121
|
+
stop(
|
|
122
|
+
new Error("Remote focus channel cancelled", {
|
|
123
|
+
cause: options.signal?.reason,
|
|
124
|
+
}),
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
128
|
+
if (options.signal?.aborted) abort();
|
|
129
|
+
try {
|
|
130
|
+
if (ended) throw new Error("Remote focus channel cancelled during startup");
|
|
131
|
+
const created = object(
|
|
132
|
+
await client.request(
|
|
133
|
+
"terminal.run",
|
|
134
|
+
{
|
|
135
|
+
on: machine.id,
|
|
136
|
+
argv,
|
|
137
|
+
name: `focus-${nonce}`,
|
|
138
|
+
no_parent: true,
|
|
139
|
+
no_notify: true,
|
|
140
|
+
rm: true,
|
|
141
|
+
},
|
|
142
|
+
{ timeoutMs: 20_000 },
|
|
143
|
+
),
|
|
144
|
+
);
|
|
145
|
+
const address = created["address"];
|
|
146
|
+
if (
|
|
147
|
+
typeof address !== "string" ||
|
|
148
|
+
!address.startsWith(`${machine.name}/`) ||
|
|
149
|
+
!/^t[0-9a-z]+$/.test(address.slice(machine.name.length + 1))
|
|
150
|
+
)
|
|
151
|
+
throw new Error("Core returned an unexpected private focus terminal");
|
|
152
|
+
terminal = `${machine.id}/${address.slice(machine.name.length + 1)}`;
|
|
153
|
+
if (ended) {
|
|
154
|
+
void client
|
|
155
|
+
.request("terminal.kill", { terminal }, { timeoutMs: 5000 })
|
|
156
|
+
.catch(() => {});
|
|
157
|
+
throw new Error("Remote focus channel cancelled during startup");
|
|
158
|
+
}
|
|
159
|
+
wire = focusWire(
|
|
160
|
+
nonce,
|
|
161
|
+
(bytes) => {
|
|
162
|
+
if (!stream) throw new Error("Remote focus stream is unavailable");
|
|
163
|
+
stream.write(bytes);
|
|
164
|
+
},
|
|
165
|
+
(value) => {
|
|
166
|
+
const frame = object(value);
|
|
167
|
+
if (frame["type"] === "admitted" && !admitted) {
|
|
168
|
+
admitted = true;
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
resolveAdmission();
|
|
171
|
+
} else if (frame["type"] === "data" && admitted && "message" in frame)
|
|
172
|
+
state.receive(frame["message"]);
|
|
173
|
+
else if (frame["type"] === "error")
|
|
174
|
+
throw new Error(
|
|
175
|
+
typeof frame["message"] === "string"
|
|
176
|
+
? frame["message"]
|
|
177
|
+
: "Remote focus failed",
|
|
178
|
+
);
|
|
179
|
+
else
|
|
180
|
+
throw new Error("Remote focus connection sent an invalid response");
|
|
181
|
+
},
|
|
182
|
+
stop,
|
|
183
|
+
() => {
|
|
184
|
+
if (!started) {
|
|
185
|
+
started = true;
|
|
186
|
+
wire?.send({
|
|
187
|
+
type: "start",
|
|
188
|
+
input: {
|
|
189
|
+
coreId: machine.id,
|
|
190
|
+
session: machine.session,
|
|
191
|
+
expected,
|
|
192
|
+
focus,
|
|
193
|
+
modules: { channel: modules.channel },
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
);
|
|
199
|
+
stream = attachCoreTerminal(
|
|
200
|
+
socketPath,
|
|
201
|
+
terminal,
|
|
202
|
+
(bytes) => wire?.push(bytes),
|
|
203
|
+
stop,
|
|
204
|
+
);
|
|
205
|
+
await stream.ready;
|
|
206
|
+
await admission;
|
|
207
|
+
return state.channel;
|
|
208
|
+
} catch (error) {
|
|
209
|
+
const reason = error instanceof Error ? error : new Error(String(error));
|
|
210
|
+
stop(reason);
|
|
211
|
+
throw reason;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { stat } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { CoreClient } from "./client.js";
|
|
8
|
+
import { object } from "./protocol.js";
|
|
9
|
+
|
|
10
|
+
const exec = promisify(execFile);
|
|
11
|
+
const delay = (ms: number) =>
|
|
12
|
+
new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
13
|
+
|
|
14
|
+
function appSocket(): string {
|
|
15
|
+
return join(
|
|
16
|
+
process.env["HERDR_APP_HOME"] ||
|
|
17
|
+
join(
|
|
18
|
+
process.env["XDG_CONFIG_HOME"] || join(homedir(), ".config"),
|
|
19
|
+
"herdr-app",
|
|
20
|
+
),
|
|
21
|
+
"herdr-app.sock",
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function app(args: string[]): Promise<Record<string, unknown>> {
|
|
26
|
+
try {
|
|
27
|
+
const { stdout } = await exec("herdr-app", args, {
|
|
28
|
+
timeout: 7_000,
|
|
29
|
+
maxBuffer: 1024 * 1024,
|
|
30
|
+
});
|
|
31
|
+
const result = object(JSON.parse(stdout));
|
|
32
|
+
if (typeof result["error"] === "string") throw new Error(result["error"]);
|
|
33
|
+
return result;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
`Herdr window did not respond: ${error instanceof Error ? error.message : String(error)}`,
|
|
37
|
+
{ cause: error },
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function panes(
|
|
43
|
+
world: Record<string, unknown>,
|
|
44
|
+
): Array<{ space: string; tab: string; terminal: string; name: string }> {
|
|
45
|
+
if (!Array.isArray(world["spaces"]))
|
|
46
|
+
throw new Error("Herdr window returned an invalid workspace list");
|
|
47
|
+
const result: Array<{
|
|
48
|
+
space: string;
|
|
49
|
+
tab: string;
|
|
50
|
+
terminal: string;
|
|
51
|
+
name: string;
|
|
52
|
+
}> = [];
|
|
53
|
+
for (const space of world["spaces"]) {
|
|
54
|
+
const s = object(space);
|
|
55
|
+
if (typeof s["id"] !== "string" || !Array.isArray(s["tabs"]))
|
|
56
|
+
throw new Error("Herdr window returned an invalid workspace");
|
|
57
|
+
for (const tab of s["tabs"]) {
|
|
58
|
+
const t = object(tab);
|
|
59
|
+
if (typeof t["id"] !== "string" || !Array.isArray(t["terminals"]))
|
|
60
|
+
throw new Error("Herdr window returned an invalid tab");
|
|
61
|
+
for (const value of t["terminals"]) {
|
|
62
|
+
const terminal = object(value);
|
|
63
|
+
if (typeof terminal["terminal"] === "string")
|
|
64
|
+
result.push({
|
|
65
|
+
space: s["id"],
|
|
66
|
+
tab: t["id"],
|
|
67
|
+
terminal: terminal["terminal"],
|
|
68
|
+
name: typeof terminal["name"] === "string" ? terminal["name"] : "",
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Verify the selected window sees this Core before acting on its local terminal IDs. */
|
|
77
|
+
export async function focusCoreWindow(
|
|
78
|
+
core: CoreClient,
|
|
79
|
+
target: string,
|
|
80
|
+
): Promise<void> {
|
|
81
|
+
if (!/^t[0-9a-z]+$/.test(target))
|
|
82
|
+
throw new Error("Use the exact local terminal address");
|
|
83
|
+
const socket = appSocket();
|
|
84
|
+
const original = await stat(socket).catch(() => {
|
|
85
|
+
throw new Error("Open the Herdr window on this machine and retry focus");
|
|
86
|
+
});
|
|
87
|
+
const token = randomBytes(12).toString("hex");
|
|
88
|
+
const name = `probe-${token}`;
|
|
89
|
+
const space = `sp${token}`;
|
|
90
|
+
const tab = `tb${token}`;
|
|
91
|
+
let probe: string | undefined;
|
|
92
|
+
let focused = false;
|
|
93
|
+
let failed = false;
|
|
94
|
+
let failure: unknown;
|
|
95
|
+
try {
|
|
96
|
+
const created = object(
|
|
97
|
+
await core.request("terminal.run", {
|
|
98
|
+
argv: [process.execPath, "-e", "setTimeout(()=>{},120000)"],
|
|
99
|
+
name,
|
|
100
|
+
labels: { "herdr.space": space, "herdr.tab": tab },
|
|
101
|
+
no_parent: true,
|
|
102
|
+
no_notify: true,
|
|
103
|
+
rm: true,
|
|
104
|
+
}),
|
|
105
|
+
);
|
|
106
|
+
if (
|
|
107
|
+
typeof created["address"] !== "string" ||
|
|
108
|
+
!/^t[0-9a-z]+$/.test(created["address"])
|
|
109
|
+
)
|
|
110
|
+
throw new Error(
|
|
111
|
+
"Core did not return a probe terminal; inspect its terminals before retrying",
|
|
112
|
+
);
|
|
113
|
+
probe = created["address"];
|
|
114
|
+
const deadline = Date.now() + 8_000;
|
|
115
|
+
let world: ReturnType<typeof panes> = [];
|
|
116
|
+
while (Date.now() < deadline) {
|
|
117
|
+
world = panes(await app(["ls"]));
|
|
118
|
+
if (
|
|
119
|
+
world.some(
|
|
120
|
+
(entry) =>
|
|
121
|
+
entry.space === space &&
|
|
122
|
+
entry.tab === tab &&
|
|
123
|
+
entry.terminal === probe &&
|
|
124
|
+
entry.name === name,
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
break;
|
|
128
|
+
await delay(100);
|
|
129
|
+
}
|
|
130
|
+
if (
|
|
131
|
+
!world.some(
|
|
132
|
+
(entry) =>
|
|
133
|
+
entry.space === space &&
|
|
134
|
+
entry.tab === tab &&
|
|
135
|
+
entry.terminal === probe &&
|
|
136
|
+
entry.name === name,
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
throw new Error(
|
|
140
|
+
"This Herdr window is not connected to the target Core; open its window and retry",
|
|
141
|
+
);
|
|
142
|
+
const checkWindow = async () => {
|
|
143
|
+
const current = await stat(socket);
|
|
144
|
+
if (current.dev !== original.dev || current.ino !== original.ino)
|
|
145
|
+
throw new Error(
|
|
146
|
+
"Herdr window changed during focus; inspect it before retrying",
|
|
147
|
+
);
|
|
148
|
+
};
|
|
149
|
+
await checkWindow();
|
|
150
|
+
if (!world.some((entry) => entry.terminal === target)) {
|
|
151
|
+
await app(["do", "space.select", JSON.stringify({ id: space })]);
|
|
152
|
+
await checkWindow();
|
|
153
|
+
await app(["do", "terminal.keep", JSON.stringify({ terminal: target })]);
|
|
154
|
+
const adoptionDeadline = Date.now() + 8_000;
|
|
155
|
+
while (Date.now() < adoptionDeadline) {
|
|
156
|
+
world = panes(await app(["ls"]));
|
|
157
|
+
if (world.some((entry) => entry.terminal === target)) break;
|
|
158
|
+
await delay(100);
|
|
159
|
+
}
|
|
160
|
+
if (!world.some((entry) => entry.terminal === target))
|
|
161
|
+
throw new Error(
|
|
162
|
+
"Herdr did not finish opening the target; inspect its window before retrying",
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
await checkWindow();
|
|
166
|
+
await app(["do", "pane.focus", JSON.stringify({ terminal: target })]);
|
|
167
|
+
focused = true;
|
|
168
|
+
} catch (error) {
|
|
169
|
+
failed = true;
|
|
170
|
+
failure = error;
|
|
171
|
+
} finally {
|
|
172
|
+
if (probe) {
|
|
173
|
+
try {
|
|
174
|
+
await core.request("terminal.kill", { terminal: probe });
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (
|
|
177
|
+
error instanceof Error &&
|
|
178
|
+
"kind" in error &&
|
|
179
|
+
error.kind === "not_found"
|
|
180
|
+
) {
|
|
181
|
+
if (failed) throw failure;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
throw new Error(
|
|
185
|
+
`${focused ? "Focus succeeded" : `Focus failed: ${String(failure)}`} but its temporary terminal could not be closed: ${String(error)}`,
|
|
186
|
+
{ cause: failure ?? error },
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (failed) throw failure;
|
|
192
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access, stat } from "node:fs/promises";
|
|
3
|
+
import { delimiter, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
/** @param {string} cwd Resolve on the target so Core cannot mistake Pi for a template. */
|
|
6
|
+
export async function piExecutable(cwd) {
|
|
7
|
+
const windows = process.platform === "win32";
|
|
8
|
+
const suffixes = windows
|
|
9
|
+
? (process.env["PATHEXT"] || ".COM;.EXE;.BAT;.CMD")
|
|
10
|
+
.split(";")
|
|
11
|
+
.filter(Boolean)
|
|
12
|
+
: [""];
|
|
13
|
+
for (const directory of (process.env["PATH"] || "").split(delimiter)) {
|
|
14
|
+
for (const suffix of suffixes) {
|
|
15
|
+
const path = resolve(cwd, directory || ".", `pi${suffix}`);
|
|
16
|
+
try {
|
|
17
|
+
if (!(await stat(path)).isFile()) continue;
|
|
18
|
+
await access(path, windows ? constants.F_OK : constants.X_OK);
|
|
19
|
+
return windows ? path.replaceAll("\\", "/") : path;
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (
|
|
22
|
+
!error ||
|
|
23
|
+
typeof error !== "object" ||
|
|
24
|
+
!("code" in error) ||
|
|
25
|
+
!["ENOENT", "EACCES", "ENOTDIR"].includes(String(error.code))
|
|
26
|
+
)
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
throw new Error(
|
|
32
|
+
"Pi is not on PATH on the target machine; install it before spawning an agent",
|
|
33
|
+
);
|
|
34
|
+
}
|