@bli-cockpit/telemetry-core 0.1.49 → 0.1.51
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.
|
@@ -55,6 +55,56 @@ export declare const MEMORY_DAEMON_CONNECT_TIMEOUT_MS = 50;
|
|
|
55
55
|
export declare const MEMORY_DAEMON_SPAWN_INTERVAL_MS = 3600000;
|
|
56
56
|
/** The daemon exits after this long with no request. Two hours. */
|
|
57
57
|
export declare const MEMORY_DAEMON_IDLE_EXIT_MS = 7200000;
|
|
58
|
+
/**
|
|
59
|
+
* How long the daemon's OUTBOUND connection to Tower is allowed to sit idle
|
|
60
|
+
* before this process's OWN dispatcher considers reusing it stale (BLI-10741).
|
|
61
|
+
*
|
|
62
|
+
* The daemon existing was never the whole promise — BLI-3884's docstring
|
|
63
|
+
* calls a warm connection out by name, and structurally it never landed:
|
|
64
|
+
* Node's BUILT-IN global `fetch` does not read the external `undici`
|
|
65
|
+
* package's `setGlobalDispatcher` at all. Verified live against this build
|
|
66
|
+
* (`node@26.8.1`, `undici@6.28.1` in `node_modules`): installing a custom
|
|
67
|
+
* `Agent` as the global dispatcher and then calling the ordinary global
|
|
68
|
+
* `fetch()` left three real `/api/memory/search` calls, spaced 6 s apart,
|
|
69
|
+
* exactly as slow as an unmodified run (569 / 523 / 546 ms — cold every
|
|
70
|
+
* time). So whatever pooling the daemon's `fetch()` calls were doing, this
|
|
71
|
+
* package had NO way to see it, tune it, or even confirm it was happening —
|
|
72
|
+
* `warm-fetch.ts` exists to give the daemon a connection it actually
|
|
73
|
+
* controls, over `undici`'s own `fetch` export with an explicit `dispatcher`,
|
|
74
|
+
* which a local test proves reuses one socket across an idle gap
|
|
75
|
+
* (`warm-fetch.test.ts`).
|
|
76
|
+
*
|
|
77
|
+
* The value is sized off two measurements, not guessed. 578 real gaps
|
|
78
|
+
* between one prompt-hook call and the next on Edward's own machine
|
|
79
|
+
* (`~/.local/state/bli-cockpit/memory-hook-samples`, 2026-09-24 to
|
|
80
|
+
* 2026-09-28) put only 9.2% of them under undici's own 4,000 ms default;
|
|
81
|
+
* 120,000 ms (two minutes) covers 76.6% of the same gaps — most of a working
|
|
82
|
+
* session's back-and-forth — while staying inside what ordinary HTTP/1.1
|
|
83
|
+
* reverse proxies keep an idle keep-alive connection open for; past that,
|
|
84
|
+
* the gain per extra second shrinks fast (300,000 ms only reaches 90.3%)
|
|
85
|
+
* against a growing chance the far end has already dropped the socket
|
|
86
|
+
* anyway. `docs/architecture/agent-memory.md` (BLI-10741) carries the
|
|
87
|
+
* end-to-end replay this sizing was checked against: 50 real recent prompt
|
|
88
|
+
* strings from this machine's own transcripts, run through the real search
|
|
89
|
+
* door with the hook's own 2,000 ms request deadline, once with a fresh
|
|
90
|
+
* dispatcher per call (the daemon's old, uncontrolled shape) and once
|
|
91
|
+
* through one shared warm dispatcher (this fix) — timeouts before and after,
|
|
92
|
+
* same measurement.
|
|
93
|
+
*
|
|
94
|
+
* A connection this process believed was warm and was not is never a hang: a
|
|
95
|
+
* write to a socket the far end already closed fails fast or the request
|
|
96
|
+
* simply opens a new one, and either way the hook's own per-request
|
|
97
|
+
* `AbortController` (`HOOK_BUDGETS`) still bounds the wait. Raising this
|
|
98
|
+
* number can only ever save time, never cost more of it than today.
|
|
99
|
+
*/
|
|
100
|
+
export declare const MEMORY_DAEMON_KEEPALIVE_TIMEOUT_MS = 120000;
|
|
101
|
+
/**
|
|
102
|
+
* The absolute cap on one connection's life, warm or not — undici's own
|
|
103
|
+
* `keepAliveMaxTimeout`. Left far above the idle timeout above so the idle
|
|
104
|
+
* rule is always what actually retires a connection; it exists at all so a
|
|
105
|
+
* connection cannot be held open forever by a daemon that never goes idle.
|
|
106
|
+
*/
|
|
107
|
+
export declare const MEMORY_DAEMON_KEEPALIVE_MAX_TIMEOUT_MS = 600000;
|
|
58
108
|
/**
|
|
59
109
|
* How long a unix socket PATH may be, in bytes, before the platform refuses to
|
|
60
110
|
* bind it. `sun_path` is 104 on macOS/BSD and 108 on Linux; 100 is the safe
|
|
@@ -71,6 +121,18 @@ export declare const MEMORY_DAEMON_UNIX_PATH_MAX = 100;
|
|
|
71
121
|
* 1 MB is far above both and bounds a peer that never sends a newline.
|
|
72
122
|
*/
|
|
73
123
|
export declare const MEMORY_DAEMON_MAX_LINE_BYTES = 1048576;
|
|
124
|
+
/**
|
|
125
|
+
* How long a proxied `http` request may run before the daemon gives up on
|
|
126
|
+
* Tower and answers `daemon_http_timeout` (BLI-10746).
|
|
127
|
+
*
|
|
128
|
+
* This is the DAEMON's own ceiling on the request it makes with its warm
|
|
129
|
+
* dispatcher, separate from `deadlineMs` a caller passes to
|
|
130
|
+
* `askMemoryDaemonHttp` (the whole round trip including the local socket).
|
|
131
|
+
* CLI reads today (`work list`, `docs list`, …) already carry a
|
|
132
|
+
* `READ_DEADLINE_MS` of their own well under this; the daemon's ceiling only
|
|
133
|
+
* has to sit under that, never define it.
|
|
134
|
+
*/
|
|
135
|
+
export declare const MEMORY_DAEMON_HTTP_PROXY_TIMEOUT_MS = 8000;
|
|
74
136
|
export interface MemoryDaemonEndpoint {
|
|
75
137
|
/** Which kind of endpoint this platform gets. */
|
|
76
138
|
kind: "unix" | "pipe";
|
|
@@ -56,6 +56,56 @@ export const MEMORY_DAEMON_CONNECT_TIMEOUT_MS = 50;
|
|
|
56
56
|
export const MEMORY_DAEMON_SPAWN_INTERVAL_MS = 3_600_000;
|
|
57
57
|
/** The daemon exits after this long with no request. Two hours. */
|
|
58
58
|
export const MEMORY_DAEMON_IDLE_EXIT_MS = 7_200_000;
|
|
59
|
+
/**
|
|
60
|
+
* How long the daemon's OUTBOUND connection to Tower is allowed to sit idle
|
|
61
|
+
* before this process's OWN dispatcher considers reusing it stale (BLI-10741).
|
|
62
|
+
*
|
|
63
|
+
* The daemon existing was never the whole promise — BLI-3884's docstring
|
|
64
|
+
* calls a warm connection out by name, and structurally it never landed:
|
|
65
|
+
* Node's BUILT-IN global `fetch` does not read the external `undici`
|
|
66
|
+
* package's `setGlobalDispatcher` at all. Verified live against this build
|
|
67
|
+
* (`node@26.8.1`, `undici@6.28.1` in `node_modules`): installing a custom
|
|
68
|
+
* `Agent` as the global dispatcher and then calling the ordinary global
|
|
69
|
+
* `fetch()` left three real `/api/memory/search` calls, spaced 6 s apart,
|
|
70
|
+
* exactly as slow as an unmodified run (569 / 523 / 546 ms — cold every
|
|
71
|
+
* time). So whatever pooling the daemon's `fetch()` calls were doing, this
|
|
72
|
+
* package had NO way to see it, tune it, or even confirm it was happening —
|
|
73
|
+
* `warm-fetch.ts` exists to give the daemon a connection it actually
|
|
74
|
+
* controls, over `undici`'s own `fetch` export with an explicit `dispatcher`,
|
|
75
|
+
* which a local test proves reuses one socket across an idle gap
|
|
76
|
+
* (`warm-fetch.test.ts`).
|
|
77
|
+
*
|
|
78
|
+
* The value is sized off two measurements, not guessed. 578 real gaps
|
|
79
|
+
* between one prompt-hook call and the next on Edward's own machine
|
|
80
|
+
* (`~/.local/state/bli-cockpit/memory-hook-samples`, 2026-09-24 to
|
|
81
|
+
* 2026-09-28) put only 9.2% of them under undici's own 4,000 ms default;
|
|
82
|
+
* 120,000 ms (two minutes) covers 76.6% of the same gaps — most of a working
|
|
83
|
+
* session's back-and-forth — while staying inside what ordinary HTTP/1.1
|
|
84
|
+
* reverse proxies keep an idle keep-alive connection open for; past that,
|
|
85
|
+
* the gain per extra second shrinks fast (300,000 ms only reaches 90.3%)
|
|
86
|
+
* against a growing chance the far end has already dropped the socket
|
|
87
|
+
* anyway. `docs/architecture/agent-memory.md` (BLI-10741) carries the
|
|
88
|
+
* end-to-end replay this sizing was checked against: 50 real recent prompt
|
|
89
|
+
* strings from this machine's own transcripts, run through the real search
|
|
90
|
+
* door with the hook's own 2,000 ms request deadline, once with a fresh
|
|
91
|
+
* dispatcher per call (the daemon's old, uncontrolled shape) and once
|
|
92
|
+
* through one shared warm dispatcher (this fix) — timeouts before and after,
|
|
93
|
+
* same measurement.
|
|
94
|
+
*
|
|
95
|
+
* A connection this process believed was warm and was not is never a hang: a
|
|
96
|
+
* write to a socket the far end already closed fails fast or the request
|
|
97
|
+
* simply opens a new one, and either way the hook's own per-request
|
|
98
|
+
* `AbortController` (`HOOK_BUDGETS`) still bounds the wait. Raising this
|
|
99
|
+
* number can only ever save time, never cost more of it than today.
|
|
100
|
+
*/
|
|
101
|
+
export const MEMORY_DAEMON_KEEPALIVE_TIMEOUT_MS = 120_000;
|
|
102
|
+
/**
|
|
103
|
+
* The absolute cap on one connection's life, warm or not — undici's own
|
|
104
|
+
* `keepAliveMaxTimeout`. Left far above the idle timeout above so the idle
|
|
105
|
+
* rule is always what actually retires a connection; it exists at all so a
|
|
106
|
+
* connection cannot be held open forever by a daemon that never goes idle.
|
|
107
|
+
*/
|
|
108
|
+
export const MEMORY_DAEMON_KEEPALIVE_MAX_TIMEOUT_MS = 600_000;
|
|
59
109
|
/**
|
|
60
110
|
* How long a unix socket PATH may be, in bytes, before the platform refuses to
|
|
61
111
|
* bind it. `sun_path` is 104 on macOS/BSD and 108 on Linux; 100 is the safe
|
|
@@ -72,6 +122,18 @@ export const MEMORY_DAEMON_UNIX_PATH_MAX = 100;
|
|
|
72
122
|
* 1 MB is far above both and bounds a peer that never sends a newline.
|
|
73
123
|
*/
|
|
74
124
|
export const MEMORY_DAEMON_MAX_LINE_BYTES = 1_048_576;
|
|
125
|
+
/**
|
|
126
|
+
* How long a proxied `http` request may run before the daemon gives up on
|
|
127
|
+
* Tower and answers `daemon_http_timeout` (BLI-10746).
|
|
128
|
+
*
|
|
129
|
+
* This is the DAEMON's own ceiling on the request it makes with its warm
|
|
130
|
+
* dispatcher, separate from `deadlineMs` a caller passes to
|
|
131
|
+
* `askMemoryDaemonHttp` (the whole round trip including the local socket).
|
|
132
|
+
* CLI reads today (`work list`, `docs list`, …) already carry a
|
|
133
|
+
* `READ_DEADLINE_MS` of their own well under this; the daemon's ceiling only
|
|
134
|
+
* has to sit under that, never define it.
|
|
135
|
+
*/
|
|
136
|
+
export const MEMORY_DAEMON_HTTP_PROXY_TIMEOUT_MS = 8_000;
|
|
75
137
|
/**
|
|
76
138
|
* The one place the daemon's address is computed. Both packages call this;
|
|
77
139
|
* nobody joins a socket path by hand.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE CLIENT HALF OF THE DAEMON'S `http` EVENT, NODE ONLY (BLI-10746).
|
|
3
|
+
*
|
|
4
|
+
* `memory-daemon-endpoint.ts` next door is imported by the dashboard as well
|
|
5
|
+
* as by two CLIs, so it stays pure path/string arithmetic — nothing in it
|
|
6
|
+
* ever opens a socket. This module is the part that does, and it lives
|
|
7
|
+
* behind this package's own `./node-daemon-http-client` export rather than
|
|
8
|
+
* the root one, so a browser/edge bundle that imports `@bli-cockpit/
|
|
9
|
+
* telemetry-core` never pulls in `node:net`.
|
|
10
|
+
*
|
|
11
|
+
* `@bli-cockpit/local-collector` (the CLI) and `@bli-cockpit/mcp` (the MCP
|
|
12
|
+
* server) both need to ask the SAME resident daemon
|
|
13
|
+
* (`@bli-cockpit/memory-mcp`'s `bli-memory-mcp daemon`) to proxy one HTTP
|
|
14
|
+
* request over its already-warm connection to Tower (BLI-10741 built that
|
|
15
|
+
* connection for recall; this reuses it for every other read). Neither
|
|
16
|
+
* package may casually depend on `@bli-cockpit/memory-mcp` for this — the MCP
|
|
17
|
+
* server does not depend on it at all today, and the packed CLI's dependency
|
|
18
|
+
* list is its own contract — so this module speaks the daemon's
|
|
19
|
+
* `memory-daemon.v1` wire format directly, using only the address and
|
|
20
|
+
* timing constants both sides already share from `memory-daemon-endpoint.ts`.
|
|
21
|
+
* The daemon's own request/answer parsing (`@bli-cockpit/memory-mcp`'s
|
|
22
|
+
* `daemon/protocol.ts`) reads and writes the exact same shape; the two are
|
|
23
|
+
* bound together by `daemon/http-proxy.test.ts` on the daemon's side and by
|
|
24
|
+
* this module's own tests here, the same "two independent envelopes, proven
|
|
25
|
+
* by tests on each side" shape `memory-daemon-probe.ts` already uses for
|
|
26
|
+
* `ping`.
|
|
27
|
+
*
|
|
28
|
+
* **The device token is NOT part of this contract.** The caller's own
|
|
29
|
+
* `authorization` header travels inside `request.headers` exactly as it
|
|
30
|
+
* would have gone out directly — the daemon only forwards bytes over a
|
|
31
|
+
* socket it already trusts (owner-only, same OS user), never inspects or
|
|
32
|
+
* caches the credential. A daemon that is absent, refuses, times out or
|
|
33
|
+
* answers something this client cannot parse is a NAMED reason, never a
|
|
34
|
+
* thrown exception: every caller's contract is "fall back to a direct
|
|
35
|
+
* request", and that only works if this never hangs or throws.
|
|
36
|
+
*/
|
|
37
|
+
import net from "node:net";
|
|
38
|
+
/** What travels out: enough to replay one `fetch(url, init)` on the daemon's own dispatcher. */
|
|
39
|
+
export interface DaemonHttpProxyRequest {
|
|
40
|
+
method: string;
|
|
41
|
+
url: string;
|
|
42
|
+
headers: Record<string, string>;
|
|
43
|
+
/** Already-serialised, exactly what `fetch`'s `body` would have been. */
|
|
44
|
+
body?: string;
|
|
45
|
+
}
|
|
46
|
+
/** What comes back: enough to reconstruct the `Response` the caller expected. */
|
|
47
|
+
export interface DaemonHttpProxyAnswer {
|
|
48
|
+
status: number;
|
|
49
|
+
headers: Record<string, string>;
|
|
50
|
+
body: string;
|
|
51
|
+
}
|
|
52
|
+
export type AskMemoryDaemonHttpSettled = {
|
|
53
|
+
ok: true;
|
|
54
|
+
answer: DaemonHttpProxyAnswer;
|
|
55
|
+
} | {
|
|
56
|
+
ok: false;
|
|
57
|
+
reason: string;
|
|
58
|
+
};
|
|
59
|
+
export type AskMemoryDaemonHttpResult = AskMemoryDaemonHttpSettled & {
|
|
60
|
+
elapsedMs: number;
|
|
61
|
+
};
|
|
62
|
+
export interface AskMemoryDaemonHttpOptions {
|
|
63
|
+
/** The unix socket path or the Windows pipe name (`memoryDaemonEndpoint(...).address`). */
|
|
64
|
+
address: string;
|
|
65
|
+
request: DaemonHttpProxyRequest;
|
|
66
|
+
/** Bounds the connect alone. Defaults to the shared 50 ms. */
|
|
67
|
+
connectTimeoutMs?: number;
|
|
68
|
+
/** Bounds the whole ask, local socket plus the daemon's own outbound call. */
|
|
69
|
+
deadlineMs: number;
|
|
70
|
+
/** Test seam. Real callers use `net.createConnection`. */
|
|
71
|
+
connectImpl?: (address: string) => net.Socket;
|
|
72
|
+
now?: () => number;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Ask the daemon to proxy one HTTP request over its warm connection.
|
|
76
|
+
* Resolves once, always — never throws, never hangs, never holds the event
|
|
77
|
+
* loop open past its own timers (all `unref`'d, same discipline as
|
|
78
|
+
* `memory-daemon-probe.ts` and `@bli-cockpit/memory-mcp`'s `askDaemon`).
|
|
79
|
+
*/
|
|
80
|
+
export declare function askMemoryDaemonHttp(options: AskMemoryDaemonHttpOptions): Promise<AskMemoryDaemonHttpResult>;
|
|
81
|
+
/** One JSON line, the same envelope every daemon event uses. */
|
|
82
|
+
export declare function encodeHttpProxyLine(request: DaemonHttpProxyRequest): string;
|
|
83
|
+
export type ParsedHttpProxyAnswer = {
|
|
84
|
+
ok: true;
|
|
85
|
+
answer: DaemonHttpProxyAnswer;
|
|
86
|
+
} | {
|
|
87
|
+
ok: false;
|
|
88
|
+
reason: string;
|
|
89
|
+
};
|
|
90
|
+
/** Reads one answer line. Any shape this client cannot trust is a named reason, never a guess. */
|
|
91
|
+
export declare function parseHttpProxyAnswerLine(line: string): ParsedHttpProxyAnswer;
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE CLIENT HALF OF THE DAEMON'S `http` EVENT, NODE ONLY (BLI-10746).
|
|
3
|
+
*
|
|
4
|
+
* `memory-daemon-endpoint.ts` next door is imported by the dashboard as well
|
|
5
|
+
* as by two CLIs, so it stays pure path/string arithmetic — nothing in it
|
|
6
|
+
* ever opens a socket. This module is the part that does, and it lives
|
|
7
|
+
* behind this package's own `./node-daemon-http-client` export rather than
|
|
8
|
+
* the root one, so a browser/edge bundle that imports `@bli-cockpit/
|
|
9
|
+
* telemetry-core` never pulls in `node:net`.
|
|
10
|
+
*
|
|
11
|
+
* `@bli-cockpit/local-collector` (the CLI) and `@bli-cockpit/mcp` (the MCP
|
|
12
|
+
* server) both need to ask the SAME resident daemon
|
|
13
|
+
* (`@bli-cockpit/memory-mcp`'s `bli-memory-mcp daemon`) to proxy one HTTP
|
|
14
|
+
* request over its already-warm connection to Tower (BLI-10741 built that
|
|
15
|
+
* connection for recall; this reuses it for every other read). Neither
|
|
16
|
+
* package may casually depend on `@bli-cockpit/memory-mcp` for this — the MCP
|
|
17
|
+
* server does not depend on it at all today, and the packed CLI's dependency
|
|
18
|
+
* list is its own contract — so this module speaks the daemon's
|
|
19
|
+
* `memory-daemon.v1` wire format directly, using only the address and
|
|
20
|
+
* timing constants both sides already share from `memory-daemon-endpoint.ts`.
|
|
21
|
+
* The daemon's own request/answer parsing (`@bli-cockpit/memory-mcp`'s
|
|
22
|
+
* `daemon/protocol.ts`) reads and writes the exact same shape; the two are
|
|
23
|
+
* bound together by `daemon/http-proxy.test.ts` on the daemon's side and by
|
|
24
|
+
* this module's own tests here, the same "two independent envelopes, proven
|
|
25
|
+
* by tests on each side" shape `memory-daemon-probe.ts` already uses for
|
|
26
|
+
* `ping`.
|
|
27
|
+
*
|
|
28
|
+
* **The device token is NOT part of this contract.** The caller's own
|
|
29
|
+
* `authorization` header travels inside `request.headers` exactly as it
|
|
30
|
+
* would have gone out directly — the daemon only forwards bytes over a
|
|
31
|
+
* socket it already trusts (owner-only, same OS user), never inspects or
|
|
32
|
+
* caches the credential. A daemon that is absent, refuses, times out or
|
|
33
|
+
* answers something this client cannot parse is a NAMED reason, never a
|
|
34
|
+
* thrown exception: every caller's contract is "fall back to a direct
|
|
35
|
+
* request", and that only works if this never hangs or throws.
|
|
36
|
+
*/
|
|
37
|
+
import net from "node:net";
|
|
38
|
+
import { MEMORY_DAEMON_CONNECT_TIMEOUT_MS, MEMORY_DAEMON_MAX_LINE_BYTES, MEMORY_DAEMON_PROTOCOL_VERSION, } from "./memory-daemon-endpoint.js";
|
|
39
|
+
/**
|
|
40
|
+
* Ask the daemon to proxy one HTTP request over its warm connection.
|
|
41
|
+
* Resolves once, always — never throws, never hangs, never holds the event
|
|
42
|
+
* loop open past its own timers (all `unref`'d, same discipline as
|
|
43
|
+
* `memory-daemon-probe.ts` and `@bli-cockpit/memory-mcp`'s `askDaemon`).
|
|
44
|
+
*/
|
|
45
|
+
export function askMemoryDaemonHttp(options) {
|
|
46
|
+
const now = options.now ?? Date.now;
|
|
47
|
+
const started = now();
|
|
48
|
+
const connectTimeoutMs = options.connectTimeoutMs ?? MEMORY_DAEMON_CONNECT_TIMEOUT_MS;
|
|
49
|
+
const connect = options.connectImpl ?? ((address) => net.createConnection({ path: address }));
|
|
50
|
+
return new Promise((resolve) => {
|
|
51
|
+
let settled = false;
|
|
52
|
+
let buffered = "";
|
|
53
|
+
let socket;
|
|
54
|
+
const timers = [];
|
|
55
|
+
const finish = (result) => {
|
|
56
|
+
if (settled)
|
|
57
|
+
return;
|
|
58
|
+
settled = true;
|
|
59
|
+
for (const timer of timers)
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
try {
|
|
62
|
+
socket?.destroy();
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// Already gone.
|
|
66
|
+
}
|
|
67
|
+
resolve({ ...result, elapsedMs: now() - started });
|
|
68
|
+
};
|
|
69
|
+
const arm = (ms, reason) => {
|
|
70
|
+
const timer = setTimeout(() => finish({ ok: false, reason }), Math.max(1, ms));
|
|
71
|
+
timer.unref?.();
|
|
72
|
+
timers.push(timer);
|
|
73
|
+
};
|
|
74
|
+
let connectTimer;
|
|
75
|
+
try {
|
|
76
|
+
socket = connect(options.address);
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
finish({ ok: false, reason: connectReason(error) });
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
socket.setNoDelay?.(true);
|
|
83
|
+
arm(options.deadlineMs, "daemon_http_deadline");
|
|
84
|
+
connectTimer = setTimeout(() => finish({ ok: false, reason: "daemon_connect_timeout" }), Math.max(1, connectTimeoutMs));
|
|
85
|
+
connectTimer.unref?.();
|
|
86
|
+
timers.push(connectTimer);
|
|
87
|
+
socket.on("error", (error) => {
|
|
88
|
+
finish({ ok: false, reason: connectReason(error) });
|
|
89
|
+
});
|
|
90
|
+
socket.on("connect", () => {
|
|
91
|
+
clearTimeout(connectTimer);
|
|
92
|
+
socket.write(encodeHttpProxyLine(options.request));
|
|
93
|
+
});
|
|
94
|
+
socket.on("data", (chunk) => {
|
|
95
|
+
buffered += chunk.toString("utf8");
|
|
96
|
+
if (buffered.length > MEMORY_DAEMON_MAX_LINE_BYTES) {
|
|
97
|
+
finish({ ok: false, reason: "daemon_answer_too_large" });
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const newline = buffered.indexOf("\n");
|
|
101
|
+
if (newline === -1)
|
|
102
|
+
return;
|
|
103
|
+
const parsed = parseHttpProxyAnswerLine(buffered.slice(0, newline));
|
|
104
|
+
if (!parsed.ok) {
|
|
105
|
+
finish({ ok: false, reason: parsed.reason });
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
finish({ ok: true, answer: parsed.answer });
|
|
109
|
+
});
|
|
110
|
+
socket.on("close", () => {
|
|
111
|
+
finish({ ok: false, reason: "daemon_closed_without_answer" });
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/** One JSON line, the same envelope every daemon event uses. */
|
|
116
|
+
export function encodeHttpProxyLine(request) {
|
|
117
|
+
return `${JSON.stringify({
|
|
118
|
+
v: MEMORY_DAEMON_PROTOCOL_VERSION,
|
|
119
|
+
event: "http",
|
|
120
|
+
http: request,
|
|
121
|
+
})}\n`;
|
|
122
|
+
}
|
|
123
|
+
/** Reads one answer line. Any shape this client cannot trust is a named reason, never a guess. */
|
|
124
|
+
export function parseHttpProxyAnswerLine(line) {
|
|
125
|
+
let parsed;
|
|
126
|
+
try {
|
|
127
|
+
parsed = JSON.parse(line);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return { ok: false, reason: "daemon_answer_unparseable" };
|
|
131
|
+
}
|
|
132
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
133
|
+
return { ok: false, reason: "daemon_answer_not_an_object" };
|
|
134
|
+
}
|
|
135
|
+
const record = parsed;
|
|
136
|
+
if (record["ok"] !== true) {
|
|
137
|
+
const reason = record["reason"];
|
|
138
|
+
return { ok: false, reason: typeof reason === "string" ? reason : "daemon_refused" };
|
|
139
|
+
}
|
|
140
|
+
const http = record["http"];
|
|
141
|
+
if (!http || typeof http !== "object" || Array.isArray(http)) {
|
|
142
|
+
return { ok: false, reason: "daemon_answer_without_http" };
|
|
143
|
+
}
|
|
144
|
+
const httpRecord = http;
|
|
145
|
+
const status = httpRecord["status"];
|
|
146
|
+
const body = httpRecord["body"];
|
|
147
|
+
if (typeof status !== "number" || typeof body !== "string") {
|
|
148
|
+
return { ok: false, reason: "daemon_answer_http_malformed" };
|
|
149
|
+
}
|
|
150
|
+
const headers = {};
|
|
151
|
+
const rawHeaders = httpRecord["headers"];
|
|
152
|
+
if (rawHeaders && typeof rawHeaders === "object" && !Array.isArray(rawHeaders)) {
|
|
153
|
+
for (const [key, value] of Object.entries(rawHeaders)) {
|
|
154
|
+
if (typeof value === "string")
|
|
155
|
+
headers[key] = value;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { ok: true, answer: { status, headers, body } };
|
|
159
|
+
}
|
|
160
|
+
/** The closed reason vocabulary for a failed connect. `errno` codes only, never an exception message. */
|
|
161
|
+
function connectReason(error) {
|
|
162
|
+
const code = error?.code;
|
|
163
|
+
if (code === "ENOENT" || code === "ECONNREFUSED")
|
|
164
|
+
return "daemon_absent";
|
|
165
|
+
if (code === "EACCES" || code === "EPERM")
|
|
166
|
+
return "daemon_forbidden";
|
|
167
|
+
if (code === "ETIMEDOUT")
|
|
168
|
+
return "daemon_connect_timeout";
|
|
169
|
+
return typeof code === "string" ? `daemon_socket_${code.toLowerCase()}` : "daemon_socket_error";
|
|
170
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE ON-DISK, PER-OPERATOR, STALE-WHILE-REVALIDATE READ CACHE (BLI-10746).
|
|
3
|
+
*
|
|
4
|
+
* Node only — file permissions and `node:fs`/`node:crypto` are not something
|
|
5
|
+
* a dashboard bundle needs — so this lives behind this package's own
|
|
6
|
+
* `./node-read-cache` export, the same isolation `./node-daemon-http-client`
|
|
7
|
+
* next door uses.
|
|
8
|
+
*
|
|
9
|
+
* `@bli-cockpit/local-collector` (the CLI) owns the actual stale-while-
|
|
10
|
+
* revalidate DECISION — when to serve cache, when a fresh call is required,
|
|
11
|
+
* when to kick off a background refresh — because that decision needs
|
|
12
|
+
* `--fresh`/`--allow-stale`/`--json`, which are CLI concepts this module
|
|
13
|
+
* knows nothing about. What lives HERE is the shared, dumb, provably-correct
|
|
14
|
+
* bottom half both the CLI (reading and writing) and `@bli-cockpit/mcp` (only
|
|
15
|
+
* ever invalidating, on its own writes) need to agree on byte-for-byte:
|
|
16
|
+
* where an entry lives on disk, how it is written so a reader never sees a
|
|
17
|
+
* half-written file, and how a whole surface is thrown away after a write.
|
|
18
|
+
* Two independent computations of the same cache path is exactly the
|
|
19
|
+
* BLI-2541 shape (a reader that "worked" against a path nothing ever wrote)
|
|
20
|
+
* this module exists to rule out.
|
|
21
|
+
*
|
|
22
|
+
* **Per-operator, never shared.** The device token is never stored — only
|
|
23
|
+
* its SHA-256, truncated, as a directory segment — but two different people
|
|
24
|
+
* pairing the same machine still get two different cache trees, so a shared
|
|
25
|
+
* intern laptop can never show one operator's Tower data to another.
|
|
26
|
+
*
|
|
27
|
+
* **Owner-only on disk.** Directories `0700`, files `0600`, same as every
|
|
28
|
+
* other collector state directory (`local-state-paths.ts`). No secret is
|
|
29
|
+
* ever written here — this stores API RESPONSE bodies, the same bodies the
|
|
30
|
+
* CLI already prints to a terminal — but the discipline is kept anyway.
|
|
31
|
+
*/
|
|
32
|
+
/** The seven surfaces this ticket's cache covers. A write to any other path invalidates nothing (and is never asked to). */
|
|
33
|
+
export declare const READ_CACHE_SURFACES: readonly ["work", "docs", "cal", "mail", "msg", "settings", "memory"];
|
|
34
|
+
export type ReadCacheSurface = (typeof READ_CACHE_SURFACES)[number];
|
|
35
|
+
/** `/api/work/...` → `"work"`, and so on. `null` for anything this cache does not cover. */
|
|
36
|
+
export declare function readCacheSurfaceForPath(apiPath: string): ReadCacheSurface | null;
|
|
37
|
+
/** One entry, as it sits on disk. */
|
|
38
|
+
export interface ReadCacheEntry {
|
|
39
|
+
storedAt: number;
|
|
40
|
+
status: number;
|
|
41
|
+
body: unknown;
|
|
42
|
+
}
|
|
43
|
+
/** Never the raw token — a machine-scoping label only, never reversible in practice and never logged with its input. */
|
|
44
|
+
export declare function operatorScope(deviceToken: string): string;
|
|
45
|
+
/** One request, folded to a filename-safe key. Includes the body so `memory search`'s different queries never collide. */
|
|
46
|
+
export declare function readCacheKey(label: string, apiPath: string, body: unknown): string;
|
|
47
|
+
export declare function readCacheSurfaceDir(stateDir: string, deviceToken: string, surface: ReadCacheSurface): string;
|
|
48
|
+
export declare function readCacheEntryPath(stateDir: string, deviceToken: string, surface: ReadCacheSurface, key: string): string;
|
|
49
|
+
/**
|
|
50
|
+
* Reads one entry. Missing, corrupt, or an unreadable shape are all the same
|
|
51
|
+
* answer — `null`, a cache miss — never a thrown error: a cache is a
|
|
52
|
+
* performance optimisation, and a command that crashed because its cache
|
|
53
|
+
* file was half-written would be worse than no cache at all.
|
|
54
|
+
*/
|
|
55
|
+
export declare function readReadCacheEntry(entryPath: string): ReadCacheEntry | null;
|
|
56
|
+
/**
|
|
57
|
+
* Writes one entry atomically: a temp file in the SAME directory (so the
|
|
58
|
+
* rename is on one filesystem, never a cross-device copy), then `rename`,
|
|
59
|
+
* which POSIX and NTFS both make an atomic replace. A reader mid-refresh
|
|
60
|
+
* therefore always sees either the old whole entry or the new whole entry,
|
|
61
|
+
* never a partial write.
|
|
62
|
+
*/
|
|
63
|
+
export declare function writeReadCacheEntryAtomic(entryPath: string, entry: Omit<ReadCacheEntry, "storedAt"> & {
|
|
64
|
+
storedAt?: number;
|
|
65
|
+
}): void;
|
|
66
|
+
/**
|
|
67
|
+
* Throws away every cached read for one surface — the whole answer to "any
|
|
68
|
+
* write through the CLI or MCP invalidates the affected cache" (BLI-10746).
|
|
69
|
+
* Coarse on purpose: a write to `/api/work/issues/BLI-1` could in principle
|
|
70
|
+
* only stale one `work list` filter combination, but naming exactly which
|
|
71
|
+
* cached queries a given write affects is its own project, and "the next
|
|
72
|
+
* read of this surface is live" costs one extra request, never a wrong
|
|
73
|
+
* answer.
|
|
74
|
+
*/
|
|
75
|
+
export declare function invalidateReadCacheSurface(stateDir: string, deviceToken: string, surface: ReadCacheSurface): {
|
|
76
|
+
ok: true;
|
|
77
|
+
removed: boolean;
|
|
78
|
+
} | {
|
|
79
|
+
ok: false;
|
|
80
|
+
reason: string;
|
|
81
|
+
};
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE ON-DISK, PER-OPERATOR, STALE-WHILE-REVALIDATE READ CACHE (BLI-10746).
|
|
3
|
+
*
|
|
4
|
+
* Node only — file permissions and `node:fs`/`node:crypto` are not something
|
|
5
|
+
* a dashboard bundle needs — so this lives behind this package's own
|
|
6
|
+
* `./node-read-cache` export, the same isolation `./node-daemon-http-client`
|
|
7
|
+
* next door uses.
|
|
8
|
+
*
|
|
9
|
+
* `@bli-cockpit/local-collector` (the CLI) owns the actual stale-while-
|
|
10
|
+
* revalidate DECISION — when to serve cache, when a fresh call is required,
|
|
11
|
+
* when to kick off a background refresh — because that decision needs
|
|
12
|
+
* `--fresh`/`--allow-stale`/`--json`, which are CLI concepts this module
|
|
13
|
+
* knows nothing about. What lives HERE is the shared, dumb, provably-correct
|
|
14
|
+
* bottom half both the CLI (reading and writing) and `@bli-cockpit/mcp` (only
|
|
15
|
+
* ever invalidating, on its own writes) need to agree on byte-for-byte:
|
|
16
|
+
* where an entry lives on disk, how it is written so a reader never sees a
|
|
17
|
+
* half-written file, and how a whole surface is thrown away after a write.
|
|
18
|
+
* Two independent computations of the same cache path is exactly the
|
|
19
|
+
* BLI-2541 shape (a reader that "worked" against a path nothing ever wrote)
|
|
20
|
+
* this module exists to rule out.
|
|
21
|
+
*
|
|
22
|
+
* **Per-operator, never shared.** The device token is never stored — only
|
|
23
|
+
* its SHA-256, truncated, as a directory segment — but two different people
|
|
24
|
+
* pairing the same machine still get two different cache trees, so a shared
|
|
25
|
+
* intern laptop can never show one operator's Tower data to another.
|
|
26
|
+
*
|
|
27
|
+
* **Owner-only on disk.** Directories `0700`, files `0600`, same as every
|
|
28
|
+
* other collector state directory (`local-state-paths.ts`). No secret is
|
|
29
|
+
* ever written here — this stores API RESPONSE bodies, the same bodies the
|
|
30
|
+
* CLI already prints to a terminal — but the discipline is kept anyway.
|
|
31
|
+
*/
|
|
32
|
+
import crypto from "node:crypto";
|
|
33
|
+
import fs from "node:fs";
|
|
34
|
+
import path from "node:path";
|
|
35
|
+
/** The seven surfaces this ticket's cache covers. A write to any other path invalidates nothing (and is never asked to). */
|
|
36
|
+
export const READ_CACHE_SURFACES = [
|
|
37
|
+
"work",
|
|
38
|
+
"docs",
|
|
39
|
+
"cal",
|
|
40
|
+
"mail",
|
|
41
|
+
"msg",
|
|
42
|
+
"settings",
|
|
43
|
+
"memory",
|
|
44
|
+
];
|
|
45
|
+
/** `/api/work/...` → `"work"`, and so on. `null` for anything this cache does not cover. */
|
|
46
|
+
export function readCacheSurfaceForPath(apiPath) {
|
|
47
|
+
const segment = apiPath.replace(/^\/+/, "").split("/")[1];
|
|
48
|
+
return READ_CACHE_SURFACES.includes(segment ?? "")
|
|
49
|
+
? segment
|
|
50
|
+
: null;
|
|
51
|
+
}
|
|
52
|
+
/** Never the raw token — a machine-scoping label only, never reversible in practice and never logged with its input. */
|
|
53
|
+
export function operatorScope(deviceToken) {
|
|
54
|
+
return crypto.createHash("sha256").update(deviceToken).digest("hex").slice(0, 16);
|
|
55
|
+
}
|
|
56
|
+
/** One request, folded to a filename-safe key. Includes the body so `memory search`'s different queries never collide. */
|
|
57
|
+
export function readCacheKey(label, apiPath, body) {
|
|
58
|
+
const material = `${label}\n${apiPath}\n${body === undefined ? "" : JSON.stringify(body)}`;
|
|
59
|
+
return crypto.createHash("sha256").update(material).digest("hex").slice(0, 40);
|
|
60
|
+
}
|
|
61
|
+
export function readCacheSurfaceDir(stateDir, deviceToken, surface) {
|
|
62
|
+
return path.join(stateDir, "read-cache", operatorScope(deviceToken), surface);
|
|
63
|
+
}
|
|
64
|
+
export function readCacheEntryPath(stateDir, deviceToken, surface, key) {
|
|
65
|
+
return path.join(readCacheSurfaceDir(stateDir, deviceToken, surface), `${key}.json`);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Reads one entry. Missing, corrupt, or an unreadable shape are all the same
|
|
69
|
+
* answer — `null`, a cache miss — never a thrown error: a cache is a
|
|
70
|
+
* performance optimisation, and a command that crashed because its cache
|
|
71
|
+
* file was half-written would be worse than no cache at all.
|
|
72
|
+
*/
|
|
73
|
+
export function readReadCacheEntry(entryPath) {
|
|
74
|
+
let raw;
|
|
75
|
+
try {
|
|
76
|
+
raw = fs.readFileSync(entryPath, "utf8");
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const parsed = JSON.parse(raw);
|
|
83
|
+
const storedAt = parsed["storedAt"];
|
|
84
|
+
const status = parsed["status"];
|
|
85
|
+
if (typeof storedAt !== "number" || typeof status !== "number" || !("body" in parsed)) {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
return { storedAt, status, body: parsed["body"] };
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Writes one entry atomically: a temp file in the SAME directory (so the
|
|
96
|
+
* rename is on one filesystem, never a cross-device copy), then `rename`,
|
|
97
|
+
* which POSIX and NTFS both make an atomic replace. A reader mid-refresh
|
|
98
|
+
* therefore always sees either the old whole entry or the new whole entry,
|
|
99
|
+
* never a partial write.
|
|
100
|
+
*/
|
|
101
|
+
export function writeReadCacheEntryAtomic(entryPath, entry) {
|
|
102
|
+
const dir = path.dirname(entryPath);
|
|
103
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
104
|
+
const payload = { storedAt: entry.storedAt ?? Date.now(), status: entry.status, body: entry.body };
|
|
105
|
+
const tmpPath = path.join(dir, `.${path.basename(entryPath)}.${process.pid}.tmp`);
|
|
106
|
+
fs.writeFileSync(tmpPath, JSON.stringify(payload), { mode: 0o600 });
|
|
107
|
+
fs.renameSync(tmpPath, entryPath);
|
|
108
|
+
if (process.platform !== "win32") {
|
|
109
|
+
try {
|
|
110
|
+
fs.chmodSync(dir, 0o700);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
// Best-effort tightening only; the mkdir mode above already asked for it.
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Throws away every cached read for one surface — the whole answer to "any
|
|
119
|
+
* write through the CLI or MCP invalidates the affected cache" (BLI-10746).
|
|
120
|
+
* Coarse on purpose: a write to `/api/work/issues/BLI-1` could in principle
|
|
121
|
+
* only stale one `work list` filter combination, but naming exactly which
|
|
122
|
+
* cached queries a given write affects is its own project, and "the next
|
|
123
|
+
* read of this surface is live" costs one extra request, never a wrong
|
|
124
|
+
* answer.
|
|
125
|
+
*/
|
|
126
|
+
export function invalidateReadCacheSurface(stateDir, deviceToken, surface) {
|
|
127
|
+
const dir = readCacheSurfaceDir(stateDir, deviceToken, surface);
|
|
128
|
+
try {
|
|
129
|
+
const existed = fs.existsSync(dir);
|
|
130
|
+
if (existed)
|
|
131
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
132
|
+
return { ok: true, removed: existed };
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
return { ok: false, reason: error instanceof Error ? error.name : "unknown" };
|
|
136
|
+
}
|
|
137
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bli-cockpit/telemetry-core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.51",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -24,6 +24,16 @@
|
|
|
24
24
|
"types": "./dist/evidence-storage-encoding.d.ts",
|
|
25
25
|
"import": "./dist/evidence-storage-encoding.js",
|
|
26
26
|
"default": "./dist/evidence-storage-encoding.js"
|
|
27
|
+
},
|
|
28
|
+
"./node-daemon-http-client": {
|
|
29
|
+
"types": "./dist/node-daemon-http-client.d.ts",
|
|
30
|
+
"import": "./dist/node-daemon-http-client.js",
|
|
31
|
+
"default": "./dist/node-daemon-http-client.js"
|
|
32
|
+
},
|
|
33
|
+
"./node-read-cache": {
|
|
34
|
+
"types": "./dist/node-read-cache.d.ts",
|
|
35
|
+
"import": "./dist/node-read-cache.js",
|
|
36
|
+
"default": "./dist/node-read-cache.js"
|
|
27
37
|
}
|
|
28
38
|
},
|
|
29
39
|
"publishConfig": {
|