@jini-ai/sidecar 0.1.0

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.
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @module json-file
3
+ *
4
+ * Small JSON file helpers for sidecar runtime state: a forgiving reader (null on
5
+ * any failure), an atomic pretty-printed writer via temp-file rename, a
6
+ * best-effort remove, and a guarded pointer removal that only deletes when the
7
+ * pointer still names the given run. Depends on `node:fs/promises` and
8
+ * `node:path`.
9
+ */
10
+ /**
11
+ * Read and parse a JSON file, swallowing any read/parse error.
12
+ * @returns The parsed value, or `null` if missing or unreadable.
13
+ */
14
+ export declare function readJsonFile<T = any>(filePath: string): Promise<T | null>;
15
+ /**
16
+ * Atomically write `payload` as pretty-printed JSON via a temp-file rename,
17
+ * creating the parent directory if needed.
18
+ */
19
+ export declare function writeJsonFile(filePath: string, payload: unknown): Promise<void>;
20
+ /**
21
+ * Remove a file, forcing (no error if absent).
22
+ */
23
+ export declare function removeFile(filePath: string): Promise<void>;
24
+ /**
25
+ * Remove a pointer file only if it still points at `runId`.
26
+ */
27
+ export declare function removePointerIfCurrent(pointerPath: string, runId: string): Promise<void>;
28
+ //# sourceMappingURL=json-file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-file.d.ts","sourceRoot":"","sources":["../src/json-file.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH;;;GAGG;AACH,wBAAsB,YAAY,CAAC,CAAC,GAAG,GAAG,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAM/E;AAED;;;GAGG;AACH,wBAAsB,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAKrF;AAED;;GAEG;AACH,wBAAsB,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhE;AAED;;GAEG;AACH,wBAAsB,sBAAsB,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAG9F"}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @module json-file
3
+ *
4
+ * Small JSON file helpers for sidecar runtime state: a forgiving reader (null on
5
+ * any failure), an atomic pretty-printed writer via temp-file rename, a
6
+ * best-effort remove, and a guarded pointer removal that only deletes when the
7
+ * pointer still names the given run. Depends on `node:fs/promises` and
8
+ * `node:path`.
9
+ */
10
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
11
+ import { dirname } from "node:path";
12
+ /**
13
+ * Read and parse a JSON file, swallowing any read/parse error.
14
+ * @returns The parsed value, or `null` if missing or unreadable.
15
+ */
16
+ export async function readJsonFile(filePath) {
17
+ try {
18
+ return JSON.parse(await readFile(filePath, "utf8"));
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
24
+ /**
25
+ * Atomically write `payload` as pretty-printed JSON via a temp-file rename,
26
+ * creating the parent directory if needed.
27
+ */
28
+ export async function writeJsonFile(filePath, payload) {
29
+ await mkdir(dirname(filePath), { recursive: true });
30
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
31
+ await writeFile(tmpPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
32
+ await rename(tmpPath, filePath);
33
+ }
34
+ /**
35
+ * Remove a file, forcing (no error if absent).
36
+ */
37
+ export async function removeFile(filePath) {
38
+ await rm(filePath, { force: true });
39
+ }
40
+ /**
41
+ * Remove a pointer file only if it still points at `runId`.
42
+ */
43
+ export async function removePointerIfCurrent(pointerPath, runId) {
44
+ const pointer = await readJsonFile(pointerPath);
45
+ if (pointer?.runId === runId)
46
+ await removeFile(pointerPath);
47
+ }
48
+ //# sourceMappingURL=json-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-file.js","sourceRoot":"","sources":["../src/json-file.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAU,QAAgB;IAC1D,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAM,CAAC;IAC3D,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,QAAgB,EAAE,OAAgB;IACpE,MAAM,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,MAAM,OAAO,GAAG,GAAG,QAAQ,IAAI,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC;IAC/D,MAAM,SAAS,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IAC1E,MAAM,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AAClC,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,QAAgB;IAC/C,MAAM,EAAE,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AACtC,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,WAAmB,EAAE,KAAa;IAC7E,MAAM,OAAO,GAAG,MAAM,YAAY,CAAqB,WAAW,CAAC,CAAC;IACpE,IAAI,OAAO,EAAE,KAAK,KAAK,KAAK;QAAE,MAAM,UAAU,CAAC,WAAW,CAAC,CAAC;AAC9D,CAAC"}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @module json-ipc
3
+ *
4
+ * Newline-delimited JSON IPC over a unix socket / Windows named pipe. Provides a
5
+ * server that decodes one JSON frame per connection (UTF-8 safe across chunk
6
+ * boundaries), runs a handler, and replies `{ok,result}`/`{ok:false,error}`, plus
7
+ * a client request with timeout. Includes opt-in structured tracing (gated by
8
+ * `JINI_JSON_IPC_TRACE`) and stale-socket cleanup before binding. The trace
9
+ * sequence counter is module-private singleton state. Depends on `node:fs`,
10
+ * `node:net`, `node:path`, `node:string_decoder`, the shared net close helper,
11
+ * the IPC-path recognizer, and the public IPC types.
12
+ */
13
+ import type { JsonIpcHandler, JsonIpcServerHandle } from "./types.js";
14
+ /**
15
+ * Shape an unknown error into the `{code?,message}` IPC error payload.
16
+ *
17
+ * Exported (previously module-private) for direct unit testing: its only
18
+ * current caller (a `JSON.parse` frame-parse failure) always passes a
19
+ * codeless `SyntaxError`, so the `code`-present branch below is real,
20
+ * generically useful behavior (any future caller with a Node-style errno
21
+ * error benefits from it) with no in-tree caller that happens to have one in
22
+ * hand today — matching this repo's "extract into a directly-testable pure
23
+ * function" convention rather than narrowing the type away.
24
+ */
25
+ export declare function jsonIpcError(error: unknown): {
26
+ code?: string;
27
+ message: string;
28
+ };
29
+ /**
30
+ * Prepare a socket path for binding: ensure the parent dir exists and
31
+ * unlink a stale socket (no-op for Windows named pipes).
32
+ *
33
+ * Exported (previously module-private) for direct unit testing: its
34
+ * Windows-named-pipe early return is real, load-bearing behavior (skipping
35
+ * filesystem staging that would be meaningless — or fail outright — for a
36
+ * pipe path), but this repo's CI runs on Linux, so the only way to actually
37
+ * *bind* one end-to-end and observe the early return's effect is on real
38
+ * Windows. Testing this function directly (asserting no filesystem call
39
+ * happens) verifies the real behavior on every platform this runs on.
40
+ */
41
+ export declare function prepareIpcPath(socketPath: string): Promise<void>;
42
+ /**
43
+ * Start a newline-delimited JSON IPC server on a unix socket / named pipe: each
44
+ * connection carries one JSON request, the handler's result is written back as
45
+ * `{ok:true,result}` (or `{ok:false,error}` on parse/handler failure).
46
+ * @returns A handle whose `close()` stops the server and unlinks the socket.
47
+ */
48
+ export declare function createJsonIpcServer({ handler, socketPath, maxFrameBytes, idleTimeoutMs, }: {
49
+ handler: JsonIpcHandler;
50
+ socketPath: string;
51
+ /** Reject a connection whose single frame exceeds this many bytes before a newline arrives (SEC-004). @default 1_000_000 */
52
+ maxFrameBytes?: number;
53
+ /** Drop a connection that has not delivered one complete frame within this many ms (SEC-004). @default 30_000 */
54
+ idleTimeoutMs?: number;
55
+ }): Promise<JsonIpcServerHandle>;
56
+ /**
57
+ * Send one newline-delimited JSON request over a unix socket / named pipe and
58
+ * resolve with the server's `result`, rejecting on error response or timeout.
59
+ * @returns The server's `result` payload.
60
+ */
61
+ export declare function requestJsonIpc<T = any>(socketPath: string, payload: unknown, { timeoutMs }?: {
62
+ timeoutMs?: number;
63
+ }): Promise<T>;
64
+ //# sourceMappingURL=json-ipc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-ipc.d.ts","sourceRoot":"","sources":["../src/json-ipc.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAYH,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AA8EtE;;;;;;;;;;GAUG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAK/E;AA6CD;;;;;;;;;;;GAWG;AACH,wBAAsB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAItE;AAED;;;;;GAKG;AACH,wBAAsB,mBAAmB,CAAC,EACxC,OAAO,EACP,UAAU,EACV,aAAuC,EACvC,aAAuC,GACxC,EAAE;IACD,OAAO,EAAE,cAAc,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,4HAA4H;IAC5H,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iHAAiH;IACjH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAiM/B;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,CAAC,GAAG,GAAG,EAC1C,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,OAAO,EAChB,EAAE,SAAgB,EAAE,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GAChD,OAAO,CAAC,CAAC,CAAC,CAkIZ"}
@@ -0,0 +1,498 @@
1
+ /**
2
+ * @module json-ipc
3
+ *
4
+ * Newline-delimited JSON IPC over a unix socket / Windows named pipe. Provides a
5
+ * server that decodes one JSON frame per connection (UTF-8 safe across chunk
6
+ * boundaries), runs a handler, and replies `{ok,result}`/`{ok:false,error}`, plus
7
+ * a client request with timeout. Includes opt-in structured tracing (gated by
8
+ * `JINI_JSON_IPC_TRACE`) and stale-socket cleanup before binding. The trace
9
+ * sequence counter is module-private singleton state. Depends on `node:fs`,
10
+ * `node:net`, `node:path`, `node:string_decoder`, the shared net close helper,
11
+ * the IPC-path recognizer, and the public IPC types.
12
+ */
13
+ import { lstat, mkdir, rm } from "node:fs/promises";
14
+ import { createConnection } from "node:net";
15
+ import { createServer as createNetServer } from "node:net";
16
+ import { dirname } from "node:path";
17
+ import { StringDecoder } from "node:string_decoder";
18
+ import { redactSecrets } from "@jini-ai/core";
19
+ import { isWindowsNamedPipePath } from "./ipc-path.js";
20
+ import { closeServer } from "./net.js";
21
+ /** Default cap on one connection's single frame (SEC-004): bytes received before a newline
22
+ * arrives. Generous for any realistic request/response payload while still bounding a
23
+ * streamed-without-a-newline attacker/misbehaving peer to a fixed amount of memory. */
24
+ const DEFAULT_MAX_FRAME_BYTES = 1_000_000;
25
+ /** Default idle deadline (SEC-004): a connection that has not delivered one complete
26
+ * newline-terminated frame within this window is dropped rather than held open forever. */
27
+ const DEFAULT_IDLE_TIMEOUT_MS = 30_000;
28
+ let jsonIpcTraceSeq = 0;
29
+ /**
30
+ * @internal Whether JSON-IPC tracing is enabled via `JINI_JSON_IPC_TRACE`.
31
+ */
32
+ function jsonIpcTraceEnabled() {
33
+ const value = process.env.JINI_JSON_IPC_TRACE;
34
+ return value === "1" || value === "true" || value === "yes";
35
+ }
36
+ /**
37
+ * @internal Allocate a per-connection trace id.
38
+ */
39
+ function nextJsonIpcTraceId() {
40
+ jsonIpcTraceSeq += 1;
41
+ return `ipc-${process.pid}-${jsonIpcTraceSeq}`;
42
+ }
43
+ /**
44
+ * @internal Elapsed milliseconds since `startedAt` (an hrtime bigint).
45
+ */
46
+ function jsonIpcTraceDurationMs(startedAt) {
47
+ return Number((process.hrtime.bigint() - startedAt) / 1000000n);
48
+ }
49
+ /**
50
+ * @internal Produce a compact, PII-light summary of a message for tracing.
51
+ */
52
+ function summarizeJsonIpcMessage(message) {
53
+ if (message == null || typeof message !== "object")
54
+ return { type: typeof message };
55
+ const input = message;
56
+ const summary = { type: typeof input.type === "string" ? input.type : typeof input.type };
57
+ if ("input" in input) {
58
+ summary.hasInput = true;
59
+ if (input.input != null && typeof input.input === "object") {
60
+ summary.inputKeys = Object.keys(input.input).sort();
61
+ }
62
+ else {
63
+ summary.inputType = typeof input.input;
64
+ }
65
+ }
66
+ return summary;
67
+ }
68
+ /**
69
+ * @internal Emit a trace line to stderr when tracing is enabled.
70
+ */
71
+ function traceJsonIpc(event, details) {
72
+ if (!jsonIpcTraceEnabled())
73
+ return;
74
+ console.error("[jini sidecar] json ipc trace", { event, ...details });
75
+ }
76
+ /**
77
+ * @internal Extract a Node error `code` string from an unknown thrown value.
78
+ */
79
+ function errorCode(error) {
80
+ if (typeof error !== "object" || error == null || !("code" in error))
81
+ return null;
82
+ const code = error.code;
83
+ return code == null ? null : String(code);
84
+ }
85
+ /**
86
+ * @internal Extract a human-readable message from an unknown thrown value.
87
+ */
88
+ function errorMessage(error) {
89
+ return error instanceof Error ? error.message : String(error);
90
+ }
91
+ /**
92
+ * Shape an unknown error into the `{code?,message}` IPC error payload.
93
+ *
94
+ * Exported (previously module-private) for direct unit testing: its only
95
+ * current caller (a `JSON.parse` frame-parse failure) always passes a
96
+ * codeless `SyntaxError`, so the `code`-present branch below is real,
97
+ * generically useful behavior (any future caller with a Node-style errno
98
+ * error benefits from it) with no in-tree caller that happens to have one in
99
+ * hand today — matching this repo's "extract into a directly-testable pure
100
+ * function" convention rather than narrowing the type away.
101
+ */
102
+ export function jsonIpcError(error) {
103
+ return {
104
+ ...(errorCode(error) == null ? {} : { code: errorCode(error) }),
105
+ message: errorMessage(error),
106
+ };
107
+ }
108
+ /**
109
+ * @internal Decide whether a unix socket path is a stale (dead) endpoint safe to
110
+ * unlink: it exists as a socket but refuses/ENOENTs on connect.
111
+ */
112
+ async function staleUnixSocketExists(socketPath) {
113
+ try {
114
+ const stat = await lstat(socketPath);
115
+ if (!stat.isSocket())
116
+ return false;
117
+ }
118
+ catch (error) {
119
+ if (errorCode(error) === "ENOENT")
120
+ return false;
121
+ throw error;
122
+ }
123
+ return await new Promise((resolveStale, rejectStale) => {
124
+ const socket = createConnection(socketPath);
125
+ // No `settled`-flag re-entrancy guard: `connect`/`error` are each
126
+ // registered with `.once()` (which self-removes *before* invoking the
127
+ // listener), and `settle` itself calls `removeAllListeners()` as its
128
+ // first side effect — so no code path here can ever invoke `settle`
129
+ // twice. A prior version carried a defensive `if (settled) return;` that
130
+ // was provably unreachable (verified empirically this session: forcing
131
+ // a second event through a fake socket finds zero listeners and crashes
132
+ // the process outright, rather than reaching that guard — see
133
+ // source-map.md's 2026-07-22 entry) — removed as a real refactor rather
134
+ // than padded with a test that can't exercise real behavior.
135
+ const settle = (callback) => {
136
+ socket.removeAllListeners();
137
+ socket.destroy();
138
+ callback();
139
+ };
140
+ socket.once("connect", () => settle(() => resolveStale(false)));
141
+ socket.once("error", (error) => {
142
+ const code = errorCode(error);
143
+ if (code === "ENOENT" || code === "ECONNREFUSED") {
144
+ settle(() => resolveStale(true));
145
+ return;
146
+ }
147
+ settle(() => rejectStale(error));
148
+ });
149
+ });
150
+ }
151
+ /**
152
+ * Prepare a socket path for binding: ensure the parent dir exists and
153
+ * unlink a stale socket (no-op for Windows named pipes).
154
+ *
155
+ * Exported (previously module-private) for direct unit testing: its
156
+ * Windows-named-pipe early return is real, load-bearing behavior (skipping
157
+ * filesystem staging that would be meaningless — or fail outright — for a
158
+ * pipe path), but this repo's CI runs on Linux, so the only way to actually
159
+ * *bind* one end-to-end and observe the early return's effect is on real
160
+ * Windows. Testing this function directly (asserting no filesystem call
161
+ * happens) verifies the real behavior on every platform this runs on.
162
+ */
163
+ export async function prepareIpcPath(socketPath) {
164
+ if (isWindowsNamedPipePath(socketPath))
165
+ return;
166
+ await mkdir(dirname(socketPath), { recursive: true });
167
+ if (await staleUnixSocketExists(socketPath))
168
+ await rm(socketPath, { force: true });
169
+ }
170
+ /**
171
+ * Start a newline-delimited JSON IPC server on a unix socket / named pipe: each
172
+ * connection carries one JSON request, the handler's result is written back as
173
+ * `{ok:true,result}` (or `{ok:false,error}` on parse/handler failure).
174
+ * @returns A handle whose `close()` stops the server and unlinks the socket.
175
+ */
176
+ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes = DEFAULT_MAX_FRAME_BYTES, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS, }) {
177
+ await prepareIpcPath(socketPath);
178
+ const server = createNetServer((socket) => {
179
+ let buffer = "";
180
+ let receivedBytes = 0;
181
+ // One-request-per-connection guard (SEC-004): the `data` listener is `async`, so its
182
+ // synchronous prefix (up to the first `await`) always finishes — and can set this flag —
183
+ // before Node dispatches the next queued `data` event on this same socket. Once a frame has
184
+ // been claimed, any further bytes on this connection (a second frame arriving while the
185
+ // handler is still awaiting, or trailing garbage after the first frame) are ignored rather
186
+ // than starting a second concurrent handler call / response race.
187
+ let handled = false;
188
+ // Decode UTF-8 across chunk boundaries: a multibyte character (e.g. CJK,
189
+ // 3 bytes) can be split across two `data` events. `chunk.toString()` per
190
+ // chunk would turn each half into U+FFFD, corrupting the payload (observed
191
+ // as `???`/`◆?◆?◆?` in exported CJK artifacts). StringDecoder holds an
192
+ // incomplete trailing sequence until the next chunk completes it.
193
+ const decoder = new StringDecoder("utf8");
194
+ const traceId = nextJsonIpcTraceId();
195
+ const startedAt = process.hrtime.bigint();
196
+ traceJsonIpc("server.connection", { socketPath, traceId });
197
+ // Idle deadline (SEC-004): a peer that opens a connection and never completes a
198
+ // newline-terminated frame (or dribbles bytes indefinitely) would otherwise hold the
199
+ // connection — and this closure's buffer — open forever.
200
+ const idleTimer = setTimeout(() => {
201
+ // Defense-in-depth, not reachable through any real timer/socket
202
+ // interleaving: every real path that sets `handled = true` (a
203
+ // complete frame arriving, or the oversized-frame guard) calls
204
+ // `clearTimeout(idleTimer)` in the very same synchronous prefix of a
205
+ // single `data`-listener invocation — and Node/V8's single-threaded
206
+ // execution model means no other callback (including this one) can
207
+ // run in between that assignment and the `clearTimeout` call. Kept as
208
+ // a real fail-safe (in case a future edit reorders that sequence)
209
+ // rather than asserted away — see source-map.md's 2026-07-22 entry.
210
+ if (handled)
211
+ return;
212
+ handled = true;
213
+ traceJsonIpc("server.idle_timeout", {
214
+ durationMs: jsonIpcTraceDurationMs(startedAt),
215
+ idleTimeoutMs,
216
+ socketPath,
217
+ traceId,
218
+ });
219
+ socket.destroy();
220
+ }, idleTimeoutMs);
221
+ idleTimer.unref();
222
+ socket.on("error", (error) => {
223
+ // `error instanceof Error` here is defense-in-depth, not reachable
224
+ // through real socket usage: @types/node itself types a `Socket`'s
225
+ // `'error'` listener parameter as `Error` (not `unknown`), matching
226
+ // Node's own real implementation, which only ever emits genuine
227
+ // `Error`/`SystemError` instances for this event — verified against
228
+ // the installed `@types/node`'s `net.d.ts` this session; not asserted
229
+ // away since a test would have to manually `.emit()` a fabricated
230
+ // non-Error value to reach the other side, which isn't real socket
231
+ // behavior (see source-map.md's 2026-07-22 entry).
232
+ traceJsonIpc("server.socket_error", {
233
+ durationMs: jsonIpcTraceDurationMs(startedAt),
234
+ error: error instanceof Error ? error.message : String(error),
235
+ socketPath,
236
+ traceId,
237
+ });
238
+ });
239
+ socket.on("close", () => {
240
+ clearTimeout(idleTimer);
241
+ traceJsonIpc("server.socket_close", {
242
+ durationMs: jsonIpcTraceDurationMs(startedAt),
243
+ socketPath,
244
+ traceId,
245
+ });
246
+ });
247
+ socket.on("data", async (chunk) => {
248
+ if (handled)
249
+ return;
250
+ traceJsonIpc("server.data", {
251
+ bytes: chunk.byteLength,
252
+ durationMs: jsonIpcTraceDurationMs(startedAt),
253
+ socketPath,
254
+ traceId,
255
+ });
256
+ receivedBytes += chunk.byteLength;
257
+ if (receivedBytes > maxFrameBytes) {
258
+ handled = true;
259
+ clearTimeout(idleTimer);
260
+ traceJsonIpc("server.frame_too_large", {
261
+ durationMs: jsonIpcTraceDurationMs(startedAt),
262
+ maxFrameBytes,
263
+ receivedBytes,
264
+ socketPath,
265
+ traceId,
266
+ });
267
+ socket.end(`${JSON.stringify({
268
+ ok: false,
269
+ error: { code: "FRAME_TOO_LARGE", message: "request frame exceeds the maximum size" },
270
+ })}\n`);
271
+ return;
272
+ }
273
+ buffer += decoder.write(chunk);
274
+ const newlineIndex = buffer.indexOf("\n");
275
+ if (newlineIndex < 0)
276
+ return;
277
+ handled = true; // Claim the connection before awaiting the handler — see the flag's own doc above.
278
+ clearTimeout(idleTimer);
279
+ const frame = buffer.slice(0, newlineIndex);
280
+ buffer = buffer.slice(newlineIndex + 1);
281
+ let message;
282
+ try {
283
+ message = JSON.parse(frame);
284
+ }
285
+ catch (error) {
286
+ // `error instanceof Error` here is defense-in-depth, not reachable
287
+ // through a real `JSON.parse` failure: it only ever throws a
288
+ // genuine `SyntaxError` (an `Error` instance) for any string input
289
+ // — never a non-Error value — matching the same reasoning as the
290
+ // socket-error `instanceof Error` checks above (see
291
+ // source-map.md's 2026-07-22 entry).
292
+ traceJsonIpc("server.frame_parse_failed", {
293
+ durationMs: jsonIpcTraceDurationMs(startedAt),
294
+ error: error instanceof Error ? error.message : String(error),
295
+ frameBytes: Buffer.byteLength(frame),
296
+ socketPath,
297
+ traceId,
298
+ });
299
+ socket.end(`${JSON.stringify({
300
+ ok: false,
301
+ error: jsonIpcError(error),
302
+ })}\n`);
303
+ return;
304
+ }
305
+ const messageSummary = summarizeJsonIpcMessage(message);
306
+ traceJsonIpc("server.frame_parsed", {
307
+ durationMs: jsonIpcTraceDurationMs(startedAt),
308
+ frameBytes: Buffer.byteLength(frame),
309
+ message: messageSummary,
310
+ socketPath,
311
+ traceId,
312
+ });
313
+ try {
314
+ traceJsonIpc("server.handler_start", {
315
+ durationMs: jsonIpcTraceDurationMs(startedAt),
316
+ message: messageSummary,
317
+ socketPath,
318
+ traceId,
319
+ });
320
+ const result = await handler(message);
321
+ traceJsonIpc("server.handler_success", {
322
+ durationMs: jsonIpcTraceDurationMs(startedAt),
323
+ message: messageSummary,
324
+ socketPath,
325
+ traceId,
326
+ });
327
+ socket.end(`${JSON.stringify({ ok: true, result })}\n`);
328
+ }
329
+ catch (error) {
330
+ // SEC-004: a handler failure can embed paths, credentials, or other host detail (the
331
+ // same trust-boundary concern as SEC-005's HTTP fix). The peer gets a stable code plus
332
+ // the traceId as a correlation handle; the real detail is redacted and logged
333
+ // server-side only, unconditionally (not gated behind JINI_JSON_IPC_TRACE).
334
+ const redactedDetail = redactSecrets(error instanceof Error ? error.message : String(error));
335
+ // eslint-disable-next-line no-console
336
+ console.error(`[@jini-ai/sidecar] json-ipc handler failed (traceId=${traceId})`, redactedDetail);
337
+ traceJsonIpc("server.handler_failed", {
338
+ durationMs: jsonIpcTraceDurationMs(startedAt),
339
+ error: redactedDetail,
340
+ message: messageSummary,
341
+ socketPath,
342
+ traceId,
343
+ });
344
+ socket.end(`${JSON.stringify({
345
+ ok: false,
346
+ error: { code: "HANDLER_ERROR", message: "internal error", requestId: traceId },
347
+ })}\n`);
348
+ }
349
+ });
350
+ });
351
+ await new Promise((resolveListen, rejectListen) => {
352
+ server.once("error", rejectListen);
353
+ server.listen(socketPath, () => {
354
+ server.off("error", rejectListen);
355
+ resolveListen();
356
+ });
357
+ });
358
+ return {
359
+ async close() {
360
+ await closeServer(server);
361
+ if (!isWindowsNamedPipePath(socketPath))
362
+ await rm(socketPath, { force: true });
363
+ },
364
+ };
365
+ }
366
+ /**
367
+ * Send one newline-delimited JSON request over a unix socket / named pipe and
368
+ * resolve with the server's `result`, rejecting on error response or timeout.
369
+ * @returns The server's `result` payload.
370
+ */
371
+ export async function requestJsonIpc(socketPath, payload, { timeoutMs = 1500 } = {}) {
372
+ return await new Promise((resolveRequest, rejectRequest) => {
373
+ const socket = createConnection(socketPath);
374
+ const traceId = nextJsonIpcTraceId();
375
+ const startedAt = process.hrtime.bigint();
376
+ let settled = false;
377
+ let buffer = "";
378
+ // See the server reader above: decode UTF-8 across chunk boundaries so a
379
+ // multibyte character split across two `data` events is not corrupted.
380
+ const decoder = new StringDecoder("utf8");
381
+ const messageSummary = summarizeJsonIpcMessage(payload);
382
+ traceJsonIpc("client.connect_start", { message: messageSummary, socketPath, timeoutMs, traceId });
383
+ const settle = (callback) => {
384
+ if (settled)
385
+ return;
386
+ settled = true;
387
+ clearTimeout(timeout);
388
+ callback();
389
+ };
390
+ const timeout = setTimeout(() => {
391
+ traceJsonIpc("client.timeout", {
392
+ durationMs: jsonIpcTraceDurationMs(startedAt),
393
+ message: messageSummary,
394
+ socketPath,
395
+ timeoutMs,
396
+ traceId,
397
+ });
398
+ socket.destroy();
399
+ settle(() => rejectRequest(new Error(`IPC request timed out: ${socketPath}`)));
400
+ }, timeoutMs);
401
+ socket.on("connect", () => {
402
+ traceJsonIpc("client.connected", {
403
+ durationMs: jsonIpcTraceDurationMs(startedAt),
404
+ message: messageSummary,
405
+ socketPath,
406
+ traceId,
407
+ });
408
+ const frame = `${JSON.stringify(payload)}\n`;
409
+ traceJsonIpc("client.write_start", {
410
+ bytes: Buffer.byteLength(frame),
411
+ durationMs: jsonIpcTraceDurationMs(startedAt),
412
+ message: messageSummary,
413
+ socketPath,
414
+ traceId,
415
+ });
416
+ const flushed = socket.write(frame, () => {
417
+ traceJsonIpc("client.write_callback", {
418
+ durationMs: jsonIpcTraceDurationMs(startedAt),
419
+ message: messageSummary,
420
+ socketPath,
421
+ traceId,
422
+ });
423
+ });
424
+ if (!flushed) {
425
+ socket.once("drain", () => {
426
+ traceJsonIpc("client.drain", {
427
+ durationMs: jsonIpcTraceDurationMs(startedAt),
428
+ message: messageSummary,
429
+ socketPath,
430
+ traceId,
431
+ });
432
+ });
433
+ }
434
+ });
435
+ socket.on("data", (chunk) => {
436
+ traceJsonIpc("client.data", {
437
+ bytes: chunk.byteLength,
438
+ durationMs: jsonIpcTraceDurationMs(startedAt),
439
+ message: messageSummary,
440
+ socketPath,
441
+ traceId,
442
+ });
443
+ buffer += decoder.write(chunk);
444
+ const newlineIndex = buffer.indexOf("\n");
445
+ if (newlineIndex < 0)
446
+ return;
447
+ socket.end();
448
+ settle(() => {
449
+ const response = JSON.parse(buffer.slice(0, newlineIndex));
450
+ if (!response.ok) {
451
+ traceJsonIpc("client.response_error", {
452
+ durationMs: jsonIpcTraceDurationMs(startedAt),
453
+ error: response.error?.message ?? "IPC request failed",
454
+ message: messageSummary,
455
+ socketPath,
456
+ traceId,
457
+ });
458
+ const rejection = new Error(response.error?.message ?? "IPC request failed");
459
+ if (response.error?.code !== undefined)
460
+ rejection.code = response.error.code;
461
+ if (response.error?.requestId !== undefined)
462
+ rejection.requestId = response.error.requestId;
463
+ rejectRequest(rejection);
464
+ return;
465
+ }
466
+ traceJsonIpc("client.response_success", {
467
+ durationMs: jsonIpcTraceDurationMs(startedAt),
468
+ message: messageSummary,
469
+ socketPath,
470
+ traceId,
471
+ });
472
+ resolveRequest(response.result);
473
+ });
474
+ });
475
+ socket.on("error", (error) => {
476
+ // Same defense-in-depth, not-reachable-through-real-usage reasoning as
477
+ // the server-side `error instanceof Error` check above (see that
478
+ // comment + source-map.md's 2026-07-22 entry).
479
+ traceJsonIpc("client.socket_error", {
480
+ durationMs: jsonIpcTraceDurationMs(startedAt),
481
+ error: error instanceof Error ? error.message : String(error),
482
+ message: messageSummary,
483
+ socketPath,
484
+ traceId,
485
+ });
486
+ settle(() => rejectRequest(error));
487
+ });
488
+ socket.on("close", () => {
489
+ traceJsonIpc("client.socket_close", {
490
+ durationMs: jsonIpcTraceDurationMs(startedAt),
491
+ message: messageSummary,
492
+ socketPath,
493
+ traceId,
494
+ });
495
+ });
496
+ });
497
+ }
498
+ //# sourceMappingURL=json-ipc.js.map