@lensmcp/node-instrumentation 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # @lensmcp/node-instrumentation
2
+
3
+ > Zero-touch Node runtime taps for [LensMCP](https://github.com/kiwiapps-ltd/lensmcp) — the observability lens for coding agents.
4
+
5
+ `@lensmcp/node-instrumentation` instruments a running Node.js service **without touching its source**. It is loaded by the runner via `node --require @lensmcp/node-instrumentation/register`, before your app bundle, so it can patch Node built-ins and external modules (`fs`, `fetch`/`http(s)`, `child_process`, `pg`, `ioredis`, `bullmq`, `@nestjs/core`) and the process streams **in place**. As your service runs, those patches emit LensMCP events onto the bus that the dashboard and MCP server consume.
6
+
7
+ The whole point is that the host stays completely ordinary. There are no emit helpers, no `createLensmcpNestApp`, no dual-mode bootstrap — your `main.ts` looks exactly like an uninstrumented service. Requiring the module *is* the installation: it must run before the app loads so the require hook sees every external on first `require`/`import`. Every tap is wrapped in `try/catch` and the bus writer fails silently, so instrumentation can never throw into — or break — the host.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ yarn add @lensmcp/node-instrumentation
13
+ ```
14
+
15
+ You normally do not install or import this package yourself. The `@lensmcp/cluster` serve executor injects it into each service pod via `--require` and sets the relevant environment variables. Add it directly only if you are wiring a runner by hand.
16
+
17
+ ## Usage
18
+
19
+ Activate it by preloading `register` ahead of your entrypoint — this is what does the instrumentation:
20
+
21
+ ```bash
22
+ node --require @lensmcp/node-instrumentation/register your-app.js
23
+ ```
24
+
25
+ `@lensmcp/cluster` does exactly this for you when it serves a pod, so under the cluster you do nothing.
26
+
27
+ If you need to install the taps programmatically (e.g. from a custom runner), call the idempotent installer exported from the package root:
28
+
29
+ ```ts
30
+ import { installLensmcpNodeInstrumentation } from '@lensmcp/node-instrumentation';
31
+
32
+ installLensmcpNodeInstrumentation(); // safe to call more than once — guarded by a global marker
33
+ ```
34
+
35
+ The package root also re-exports the individual tap functions (`tapFs`, `tapEgress`, `tapExec`, `pgTap`, `redisTap`, `bullmqTap`, `nestTap`, `installChildAppBridge`) and the bus helpers (`lensEmit`, `PROJECT`, `EVENT_FILE`) for advanced use.
36
+
37
+ ## What it taps
38
+
39
+ Built-ins and globals are patched at install; external modules (`pg`, `ioredis`, `bullmq`, `@nestjs/core`) are patched lazily through a require hook the first time they load.
40
+
41
+ | Layer | How it's patched | Emits (source / kind) |
42
+ |---|---|---|
43
+ | Filesystem | `fs` read/write/append/stream (sync, callback, promise) | `fs` / `fs-ops` — a 1s aggregate (read/write counts, bytes, top paths) |
44
+ | Network egress | global `fetch` + `http`/`https.request` wrap | `external` / `egress` — outbound method, host, status, duration (internal/loopback/RFC1918 destinations skipped) |
45
+ | Child processes | `child_process` spawn/fork/exec/execFile (+ sync forms) | `exec` / `exec` — command, exit code/signal, duration |
46
+ | Postgres | require hook → `pg` `Client.prototype.query` | `db` / `db-query` — op, table, query, params, row count, duration |
47
+ | Redis | require hook → `ioredis` `Redis.prototype.sendCommand` | `redis` / `redis-op` — op, key, command (BullMQ traffic and housekeeping excluded; rate-capped) |
48
+ | Queues | require hook → `bullmq` `Queue`/`Worker` prototypes | `queue` / `queue-enqueued`, `queue-active`, `queue-completed`, `queue-failed`, `queue-process`, plus a 2s `queue-state` snapshot |
49
+ | NestJS | require hook → `@nestjs/core` `NestFactory.create` grafts `LensmcpModule` | the events from [`@lensmcp/nest-instrumentation`](https://github.com/kiwiapps-ltd/lensmcp) — class traces, request flows, memory |
50
+ | stdout / stderr | `process.stdout`/`stderr` `write` wrap | `nestjs` / `runtime` — one log event per line (original output is preserved) |
51
+
52
+ Under the cluster devserver (`APP_RUNNER=1`) the NestJS tap also makes a standard `NestFactory.create(...)` + `app.listen(port)` service pod-servable: `listen` is intercepted to `init()` the app and hand its raw request handler to a capture queue instead of binding TCP, with no devserver contract in your `main.ts`.
53
+
54
+ ## Configuration
55
+
56
+ All configuration is via environment variables (the cluster serve executor sets these for you).
57
+
58
+ | Variable | Effect |
59
+ |---|---|
60
+ | `LENSMCP_AUTO=0` | Disable **all** instrumentation — no taps are installed. |
61
+ | `LENSMCP_NEST=0` | Keep the other taps but **skip the NestJS graft** (`NestFactory.create` is left untouched). |
62
+ | `LENSMCP_LOGS=0` | Disable the stdout/stderr log tap. |
63
+ | `LENSMCP_PROJECT` | Service identity stamped on every event. Falls back to `SERVICE_NAME`, then `"app"`. |
64
+ | `LENSMCP_EVENT_FILE` | Path to the JSONL event bus. Defaults to `$CWD/.lensmcp/events.jsonl`. |
65
+
66
+ The stdout/stderr tap and the zero-touch pod bootstrap additionally require `APP_RUNNER=1` (set by the cluster runner); outside a pod they are no-ops so a standalone `--require` run stays quiet.
67
+
68
+ ## How it fits
69
+
70
+ `@lensmcp/node-instrumentation` is injected by **`@lensmcp/cluster`**, which serves each service as a hot-swappable pod with this module preloaded. The taps write `BaseEvent`-shaped JSON lines to the LensMCP bus, where they are picked up by `@lensmcp/core` and surfaced through the MCP server and dashboard.
71
+
72
+ It pairs with **`@lensmcp/nest-instrumentation`** (a direct dependency): the NestJS tap grafts that package's `LensmcpModule` onto your root module to add class-level traces, request flows, and memory tracking — again without any import in host code.
73
+
74
+ ---
75
+
76
+ Part of [LensMCP](https://github.com/kiwiapps-ltd/lensmcp). Apache-2.0.
package/index.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ export { lensEmit, isLensWriting, PROJECT, EVENT_FILE } from './lib/emit';
2
+ export type { LensSeverity } from './lib/emit';
3
+ export { installRequireHook } from './lib/require-hook';
4
+ export type { ModuleTap } from './lib/require-hook';
5
+ export { tapEgress } from './lib/tap-egress';
6
+ export { tapFs } from './lib/tap-fs';
7
+ export { tapExec } from './lib/tap-exec';
8
+ export { pgTap } from './lib/tap-pg';
9
+ export { redisTap } from './lib/tap-redis';
10
+ export { bullmqTap } from './lib/tap-bullmq';
11
+ export { nestTap, installChildAppBridge } from './lib/tap-nest';
12
+ export type { CapturedChildApp } from './lib/tap-nest';
13
+ export { installLensmcpNodeInstrumentation } from './lib/install';
14
+ //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC1E,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,YAAY,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAChE,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAAE,iCAAiC,EAAE,MAAM,eAAe,CAAC"}
package/index.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.installLensmcpNodeInstrumentation = exports.installChildAppBridge = exports.nestTap = exports.bullmqTap = exports.redisTap = exports.pgTap = exports.tapExec = exports.tapFs = exports.tapEgress = exports.installRequireHook = exports.EVENT_FILE = exports.PROJECT = exports.isLensWriting = exports.lensEmit = void 0;
4
+ var emit_1 = require("./lib/emit");
5
+ Object.defineProperty(exports, "lensEmit", { enumerable: true, get: function () { return emit_1.lensEmit; } });
6
+ Object.defineProperty(exports, "isLensWriting", { enumerable: true, get: function () { return emit_1.isLensWriting; } });
7
+ Object.defineProperty(exports, "PROJECT", { enumerable: true, get: function () { return emit_1.PROJECT; } });
8
+ Object.defineProperty(exports, "EVENT_FILE", { enumerable: true, get: function () { return emit_1.EVENT_FILE; } });
9
+ var require_hook_1 = require("./lib/require-hook");
10
+ Object.defineProperty(exports, "installRequireHook", { enumerable: true, get: function () { return require_hook_1.installRequireHook; } });
11
+ var tap_egress_1 = require("./lib/tap-egress");
12
+ Object.defineProperty(exports, "tapEgress", { enumerable: true, get: function () { return tap_egress_1.tapEgress; } });
13
+ var tap_fs_1 = require("./lib/tap-fs");
14
+ Object.defineProperty(exports, "tapFs", { enumerable: true, get: function () { return tap_fs_1.tapFs; } });
15
+ var tap_exec_1 = require("./lib/tap-exec");
16
+ Object.defineProperty(exports, "tapExec", { enumerable: true, get: function () { return tap_exec_1.tapExec; } });
17
+ var tap_pg_1 = require("./lib/tap-pg");
18
+ Object.defineProperty(exports, "pgTap", { enumerable: true, get: function () { return tap_pg_1.pgTap; } });
19
+ var tap_redis_1 = require("./lib/tap-redis");
20
+ Object.defineProperty(exports, "redisTap", { enumerable: true, get: function () { return tap_redis_1.redisTap; } });
21
+ var tap_bullmq_1 = require("./lib/tap-bullmq");
22
+ Object.defineProperty(exports, "bullmqTap", { enumerable: true, get: function () { return tap_bullmq_1.bullmqTap; } });
23
+ var tap_nest_1 = require("./lib/tap-nest");
24
+ Object.defineProperty(exports, "nestTap", { enumerable: true, get: function () { return tap_nest_1.nestTap; } });
25
+ Object.defineProperty(exports, "installChildAppBridge", { enumerable: true, get: function () { return tap_nest_1.installChildAppBridge; } });
26
+ var install_1 = require("./lib/install");
27
+ Object.defineProperty(exports, "installLensmcpNodeInstrumentation", { enumerable: true, get: function () { return install_1.installLensmcpNodeInstrumentation; } });
package/lib/emit.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ export type LensSeverity = 'info' | 'error';
2
+ export type LogSeverity = 'debug' | 'info' | 'warning' | 'error' | 'fatal';
3
+ /** Service identity stamped on every event (set by the cluster serve executor). */
4
+ export declare const PROJECT: string;
5
+ /** The file bus — same default the cluster gateway and dashboard use. */
6
+ export declare const EVENT_FILE: string;
7
+ /** True while the lens itself is appending — the fs tap skips self-writes. */
8
+ export declare function isLensWriting(): boolean;
9
+ /** Flow correlation stamped into `context` so the event joins a request trace. */
10
+ export interface FlowCtx {
11
+ flowId?: string;
12
+ requestId?: string;
13
+ originNodeId?: string;
14
+ }
15
+ export declare function lensEmit(source: string, severity: LensSeverity, title: string, raw: Record<string, unknown>, fingerprint?: string, flowCtx?: FlowCtx): void;
16
+ /**
17
+ * Emit a raw service log line — the ACTUAL stdout/Logger output a pod prints — as
18
+ * a `runtime` event so it surfaces in the dashboard Logs view. Same fs-tap-safe
19
+ * write path as {@link lensEmit}; `source: 'nestjs'` + `raw.project` carries the
20
+ * concrete service name (which the dashboard prefers as the log's source).
21
+ */
22
+ export declare function lensLog(severity: LogSeverity, title: string): void;
23
+ //# sourceMappingURL=emit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emit.d.ts","sourceRoot":"","sources":["../../src/lib/emit.ts"],"names":[],"mappings":"AAoBA,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,OAAO,CAAC;AAC5C,MAAM,MAAM,WAAW,GAAG,OAAO,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;AAE3E,mFAAmF;AACnF,eAAO,MAAM,OAAO,EAAE,MACkD,CAAC;AAEzE,yEAAyE;AACzE,eAAO,MAAM,UAAU,EAAE,MACsD,CAAC;AAKhF,8EAA8E;AAC9E,wBAAgB,aAAa,IAAI,OAAO,CAEvC;AAED,kFAAkF;AAClF,MAAM,WAAW,OAAO;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,wBAAgB,QAAQ,CACtB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,YAAY,EACtB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,WAAW,CAAC,EAAE,MAAM,EACpB,OAAO,CAAC,EAAE,OAAO,GAChB,IAAI,CAiCN;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CA2BlE"}
package/lib/emit.js ADDED
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EVENT_FILE = exports.PROJECT = void 0;
4
+ exports.isLensWriting = isLensWriting;
5
+ exports.lensEmit = lensEmit;
6
+ exports.lensLog = lensLog;
7
+ const tslib_1 = require("tslib");
8
+ /**
9
+ * The LensMCP bus writer for zero-touch taps — file rendezvous, one
10
+ * BaseEvent-shaped JSON line per event (the exact shape the cluster
11
+ * dashboard reducers consume: source db/redis/queue/external/fs/exec,
12
+ * category `cluster`, raw `{ project, name, kind, … }`).
13
+ *
14
+ * The fs originals are BOUND to local consts at module load, BEFORE the fs
15
+ * tap patches the fs namespace — so the lens writing to its own bus calls the
16
+ * pristine functions and can never recurse into its own instrumentation. (A
17
+ * bare `import { appendFileSync }` compiles to a LIVE namespace read, which
18
+ * would pick up the tap's wrapper after patching — hence the explicit bind.)
19
+ * `isLensWriting()` is a second belt for anything that still re-enters.
20
+ */
21
+ const nodeFs = tslib_1.__importStar(require("node:fs"));
22
+ const node_path_1 = require("node:path");
23
+ // Pristine references, frozen at load — immune to the fs tap's later patching.
24
+ const appendFileSync = nodeFs.appendFileSync;
25
+ const mkdirSync = nodeFs.mkdirSync;
26
+ /** Service identity stamped on every event (set by the cluster serve executor). */
27
+ exports.PROJECT = process.env['LENSMCP_PROJECT'] || process.env['SERVICE_NAME'] || 'app';
28
+ /** The file bus — same default the cluster gateway and dashboard use. */
29
+ exports.EVENT_FILE = process.env['LENSMCP_EVENT_FILE'] || `${process.cwd()}/.lensmcp/events.jsonl`;
30
+ let writing = false;
31
+ let dirReady = false;
32
+ /** True while the lens itself is appending — the fs tap skips self-writes. */
33
+ function isLensWriting() {
34
+ return writing;
35
+ }
36
+ function lensEmit(source, severity, title, raw, fingerprint, flowCtx) {
37
+ try {
38
+ writing = true;
39
+ if (!dirReady) {
40
+ mkdirSync((0, node_path_1.dirname)(exports.EVENT_FILE), { recursive: true });
41
+ dirReady = true;
42
+ }
43
+ appendFileSync(exports.EVENT_FILE, JSON.stringify({
44
+ id: Date.now().toString(36) + Math.random().toString(36).slice(2, 10),
45
+ sessionId: 'pending',
46
+ timestamp: Date.now(),
47
+ source,
48
+ category: 'cluster',
49
+ severity,
50
+ context: {
51
+ sessionId: 'pending',
52
+ projectName: exports.PROJECT,
53
+ ...(flowCtx?.flowId ? { flowId: flowCtx.flowId } : {}),
54
+ ...(flowCtx?.requestId ? { requestId: flowCtx.requestId } : {}),
55
+ ...(flowCtx?.originNodeId ? { originNodeId: flowCtx.originNodeId } : {}),
56
+ },
57
+ fingerprint: fingerprint ?? `${source}:${String(raw['name'] ?? source)}`,
58
+ title,
59
+ raw: { project: exports.PROJECT, ...raw },
60
+ }) + '\n');
61
+ }
62
+ catch {
63
+ /* lens offline — never break the host */
64
+ }
65
+ finally {
66
+ writing = false;
67
+ }
68
+ }
69
+ /**
70
+ * Emit a raw service log line — the ACTUAL stdout/Logger output a pod prints — as
71
+ * a `runtime` event so it surfaces in the dashboard Logs view. Same fs-tap-safe
72
+ * write path as {@link lensEmit}; `source: 'nestjs'` + `raw.project` carries the
73
+ * concrete service name (which the dashboard prefers as the log's source).
74
+ */
75
+ function lensLog(severity, title) {
76
+ try {
77
+ writing = true;
78
+ if (!dirReady) {
79
+ mkdirSync((0, node_path_1.dirname)(exports.EVENT_FILE), { recursive: true });
80
+ dirReady = true;
81
+ }
82
+ appendFileSync(exports.EVENT_FILE, JSON.stringify({
83
+ id: Date.now().toString(36) + Math.random().toString(36).slice(2, 10),
84
+ sessionId: 'pending',
85
+ timestamp: Date.now(),
86
+ source: 'nestjs',
87
+ category: 'runtime',
88
+ severity,
89
+ context: { sessionId: 'pending', projectName: exports.PROJECT },
90
+ fingerprint: `log:${exports.PROJECT}`,
91
+ title,
92
+ raw: { project: exports.PROJECT, kind: 'log' },
93
+ }) + '\n');
94
+ }
95
+ catch {
96
+ /* lens offline — never break the host */
97
+ }
98
+ finally {
99
+ writing = false;
100
+ }
101
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Bridge to the request's flow context. The grafted nest module runs every
3
+ * request inside `@lensmcp/nest-instrumentation`'s AsyncLocalStorage scope —
4
+ * since taps fire INSIDE that scope (a pg query awaited by a controller, a
5
+ * fetch from a service), reading the same ALS at call time yields the
6
+ * flowId/requestId that stitches the tap event into the request's trace.
7
+ *
8
+ * The module is ESM and this lib is CJS, so the getter is resolved once via
9
+ * dynamic import (primed at install; resolved long before the first request).
10
+ */
11
+ import type { FlowCtx } from './emit';
12
+ interface LiveCtx {
13
+ flowId?: string;
14
+ requestId?: string;
15
+ originNodeId?: string;
16
+ dbCallCount?: number;
17
+ redisCallCount?: number;
18
+ externalCallCount?: number;
19
+ }
20
+ export declare function primeFlowContext(): void;
21
+ /**
22
+ * Run `fn` inside a fresh flow context (queue workers, timers — async
23
+ * entry points that aren't HTTP requests). Inner taps then inherit the
24
+ * flowId exactly like they do inside a traced request.
25
+ */
26
+ export declare function runInFlowContext<T>(ctx: {
27
+ flowId?: string;
28
+ requestId: string;
29
+ }, fn: () => T): T;
30
+ /**
31
+ * The LIVE (mutable) request context — taps bump its operation counters
32
+ * (db/redis/external) so the span wrapper's loop detector can report
33
+ * "this method issued N of these" (the N+1 / fan-out signal).
34
+ */
35
+ export declare function liveFlowContext(): LiveCtx | undefined;
36
+ /** Snapshot the live flow context — call AT the operation site, before awaits. */
37
+ export declare function flowContext(): FlowCtx | undefined;
38
+ export {};
39
+ //# sourceMappingURL=flow-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flow-context.d.ts","sourceRoot":"","sources":["../../src/lib/flow-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEtC,UAAU,OAAO;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAMD,wBAAgB,gBAAgB,IAAI,IAAI,CASvC;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAChC,GAAG,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,EAC3C,EAAE,EAAE,MAAM,CAAC,GACV,CAAC,CAOH;AAED;;;;GAIG;AACH,wBAAgB,eAAe,IAAI,OAAO,GAAG,SAAS,CAMrD;AAED,kFAAkF;AAClF,wBAAgB,WAAW,IAAI,OAAO,GAAG,SAAS,CAQjD"}
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.primeFlowContext = primeFlowContext;
4
+ exports.runInFlowContext = runInFlowContext;
5
+ exports.liveFlowContext = liveFlowContext;
6
+ exports.flowContext = flowContext;
7
+ let getCtx = null;
8
+ let runWith = null;
9
+ function primeFlowContext() {
10
+ import('@lensmcp/nest-instrumentation')
11
+ .then((m) => {
12
+ getCtx = m.currentLensmcpContext;
13
+ runWith = m.runInLensmcpContext;
14
+ })
15
+ .catch(() => {
16
+ /* nest instrumentation absent — tap events stay un-correlated */
17
+ });
18
+ }
19
+ /**
20
+ * Run `fn` inside a fresh flow context (queue workers, timers — async
21
+ * entry points that aren't HTTP requests). Inner taps then inherit the
22
+ * flowId exactly like they do inside a traced request.
23
+ */
24
+ function runInFlowContext(ctx, fn) {
25
+ if (!runWith)
26
+ return fn();
27
+ try {
28
+ return runWith({ sessionId: 'pending', requestId: ctx.requestId, ...(ctx.flowId ? { flowId: ctx.flowId } : {}) }, fn);
29
+ }
30
+ catch {
31
+ return fn();
32
+ }
33
+ }
34
+ /**
35
+ * The LIVE (mutable) request context — taps bump its operation counters
36
+ * (db/redis/external) so the span wrapper's loop detector can report
37
+ * "this method issued N of these" (the N+1 / fan-out signal).
38
+ */
39
+ function liveFlowContext() {
40
+ try {
41
+ return getCtx?.();
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ }
47
+ /** Snapshot the live flow context — call AT the operation site, before awaits. */
48
+ function flowContext() {
49
+ const ctx = liveFlowContext();
50
+ if (!ctx)
51
+ return undefined;
52
+ return {
53
+ ...(ctx.flowId ? { flowId: ctx.flowId } : {}),
54
+ ...(ctx.requestId ? { requestId: ctx.requestId } : {}),
55
+ ...(ctx.originNodeId ? { originNodeId: ctx.originNodeId } : {}),
56
+ };
57
+ }
@@ -0,0 +1,2 @@
1
+ export declare function installLensmcpNodeInstrumentation(): void;
2
+ //# sourceMappingURL=install.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"install.d.ts","sourceRoot":"","sources":["../../src/lib/install.ts"],"names":[],"mappings":"AAqBA,wBAAgB,iCAAiC,IAAI,IAAI,CAoBxD"}
package/lib/install.js ADDED
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.installLensmcpNodeInstrumentation = installLensmcpNodeInstrumentation;
4
+ /**
5
+ * Installs every zero-touch tap once (idempotent via a global marker):
6
+ *
7
+ * builtins/globals — fetch + http/https (egress), fs (aggregated), child_process (exec)
8
+ * require hook — pg (db) · ioredis (redis) · bullmq (queue) · @nestjs/core (class
9
+ * traces via LensmcpModule graft + zero-touch pod bootstrap)
10
+ *
11
+ * Kill switches: LENSMCP_AUTO=0 disables everything; LENSMCP_NEST=0 keeps the
12
+ * taps but skips the NestJS graft.
13
+ */
14
+ const require_hook_1 = require("./require-hook");
15
+ const flow_context_1 = require("./flow-context");
16
+ const tap_egress_1 = require("./tap-egress");
17
+ const tap_fs_1 = require("./tap-fs");
18
+ const tap_exec_1 = require("./tap-exec");
19
+ const tap_pg_1 = require("./tap-pg");
20
+ const tap_redis_1 = require("./tap-redis");
21
+ const tap_bullmq_1 = require("./tap-bullmq");
22
+ const tap_nest_1 = require("./tap-nest");
23
+ const tap_stdout_1 = require("./tap-stdout");
24
+ function installLensmcpNodeInstrumentation() {
25
+ const g = globalThis;
26
+ if (g['__lensmcpNodeInstrumented'])
27
+ return;
28
+ g['__lensmcpNodeInstrumented'] = true;
29
+ if (process.env['LENSMCP_AUTO'] === '0')
30
+ return;
31
+ try {
32
+ (0, flow_context_1.primeFlowContext)();
33
+ }
34
+ catch { /* never break the host */ }
35
+ try {
36
+ (0, tap_egress_1.tapEgress)();
37
+ }
38
+ catch { /* never break the host */ }
39
+ try {
40
+ (0, tap_fs_1.tapFs)();
41
+ }
42
+ catch { /* never break the host */ }
43
+ try {
44
+ (0, tap_exec_1.tapExec)();
45
+ }
46
+ catch { /* never break the host */ }
47
+ try {
48
+ (0, tap_stdout_1.tapStdout)();
49
+ }
50
+ catch { /* never break the host */ }
51
+ try {
52
+ (0, require_hook_1.installRequireHook)({
53
+ pg: tap_pg_1.pgTap,
54
+ ioredis: tap_redis_1.redisTap,
55
+ bullmq: tap_bullmq_1.bullmqTap,
56
+ '@nestjs/core': tap_nest_1.nestTap,
57
+ });
58
+ }
59
+ catch { /* never break the host */ }
60
+ try {
61
+ (0, tap_nest_1.installChildAppBridge)();
62
+ }
63
+ catch { /* never break the host */ }
64
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * CJS require hook: the cluster's dev webpack config externalizes every real
3
+ * node_modules package (`commonjs <request>`), so at pod runtime `pg`,
4
+ * `ioredis`, `bullmq` and `@nestjs/core` arrive through `Module._load`. We
5
+ * intercept the EXACT package names and mutate their exports IN PLACE
6
+ * (prototype/static patches, never proxies) — ESM `import` of the same CJS
7
+ * package yields the same exports object, so both module systems observe the
8
+ * patched behavior.
9
+ */
10
+ /**
11
+ * A tap returns `true` once it actually patched its target, `false` when the
12
+ * exports it needs aren't there YET. The distinction matters because of
13
+ * CIRCULAR requires: `@nestjs/core` requires itself while loading, so the
14
+ * hook fires mid-load with a PARTIALLY populated exports object
15
+ * (`NestFactory` still undefined). Marking that attempt as done would
16
+ * permanently skip the tap — instead a `false` keeps the request eligible
17
+ * and the next (post-load, fully populated) require installs it.
18
+ */
19
+ export type ModuleTap = (exportsObject: unknown) => boolean | void;
20
+ export declare function installRequireHook(taps: Record<string, ModuleTap>): void;
21
+ //# sourceMappingURL=require-hook.d.ts.map