@powerhousedao/host-core 6.4.0-next.3 → 6.4.0-next.5

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.
Files changed (44) hide show
  1. package/dist/{compound-L62ALvYc.d.mts → compound-BLhEewO6.d.mts} +8 -2
  2. package/dist/compound-BLhEewO6.d.mts.map +1 -0
  3. package/dist/{compound-Q9sZSEZF.mjs → compound-g6x_KkWp.mjs} +133 -1208
  4. package/dist/compound-g6x_KkWp.mjs.map +1 -0
  5. package/dist/control-channel-DVn4dvfQ.d.mts +206 -0
  6. package/dist/control-channel-DVn4dvfQ.d.mts.map +1 -0
  7. package/dist/control-channel.d.mts +2 -2
  8. package/dist/control-channel.mjs +358 -47
  9. package/dist/control-channel.mjs.map +1 -1
  10. package/dist/host-entry-B8n_590_.mjs +188 -0
  11. package/dist/host-entry-B8n_590_.mjs.map +1 -0
  12. package/dist/index.d.mts +68 -102
  13. package/dist/index.d.mts.map +1 -1
  14. package/dist/index.mjs +6 -3
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/instance-C6uugZ32.d.mts +165 -0
  17. package/dist/instance-C6uugZ32.d.mts.map +1 -0
  18. package/dist/instance.d.mts +3 -0
  19. package/dist/instance.mjs +145 -0
  20. package/dist/instance.mjs.map +1 -0
  21. package/dist/kill-tree.d.mts +2 -0
  22. package/dist/kill-tree.d.mts.map +1 -1
  23. package/dist/kill-tree.mjs +1 -1
  24. package/dist/kill-tree.mjs.map +1 -1
  25. package/dist/run-record-C6oTZF_C.mjs +1077 -0
  26. package/dist/run-record-C6oTZF_C.mjs.map +1 -0
  27. package/dist/runners/compound.d.mts +1 -1
  28. package/dist/runners/compound.mjs +2 -1
  29. package/dist/runners/compound.mjs.map +1 -1
  30. package/dist/spawn-host-DWroRe1S.d.mts +107 -0
  31. package/dist/spawn-host-DWroRe1S.d.mts.map +1 -0
  32. package/dist/supervisor-record.d.mts +88 -0
  33. package/dist/supervisor-record.d.mts.map +1 -0
  34. package/dist/supervisor-record.mjs +127 -0
  35. package/dist/supervisor-record.mjs.map +1 -0
  36. package/dist/supervisor.d.mts +205 -0
  37. package/dist/supervisor.d.mts.map +1 -0
  38. package/dist/supervisor.mjs +905 -0
  39. package/dist/supervisor.mjs.map +1 -0
  40. package/package.json +21 -3
  41. package/dist/compound-L62ALvYc.d.mts.map +0 -1
  42. package/dist/compound-Q9sZSEZF.mjs.map +0 -1
  43. package/dist/control-channel-eqvyUF03.d.mts +0 -123
  44. package/dist/control-channel-eqvyUF03.d.mts.map +0 -1
@@ -2,6 +2,7 @@ import crypto from "node:crypto";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { z } from "zod";
5
+ import { execFile } from "node:child_process";
5
6
  import net from "node:net";
6
7
  import os from "node:os";
7
8
  //#region src/control-channel.ts
@@ -13,21 +14,57 @@ import os from "node:os";
13
14
  * address and token are in the process's run record (`extra.control`).
14
15
  *
15
16
  * Same user only. Elsewhere the socket is mode 0600 in a 0700 folder of the
16
- * user. On Windows the pipe's default access lets only its creator,
17
- * administrators and the system write to it; everyone may open it to read,
18
- * so the server sends nothing before a request that carries the token.
17
+ * user. On Windows the pipe's access list is replaced once it listens: the
18
+ * user alone, and no caller from the network ({@link ControlChannel.ownerOnly}
19
+ * says whether that took). Until then, and when it did not take, the pipe has
20
+ * the system's default list: only its creator, administrators and the system
21
+ * write to it, everyone may open it to read. So the server sends nothing
22
+ * before a request that carries the token, and drops a caller that sends
23
+ * none in time.
19
24
  *
20
- * One request and one answer per line, as JSON:
21
- * `{ protocol, id, token, method, params }` and
22
- * `{ id, ok: true, result }` or `{ id, ok: false, error: { code, message } }`.
25
+ * One JSON value per line. A request is
26
+ * `{ protocol, id, token, method, params }`. Its answer ends with
27
+ * `{ id, ok: true, result }` or `{ id, ok: false, error: { code, message } }`;
28
+ * before that a handler may send output as it is produced:
29
+ * `{ id, stream: "stdout" | "stderr", data }`, in the order it was written.
30
+ * `{ protocol, id, token, cancel: true }` cancels the request `id` of the
31
+ * same connection, and so does the end of the connection.
32
+ *
33
+ * A caller that can answer questions while its request runs lists their
34
+ * kinds in the request, `asks: [kind, ...]`. The handler may then ask one:
35
+ * `{ id, ask: { seq, kind, payload } }`, and the caller answers on the same
36
+ * connection with `{ protocol, id, token, answer: { seq, ok: true, result } }`
37
+ * or `{ ..., answer: { seq, ok: false, error: { code, message } } }`. An
38
+ * answer is taken at once, not behind the request it answers.
23
39
  */
24
- const CONTROL_PROTOCOL = 1;
40
+ /** 2: output frames, `cancel`, and asks for the kinds a request lists. A
41
+ * caller and a process of different protocols refuse each other, each naming
42
+ * both. */
43
+ const CONTROL_PROTOCOL = 2;
44
+ /** How long an ask waits for its answer unless told otherwise. */
45
+ const ASK_TIMEOUT_MS = 6e5;
25
46
  /** A run record's `extra.control`. */
26
47
  const controlRecordSchema = z.object({
27
48
  protocol: z.number().int(),
28
49
  address: z.string().min(1),
29
50
  token: z.string().min(1)
30
51
  });
52
+ const ERROR_CODES = /* @__PURE__ */ new Set([
53
+ "unauthorized",
54
+ "protocol",
55
+ "bad-request",
56
+ "unknown-method",
57
+ "failed",
58
+ "cancelled",
59
+ "unreachable",
60
+ "unsupported",
61
+ "refused",
62
+ "timeout"
63
+ ]);
64
+ /** `code` when it is one of ours, else `failed`. */
65
+ function errorCodeOf(code) {
66
+ return typeof code === "string" && ERROR_CODES.has(code) ? code : "failed";
67
+ }
31
68
  var ControlError = class extends Error {
32
69
  code;
33
70
  constructor(code, message) {
@@ -36,14 +73,27 @@ var ControlError = class extends Error {
36
73
  this.name = "ControlError";
37
74
  }
38
75
  };
76
+ /** The longest request line, and the longest line of output. */
39
77
  const MAX_LINE_BYTES = 1048576;
78
+ const MAX_FRAME_CHARS = 65536;
79
+ const HANDSHAKE_TIMEOUT_MS = 5e3;
80
+ const MAX_CONNECTIONS = 64;
40
81
  /** The control channel a live run of this record answers on, when it has
41
82
  * one of a protocol this version speaks. */
42
83
  function controlRecordOf(record) {
43
84
  const parsed = controlRecordSchema.safeParse(record?.extra?.control);
44
- if (!parsed.success || parsed.data.protocol !== 1) return;
85
+ if (!parsed.success || parsed.data.protocol !== 2) return;
45
86
  return parsed.data;
46
87
  }
88
+ /** The protocol of the control channel a record names, whichever it is. */
89
+ function controlProtocolOf(record) {
90
+ const parsed = controlRecordSchema.safeParse(record?.extra?.control);
91
+ return parsed.success ? parsed.data.protocol : void 0;
92
+ }
93
+ /** What a caller of one protocol is told about a process of another. */
94
+ function protocolMismatch(theirs) {
95
+ return `It speaks control protocol ${JSON.stringify(theirs)}, this process speaks 2: both must run the same version.`;
96
+ }
47
97
  function sameToken(given, token) {
48
98
  if (typeof given !== "string") return false;
49
99
  const a = Buffer.from(given);
@@ -85,11 +135,50 @@ function listen(server, address) {
85
135
  });
86
136
  });
87
137
  }
138
+ /** Windows PowerShell, by its own path: never one found through PATH. */
139
+ function windowsPowerShell() {
140
+ return path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
141
+ }
142
+ /** `$pipe`: the pipe `name`, opened with `rights`. */
143
+ const openPipe = (name, rights) => `$pipe = New-Object System.IO.Pipes.NamedPipeClientStream('.', '${name}', [System.IO.Pipes.PipeAccessRights]'${rights}', [System.IO.Pipes.PipeOptions]::None, [System.Security.Principal.TokenImpersonationLevel]::None, [System.IO.HandleInheritability]::None); \$pipe.Connect(2000); `;
144
+ function powerShell(script) {
145
+ return new Promise((resolve) => {
146
+ execFile(windowsPowerShell(), [
147
+ "-NoProfile",
148
+ "-NonInteractive",
149
+ "-Command",
150
+ script
151
+ ], {
152
+ windowsHide: true,
153
+ timeout: 15e3,
154
+ encoding: "utf8"
155
+ }, (error, stdout) => resolve(error ? void 0 : stdout.trim()));
156
+ });
157
+ }
158
+ /**
159
+ * The access list (SDDL) of the pipe `name` (as in `\\.\pipe\<name>`);
160
+ * undefined when it cannot be read. Windows only.
161
+ */
162
+ function pipeAccessList(name) {
163
+ return powerShell("$ErrorActionPreference = 'Stop'; " + openPipe(name, "ReadData, ReadPermissions") + "try { $pipe.GetAccessControl().GetSecurityDescriptorSddlForm('Access') } finally { $pipe.Dispose() }");
164
+ }
165
+ /** The access list a control pipe gets: no caller from the network, and the
166
+ * user `sid` alone. */
167
+ const ownerOnlyPipeAccess = (sid) => `D:P(D;;FA;;;NU)(A;;FA;;;${sid})`;
168
+ /**
169
+ * Replaces the access list of this process's pipe `name` with
170
+ * {@link ownerOnlyPipeAccess}. Node creates a pipe with the system's default
171
+ * list and has no call to set another, so a helper process of the same user
172
+ * does it (.NET's PipeSecurity through Windows PowerShell). Resolves false
173
+ * when that failed: the pipe keeps the default list.
174
+ */
175
+ async function restrictPipe(name) {
176
+ return await powerShell("$ErrorActionPreference = 'Stop'; $sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; " + openPipe(name, "ReadData, ReadPermissions, ChangePermissions") + `try { \$security = New-Object System.IO.Pipes.PipeSecurity; $security.SetSecurityDescriptorSddlForm('${ownerOnlyPipeAccess("' + $sid + '")}', 'Access'); \$pipe.SetAccessControl(\$security); 'restricted' } finally { \$pipe.Dispose() }`) === "restricted";
177
+ }
88
178
  /**
89
179
  * Opens a control channel for this process and resolves once it listens.
90
180
  * The server holds no process open. `hello` is answered by the channel
91
- * itself: `{ protocol, pid, mode: "ad hoc", methods }` and what `describe`
92
- * added.
181
+ * itself: `{ protocol, pid, mode, methods }` and what `describe` added.
93
182
  */
94
183
  async function openControlChannel(options = {}) {
95
184
  const token = crypto.randomBytes(32).toString("base64url");
@@ -98,72 +187,145 @@ async function openControlChannel(options = {}) {
98
187
  let description = {};
99
188
  handlers.set("hello", () => ({
100
189
  ...description,
101
- protocol: 1,
190
+ protocol: 2,
102
191
  pid: process.pid,
103
- mode: "ad hoc",
192
+ mode: options.mode ?? "ad hoc",
104
193
  methods: [...handlers.keys()]
105
194
  }));
106
- const answer = async (line) => {
195
+ /** The request a line holds, or the refusal it gets. */
196
+ const read = (line) => {
107
197
  let request;
108
198
  try {
109
199
  const parsed = JSON.parse(line);
110
200
  if (typeof parsed !== "object" || parsed === null) throw new Error();
111
201
  request = parsed;
112
202
  } catch {
113
- return refusal(void 0, "bad-request", "The request is not JSON.");
203
+ return { refused: refusal(void 0, "bad-request", "The request is not JSON.") };
114
204
  }
115
205
  const { id } = request;
116
- if (!sameToken(request.token, token)) return refusal(id, "unauthorized", "The token is missing or wrong.");
117
- if (request.protocol !== 1) return refusal(id, "protocol", `This process speaks control protocol 1, not ${JSON.stringify(request.protocol)}.`);
206
+ if (!sameToken(request.token, token)) return { refused: refusal(id, "unauthorized", "The token is missing or wrong.") };
207
+ if (request.protocol !== 2) return { refused: refusal(id, "protocol", `This process speaks control protocol 2, the request is of protocol ${JSON.stringify(request.protocol)}: both must run the same version.`) };
208
+ return { request };
209
+ };
210
+ const answer = async (request, call) => {
211
+ const { id } = request;
118
212
  const handler = typeof request.method === "string" ? handlers.get(request.method) : void 0;
119
213
  if (!handler) return refusal(id, "unknown-method", `Nothing here answers "${String(request.method)}".`);
120
214
  try {
121
215
  return {
122
216
  id,
123
217
  ok: true,
124
- result: await handler(request.params) ?? null
218
+ result: await handler(request.params, call) ?? null
125
219
  };
126
220
  } catch (error) {
127
- return refusal(id, "failed", error instanceof Error ? error.message : String(error));
221
+ return refusal(id, call.signal.aborted ? "cancelled" : "failed", error instanceof Error ? error.message : String(error));
128
222
  }
129
223
  };
130
224
  const sockets = /* @__PURE__ */ new Set();
131
225
  const server = net.createServer((socket) => {
132
226
  sockets.add(socket);
133
- socket.once("close", () => sockets.delete(socket));
227
+ const running = /* @__PURE__ */ new Map();
228
+ let handshake = setTimeout(() => socket.destroy(), options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS);
229
+ handshake.unref();
230
+ socket.once("close", () => {
231
+ sockets.delete(socket);
232
+ clearTimeout(handshake);
233
+ for (const { controller } of running.values()) controller.abort();
234
+ });
134
235
  socket.on("error", () => void 0);
135
236
  socket.setEncoding("utf8");
136
237
  let pending = "";
238
+ let dropped = false;
137
239
  let queue = Promise.resolve();
138
- socket.on("data", (chunk) => {
139
- pending += chunk;
140
- if (pending.length > MAX_LINE_BYTES) {
141
- socket.destroy();
240
+ const send = (value, end = false) => {
241
+ if (socket.destroyed) return;
242
+ const text = `${JSON.stringify(value)}\n`;
243
+ if (end) socket.end(text);
244
+ else socket.write(text);
245
+ };
246
+ const take = (line) => {
247
+ if (dropped) return;
248
+ const parsed = read(line);
249
+ if ("refused" in parsed) {
250
+ const { error } = parsed.refused;
251
+ dropped = error.code !== "protocol";
252
+ queue = queue.then(() => send(parsed.refused, dropped));
142
253
  return;
143
254
  }
255
+ clearTimeout(handshake);
256
+ handshake = void 0;
257
+ const { request } = parsed;
258
+ const { id } = request;
259
+ if (request.cancel === true) {
260
+ running.get(id)?.controller.abort();
261
+ return;
262
+ }
263
+ if ("answer" in request) {
264
+ settleAsk(running.get(id), request.answer);
265
+ return;
266
+ }
267
+ const controller = new AbortController();
268
+ const asks = /* @__PURE__ */ new Map();
269
+ running.set(id, {
270
+ controller,
271
+ asks
272
+ });
273
+ let seq = 0;
274
+ const call = {
275
+ signal: controller.signal,
276
+ write: (stream, data) => {
277
+ if (controller.signal.aborted) return;
278
+ for (let at = 0; at < data.length; at += MAX_FRAME_CHARS) send({
279
+ id,
280
+ stream,
281
+ data: data.slice(at, at + MAX_FRAME_CHARS)
282
+ });
283
+ },
284
+ asks: asksOf(request),
285
+ ask: (kind, payload, askOptions = {}) => askCaller({
286
+ id,
287
+ kind,
288
+ payload,
289
+ seq: ++seq,
290
+ asks,
291
+ call,
292
+ send
293
+ }, askOptions.timeoutMs ?? 6e5)
294
+ };
295
+ queue = queue.then(async () => {
296
+ const response = controller.signal.aborted ? refusal(id, "cancelled", "The request was cancelled.") : await answer(request, call);
297
+ running.delete(id);
298
+ for (const pending of asks.values()) pending.reject(new ControlError("cancelled", "The request ended first."));
299
+ asks.clear();
300
+ send(response);
301
+ });
302
+ };
303
+ socket.on("data", (chunk) => {
304
+ pending += chunk;
144
305
  for (;;) {
145
306
  const end = pending.indexOf("\n");
146
307
  if (end === -1) break;
147
308
  const line = pending.slice(0, end);
148
309
  pending = pending.slice(end + 1);
149
310
  if (line.trim() === "") continue;
150
- queue = queue.then(async () => {
151
- const response = await answer(line);
152
- if (socket.destroyed) return;
153
- const refused = response.ok === false && response.error.code === "unauthorized";
154
- const text = `${JSON.stringify(response)}\n`;
155
- if (refused) socket.end(text);
156
- else socket.write(text);
157
- });
311
+ if (Buffer.byteLength(line) > 1048576) {
312
+ socket.destroy();
313
+ return;
314
+ }
315
+ take(line);
158
316
  }
317
+ if (Buffer.byteLength(pending) > 1048576) socket.destroy();
159
318
  });
160
319
  });
320
+ server.maxConnections = MAX_CONNECTIONS;
161
321
  server.on("error", () => void 0);
162
322
  let address;
163
323
  let socketFile;
324
+ let ownerOnly;
164
325
  if (process.platform === "win32") {
165
326
  address = `\\\\.\\pipe\\ph-control-${name}`;
166
327
  await listen(server, address);
328
+ ownerOnly = await restrictPipe(`ph-control-${name}`);
167
329
  } else {
168
330
  const dir = userSocketDir(options.socketDir);
169
331
  sweepSockets(dir);
@@ -178,6 +340,7 @@ async function openControlChannel(options = {}) {
178
340
  if (umask !== void 0) process.umask(umask);
179
341
  }
180
342
  fs.chmodSync(address, 384);
343
+ ownerOnly = true;
181
344
  }
182
345
  server.unref();
183
346
  const removeSocket = () => {
@@ -187,10 +350,11 @@ async function openControlChannel(options = {}) {
187
350
  let closing;
188
351
  return {
189
352
  record: {
190
- protocol: 1,
353
+ protocol: 2,
191
354
  address,
192
355
  token
193
356
  },
357
+ ownerOnly,
194
358
  handle(method, handler) {
195
359
  handlers.set(method, handler);
196
360
  },
@@ -220,6 +384,68 @@ function refusal(id, code, message) {
220
384
  }
221
385
  };
222
386
  }
387
+ /** The kinds of ask a request says its caller answers. */
388
+ function asksOf(request) {
389
+ const { asks } = request;
390
+ return new Set(Array.isArray(asks) ? asks.filter((kind) => typeof kind === "string") : []);
391
+ }
392
+ /** Settles the ask an answer line names; one that names none is dropped. */
393
+ function settleAsk(request, answer) {
394
+ if (!request || typeof answer !== "object" || answer === null) return;
395
+ const { seq, ok, result, error } = answer;
396
+ if (typeof seq !== "number") return;
397
+ const pending = request.asks.get(seq);
398
+ if (!pending) return;
399
+ request.asks.delete(seq);
400
+ if (ok === true) {
401
+ pending.resolve(result);
402
+ return;
403
+ }
404
+ pending.reject(new ControlError(errorCodeOf(error?.code), typeof error?.message === "string" ? error.message : "The caller did not answer."));
405
+ }
406
+ /** Sends one ask to the caller and waits for its answer. */
407
+ function askCaller(o, timeoutMs) {
408
+ const { id, kind, seq, asks, call } = o;
409
+ if (!call.asks.has(kind)) return Promise.reject(new ControlError("unsupported", `The caller does not answer "${kind}": it runs another version.`));
410
+ if (call.signal.aborted) return Promise.reject(new ControlError("cancelled", "The request was cancelled."));
411
+ const frame = {
412
+ id,
413
+ ask: {
414
+ seq,
415
+ kind,
416
+ payload: o.payload ?? null
417
+ }
418
+ };
419
+ if (Buffer.byteLength(JSON.stringify(frame)) > 1047552) return Promise.reject(new ControlError("bad-request", `"${kind}" is too large to ask the caller (${Math.floor(MAX_LINE_BYTES / 1024)} KiB at most).`));
420
+ return new Promise((resolve, reject) => {
421
+ const done = () => {
422
+ clearTimeout(timer);
423
+ call.signal.removeEventListener("abort", cancelled);
424
+ asks.delete(seq);
425
+ };
426
+ const cancelled = () => {
427
+ done();
428
+ reject(new ControlError("cancelled", "The request was cancelled."));
429
+ };
430
+ const timer = setTimeout(() => {
431
+ done();
432
+ reject(new ControlError("timeout", `The caller did not answer "${kind}" within ${Math.round(timeoutMs / 1e3)} s.`));
433
+ }, timeoutMs);
434
+ timer.unref();
435
+ call.signal.addEventListener("abort", cancelled, { once: true });
436
+ asks.set(seq, {
437
+ resolve: (result) => {
438
+ done();
439
+ resolve(result);
440
+ },
441
+ reject: (error) => {
442
+ done();
443
+ reject(error);
444
+ }
445
+ });
446
+ o.send(frame);
447
+ });
448
+ }
223
449
  const SLOT = Symbol.for("@powerhousedao/host-core/control-channel");
224
450
  const slot = () => globalThis[SLOT] ??= {};
225
451
  /**
@@ -254,22 +480,91 @@ const CONNECT_TIMEOUT_MS = 2e3;
254
480
  /**
255
481
  * One request to the control channel a run record names. Resolves with the
256
482
  * result; rejects with a {@link ControlError}: `unreachable` when nothing
257
- * answers there, else the code the other process refused with.
483
+ * answers there, `protocol` when it speaks another protocol, else the code
484
+ * the other process refused with. A request that is cancelled, or whose
485
+ * caller ends, is cancelled in the other process.
258
486
  */
259
487
  function callControl(control, method, params, options = {}) {
488
+ if (control.protocol !== 2) return Promise.reject(new ControlError("protocol", `Cannot ask the process at ${control.address} for "${method}". ${protocolMismatch(control.protocol)}`));
489
+ const { signal } = options;
490
+ if (signal?.aborted) return Promise.reject(new ControlError("cancelled", `"${method}" was cancelled.`));
260
491
  return new Promise((resolve, reject) => {
261
492
  const socket = net.connect(control.address);
262
493
  if (options.unref) socket.unref();
263
494
  let settled = false;
495
+ let connected = false;
264
496
  let pending = "";
265
497
  const timers = [];
498
+ const request = {
499
+ protocol: 2,
500
+ id: 1,
501
+ token: control.token
502
+ };
503
+ const cancel = () => {
504
+ const stop = () => reject(new ControlError("cancelled", `"${method}" was cancelled.`));
505
+ if (settled) return;
506
+ if (!connected) {
507
+ settle(stop);
508
+ return;
509
+ }
510
+ settled = true;
511
+ for (const timer of timers) clearTimeout(timer);
512
+ socket.end(`${JSON.stringify({
513
+ ...request,
514
+ cancel: true
515
+ })}\n`);
516
+ setTimeout(() => socket.destroy(), 500).unref();
517
+ stop();
518
+ };
266
519
  const settle = (finish) => {
267
520
  if (settled) return;
268
521
  settled = true;
269
522
  for (const timer of timers) clearTimeout(timer);
523
+ signal?.removeEventListener("abort", cancel);
524
+ asking.abort();
270
525
  socket.destroy();
271
526
  finish();
272
527
  };
528
+ const asking = new AbortController();
529
+ signal?.addEventListener("abort", () => asking.abort(), { once: true });
530
+ const answerAsk = async (ask) => {
531
+ const reply = (answer) => {
532
+ if (settled || socket.destroyed) return;
533
+ socket.write(`${JSON.stringify({
534
+ ...request,
535
+ answer: {
536
+ seq: ask.seq,
537
+ ...answer
538
+ }
539
+ })}\n`);
540
+ };
541
+ const kind = typeof ask.kind === "string" ? ask.kind : "";
542
+ if (!options.onAsk || !options.asks?.includes(kind)) {
543
+ reply({
544
+ ok: false,
545
+ error: {
546
+ code: "unsupported",
547
+ message: `This process does not answer "${kind}".`
548
+ }
549
+ });
550
+ return;
551
+ }
552
+ try {
553
+ reply({
554
+ ok: true,
555
+ result: await options.onAsk(kind, ask.payload, asking.signal) ?? null
556
+ });
557
+ } catch (error) {
558
+ reply({
559
+ ok: false,
560
+ error: {
561
+ code: errorCodeOf(error?.code),
562
+ message: error instanceof Error ? error.message : String(error)
563
+ }
564
+ });
565
+ }
566
+ };
567
+ signal?.addEventListener("abort", cancel, { once: true });
273
568
  const unreachable = (why) => settle(() => reject(new ControlError("unreachable", why)));
274
569
  const limit = (ms, why) => {
275
570
  const timer = setTimeout(() => unreachable(why), ms);
@@ -280,38 +575,54 @@ function callControl(control, method, params, options = {}) {
280
575
  const connecting = limit(options.connectTimeoutMs ?? CONNECT_TIMEOUT_MS, `No answer at the control channel ${control.address}.`);
281
576
  socket.setEncoding("utf8");
282
577
  socket.once("connect", () => {
578
+ connected = true;
283
579
  clearTimeout(connecting);
284
580
  if (options.timeoutMs !== void 0) limit(options.timeoutMs, `"${method}" was not answered within ${options.timeoutMs} ms.`);
285
581
  socket.write(`${JSON.stringify({
286
- protocol: 1,
287
- id: 1,
288
- token: control.token,
582
+ ...request,
289
583
  method,
290
- ...params === void 0 ? {} : { params }
584
+ ...params === void 0 ? {} : { params },
585
+ ...options.onAsk && options.asks?.length ? { asks: options.asks } : {}
291
586
  })}\n`);
292
587
  });
293
- socket.on("data", (chunk) => {
294
- pending += chunk;
295
- const end = pending.indexOf("\n");
296
- if (end === -1) return;
297
- let response;
588
+ const take = (line) => {
589
+ let frame;
298
590
  try {
299
- response = JSON.parse(pending.slice(0, end));
591
+ frame = JSON.parse(line);
300
592
  } catch {
301
593
  unreachable(`The control channel ${control.address} answered no JSON.`);
302
594
  return;
303
595
  }
304
- if (response.ok === true) {
305
- settle(() => resolve(response.result));
596
+ if (frame.stream === "stdout" || frame.stream === "stderr") {
597
+ if (typeof frame.data === "string") options.onOutput?.(frame.stream, frame.data);
598
+ return;
599
+ }
600
+ if (typeof frame.ask === "object" && frame.ask !== null) {
601
+ answerAsk(frame.ask);
602
+ return;
603
+ }
604
+ if (frame.ok === true) {
605
+ settle(() => resolve(frame.result));
306
606
  return;
307
607
  }
308
- settle(() => reject(new ControlError(response.error?.code ?? "failed", response.error?.message ?? `"${method}" failed.`)));
608
+ settle(() => reject(new ControlError(frame.error?.code ?? "failed", frame.error?.message ?? `"${method}" failed.`)));
609
+ };
610
+ socket.on("data", (chunk) => {
611
+ pending += chunk;
612
+ for (;;) {
613
+ if (settled) return;
614
+ const end = pending.indexOf("\n");
615
+ if (end === -1) break;
616
+ const line = pending.slice(0, end);
617
+ pending = pending.slice(end + 1);
618
+ if (line.trim() !== "") take(line);
619
+ }
309
620
  });
310
621
  socket.once("error", (error) => unreachable(`Cannot reach the control channel ${control.address}: ${error.message}`));
311
622
  socket.once("close", () => unreachable(`The process behind the control channel ${control.address} went away before it answered "${method}".`));
312
623
  });
313
624
  }
314
625
  //#endregion
315
- export { CONTROL_PROTOCOL, ControlError, callControl, closeProcessControlChannel, controlRecordOf, controlRecordSchema, ensureProcessControlChannel, openControlChannel, processControlChannel };
626
+ export { ASK_TIMEOUT_MS, CONTROL_PROTOCOL, ControlError, MAX_LINE_BYTES, callControl, closeProcessControlChannel, controlProtocolOf, controlRecordOf, controlRecordSchema, ensureProcessControlChannel, openControlChannel, ownerOnlyPipeAccess, pipeAccessList, processControlChannel, protocolMismatch };
316
627
 
317
628
  //# sourceMappingURL=control-channel.mjs.map