@jini-ai/sidecar 0.7.3-next.2 → 0.7.4

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/dist/json-ipc.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * `node:net`, `node:path`, `node:string_decoder`, the shared net close helper,
11
11
  * the IPC-path recognizer, and the public IPC types.
12
12
  */
13
+ import { runOperation } from '@jini-ai/core/errors/reporter';
13
14
  import { createConsoleLogger } from '@jini-ai/core/primitives';
14
15
  import { lstat, mkdir, rm } from "node:fs/promises";
15
16
  import { createConnection } from "node:net";
@@ -69,11 +70,26 @@ function summarizeJsonIpcMessage(message) {
69
70
  /**
70
71
  * @internal Emit a trace line to stderr when tracing is enabled.
71
72
  */
72
- function traceJsonIpc(event, details) {
73
+ function traceJsonIpc(event, details, { ports } = {}) {
73
74
  if (!jsonIpcTraceEnabled())
74
75
  return;
76
+ if (ports?.mode === "reporter") {
77
+ // Reporter mode keeps the host's one logger the only sink: no raw console write. `error` and
78
+ // `message` are payload keys a logger describes as a bare type, so the class label moves to a
79
+ // plain field instead of being flattened to "string".
80
+ const { error, ...rest } = details;
81
+ ports.logger.warn({ message: "[jini sidecar] json ipc trace" }, { meta: { event, ...rest, ...(error === undefined ? {} : { errorSummary: error }) } });
82
+ return;
83
+ }
75
84
  console.error("[jini sidecar] json ipc trace", { event, ...details });
76
85
  }
86
+ /**
87
+ * @internal The message-summary field of a server trace. Reporter mode omits it: a summary carries
88
+ * the caller's `type` and input keys, which are raw request content, not host-chosen labels.
89
+ */
90
+ function traceMessage({ ports, summary }, _optional = {}) {
91
+ return ports.mode === "reporter" ? {} : { message: summary };
92
+ }
77
93
  /**
78
94
  * @internal Extract a Node error `code` string from an unknown thrown value.
79
95
  */
@@ -145,182 +161,24 @@ export async function prepareIpcPath({ socketPath }, _optional = {}) {
145
161
  if (await staleUnixSocketExists(socketPath))
146
162
  await rm(socketPath, { force: true });
147
163
  }
164
+ /** Wire words when the reporter has none of its own to give. */
165
+ const IPC_HANDLER_FALLBACK = { message: "The sidecar could not finish this request.", action: "Try again, and report the error ID if it keeps failing." };
166
+ /** The only request labels a host may publish as a tracker attribute: short and fixed-shape, never request text. */
167
+ const IPC_METHOD_LABEL = /^[a-z][\w.:-]{0,63}$/i;
148
168
  /**
149
169
  * Start a newline-delimited JSON IPC server on a unix socket / named pipe: each
150
170
  * connection carries one JSON request, the handler's result is written back as
151
171
  * `{ok:true,result}` (or `{ok:false,error}` on parse/handler failure).
152
172
  * @returns A handle whose `close()` stops the server and unlinks the socket.
153
173
  */
154
- export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBytes = DEFAULT_MAX_FRAME_BYTES, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
174
+ export async function createJsonIpcServer({ handler, socketPath, }, optional = {}) {
175
+ const { maxFrameBytes = DEFAULT_MAX_FRAME_BYTES, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS, errors, logger } = optional;
176
+ // The mode is decided here, once: every connection below receives the same ports object.
177
+ const sink = logger ?? createConsoleLogger({ prefix: "" });
178
+ const ports = errors === undefined ? { mode: "legacy", logger: sink } : { mode: "reporter", errors, logger: sink };
155
179
  await prepareIpcPath({ socketPath });
156
180
  const server = createNetServer((socket) => {
157
- let buffer = "";
158
- let receivedBytes = 0;
159
- // One-request-per-connection guard (SEC-004): the `data` listener is `async`, so its
160
- // synchronous prefix (up to the first `await`) always finishes — and can set this flag —
161
- // before Node dispatches the next queued `data` event on this same socket. Once a frame has
162
- // been claimed, any further bytes on this connection (a second frame arriving while the
163
- // handler is still awaiting, or trailing garbage after the first frame) are ignored rather
164
- // than starting a second concurrent handler call / response race.
165
- let handled = false;
166
- // Decode UTF-8 across chunk boundaries: a multibyte character (e.g. CJK,
167
- // 3 bytes) can be split across two `data` events. `chunk.toString()` per
168
- // chunk would turn each half into U+FFFD, corrupting the payload (observed
169
- // as `???`/`◆?◆?◆?` in exported CJK artifacts). StringDecoder holds an
170
- // incomplete trailing sequence until the next chunk completes it.
171
- const decoder = new StringDecoder("utf8");
172
- const traceId = nextJsonIpcTraceId();
173
- const startedAt = process.hrtime.bigint();
174
- traceJsonIpc("server.connection", { socketPath, traceId });
175
- // Idle deadline (SEC-004): a peer that opens a connection and never completes a
176
- // newline-terminated frame (or dribbles bytes indefinitely) would otherwise hold the
177
- // connection — and this closure's buffer — open forever.
178
- const idleTimer = setTimeout(() => {
179
- // No `handled` re-check is needed here: the only way to set `handled` from a `data`
180
- // event is `claimFrame()` below, which clears this timer in the same synchronous step —
181
- // and Node/V8's single-threaded execution model means no other callback (including this
182
- // one) can run in between that assignment and the `clearTimeout` call. The fail-safe the
183
- // archived provenance ledger's 2026-07-22 entry kept against a future edit reordering that
184
- // sequence is now structural: the two steps live in one function and cannot be split.
185
- handled = true;
186
- traceJsonIpc("server.idle_timeout", {
187
- durationMs: jsonIpcTraceDurationMs(startedAt),
188
- idleTimeoutMs,
189
- socketPath,
190
- traceId,
191
- });
192
- socket.destroy();
193
- }, idleTimeoutMs);
194
- idleTimer.unref();
195
- /** Claim this connection's one frame: stop accepting data and cancel the idle deadline together. */
196
- const claimFrame = () => {
197
- handled = true;
198
- clearTimeout(idleTimer);
199
- };
200
- socket.on("error", (error) => {
201
- // `error instanceof Error` here is defense-in-depth, not reachable
202
- // through real socket usage: @types/node itself types a `Socket`'s
203
- // `'error'` listener parameter as `Error` (not `unknown`), matching
204
- // Node's own real implementation, which only ever emits genuine
205
- // `Error`/`SystemError` instances for this event — verified against
206
- // the installed `@types/node`'s `net.d.ts` this session; not asserted
207
- // away since a test would have to manually `.emit()` a fabricated
208
- // non-Error value to reach the other side, which isn't real socket
209
- // behavior (see archived provenance ledger's 2026-07-22 entry).
210
- traceJsonIpc("server.socket_error", {
211
- durationMs: jsonIpcTraceDurationMs(startedAt),
212
- error: describeErrorForLog({ err: error }),
213
- socketPath,
214
- traceId,
215
- });
216
- });
217
- socket.on("close", () => {
218
- clearTimeout(idleTimer);
219
- traceJsonIpc("server.socket_close", {
220
- durationMs: jsonIpcTraceDurationMs(startedAt),
221
- socketPath,
222
- traceId,
223
- });
224
- });
225
- socket.on("data", async (chunk) => {
226
- if (handled)
227
- return;
228
- traceJsonIpc("server.data", {
229
- bytes: chunk.byteLength,
230
- durationMs: jsonIpcTraceDurationMs(startedAt),
231
- socketPath,
232
- traceId,
233
- });
234
- receivedBytes += chunk.byteLength;
235
- if (receivedBytes > maxFrameBytes) {
236
- claimFrame();
237
- traceJsonIpc("server.frame_too_large", {
238
- durationMs: jsonIpcTraceDurationMs(startedAt),
239
- maxFrameBytes,
240
- receivedBytes,
241
- socketPath,
242
- traceId,
243
- });
244
- socket.end(`${JSON.stringify({
245
- ok: false,
246
- error: { code: "FRAME_TOO_LARGE", message: "request frame exceeds the maximum size" },
247
- })}\n`);
248
- return;
249
- }
250
- buffer += decoder.write(chunk);
251
- const newlineIndex = buffer.indexOf("\n");
252
- if (newlineIndex < 0)
253
- return;
254
- claimFrame(); // Claim the connection before awaiting the handler — see the flag's own doc above.
255
- const frame = buffer.slice(0, newlineIndex);
256
- buffer = buffer.slice(newlineIndex + 1);
257
- let message;
258
- try {
259
- message = JSON.parse(frame);
260
- }
261
- catch (error) {
262
- // `error instanceof Error` here is defense-in-depth, not reachable
263
- // through a real `JSON.parse` failure: it only ever throws a
264
- // genuine `SyntaxError` (an `Error` instance) for any string input
265
- // — never a non-Error value — matching the same reasoning as the
266
- // socket-error `instanceof Error` checks above (see
267
- // archived provenance ledger's 2026-07-22 entry).
268
- traceJsonIpc("server.frame_parse_failed", {
269
- durationMs: jsonIpcTraceDurationMs(startedAt),
270
- error: describeErrorForLog({ err: error }),
271
- frameBytes: Buffer.byteLength(frame),
272
- socketPath,
273
- traceId,
274
- });
275
- socket.end(`${JSON.stringify({
276
- ok: false,
277
- error: { code: "BAD_FRAME", message: "The sidecar could not read the request frame. Send one line of valid JSON." },
278
- })}\n`);
279
- return;
280
- }
281
- const messageSummary = summarizeJsonIpcMessage(message);
282
- traceJsonIpc("server.frame_parsed", {
283
- durationMs: jsonIpcTraceDurationMs(startedAt),
284
- frameBytes: Buffer.byteLength(frame),
285
- message: messageSummary,
286
- socketPath,
287
- traceId,
288
- });
289
- try {
290
- traceJsonIpc("server.handler_start", {
291
- durationMs: jsonIpcTraceDurationMs(startedAt),
292
- message: messageSummary,
293
- socketPath,
294
- traceId,
295
- });
296
- const result = await handler({ message });
297
- traceJsonIpc("server.handler_success", {
298
- durationMs: jsonIpcTraceDurationMs(startedAt),
299
- message: messageSummary,
300
- socketPath,
301
- traceId,
302
- });
303
- socket.end(`${JSON.stringify({ ok: true, result })}\n`);
304
- }
305
- catch (error) {
306
- // SEC-004: a handler failure can embed paths, credentials, or other host detail (the
307
- // same trust-boundary concern as SEC-005's HTTP fix). The peer gets a stable code plus
308
- // the traceId as a correlation handle; the error's class and code are logged
309
- // server-side only, unconditionally (not gated behind JINI_JSON_IPC_TRACE).
310
- createConsoleLogger({ prefix: '' }).error({ message: `[@jini-ai/sidecar] json-ipc handler failed (traceId=${traceId})` }, { error });
311
- traceJsonIpc("server.handler_failed", {
312
- durationMs: jsonIpcTraceDurationMs(startedAt),
313
- error: describeErrorForLog({ err: error }),
314
- message: messageSummary,
315
- socketPath,
316
- traceId,
317
- });
318
- socket.end(`${JSON.stringify({
319
- ok: false,
320
- error: { code: "HANDLER_ERROR", message: "internal error", requestId: traceId },
321
- })}\n`);
322
- }
323
- });
181
+ bindJsonIpcSocket({ socket, socketPath, handler, maxFrameBytes, idleTimeoutMs, ports });
324
182
  });
325
183
  await new Promise((resolveListen, rejectListen) => {
326
184
  server.once("error", rejectListen);
@@ -337,6 +195,265 @@ export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBy
337
195
  },
338
196
  };
339
197
  }
198
+ function bindJsonIpcSocket({ socket, socketPath, handler, maxFrameBytes, idleTimeoutMs, ports }, _optional = {}) {
199
+ // One-request-per-connection guard (SEC-004): the `data` listener is `async`, so its
200
+ // synchronous prefix (up to the first `await`) always finishes — and can set this flag —
201
+ // before Node dispatches the next queued `data` event on this same socket. Once a frame has
202
+ // been claimed, any further bytes on this connection (a second frame arriving while the
203
+ // handler is still awaiting, or trailing garbage after the first frame) are ignored rather
204
+ // than starting a second concurrent handler call / response race.
205
+ let handled = false;
206
+ // Decode UTF-8 across chunk boundaries: a multibyte character (e.g. CJK,
207
+ // 3 bytes) can be split across two `data` events. `chunk.toString()` per
208
+ // chunk would turn each half into U+FFFD, corrupting the payload (observed
209
+ // as `???`/`◆?◆?◆?` in exported CJK artifacts). StringDecoder holds an
210
+ // incomplete trailing sequence until the next chunk completes it.
211
+ const decoder = new StringDecoder("utf8");
212
+ const traceId = nextJsonIpcTraceId();
213
+ const startedAt = process.hrtime.bigint();
214
+ traceJsonIpc("server.connection", { socketPath, traceId }, { ports });
215
+ // Idle deadline (SEC-004): a peer that opens a connection and never completes a
216
+ // newline-terminated frame (or dribbles bytes indefinitely) would otherwise hold the
217
+ // connection — and this closure's buffer — open forever.
218
+ const idleTimer = setTimeout(() => {
219
+ // No `handled` re-check is needed here: the only way to set `handled` from a `data`
220
+ // event is `claimFrame()` below, which clears this timer in the same synchronous step —
221
+ // and Node/V8's single-threaded execution model means no other callback (including this
222
+ // one) can run in between that assignment and the `clearTimeout` call. The fail-safe the
223
+ // archived provenance ledger's 2026-07-22 entry kept against a future edit reordering that
224
+ // sequence is now structural: the two steps live in one function and cannot be split.
225
+ handled = true;
226
+ traceJsonIpc("server.idle_timeout", {
227
+ durationMs: jsonIpcTraceDurationMs(startedAt),
228
+ idleTimeoutMs,
229
+ socketPath,
230
+ traceId,
231
+ }, { ports });
232
+ socket.destroy();
233
+ }, idleTimeoutMs);
234
+ idleTimer.unref();
235
+ /** Claim this connection's one frame: stop accepting data and cancel the idle deadline together. */
236
+ const claimFrame = () => {
237
+ handled = true;
238
+ clearTimeout(idleTimer);
239
+ };
240
+ bindJsonIpcSocketTraces({ socket, socketPath, traceId, startedAt, idleTimer, ports });
241
+ bindJsonIpcData({ socket, socketPath, handler, maxFrameBytes, traceId, startedAt, decoder, isHandled: () => handled, claimFrame, ports });
242
+ }
243
+ function bindJsonIpcSocketTraces({ socket, socketPath, traceId, startedAt, idleTimer, ports }, _optional = {}) {
244
+ socket.on("error", (error) => {
245
+ // `error instanceof Error` here is defense-in-depth, not reachable
246
+ // through real socket usage: @types/node itself types a `Socket`'s
247
+ // `'error'` listener parameter as `Error` (not `unknown`), matching
248
+ // Node's own real implementation, which only ever emits genuine
249
+ // `Error`/`SystemError` instances for this event — verified against
250
+ // the installed `@types/node`'s `net.d.ts` this session; not asserted
251
+ // away since a test would have to manually `.emit()` a fabricated
252
+ // non-Error value to reach the other side, which isn't real socket
253
+ // behavior (see archived provenance ledger's 2026-07-22 entry).
254
+ traceJsonIpc("server.socket_error", {
255
+ durationMs: jsonIpcTraceDurationMs(startedAt),
256
+ error: describeErrorForLog({ err: error }),
257
+ socketPath,
258
+ traceId,
259
+ }, { ports });
260
+ });
261
+ socket.on("close", () => {
262
+ clearTimeout(idleTimer);
263
+ traceJsonIpc("server.socket_close", {
264
+ durationMs: jsonIpcTraceDurationMs(startedAt),
265
+ socketPath,
266
+ traceId,
267
+ }, { ports });
268
+ });
269
+ }
270
+ function bindJsonIpcData({ socket, socketPath, handler, maxFrameBytes, traceId, startedAt, decoder, isHandled, claimFrame, ports }, _optional = {}) {
271
+ let buffer = "";
272
+ let receivedBytes = 0;
273
+ socket.on("data", async (chunk) => {
274
+ if (isHandled())
275
+ return;
276
+ traceJsonIpc("server.data", {
277
+ bytes: chunk.byteLength,
278
+ durationMs: jsonIpcTraceDurationMs(startedAt),
279
+ socketPath,
280
+ traceId,
281
+ }, { ports });
282
+ receivedBytes += chunk.byteLength;
283
+ if (receivedBytes > maxFrameBytes) {
284
+ claimFrame();
285
+ traceJsonIpc("server.frame_too_large", {
286
+ durationMs: jsonIpcTraceDurationMs(startedAt),
287
+ maxFrameBytes,
288
+ receivedBytes,
289
+ socketPath,
290
+ traceId,
291
+ }, { ports });
292
+ socket.end(`${JSON.stringify({
293
+ ok: false,
294
+ error: { code: "FRAME_TOO_LARGE", message: "request frame exceeds the maximum size" },
295
+ })}\n`);
296
+ return;
297
+ }
298
+ buffer += decoder.write(chunk);
299
+ const newlineIndex = buffer.indexOf("\n");
300
+ if (newlineIndex < 0)
301
+ return;
302
+ claimFrame(); // Claim the connection before awaiting the handler — see the flag's own doc above.
303
+ const frame = buffer.slice(0, newlineIndex);
304
+ buffer = buffer.slice(newlineIndex + 1);
305
+ await parseAndDispatchJsonIpcFrame({ socket, socketPath, handler, traceId, startedAt, frame, ports });
306
+ });
307
+ }
308
+ async function parseAndDispatchJsonIpcFrame({ socket, socketPath, handler, traceId, startedAt, frame, ports }, _optional = {}) {
309
+ let message;
310
+ try {
311
+ message = JSON.parse(frame);
312
+ }
313
+ catch (error) {
314
+ // `error instanceof Error` here is defense-in-depth, not reachable
315
+ // through a real `JSON.parse` failure: it only ever throws a
316
+ // genuine `SyntaxError` (an `Error` instance) for any string input
317
+ // — never a non-Error value — matching the same reasoning as the
318
+ // socket-error `instanceof Error` checks above (see
319
+ // archived provenance ledger's 2026-07-22 entry).
320
+ traceJsonIpc("server.frame_parse_failed", {
321
+ durationMs: jsonIpcTraceDurationMs(startedAt),
322
+ error: describeErrorForLog({ err: error }),
323
+ frameBytes: Buffer.byteLength(frame),
324
+ socketPath,
325
+ traceId,
326
+ }, { ports });
327
+ socket.end(`${JSON.stringify({
328
+ ok: false,
329
+ error: { code: "BAD_FRAME", message: "The sidecar could not read the request frame. Send one line of valid JSON." },
330
+ })}\n`);
331
+ return;
332
+ }
333
+ const messageSummary = summarizeJsonIpcMessage(message);
334
+ traceJsonIpc("server.frame_parsed", {
335
+ durationMs: jsonIpcTraceDurationMs(startedAt),
336
+ frameBytes: Buffer.byteLength(frame),
337
+ ...traceMessage({ ports, summary: messageSummary }),
338
+ socketPath,
339
+ traceId,
340
+ }, { ports });
341
+ await dispatchJsonIpcHandler({ socket, socketPath, handler, traceId, startedAt, message, messageSummary, ports });
342
+ }
343
+ async function dispatchJsonIpcHandler(required, _optional = {}) {
344
+ const { ports } = required;
345
+ if (ports.mode === "reporter")
346
+ await dispatchViaReporter({ ...required, ports });
347
+ else
348
+ await dispatchLegacy(required);
349
+ }
350
+ /** The pre-reporter path, kept byte-for-byte in behavior for hosts that do not pass `errors`. */
351
+ async function dispatchLegacy({ socket, socketPath, handler, traceId, startedAt, message, messageSummary, ports }, _optional = {}) {
352
+ try {
353
+ traceJsonIpc("server.handler_start", {
354
+ durationMs: jsonIpcTraceDurationMs(startedAt),
355
+ message: messageSummary,
356
+ socketPath,
357
+ traceId,
358
+ });
359
+ const result = await handler({ message });
360
+ traceJsonIpc("server.handler_success", {
361
+ durationMs: jsonIpcTraceDurationMs(startedAt),
362
+ message: messageSummary,
363
+ socketPath,
364
+ traceId,
365
+ });
366
+ socket.end(`${JSON.stringify({ ok: true, result })}\n`);
367
+ }
368
+ catch (error) {
369
+ // SEC-004: a handler failure can embed paths, credentials, or other host detail (the
370
+ // same trust-boundary concern as SEC-005's HTTP fix). The peer gets a stable code plus
371
+ // the traceId as a correlation handle; the error's class and code are logged
372
+ // server-side only, unconditionally (not gated behind JINI_JSON_IPC_TRACE).
373
+ ports.logger.error({ message: `[@jini-ai/sidecar] json-ipc handler failed (traceId=${traceId})` }, { error });
374
+ traceJsonIpc("server.handler_failed", {
375
+ durationMs: jsonIpcTraceDurationMs(startedAt),
376
+ error: describeErrorForLog({ err: error }),
377
+ message: messageSummary,
378
+ socketPath,
379
+ traceId,
380
+ });
381
+ socket.end(`${JSON.stringify({
382
+ ok: false,
383
+ error: { code: "HANDLER_ERROR", message: "The sidecar could not finish this request. Try again, and report the request ID if it keeps failing.", requestId: traceId },
384
+ })}\n`);
385
+ }
386
+ }
387
+ /**
388
+ * @internal The host's request label as a tracker attribute value. Only a label matching
389
+ * {@link IPC_METHOD_LABEL} passes; message text, input keys and a throwing label function all
390
+ * give `unknown`, so request content can never become an indexed provider-side field.
391
+ */
392
+ function ipcMethodLabel({ methodOf, message }, _optional = {}) {
393
+ let candidate;
394
+ try {
395
+ candidate = methodOf?.({ message });
396
+ }
397
+ catch {
398
+ candidate = undefined;
399
+ }
400
+ return typeof candidate === "string" && IPC_METHOD_LABEL.test(candidate) ? candidate : "unknown";
401
+ }
402
+ /**
403
+ * @internal The wire frame of a settled operation. Both failure kinds keep the legacy code; an
404
+ * incident adds the ERR id the reporter put in its words, a refusal adds its own code as `reason`
405
+ * and no id.
406
+ */
407
+ function replyFrameFor({ run, refusalCode }, _optional = {}) {
408
+ if (run.ok)
409
+ return run.value;
410
+ // core only reports a cancellation when the caller passes a `settle` hook, and this call passes
411
+ // none, so a non-ok result always carries a described failure.
412
+ const { kind, error } = run.failure;
413
+ const wire = kind === "incident"
414
+ ? { code: refusalCode, message: error.message, requestId: error.requestId }
415
+ : { code: refusalCode, message: error.message, reason: error.code };
416
+ return `${JSON.stringify({ ok: false, error: wire })}\n`;
417
+ }
418
+ /**
419
+ * @internal End the connection with `frame`, containing a peer that hung up before the reply. The
420
+ * handler's own failure, if any, was already recorded once; a dead socket is not a second incident,
421
+ * so it gets a fixed warning with no error text.
422
+ */
423
+ function safeEnd({ socket, frame, logger }, _optional = {}) {
424
+ try {
425
+ if (socket.destroyed)
426
+ throw new Error("socket already destroyed");
427
+ socket.end(frame);
428
+ }
429
+ catch {
430
+ logger.warn({ message: "[@jini-ai/sidecar] json-ipc could not write the reply; the peer is gone." });
431
+ // Nothing more can be said on this connection; close it so a half-open peer is not left waiting.
432
+ socket.destroy();
433
+ }
434
+ }
435
+ async function dispatchViaReporter({ socket, socketPath, handler, traceId, startedAt, message, ports }, _optional = {}) {
436
+ const { errors, logger } = ports;
437
+ const trace = (event) => traceJsonIpc(event, { durationMs: jsonIpcTraceDurationMs(startedAt), socketPath, traceId }, { ports });
438
+ trace("server.handler_start");
439
+ // SEC-004 still holds: the peer's words come from the reporter (fixed fallback plus the ERR id),
440
+ // never from the thrown value. Serialising the success inside the operation makes an
441
+ // unserialisable result an incident like any handler throw, instead of a rejection after the
442
+ // operation had already ended as completed.
443
+ const run = await runOperation({
444
+ deps: { reporter: errors.reporter, observability: errors.observability },
445
+ operation: "ipc.handle",
446
+ scope: "ipc",
447
+ step: "Handle sidecar request",
448
+ fallback: IPC_HANDLER_FALLBACK,
449
+ // `ipc.trace_id` is the connection's own correlation handle and stays distinct from the ERR id.
450
+ attributes: { "ipc.method": ipcMethodLabel({ methodOf: errors.methodOf, message }), "ipc.trace_id": traceId },
451
+ work: async () => `${JSON.stringify({ ok: true, result: await handler({ message }) })}\n`,
452
+ });
453
+ trace(run.ok ? "server.handler_success" : "server.handler_failed");
454
+ // The operation has ended by here: a write that fails below cannot reopen or re-report it.
455
+ safeEnd({ socket, frame: replyFrameFor({ run, refusalCode: errors.refusalCode }), logger });
456
+ }
340
457
  /**
341
458
  * Send one newline-delimited JSON request over a unix socket / named pipe and
342
459
  * resolve with the server's `result`, rejecting on error response, malformed JSON,
@@ -348,136 +465,103 @@ export async function requestJsonIpc({ socketPath, payload }, { timeoutMs = 1500
348
465
  const socket = createConnection(socketPath);
349
466
  const traceId = nextJsonIpcTraceId();
350
467
  const startedAt = process.hrtime.bigint();
351
- let settled = false;
352
468
  let buffer = "";
353
469
  // See the server reader above: decode UTF-8 across chunk boundaries so a
354
470
  // multibyte character split across two `data` events is not corrupted.
355
471
  const decoder = new StringDecoder("utf8");
356
472
  const messageSummary = summarizeJsonIpcMessage(payload);
473
+ const trace = (event, extra = {}) => traceJsonIpc(event, { durationMs: jsonIpcTraceDurationMs(startedAt), message: messageSummary, socketPath, traceId, ...extra });
357
474
  traceJsonIpc("client.connect_start", { message: messageSummary, socketPath, timeoutMs, traceId });
358
- const settle = (callback) => {
359
- if (settled)
360
- return;
361
- settled = true;
362
- clearTimeout(timeout);
363
- callback();
364
- };
365
- const timeout = setTimeout(() => {
366
- traceJsonIpc("client.timeout", {
367
- durationMs: jsonIpcTraceDurationMs(startedAt),
368
- message: messageSummary,
369
- socketPath,
370
- timeoutMs,
371
- traceId,
372
- });
475
+ const settlement = createJsonIpcSettlement();
476
+ settlement.armTimeout(timeoutMs, () => {
477
+ trace("client.timeout", { timeoutMs });
373
478
  socket.destroy();
374
- settle(() => rejectRequest(new Error(`IPC request timed out: ${socketPath}`)));
375
- }, timeoutMs);
376
- socket.on("connect", () => {
377
- traceJsonIpc("client.connected", {
378
- durationMs: jsonIpcTraceDurationMs(startedAt),
379
- message: messageSummary,
380
- socketPath,
381
- traceId,
382
- });
383
- const frame = `${JSON.stringify(payload)}\n`;
384
- traceJsonIpc("client.write_start", {
385
- bytes: Buffer.byteLength(frame),
386
- durationMs: jsonIpcTraceDurationMs(startedAt),
387
- message: messageSummary,
388
- socketPath,
389
- traceId,
390
- });
391
- const flushed = socket.write(frame, () => {
392
- traceJsonIpc("client.write_callback", {
393
- durationMs: jsonIpcTraceDurationMs(startedAt),
394
- message: messageSummary,
395
- socketPath,
396
- traceId,
397
- });
398
- });
399
- if (!flushed) {
400
- socket.once("drain", () => {
401
- traceJsonIpc("client.drain", {
402
- durationMs: jsonIpcTraceDurationMs(startedAt),
403
- message: messageSummary,
404
- socketPath,
405
- traceId,
406
- });
407
- });
408
- }
479
+ settlement.settle(() => rejectRequest(new Error(`IPC request timed out: ${socketPath}`)));
409
480
  });
481
+ socket.on("connect", () => writeJsonIpcRequest({ socket, payload, trace }));
410
482
  socket.on("data", (chunk) => {
411
- traceJsonIpc("client.data", {
412
- bytes: chunk.byteLength,
413
- durationMs: jsonIpcTraceDurationMs(startedAt),
414
- message: messageSummary,
415
- socketPath,
416
- traceId,
417
- });
483
+ trace("client.data", { bytes: chunk.byteLength });
418
484
  buffer += decoder.write(chunk);
419
485
  const newlineIndex = buffer.indexOf("\n");
420
486
  if (newlineIndex < 0)
421
487
  return;
422
488
  socket.end();
423
- settle(() => {
424
- let response;
425
- try {
426
- response = JSON.parse(buffer.slice(0, newlineIndex));
427
- }
428
- catch (error) {
429
- // Event-handler throws cannot reject the request promise.
430
- rejectRequest(error);
431
- return;
432
- }
433
- if (!response.ok) {
434
- traceJsonIpc("client.response_error", {
435
- durationMs: jsonIpcTraceDurationMs(startedAt),
436
- error: response.error?.message ?? "IPC request failed",
437
- message: messageSummary,
438
- socketPath,
439
- traceId,
440
- });
441
- rejectRequest(ipcResponseError(response.error));
442
- return;
443
- }
444
- traceJsonIpc("client.response_success", {
445
- durationMs: jsonIpcTraceDurationMs(startedAt),
446
- message: messageSummary,
447
- socketPath,
448
- traceId,
449
- });
450
- resolveRequest(response.result);
451
- });
489
+ const line = buffer.slice(0, newlineIndex);
490
+ settlement.settle(() => deliverJsonIpcReply({ line, trace, resolveRequest, rejectRequest }));
452
491
  });
453
492
  socket.on("error", (error) => {
454
493
  // Same defense-in-depth, not-reachable-through-real-usage reasoning as
455
494
  // the server-side `error instanceof Error` check above (see that
456
495
  // comment + archived provenance ledger's 2026-07-22 entry).
457
- traceJsonIpc("client.socket_error", {
458
- durationMs: jsonIpcTraceDurationMs(startedAt),
459
- error: describeErrorForLog({ err: error }),
460
- message: messageSummary,
461
- socketPath,
462
- traceId,
463
- });
464
- settle(() => rejectRequest(error));
496
+ trace("client.socket_error", { error: describeErrorForLog({ err: error }) });
497
+ settlement.settle(() => rejectRequest(error));
465
498
  });
466
499
  socket.on("close", () => {
467
- traceJsonIpc("client.socket_close", {
468
- durationMs: jsonIpcTraceDurationMs(startedAt),
469
- message: messageSummary,
470
- socketPath,
471
- traceId,
472
- });
473
- settle(() => rejectRequest(new Error(`IPC connection closed before a complete response: ${socketPath}`)));
500
+ trace("client.socket_close");
501
+ settlement.settle(() => rejectRequest(new Error(`IPC connection closed before a complete response: ${socketPath}`)));
474
502
  });
475
503
  });
476
504
  }
505
+ /**
506
+ * @internal The single owner of one client request's final resolution and timer cleanup:
507
+ * `settle` runs its callback at most once (later socket events — a late reply, the close that
508
+ * follows a timeout — are no-ops) and clears the timeout first.
509
+ */
510
+ function createJsonIpcSettlement() {
511
+ let settled = false;
512
+ let timeout;
513
+ return {
514
+ armTimeout: (timeoutMs, onTimeout) => {
515
+ timeout = setTimeout(onTimeout, timeoutMs);
516
+ },
517
+ settle: (callback) => {
518
+ if (settled)
519
+ return;
520
+ settled = true;
521
+ clearTimeout(timeout);
522
+ callback();
523
+ },
524
+ };
525
+ }
526
+ /** @internal Encode the request as one newline-terminated JSON frame and write it, tracing each write stage. */
527
+ function writeJsonIpcRequest({ socket, payload, trace }, _optional = {}) {
528
+ trace("client.connected");
529
+ const frame = `${JSON.stringify(payload)}\n`;
530
+ trace("client.write_start", { bytes: Buffer.byteLength(frame) });
531
+ const flushed = socket.write(frame, () => trace("client.write_callback"));
532
+ if (!flushed)
533
+ socket.once("drain", () => trace("client.drain"));
534
+ }
535
+ /**
536
+ * @internal Parse one complete reply line and resolve/reject the request accordingly. Runs inside
537
+ * the settlement callback, so a parse failure rejects here (event-handler throws cannot reject
538
+ * the request promise).
539
+ */
540
+ function deliverJsonIpcReply({ line, trace, resolveRequest, rejectRequest }, _optional = {}) {
541
+ let response;
542
+ try {
543
+ response = JSON.parse(line);
544
+ }
545
+ catch (error) {
546
+ // Event-handler throws cannot reject the request promise.
547
+ rejectRequest(error);
548
+ return;
549
+ }
550
+ if (!response.ok) {
551
+ trace("client.response_error", { error: response.error?.message ?? "IPC request failed" });
552
+ rejectRequest(ipcResponseError(response.error));
553
+ return;
554
+ }
555
+ trace("client.response_success");
556
+ resolveRequest(response.result);
557
+ }
477
558
  function ipcResponseError(error) {
478
559
  const rejection = new Error(error?.message ?? "IPC request failed");
479
560
  if (error?.code !== undefined)
480
561
  rejection.code = error.code;
562
+ // `reason` names a refusal's own code and rides beside `code`, which keeps its legacy value.
563
+ if (error?.reason !== undefined)
564
+ rejection.reason = error.reason;
481
565
  if (error?.requestId !== undefined)
482
566
  rejection.requestId = error.requestId;
483
567
  return rejection;