@lensmcp/node-instrumentation 1.25.3 → 1.25.6

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/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export type { FloodGuard, FloodGuardOptions, FloodAdmit } from './lib/flood-guar
5
5
  export { installRequireHook } from './lib/require-hook';
6
6
  export type { ModuleTap } from './lib/require-hook';
7
7
  export { tapEgress, resetEgressTapForTests } from './lib/tap-egress';
8
+ export { tapIngress, resetIngressTapForTests, EXCHANGE_ID } from './lib/tap-ingress';
8
9
  export { tapEventLoop, stopEventLoopTapForTests } from './lib/tap-event-loop';
9
10
  export { tapFs } from './lib/tap-fs';
10
11
  export { tapExec } from './lib/tap-exec';
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var o=(t,r)=>p(t,"name",{value:r,configurable:!0});var n=Object.defineProperty,e=o((t,r)=>n(t,"name",{value:r,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.resetActiveWorkForTests=exports.installActiveWorkProbe=exports.beginActiveWork=exports.activeWorkSnapshot=exports.installLensmcpNodeInstrumentation=exports.installChildAppBridge=exports.nestTap=exports.bullmqTap=exports.redisTap=exports.pgTap=exports.tapExec=exports.tapFs=exports.stopEventLoopTapForTests=exports.tapEventLoop=exports.resetEgressTapForTests=exports.tapEgress=exports.installRequireHook=exports.createEventFloodGuard=exports.maybeRotateEventFile=exports.EVENT_MAX_FILES=exports.EVENT_MAX_BYTES=exports.EVENT_FILE=exports.PROJECT=exports.isLensWriting=exports.lensEmit=void 0;var emit_1=require("./lib/emit");Object.defineProperty(exports,"lensEmit",{enumerable:!0,get:e(function(){return emit_1.lensEmit},"get")}),Object.defineProperty(exports,"isLensWriting",{enumerable:!0,get:e(function(){return emit_1.isLensWriting},"get")}),Object.defineProperty(exports,"PROJECT",{enumerable:!0,get:e(function(){return emit_1.PROJECT},"get")}),Object.defineProperty(exports,"EVENT_FILE",{enumerable:!0,get:e(function(){return emit_1.EVENT_FILE},"get")}),Object.defineProperty(exports,"EVENT_MAX_BYTES",{enumerable:!0,get:e(function(){return emit_1.EVENT_MAX_BYTES},"get")}),Object.defineProperty(exports,"EVENT_MAX_FILES",{enumerable:!0,get:e(function(){return emit_1.EVENT_MAX_FILES},"get")}),Object.defineProperty(exports,"maybeRotateEventFile",{enumerable:!0,get:e(function(){return emit_1.maybeRotateEventFile},"get")});var flood_guard_1=require("./lib/flood-guard");Object.defineProperty(exports,"createEventFloodGuard",{enumerable:!0,get:e(function(){return flood_guard_1.createEventFloodGuard},"get")});var require_hook_1=require("./lib/require-hook");Object.defineProperty(exports,"installRequireHook",{enumerable:!0,get:e(function(){return require_hook_1.installRequireHook},"get")});var tap_egress_1=require("./lib/tap-egress");Object.defineProperty(exports,"tapEgress",{enumerable:!0,get:e(function(){return tap_egress_1.tapEgress},"get")}),Object.defineProperty(exports,"resetEgressTapForTests",{enumerable:!0,get:e(function(){return tap_egress_1.resetEgressTapForTests},"get")});var tap_event_loop_1=require("./lib/tap-event-loop");Object.defineProperty(exports,"tapEventLoop",{enumerable:!0,get:e(function(){return tap_event_loop_1.tapEventLoop},"get")}),Object.defineProperty(exports,"stopEventLoopTapForTests",{enumerable:!0,get:e(function(){return tap_event_loop_1.stopEventLoopTapForTests},"get")});var tap_fs_1=require("./lib/tap-fs");Object.defineProperty(exports,"tapFs",{enumerable:!0,get:e(function(){return tap_fs_1.tapFs},"get")});var tap_exec_1=require("./lib/tap-exec");Object.defineProperty(exports,"tapExec",{enumerable:!0,get:e(function(){return tap_exec_1.tapExec},"get")});var tap_pg_1=require("./lib/tap-pg");Object.defineProperty(exports,"pgTap",{enumerable:!0,get:e(function(){return tap_pg_1.pgTap},"get")});var tap_redis_1=require("./lib/tap-redis");Object.defineProperty(exports,"redisTap",{enumerable:!0,get:e(function(){return tap_redis_1.redisTap},"get")});var tap_bullmq_1=require("./lib/tap-bullmq");Object.defineProperty(exports,"bullmqTap",{enumerable:!0,get:e(function(){return tap_bullmq_1.bullmqTap},"get")});var tap_nest_1=require("./lib/tap-nest");Object.defineProperty(exports,"nestTap",{enumerable:!0,get:e(function(){return tap_nest_1.nestTap},"get")}),Object.defineProperty(exports,"installChildAppBridge",{enumerable:!0,get:e(function(){return tap_nest_1.installChildAppBridge},"get")});var install_1=require("./lib/install");Object.defineProperty(exports,"installLensmcpNodeInstrumentation",{enumerable:!0,get:e(function(){return install_1.installLensmcpNodeInstrumentation},"get")});var active_work_1=require("./lib/active-work");Object.defineProperty(exports,"activeWorkSnapshot",{enumerable:!0,get:e(function(){return active_work_1.activeWorkSnapshot},"get")}),Object.defineProperty(exports,"beginActiveWork",{enumerable:!0,get:e(function(){return active_work_1.beginActiveWork},"get")}),Object.defineProperty(exports,"installActiveWorkProbe",{enumerable:!0,get:e(function(){return active_work_1.installActiveWorkProbe},"get")}),Object.defineProperty(exports,"resetActiveWorkForTests",{enumerable:!0,get:e(function(){return active_work_1.resetActiveWorkForTests},"get")});
1
+ "use strict";var s=Object.defineProperty;var o=(t,r)=>s(t,"name",{value:r,configurable:!0});var n=Object.defineProperty,e=o((t,r)=>n(t,"name",{value:r,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.resetActiveWorkForTests=exports.installActiveWorkProbe=exports.beginActiveWork=exports.activeWorkSnapshot=exports.installLensmcpNodeInstrumentation=exports.installChildAppBridge=exports.nestTap=exports.bullmqTap=exports.redisTap=exports.pgTap=exports.tapExec=exports.tapFs=exports.stopEventLoopTapForTests=exports.tapEventLoop=exports.EXCHANGE_ID=exports.resetIngressTapForTests=exports.tapIngress=exports.resetEgressTapForTests=exports.tapEgress=exports.installRequireHook=exports.createEventFloodGuard=exports.maybeRotateEventFile=exports.EVENT_MAX_FILES=exports.EVENT_MAX_BYTES=exports.EVENT_FILE=exports.PROJECT=exports.isLensWriting=exports.lensEmit=void 0;var emit_1=require("./lib/emit");Object.defineProperty(exports,"lensEmit",{enumerable:!0,get:e(function(){return emit_1.lensEmit},"get")}),Object.defineProperty(exports,"isLensWriting",{enumerable:!0,get:e(function(){return emit_1.isLensWriting},"get")}),Object.defineProperty(exports,"PROJECT",{enumerable:!0,get:e(function(){return emit_1.PROJECT},"get")}),Object.defineProperty(exports,"EVENT_FILE",{enumerable:!0,get:e(function(){return emit_1.EVENT_FILE},"get")}),Object.defineProperty(exports,"EVENT_MAX_BYTES",{enumerable:!0,get:e(function(){return emit_1.EVENT_MAX_BYTES},"get")}),Object.defineProperty(exports,"EVENT_MAX_FILES",{enumerable:!0,get:e(function(){return emit_1.EVENT_MAX_FILES},"get")}),Object.defineProperty(exports,"maybeRotateEventFile",{enumerable:!0,get:e(function(){return emit_1.maybeRotateEventFile},"get")});var flood_guard_1=require("./lib/flood-guard");Object.defineProperty(exports,"createEventFloodGuard",{enumerable:!0,get:e(function(){return flood_guard_1.createEventFloodGuard},"get")});var require_hook_1=require("./lib/require-hook");Object.defineProperty(exports,"installRequireHook",{enumerable:!0,get:e(function(){return require_hook_1.installRequireHook},"get")});var tap_egress_1=require("./lib/tap-egress");Object.defineProperty(exports,"tapEgress",{enumerable:!0,get:e(function(){return tap_egress_1.tapEgress},"get")}),Object.defineProperty(exports,"resetEgressTapForTests",{enumerable:!0,get:e(function(){return tap_egress_1.resetEgressTapForTests},"get")});var tap_ingress_1=require("./lib/tap-ingress");Object.defineProperty(exports,"tapIngress",{enumerable:!0,get:e(function(){return tap_ingress_1.tapIngress},"get")}),Object.defineProperty(exports,"resetIngressTapForTests",{enumerable:!0,get:e(function(){return tap_ingress_1.resetIngressTapForTests},"get")}),Object.defineProperty(exports,"EXCHANGE_ID",{enumerable:!0,get:e(function(){return tap_ingress_1.EXCHANGE_ID},"get")});var tap_event_loop_1=require("./lib/tap-event-loop");Object.defineProperty(exports,"tapEventLoop",{enumerable:!0,get:e(function(){return tap_event_loop_1.tapEventLoop},"get")}),Object.defineProperty(exports,"stopEventLoopTapForTests",{enumerable:!0,get:e(function(){return tap_event_loop_1.stopEventLoopTapForTests},"get")});var tap_fs_1=require("./lib/tap-fs");Object.defineProperty(exports,"tapFs",{enumerable:!0,get:e(function(){return tap_fs_1.tapFs},"get")});var tap_exec_1=require("./lib/tap-exec");Object.defineProperty(exports,"tapExec",{enumerable:!0,get:e(function(){return tap_exec_1.tapExec},"get")});var tap_pg_1=require("./lib/tap-pg");Object.defineProperty(exports,"pgTap",{enumerable:!0,get:e(function(){return tap_pg_1.pgTap},"get")});var tap_redis_1=require("./lib/tap-redis");Object.defineProperty(exports,"redisTap",{enumerable:!0,get:e(function(){return tap_redis_1.redisTap},"get")});var tap_bullmq_1=require("./lib/tap-bullmq");Object.defineProperty(exports,"bullmqTap",{enumerable:!0,get:e(function(){return tap_bullmq_1.bullmqTap},"get")});var tap_nest_1=require("./lib/tap-nest");Object.defineProperty(exports,"nestTap",{enumerable:!0,get:e(function(){return tap_nest_1.nestTap},"get")}),Object.defineProperty(exports,"installChildAppBridge",{enumerable:!0,get:e(function(){return tap_nest_1.installChildAppBridge},"get")});var install_1=require("./lib/install");Object.defineProperty(exports,"installLensmcpNodeInstrumentation",{enumerable:!0,get:e(function(){return install_1.installLensmcpNodeInstrumentation},"get")});var active_work_1=require("./lib/active-work");Object.defineProperty(exports,"activeWorkSnapshot",{enumerable:!0,get:e(function(){return active_work_1.activeWorkSnapshot},"get")}),Object.defineProperty(exports,"beginActiveWork",{enumerable:!0,get:e(function(){return active_work_1.beginActiveWork},"get")}),Object.defineProperty(exports,"installActiveWorkProbe",{enumerable:!0,get:e(function(){return active_work_1.installActiveWorkProbe},"get")}),Object.defineProperty(exports,"resetActiveWorkForTests",{enumerable:!0,get:e(function(){return active_work_1.resetActiveWorkForTests},"get")});
@@ -0,0 +1,4 @@
1
+ export declare const captureFile: () => string;
2
+ /** Whether Settings › Features asks for AI providers' bodies to be kept, as of at most 5 s ago. */
3
+ export declare function aiBodiesAsked(now?: number): boolean;
4
+ export declare function resetCaptureFileForTests(): void;
@@ -0,0 +1 @@
1
+ "use strict";var o=Object.defineProperty;var a=(e,t)=>o(e,"name",{value:t,configurable:!0});var i=Object.defineProperty,r=a((e,t)=>i(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.captureFile=void 0,exports.aiBodiesAsked=aiBodiesAsked,exports.resetCaptureFileForTests=resetCaptureFileForTests;const tslib_1=require("tslib"),nodeFs=tslib_1.__importStar(require("node:fs")),node_path_1=require("node:path"),emit_1=require("./emit"),statSync=nodeFs.statSync,readFileSync=nodeFs.readFileSync,EVERY_MS=5e3;let last;const captureFile=r(()=>(0,node_path_1.join)((0,node_path_1.dirname)(emit_1.EVENT_FILE),"capture.json"),"captureFile");exports.captureFile=captureFile;function aiBodiesAsked(e=Date.now()){if(last&&e-last.at<EVERY_MS)return last.ai;let t=-1;try{t=statSync((0,exports.captureFile)()).mtimeMs}catch{return last={at:e,mtimeMs:-1,ai:!1},!1}if(last&&last.mtimeMs===t)return last={...last,at:e},last.ai;let s=!1;try{s=JSON.parse(readFileSync((0,exports.captureFile)(),"utf8")).ai==="content"}catch{}return last={at:e,mtimeMs:t,ai:s},s}a(aiBodiesAsked,"aiBodiesAsked"),r(aiBodiesAsked,"aiBodiesAsked");function resetCaptureFileForTests(){last=void 0}a(resetCaptureFileForTests,"resetCaptureFileForTests"),r(resetCaptureFileForTests,"resetCaptureFileForTests");
@@ -23,7 +23,8 @@ export declare function keepBody(contentType: string, bytes: Uint8Array, size: n
23
23
  * How much of `.lensmcp/http/` is kept (issues/closed/foodguard-79). It was 500 files — about a minute at FoodGuard's
24
24
  * ten exchanges a second, while the events that point at them stay on the bus for many minutes: a quarter of the
25
25
  * exchange ids in the live event file were already gone. Now 10,000 files (~14 KB each there, so ~140 MB — the bus's
26
- * own budget is 300 MB) and a day at most, `LENSMCP_HTTP_MAX_FILES` / `LENSMCP_HTTP_MAX_AGE_MS` to move them.
26
+ * own budget is 300 MB) and a day at most, `LENSMCP_HTTP_MAX_FILES` / `LENSMCP_HTTP_MAX_AGE_MS` to move them — for EACH
27
+ * place (core `exchangePlace`): third-party calls, requests served, calls between the cluster's services.
27
28
  */
28
29
  export declare const DEFAULT_HTTP_MAX_FILES = 10000;
29
30
  export declare const DEFAULT_HTTP_MAX_AGE_MS: number;
package/lib/http-store.js CHANGED
@@ -1 +1 @@
1
- "use strict";var d=Object.defineProperty;var u=(e,t)=>d(e,"name",{value:t,configurable:!0});var f=Object.defineProperty,i=u((e,t)=>f(e,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.exchangeTime=exports.DEFAULT_HTTP_MAX_AGE_MS=exports.DEFAULT_HTTP_MAX_FILES=exports.newExchangeId=exports.MAX_KEPT_BYTES=exports.REMOVED=void 0,exports.httpCaptureMode=httpCaptureMode,exports.redactHeaders=redactHeaders,exports.redactQuery=redactQuery,exports.keepBody=keepBody,exports.pruneHttpExchanges=pruneHttpExchanges,exports.writeHttpExchange=writeHttpExchange;const tslib_1=require("tslib"),nodeFs=tslib_1.__importStar(require("node:fs")),node_crypto_1=require("node:crypto"),http_exchange_1=require("@lensmcp/core/http-exchange"),redact_1=require("@lensmcp/core/redact"),ai_store_1=require("./ai-store"),emit_1=require("./emit"),mkdirSync=nodeFs.mkdirSync,writeFileSync=nodeFs.writeFileSync,renameSync=nodeFs.renameSync,readdirSync=nodeFs.readdirSync,unlinkSync=nodeFs.unlinkSync;function httpCaptureMode(e=process.env){const t=(e.LENSMCP_HTTP_CAPTURE??"").trim().toLowerCase();return t==="off"||t==="0"||t==="false"||t==="none"?"off":t==="headers"?"headers":"bodies"}u(httpCaptureMode,"httpCaptureMode"),i(httpCaptureMode,"httpCaptureMode"),exports.REMOVED="\u2022\u2022\u2022\u2022 redacted",exports.MAX_KEPT_BYTES=64*1024;const MAX_PARSE_BYTES=2*1024*1024,newExchangeId=i(()=>`hx_${Date.now().toString(36)}${(0,node_crypto_1.randomBytes)(5).toString("hex")}`,"newExchangeId");exports.newExchangeId=newExchangeId;const CREDENTIAL_HEADERS=/^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|api-key|openai-organization|openai-project|x-internal-token|x-amz-security-token)$|-api-key$|-token$|-secret$/i,CREDENTIAL_FIELD=/pass(word|wd)?|secret|token|api[-_]?key|authorization|credential|cookie|signature/i;function jwtClaims(e){const t=e.split(".");if(t.length===3)try{const r=JSON.parse(Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return`JWT \xB7 ${["iss","aud","sub","exp"].filter(n=>r[n]!==void 0).map(n=>`${n}=${n==="exp"&&typeof r[n]=="number"?new Date(r[n]*1e3).toISOString():String(r[n]).slice(0,80)}`).join(" \xB7 ")||"no claims"} \xB7 ${exports.REMOVED.split(" ")[0]} signature`}catch{return}}u(jwtClaims,"jwtClaims"),i(jwtClaims,"jwtClaims");function redactHeaders(e){const t=[],r=[];for(const[n,c]of e){const o=n.toLowerCase();if(CREDENTIAL_HEADERS.test(o)||(0,redact_1.isSecretParam)(o)){r.push(o);const s=/^bearer\s+(\S+)$/i.exec(c.trim()),a=s?jwtClaims(s[1]):void 0,p=/^(\w+)\s+\S/.exec(c.trim())?.[1];t.push([o,a?`Bearer ${a}`:p&&o.endsWith("authorization")?`${p} ${exports.REMOVED}`:exports.REMOVED])}else t.push([o,(0,ai_store_1.redactAiText)(c).slice(0,2048)])}return{headers:t,redacted:r}}u(redactHeaders,"redactHeaders"),i(redactHeaders,"redactHeaders");function redactQuery(e){const t=[];try{for(const[r,n]of new URLSearchParams(e))t.push([r,(0,redact_1.isSecretParam)(r)||CREDENTIAL_FIELD.test(r)?exports.REMOVED:(0,ai_store_1.redactAiText)(n).slice(0,1024)])}catch{}return t.slice(0,100)}u(redactQuery,"redactQuery"),i(redactQuery,"redactQuery");function redactJson(e,t,r,n=0){if(n>32||e===null||typeof e!="object")return typeof e=="string"?(0,ai_store_1.redactAiText)(e):e;if(Array.isArray(e))return e.map((o,s)=>redactJson(o,`${t}[${s}]`,r,n+1));const c={};for(const[o,s]of Object.entries(e)){const a=t?`${t}.${o}`:o;CREDENTIAL_FIELD.test(o)&&s!==null&&typeof s!="object"?(c[o]=exports.REMOVED,r.length<50&&r.push(a)):c[o]=redactJson(s,a,r,n+1)}return c}u(redactJson,"redactJson"),i(redactJson,"redactJson");const textual=i(e=>/json|^text\/|x-www-form-urlencoded|xml|javascript|graphql|event-stream/i.test(e)||e==="","textual");function keepBody(e,t,r,n,c){const o=e.split(";")[0].trim().toLowerCase();if(!textual(o))return{contentType:o||"application/octet-stream",size:r,kept:0,truncated:!1,omitted:"binary",...c?{sha256:c}:{}};const s=t.byteLength>=r&&r<=MAX_PARSE_BYTES,a=Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8");let p;if(s&&/json/.test(o))try{p=JSON.stringify(redactJson(JSON.parse(a),"",n))}catch{p=(0,ai_store_1.redactAiText)(a)}else s&&/x-www-form-urlencoded/.test(o)?p=new URLSearchParams(redactQuery(a)).toString():p=(0,ai_store_1.redactAiText)(a);const x=Buffer.byteLength(p)>exports.MAX_KEPT_BYTES?Buffer.from(p).subarray(0,exports.MAX_KEPT_BYTES).toString("utf8"):p;return{contentType:o,size:r,kept:Buffer.byteLength(x),text:x,truncated:r>t.byteLength||x.length<p.length}}u(keepBody,"keepBody"),i(keepBody,"keepBody"),exports.DEFAULT_HTTP_MAX_FILES=1e4,exports.DEFAULT_HTTP_MAX_AGE_MS=1440*6e4;const PRUNE_EVERY_MS=3e4,maxFiles=i(()=>{const e=Number(process.env.LENSMCP_HTTP_MAX_FILES);return Number.isInteger(e)&&e>=10?e:exports.DEFAULT_HTTP_MAX_FILES},"maxFiles"),maxAgeMs=i(()=>{const e=Number(process.env.LENSMCP_HTTP_MAX_AGE_MS);return Number.isFinite(e)&&e>=6e4?e:exports.DEFAULT_HTTP_MAX_AGE_MS},"maxAgeMs"),exchangeTime=i(e=>{const t=/^hx_([0-9a-z]{8})/.exec(e),r=t?parseInt(t[1],36):NaN;return Number.isFinite(r)?r:void 0},"exchangeTime");exports.exchangeTime=exchangeTime;let lastPrune=0;function pruneHttpExchanges(e,t=Date.now()){let r=0;try{const n=readdirSync(e).filter(s=>/^hx_[0-9a-z]+\.json$/.test(s)).sort(),c=n.length-maxFiles(),o=t-maxAgeMs();for(let s=0;s<n.length;s+=1){const a=(0,exports.exchangeTime)(n[s]);if(s>=c&&(a===void 0||a>=o))break;try{unlinkSync(`${e}/${n[s]}`),r+=1}catch{}}}catch{}return r}u(pruneHttpExchanges,"pruneHttpExchanges"),i(pruneHttpExchanges,"pruneHttpExchanges");function writeHttpExchange(e){try{const t=(0,http_exchange_1.httpExchangeDir)(emit_1.EVENT_FILE);mkdirSync(t,{recursive:!0,mode:448});const r=(0,http_exchange_1.httpExchangeFile)(emit_1.EVENT_FILE,e.id);writeFileSync(`${r}.tmp`,JSON.stringify(e),{mode:384}),renameSync(`${r}.tmp`,r);const n=Date.now();return n-lastPrune>=PRUNE_EVERY_MS&&(lastPrune=n,pruneHttpExchanges(t,n)),!0}catch{return!1}}u(writeHttpExchange,"writeHttpExchange"),i(writeHttpExchange,"writeHttpExchange");
1
+ "use strict";var d=Object.defineProperty;var u=(e,t)=>d(e,"name",{value:t,configurable:!0});var f=Object.defineProperty,i=u((e,t)=>f(e,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.exchangeTime=exports.DEFAULT_HTTP_MAX_AGE_MS=exports.DEFAULT_HTTP_MAX_FILES=exports.newExchangeId=exports.MAX_KEPT_BYTES=exports.REMOVED=void 0,exports.httpCaptureMode=httpCaptureMode,exports.redactHeaders=redactHeaders,exports.redactQuery=redactQuery,exports.keepBody=keepBody,exports.pruneHttpExchanges=pruneHttpExchanges,exports.writeHttpExchange=writeHttpExchange;const tslib_1=require("tslib"),nodeFs=tslib_1.__importStar(require("node:fs")),node_crypto_1=require("node:crypto"),http_exchange_1=require("@lensmcp/core/http-exchange"),redact_1=require("@lensmcp/core/redact"),ai_store_1=require("./ai-store"),emit_1=require("./emit"),mkdirSync=nodeFs.mkdirSync,writeFileSync=nodeFs.writeFileSync,renameSync=nodeFs.renameSync,readdirSync=nodeFs.readdirSync,unlinkSync=nodeFs.unlinkSync;function httpCaptureMode(e=process.env){const t=(e.LENSMCP_HTTP_CAPTURE??"").trim().toLowerCase();return t==="off"||t==="0"||t==="false"||t==="none"?"off":t==="headers"?"headers":"bodies"}u(httpCaptureMode,"httpCaptureMode"),i(httpCaptureMode,"httpCaptureMode"),exports.REMOVED="\u2022\u2022\u2022\u2022 redacted",exports.MAX_KEPT_BYTES=64*1024;const MAX_PARSE_BYTES=2*1024*1024,newExchangeId=i(()=>`hx_${Date.now().toString(36)}${(0,node_crypto_1.randomBytes)(5).toString("hex")}`,"newExchangeId");exports.newExchangeId=newExchangeId;const CREDENTIAL_HEADERS=/^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|api-key|openai-organization|openai-project|x-internal-token|x-amz-security-token)$|-api-key$|-token$|-secret$/i,CREDENTIAL_FIELD=/pass(word|wd)?|secret|token|api[-_]?key|authorization|credential|cookie|signature/i;function jwtClaims(e){const t=e.split(".");if(t.length===3)try{const r=JSON.parse(Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return`JWT \xB7 ${["iss","aud","sub","exp"].filter(n=>r[n]!==void 0).map(n=>`${n}=${n==="exp"&&typeof r[n]=="number"?new Date(r[n]*1e3).toISOString():String(r[n]).slice(0,80)}`).join(" \xB7 ")||"no claims"} \xB7 ${exports.REMOVED.split(" ")[0]} signature`}catch{return}}u(jwtClaims,"jwtClaims"),i(jwtClaims,"jwtClaims");function redactHeaders(e){const t=[],r=[];for(const[n,a]of e){const o=n.toLowerCase();if(CREDENTIAL_HEADERS.test(o)||(0,redact_1.isSecretParam)(o)){r.push(o);const s=/^bearer\s+(\S+)$/i.exec(a.trim()),c=s?jwtClaims(s[1]):void 0,p=/^(\w+)\s+\S/.exec(a.trim())?.[1];t.push([o,c?`Bearer ${c}`:p&&o.endsWith("authorization")?`${p} ${exports.REMOVED}`:exports.REMOVED])}else t.push([o,(0,ai_store_1.redactAiText)(a).slice(0,2048)])}return{headers:t,redacted:r}}u(redactHeaders,"redactHeaders"),i(redactHeaders,"redactHeaders");function redactQuery(e){const t=[];try{for(const[r,n]of new URLSearchParams(e))t.push([r,(0,redact_1.isSecretParam)(r)||CREDENTIAL_FIELD.test(r)?exports.REMOVED:(0,ai_store_1.redactAiText)(n).slice(0,1024)])}catch{}return t.slice(0,100)}u(redactQuery,"redactQuery"),i(redactQuery,"redactQuery");function redactJson(e,t,r,n=0){if(n>32||e===null||typeof e!="object")return typeof e=="string"?(0,ai_store_1.redactAiText)(e):e;if(Array.isArray(e))return e.map((o,s)=>redactJson(o,`${t}[${s}]`,r,n+1));const a={};for(const[o,s]of Object.entries(e)){const c=t?`${t}.${o}`:o,p=typeof s=="number"&&/tokens/i.test(o);CREDENTIAL_FIELD.test(o)&&s!==null&&typeof s!="object"&&!p?(a[o]=exports.REMOVED,r.length<50&&r.push(c)):a[o]=redactJson(s,c,r,n+1)}return a}u(redactJson,"redactJson"),i(redactJson,"redactJson");const textual=i(e=>/json|^text\/|x-www-form-urlencoded|xml|javascript|graphql|event-stream/i.test(e)||e==="","textual");function keepBody(e,t,r,n,a){const o=e.split(";")[0].trim().toLowerCase();if(!textual(o))return{contentType:o||"application/octet-stream",size:r,kept:0,truncated:!1,omitted:"binary",...a?{sha256:a}:{}};const s=t.byteLength>=r&&r<=MAX_PARSE_BYTES,c=Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8");let p;if(s&&/json/.test(o))try{p=JSON.stringify(redactJson(JSON.parse(c),"",n))}catch{p=(0,ai_store_1.redactAiText)(c)}else s&&/x-www-form-urlencoded/.test(o)?p=new URLSearchParams(redactQuery(c)).toString():p=(0,ai_store_1.redactAiText)(c);const x=Buffer.byteLength(p)>exports.MAX_KEPT_BYTES?Buffer.from(p).subarray(0,exports.MAX_KEPT_BYTES).toString("utf8"):p;return{contentType:o,size:r,kept:Buffer.byteLength(x),text:x,truncated:r>t.byteLength||x.length<p.length}}u(keepBody,"keepBody"),i(keepBody,"keepBody"),exports.DEFAULT_HTTP_MAX_FILES=1e4,exports.DEFAULT_HTTP_MAX_AGE_MS=1440*6e4;const PRUNE_EVERY_MS=3e4,maxFiles=i(()=>{const e=Number(process.env.LENSMCP_HTTP_MAX_FILES);return Number.isInteger(e)&&e>=10?e:exports.DEFAULT_HTTP_MAX_FILES},"maxFiles"),maxAgeMs=i(()=>{const e=Number(process.env.LENSMCP_HTTP_MAX_AGE_MS);return Number.isFinite(e)&&e>=6e4?e:exports.DEFAULT_HTTP_MAX_AGE_MS},"maxAgeMs"),exchangeTime=i(e=>{const t=/^hx_([0-9a-z]{8})/.exec(e),r=t?parseInt(t[1],36):NaN;return Number.isFinite(r)?r:void 0},"exchangeTime");exports.exchangeTime=exchangeTime;const lastPrune=new Map;function pruneHttpExchanges(e,t=Date.now()){let r=0;try{const n=readdirSync(e).filter(s=>/^hx_[0-9a-z]+\.json$/.test(s)).sort(),a=n.length-maxFiles(),o=t-maxAgeMs();for(let s=0;s<n.length;s+=1){const c=(0,exports.exchangeTime)(n[s]);if(s>=a&&(c===void 0||c>=o))break;try{unlinkSync(`${e}/${n[s]}`),r+=1}catch{}}}catch{}return r}u(pruneHttpExchanges,"pruneHttpExchanges"),i(pruneHttpExchanges,"pruneHttpExchanges");function writeHttpExchange(e){try{const t=(0,http_exchange_1.exchangePlace)(e),r=(0,http_exchange_1.httpExchangeDir)(emit_1.EVENT_FILE,t);mkdirSync(r,{recursive:!0,mode:448});const n=(0,http_exchange_1.httpExchangeFile)(emit_1.EVENT_FILE,e.id,t);writeFileSync(`${n}.tmp`,JSON.stringify(e),{mode:384}),renameSync(`${n}.tmp`,n);const a=Date.now();return a-(lastPrune.get(t)??0)>=PRUNE_EVERY_MS&&(lastPrune.set(t,a),pruneHttpExchanges(r,a)),!0}catch{return!1}}u(writeHttpExchange,"writeHttpExchange"),i(writeHttpExchange,"writeHttpExchange");
package/lib/install.js CHANGED
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var a=(t,r)=>p(t,"name",{value:r,configurable:!0});var s=Object.defineProperty,e=a((t,r)=>s(t,"name",{value:r,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installLensmcpNodeInstrumentation=installLensmcpNodeInstrumentation;const require_hook_1=require("./require-hook"),flow_context_1=require("./flow-context"),tap_egress_1=require("./tap-egress"),tap_ai_1=require("./tap-ai"),tap_fs_1=require("./tap-fs"),tap_exec_1=require("./tap-exec"),tap_pg_1=require("./tap-pg"),tap_redis_1=require("./tap-redis"),active_work_1=require("./active-work"),tap_bullmq_1=require("./tap-bullmq"),tap_nest_1=require("./tap-nest"),tap_nest_logger_1=require("./tap-nest-logger"),tap_event_loop_1=require("./tap-event-loop"),tap_stdout_1=require("./tap-stdout");function installLensmcpNodeInstrumentation(){const t=globalThis;if(!t.__lensmcpNodeInstrumented&&(t.__lensmcpNodeInstrumented=!0,process.env.LENSMCP_AUTO!=="0")){try{(0,active_work_1.installActiveWorkProbe)()}catch{}try{(0,flow_context_1.primeFlowContext)()}catch{}try{(0,tap_egress_1.tapEgress)()}catch{}try{(0,tap_ai_1.tapAi)()}catch{}try{(0,tap_fs_1.tapFs)()}catch{}try{(0,tap_exec_1.tapExec)()}catch{}try{(0,tap_stdout_1.tapStdout)()}catch{}try{(0,tap_event_loop_1.tapEventLoop)()}catch{}try{(0,require_hook_1.installRequireHook)({pg:tap_pg_1.pgTap,ioredis:tap_redis_1.redisTap,bullmq:tap_bullmq_1.bullmqTap,"@nestjs/core":tap_nest_1.nestTap,"@nestjs/common":tap_nest_logger_1.nestLoggerTap})}catch{}try{(0,tap_nest_1.installChildAppBridge)()}catch{}}}a(installLensmcpNodeInstrumentation,"installLensmcpNodeInstrumentation"),e(installLensmcpNodeInstrumentation,"installLensmcpNodeInstrumentation");
1
+ "use strict";var p=Object.defineProperty;var a=(t,r)=>p(t,"name",{value:r,configurable:!0});var s=Object.defineProperty,e=a((t,r)=>s(t,"name",{value:r,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installLensmcpNodeInstrumentation=installLensmcpNodeInstrumentation;const require_hook_1=require("./require-hook"),flow_context_1=require("./flow-context"),tap_egress_1=require("./tap-egress"),tap_ai_1=require("./tap-ai"),tap_fs_1=require("./tap-fs"),tap_exec_1=require("./tap-exec"),tap_pg_1=require("./tap-pg"),tap_redis_1=require("./tap-redis"),active_work_1=require("./active-work"),tap_bullmq_1=require("./tap-bullmq"),tap_nest_1=require("./tap-nest"),tap_nest_logger_1=require("./tap-nest-logger"),tap_event_loop_1=require("./tap-event-loop"),tap_ingress_1=require("./tap-ingress"),tap_stdout_1=require("./tap-stdout");function installLensmcpNodeInstrumentation(){const t=globalThis;if(!t.__lensmcpNodeInstrumented&&(t.__lensmcpNodeInstrumented=!0,process.env.LENSMCP_AUTO!=="0")){try{(0,active_work_1.installActiveWorkProbe)()}catch{}try{(0,flow_context_1.primeFlowContext)()}catch{}try{(0,tap_egress_1.tapEgress)()}catch{}try{(0,tap_ingress_1.tapIngress)()}catch{}try{(0,tap_ai_1.tapAi)()}catch{}try{(0,tap_fs_1.tapFs)()}catch{}try{(0,tap_exec_1.tapExec)()}catch{}try{(0,tap_stdout_1.tapStdout)()}catch{}try{(0,tap_event_loop_1.tapEventLoop)()}catch{}try{(0,require_hook_1.installRequireHook)({pg:tap_pg_1.pgTap,ioredis:tap_redis_1.redisTap,bullmq:tap_bullmq_1.bullmqTap,"@nestjs/core":tap_nest_1.nestTap,"@nestjs/common":tap_nest_logger_1.nestLoggerTap})}catch{}try{(0,tap_nest_1.installChildAppBridge)()}catch{}}}a(installLensmcpNodeInstrumentation,"installLensmcpNodeInstrumentation"),e(installLensmcpNodeInstrumentation,"installLensmcpNodeInstrumentation");
package/lib/tap-egress.js CHANGED
@@ -1 +1 @@
1
- "use strict";var F=Object.defineProperty;var l=(t,e)=>F(t,"name",{value:e,configurable:!0});var C=Object.defineProperty,i=l((t,e)=>C(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.flushEgressCaptureForTests=flushEgressCaptureForTests,exports.tapEgress=tapEgress,exports.resetEgressTapForTests=resetEgressTapForTests;const redact_1=require("@lensmcp/core/redact"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),ai_providers_1=require("./ai-providers"),http_capture_1=require("./http-capture"),http_store_1=require("./http-store"),INTERNAL=[/\.local$/i,/\.internal$/i,/^localhost$/i,/^127\./,/^\[?::1\]?$/,/^0\.0\.0\.0$/,/^10\./,/^192\.168\./,/^172\.(1[6-9]|2\d|3[01])\./,/^169\.254\./,/^\[?[fF][cCdD][0-9a-fA-F]{2}:/,/^\[?[fF][eE]80:/],isInternal=i(t=>t===""||INTERNAL.some(e=>e.test(t)),"isInternal"),CAPTURE_QUERY=process.env.LENSMCP_EGRESS_QUERY==="1",MAX_PATH_CHARS=256,clipPath=i(t=>t.length>MAX_PATH_CHARS?`${t.slice(0,MAX_PATH_CHARS)}\u2026`:t,"clipPath");function capturePath(t,e){const s=t||"/";return!CAPTURE_QUERY||e.length<=1?clipPath(s):(0,redact_1.redactUrl)(`${s}${e}`)}l(capturePath,"capturePath"),i(capturePath,"capturePath");const fingerprintFor=i((t,e)=>e?`external:error:${t}`:`external:${t}`,"fingerprintFor"),pendingExchanges=new Set;async function flushEgressCaptureForTests(){await Promise.allSettled([...pendingExchanges])}l(flushEgressCaptureForTests,"flushEgressCaptureForTests"),i(flushEgressCaptureForTests,"flushEgressCaptureForTests");const headerPairs=i(t=>{const e=[];try{t?.headers?.forEach?.((s,d)=>e.push([d,s]))}catch{}return e},"headerPairs");async function finishExchange(t){const e=[],s=[],d=await(0,http_capture_1.requestPart)(t.request,t.url.search,t.mode,!!t.ai,s,e),r=t.reading?await t.reading.catch(()=>{}):void 0,{headers:c,redacted:a}=(0,http_store_1.redactHeaders)(headerPairs(t.res));e.push(...a);const n=typeof t.res?.status=="number"?t.res.status:void 0,p={schemaVersion:1,id:t.id,capturedAt:Date.now(),side:"egress",service:emit_1.PROJECT,...t.ctx?.flowId?{flowId:t.ctx.flowId}:{},...t.ctx?.requestId?{requestId:t.ctx.requestId}:{},method:t.method,url:`${t.url.protocol}//${t.url.host}${t.path}`,host:t.url.hostname,path:t.path,...n!==void 0?{status:n}:{},...t.res?.statusText?{statusText:t.res.statusText}:{},...t.error?{error:t.error}:{},startedAt:t.startedAt,...t.ttfbMs!==void 0?{ttfbMs:t.ttfbMs}:{},durationMs:(r?.endedAt??Date.now())-t.startedAt,capture:t.mode==="bodies"?"bodies":"headers",request:d,response:{headers:c,...r?.body?{body:r.body}:{},...r?.stream?{stream:r.stream}:{}},redacted:{headers:[...new Set(e)],bodyFields:[...s.map(o=>`request.${o}`),...t.responseFields.map(o=>`response.${o}`)]},...t.ai?{ai:{provider:t.ai}}:{}};(0,http_store_1.writeHttpExchange)(p)}l(finishExchange,"finishExchange"),i(finishExchange,"finishExchange");function trackExchange(t){const e=finishExchange(t).catch(()=>{});pendingExchanges.add(e),e.finally(()=>pendingExchanges.delete(e))}l(trackExchange,"trackExchange"),i(trackExchange,"trackExchange");function tapEgress(){tapFetch(),tapHttpModule("http"),tapHttpModule("https")}l(tapEgress,"tapEgress"),i(tapEgress,"tapEgress");let savedFetch;const httpOriginals=new Map;function resetEgressTapForTests(){const t=globalThis;savedFetch&&(t.fetch=savedFetch),delete t.__lensmcpFetchTap,restoreHttp("http"),restoreHttp("https"),savedFetch=void 0}l(resetEgressTapForTests,"resetEgressTapForTests"),i(resetEgressTapForTests,"resetEgressTapForTests");function restoreHttp(t){const e=httpOriginals.get(t);if(!e)return;const s=require(`node:${t}`);s.request=e.request,s.get=e.get,httpOriginals.delete(t)}l(restoreHttp,"restoreHttp"),i(restoreHttp,"restoreHttp");function tapFetch(){const t=globalThis;if(typeof t.fetch!="function"||t.__lensmcpFetchTap)return;t.__lensmcpFetchTap=!0;const e=t.fetch.bind(globalThis);savedFetch=t.fetch;const s=(0,http_store_1.httpCaptureMode)(),d=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS);t.fetch=(async(r,c)=>{let a="",n="/",p=!1,o;try{const h=new URL(typeof r=="string"?r:r instanceof URL?r.href:r.url);o=h,a=h.hostname,p=h.search.length>1,n=capturePath(h.pathname,h.search)}catch{}if(isInternal(a))return e(r,c);const f=Date.now(),u=(0,flow_context_1.flowContext)(),E=(0,flow_context_1.liveFlowContext)();E&&(E.externalCallCount=(E.externalCallCount??0)+1);const b=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.method:void 0,m=String(c?.method??b??"GET").toUpperCase(),g=s!=="off"&&o?(0,http_store_1.newExchangeId)():void 0,v=g?(0,http_capture_1.takeRequest)(r,c,s==="bodies"):void 0,w=g&&o&&m==="POST"?(0,ai_providers_1.matchTarget)(a,o.port,o.pathname,d)?.provider:void 0,_=i(h=>({id:g,mode:s,method:m,url:o,path:o.pathname.length>256?`${o.pathname.slice(0,256)}\u2026`:o.pathname,startedAt:f,ctx:u,request:v,...w?{ai:w}:{},responseFields:[],...h}),"job");try{const h=await e(r,c),x=Date.now()-f,T=h.status>=500,$=[];let y;if(g&&s==="bodies")try{y=(0,http_capture_1.readResponse)(h,h.clone(),f,{ai:!!w,paths:$})}catch{y=void 0}const q=(0,emit_1.lensEmit)("external","info",`egress ${m} ${a} \u2192 ${h.status}`,{name:a,kind:"egress",method:m,host:a,path:n,status:h.status,...p?{hasQuery:!0}:{},startedAt:f,durationMs:x,...g?{exchangeId:g}:{}},fingerprintFor(a,T),u);return g&&q&&trackExchange(_({res:h,ttfbMs:x,responseFields:$,...y?{reading:y}:{}})),h}catch(h){const x=String(h?.message??h),T=(0,emit_1.lensEmit)("external","error",`egress ${m} ${a} failed`,{name:a,kind:"egress",method:m,host:a,path:n,...p?{hasQuery:!0}:{},error:x,startedAt:f,durationMs:Date.now()-f,...g?{exchangeId:g}:{}},fingerprintFor(a,!0),u);throw g&&T&&trackExchange(_({error:x})),h}})}l(tapFetch,"tapFetch"),i(tapFetch,"tapFetch");function tapHttpModule(t){const e=require(`node:${t}`),s=e.request;if(typeof s!="function"||s.__lensmcp)return;httpOriginals.set(t,{request:s,get:e.get});const d=i(function(...r){const c=s.apply(this,r);try{observe(r,c)}catch{}return c},"wrapped");d.__lensmcp=!0,e.request=d,typeof e.get=="function"&&(e.get=function(...r){const c=d.apply(this,r);return c.end(),c})}l(tapHttpModule,"tapHttpModule"),i(tapHttpModule,"tapHttpModule");function observe(t,e){const{host:s,method:d,path:r,hasQuery:c}=parseTarget(t);if(isInternal(s))return;const a=Date.now(),n=(0,flow_context_1.flowContext)(),p=(0,flow_context_1.liveFlowContext)();p&&(p.externalCallCount=(p.externalCallCount??0)+1);let o=!1;e.once("response",(...f)=>{if(o)return;o=!0;const u=f[0]?.statusCode;(0,emit_1.lensEmit)("external","info",`egress ${d} ${s} \u2192 ${u??"?"}`,{name:s,kind:"egress",method:d,host:s,path:r,...u!=null?{status:u}:{},...c?{hasQuery:!0}:{},startedAt:a,durationMs:Date.now()-a},fingerprintFor(s,u!=null&&u>=500),n)}),e.once("error",(...f)=>{if(o)return;o=!0;const u=f[0];(0,emit_1.lensEmit)("external","error",`egress ${d} ${s} failed`,{name:s,kind:"egress",method:d,host:s,path:r,...c?{hasQuery:!0}:{},error:String(u?.message??u),startedAt:a,durationMs:Date.now()-a},fingerprintFor(s,!0),n)})}l(observe,"observe"),i(observe,"observe");function parseTarget(t){let e="",s="GET",d="/",r=!1;const c=i((a,n)=>{r=n.length>1,d=capturePath(a,n)},"take");for(const a of t)if(typeof a=="string")try{const n=new URL(a);e=n.hostname,c(n.pathname,n.search)}catch{}else if(a instanceof URL)e=a.hostname,c(a.pathname,a.search);else if(a&&typeof a=="object"){const n=a;if(typeof n.method=="string"&&(s=n.method.toUpperCase()),typeof n.socketPath=="string")return{host:"",method:s,path:d,hasQuery:r};if(typeof n.path=="string"){const p=n.path,o=p.indexOf("?");c(o===-1?p:p.slice(0,o),o===-1?"":p.slice(o))}typeof n.hostname=="string"&&n.hostname?e=n.hostname:typeof n.host=="string"&&n.host&&(e=n.host.split(":")[0]??"")}return{host:e,method:s,path:d,hasQuery:r}}l(parseTarget,"parseTarget"),i(parseTarget,"parseTarget");
1
+ "use strict";var A=Object.defineProperty;var u=(t,e)=>A(t,"name",{value:e,configurable:!0});var F=Object.defineProperty,i=u((t,e)=>F(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.flushEgressCaptureForTests=flushEgressCaptureForTests,exports.tapEgress=tapEgress,exports.resetEgressTapForTests=resetEgressTapForTests;const redact_1=require("@lensmcp/core/redact"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),ai_providers_1=require("./ai-providers"),http_capture_1=require("./http-capture"),http_store_1=require("./http-store"),capture_file_1=require("./capture-file"),tap_ai_1=require("./tap-ai"),INTERNAL=[/\.local$/i,/\.internal$/i,/^localhost$/i,/^127\./,/^\[?::1\]?$/,/^0\.0\.0\.0$/,/^10\./,/^192\.168\./,/^172\.(1[6-9]|2\d|3[01])\./,/^169\.254\./,/^\[?[fF][cCdD][0-9a-fA-F]{2}:/,/^\[?[fF][eE]80:/],isInternal=i(t=>t===""||INTERNAL.some(e=>e.test(t)),"isInternal"),CAPTURE_QUERY=process.env.LENSMCP_EGRESS_QUERY==="1",MAX_PATH_CHARS=256,clipPath=i(t=>t.length>MAX_PATH_CHARS?`${t.slice(0,MAX_PATH_CHARS)}\u2026`:t,"clipPath");function capturePath(t,e){const s=t||"/";return!CAPTURE_QUERY||e.length<=1?clipPath(s):(0,redact_1.redactUrl)(`${s}${e}`)}u(capturePath,"capturePath"),i(capturePath,"capturePath");const fingerprintFor=i((t,e)=>e?`external:error:${t}`:`external:${t}`,"fingerprintFor"),pendingExchanges=new Set;async function flushEgressCaptureForTests(){await Promise.allSettled([...pendingExchanges])}u(flushEgressCaptureForTests,"flushEgressCaptureForTests"),i(flushEgressCaptureForTests,"flushEgressCaptureForTests");const headerPairs=i(t=>{const e=[];try{t?.headers?.forEach?.((s,p)=>e.push([p,s]))}catch{}return e},"headerPairs");async function finishExchange(t){const e=[],s=[],p=await(0,http_capture_1.requestPart)(t.request,t.url.search,t.mode,!!t.aiOpaque,s,e),r=t.reading?await t.reading.catch(()=>{}):void 0,{headers:c,redacted:a}=(0,http_store_1.redactHeaders)(headerPairs(t.res));e.push(...a);const n=typeof t.res?.status=="number"?t.res.status:void 0,d={schemaVersion:1,id:t.id,capturedAt:Date.now(),side:"egress",service:emit_1.PROJECT,...t.ctx?.flowId?{flowId:t.ctx.flowId}:{},...t.ctx?.requestId?{requestId:t.ctx.requestId}:{},method:t.method,url:`${t.url.protocol}//${t.url.host}${t.path}`,host:t.url.hostname,path:t.path,...n!==void 0?{status:n}:{},...t.res?.statusText?{statusText:t.res.statusText}:{},...t.error?{error:t.error}:{},startedAt:t.startedAt,...t.ttfbMs!==void 0?{ttfbMs:t.ttfbMs}:{},durationMs:(r?.endedAt??Date.now())-t.startedAt,capture:t.mode==="bodies"?"bodies":"headers",request:p,response:{headers:c,...r?.body?{body:r.body}:{},...r?.stream?{stream:r.stream}:{}},redacted:{headers:[...new Set(e)],bodyFields:[...s.map(o=>`request.${o}`),...t.responseFields.map(o=>`response.${o}`)]},...t.ai?{ai:{provider:t.ai}}:{}};(0,http_store_1.writeHttpExchange)(d)}u(finishExchange,"finishExchange"),i(finishExchange,"finishExchange");function trackExchange(t){const e=finishExchange(t).catch(()=>{});pendingExchanges.add(e),e.finally(()=>pendingExchanges.delete(e))}u(trackExchange,"trackExchange"),i(trackExchange,"trackExchange");function tapEgress(){tapFetch(),tapHttpModule("http"),tapHttpModule("https")}u(tapEgress,"tapEgress"),i(tapEgress,"tapEgress");let savedFetch;const httpOriginals=new Map;function resetEgressTapForTests(){const t=globalThis;savedFetch&&(t.fetch=savedFetch),delete t.__lensmcpFetchTap,restoreHttp("http"),restoreHttp("https"),savedFetch=void 0}u(resetEgressTapForTests,"resetEgressTapForTests"),i(resetEgressTapForTests,"resetEgressTapForTests");function restoreHttp(t){const e=httpOriginals.get(t);if(!e)return;const s=require(`node:${t}`);s.request=e.request,s.get=e.get,httpOriginals.delete(t)}u(restoreHttp,"restoreHttp"),i(restoreHttp,"restoreHttp");function tapFetch(){const t=globalThis;if(typeof t.fetch!="function"||t.__lensmcpFetchTap)return;t.__lensmcpFetchTap=!0;const e=t.fetch.bind(globalThis);savedFetch=t.fetch;const s=(0,http_store_1.httpCaptureMode)(),p=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS);t.fetch=(async(r,c)=>{let a="",n="/",d=!1,o;try{const h=new URL(typeof r=="string"?r:r instanceof URL?r.href:r.url);o=h,a=h.hostname,d=h.search.length>1,n=capturePath(h.pathname,h.search)}catch{}if(isInternal(a))return e(r,c);const f=Date.now(),l=(0,flow_context_1.flowContext)(),E=(0,flow_context_1.liveFlowContext)();E&&(E.externalCallCount=(E.externalCallCount??0)+1);const C=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.method:void 0,m=String(c?.method??C??"GET").toUpperCase(),g=s!=="off"&&o?(0,http_store_1.newExchangeId)():void 0,b=g?(0,http_capture_1.takeRequest)(r,c,s==="bodies"):void 0,_=g&&o&&m==="POST"?(0,ai_providers_1.matchTarget)(a,o.port,o.pathname,p)?.provider:void 0,w=!!_&&(0,tap_ai_1.aiCaptureMode)()!=="content"&&!(0,capture_file_1.aiBodiesAsked)(),$=i(h=>({id:g,mode:s,method:m,url:o,path:o.pathname.length>256?`${o.pathname.slice(0,256)}\u2026`:o.pathname,startedAt:f,ctx:l,request:b,..._?{ai:_}:{},...w?{aiOpaque:w}:{},responseFields:[],...h}),"job");try{const h=await e(r,c),x=Date.now()-f,T=h.status>=500,q=[];let y;if(g&&s==="bodies")try{y=(0,http_capture_1.readResponse)(h,h.clone(),f,{ai:w,paths:q})}catch{y=void 0}const v=(0,emit_1.lensEmit)("external","info",`egress ${m} ${a} \u2192 ${h.status}`,{name:a,kind:"egress",method:m,host:a,path:n,status:h.status,...d?{hasQuery:!0}:{},startedAt:f,durationMs:x,...g?{exchangeId:g}:{}},fingerprintFor(a,T),l);return g&&v&&trackExchange($({res:h,ttfbMs:x,responseFields:q,...y?{reading:y}:{}})),h}catch(h){const x=String(h?.message??h),T=(0,emit_1.lensEmit)("external","error",`egress ${m} ${a} failed`,{name:a,kind:"egress",method:m,host:a,path:n,...d?{hasQuery:!0}:{},error:x,startedAt:f,durationMs:Date.now()-f,...g?{exchangeId:g}:{}},fingerprintFor(a,!0),l);throw g&&T&&trackExchange($({error:x})),h}})}u(tapFetch,"tapFetch"),i(tapFetch,"tapFetch");function tapHttpModule(t){const e=require(`node:${t}`),s=e.request;if(typeof s!="function"||s.__lensmcp)return;httpOriginals.set(t,{request:s,get:e.get});const p=i(function(...r){const c=s.apply(this,r);try{observe(r,c)}catch{}return c},"wrapped");p.__lensmcp=!0,e.request=p,typeof e.get=="function"&&(e.get=function(...r){const c=p.apply(this,r);return c.end(),c})}u(tapHttpModule,"tapHttpModule"),i(tapHttpModule,"tapHttpModule");function observe(t,e){const{host:s,method:p,path:r,hasQuery:c}=parseTarget(t);if(isInternal(s))return;const a=Date.now(),n=(0,flow_context_1.flowContext)(),d=(0,flow_context_1.liveFlowContext)();d&&(d.externalCallCount=(d.externalCallCount??0)+1);let o=!1;e.once("response",(...f)=>{if(o)return;o=!0;const l=f[0]?.statusCode;(0,emit_1.lensEmit)("external","info",`egress ${p} ${s} \u2192 ${l??"?"}`,{name:s,kind:"egress",method:p,host:s,path:r,...l!=null?{status:l}:{},...c?{hasQuery:!0}:{},startedAt:a,durationMs:Date.now()-a},fingerprintFor(s,l!=null&&l>=500),n)}),e.once("error",(...f)=>{if(o)return;o=!0;const l=f[0];(0,emit_1.lensEmit)("external","error",`egress ${p} ${s} failed`,{name:s,kind:"egress",method:p,host:s,path:r,...c?{hasQuery:!0}:{},error:String(l?.message??l),startedAt:a,durationMs:Date.now()-a},fingerprintFor(s,!0),n)})}u(observe,"observe"),i(observe,"observe");function parseTarget(t){let e="",s="GET",p="/",r=!1;const c=i((a,n)=>{r=n.length>1,p=capturePath(a,n)},"take");for(const a of t)if(typeof a=="string")try{const n=new URL(a);e=n.hostname,c(n.pathname,n.search)}catch{}else if(a instanceof URL)e=a.hostname,c(a.pathname,a.search);else if(a&&typeof a=="object"){const n=a;if(typeof n.method=="string"&&(s=n.method.toUpperCase()),typeof n.socketPath=="string")return{host:"",method:s,path:p,hasQuery:r};if(typeof n.path=="string"){const d=n.path,o=d.indexOf("?");c(o===-1?d:d.slice(0,o),o===-1?"":d.slice(o))}typeof n.hostname=="string"&&n.hostname?e=n.hostname:typeof n.host=="string"&&n.host&&(e=n.host.split(":")[0]??"")}return{host:e,method:s,path:p,hasQuery:r}}u(parseTarget,"parseTarget"),i(parseTarget,"parseTarget");
@@ -0,0 +1,5 @@
1
+ /** Where the request's exchange id is left for the framework's hook (`Symbol.for`, so no import is needed to read it). */
2
+ export declare const EXCHANGE_ID: unique symbol;
3
+ export declare function tapIngress(): void;
4
+ /** Restore `http.Server.prototype.emit` — for tests, whose servers outlive one install. */
5
+ export declare function resetIngressTapForTests(): void;
@@ -0,0 +1 @@
1
+ "use strict";var q=Object.defineProperty;var a=(r,e)=>q(r,"name",{value:e,configurable:!0});var _=Object.defineProperty,d=a((r,e)=>_(r,"name",{value:e,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.EXCHANGE_ID=void 0,exports.tapIngress=tapIngress,exports.resetIngressTapForTests=resetIngressTapForTests;const tslib_1=require("tslib"),http=tslib_1.__importStar(require("node:http")),zlib=tslib_1.__importStar(require("node:zlib")),headless_flow_1=require("@lensmcp/core/headless-flow"),emit_1=require("./emit"),http_store_1=require("./http-store");exports.EXCHANGE_ID=Symbol.for("lensmcp.exchangeId");const MAX_READ=2*1024*1024,MAX_PATH_CHARS=256;let originalEmit;function tapIngress(){if(originalEmit)return;const r=(0,http_store_1.httpCaptureMode)();if(r==="off")return;const e=http.Server.prototype,s=e.emit;originalEmit=s,e.emit=function(t,...i){if(t==="request")try{watch(i[0],i[1],r)}catch{}return s.call(this,t,...i)}}a(tapIngress,"tapIngress"),d(tapIngress,"tapIngress");function resetIngressTapForTests(){originalEmit&&(http.Server.prototype.emit=originalEmit),originalEmit=void 0}a(resetIngressTapForTests,"resetIngressTapForTests"),d(resetIngressTapForTests,"resetIngressTapForTests");const one=d(r=>r===void 0?void 0:Array.isArray(r)?r.join(", "):String(r),"one"),pairs=d(r=>Object.entries(r).flatMap(([e,s])=>s===void 0?[]:[[e,one(s)]]),"pairs");class Tee{static{a(this,"Tee")}static{d(this,"Tee")}constructor(){this.chunks=[],this.read=0,this.size=0}take(e,s){if(e==null||typeof e=="function")return;const t=Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?Buffer.from(e,typeof s=="string"?s:"utf8"):void 0;t&&(this.size+=t.length,this.read<MAX_READ&&(this.chunks.push(t),this.read+=t.length))}bytes(){return Buffer.concat(this.chunks)}}function watch(r,e,s){if(!r||!e||r[exports.EXCHANGE_ID])return;const t=r.url??"/",i=t.indexOf("?"),f=i<0?t:t.slice(0,i);if((0,headless_flow_1.isProbePath)(f))return;const h=(0,http_store_1.newExchangeId)();r[exports.EXCHANGE_ID]=h;const g=Date.now(),l=s==="bodies",y=new Tee,c=new Tee;if(l){const m=r.emit;r.emit=function(o,...n){return o==="data"&&y.take(n[0]),m.call(this,o,...n)};const w=e.write,b=e.end;e.write=function(o,...n){return c.take(o,n[0]),w.call(this,o,...n)},e.end=function(o,...n){return c.take(o,n[0]),b.call(this,o,...n)}}let u=!1;const p=d(()=>{if(!u){u=!0;try{(0,http_store_1.writeHttpExchange)(exchangeOf(h,r,e,{url:t,q:i,path:f,startedAt:g,bodies:l,sent:y,answered:c}))}catch{}}},"finish");e.once("finish",p),e.once("close",p)}a(watch,"watch"),d(watch,"watch");function unpacked(r,e){try{if(r==="gzip"||r==="x-gzip")return zlib.gunzipSync(e,{maxOutputLength:MAX_READ});if(r==="br")return zlib.brotliDecompressSync(e,{maxOutputLength:MAX_READ});if(r==="deflate")return zlib.inflateSync(e,{maxOutputLength:MAX_READ})}catch{return}}a(unpacked,"unpacked"),d(unpacked,"unpacked");function exchangeOf(r,e,s,t){const i=[],f=[],h=[],g=(0,http_store_1.redactHeaders)(pairs(e.headers));i.push(...g.redacted);const l=(0,http_store_1.redactHeaders)(pairs(s.getHeaders()));i.push(...l.redacted);const y=t.bodies&&t.q>=0?(0,http_store_1.redactQuery)(t.url.slice(t.q)):[];let c;t.bodies&&t.sent.size&&(c=(0,http_store_1.keepBody)(one(e.headers["content-type"])??"",t.sent.bytes(),t.sent.size,f));let u;if(t.bodies&&t.answered.size){const n=one(s.getHeader("content-type"))??"",x=(one(s.getHeader("content-encoding"))??"").trim().toLowerCase();if(!x||x==="identity")u=(0,http_store_1.keepBody)(n,t.answered.bytes(),t.answered.size,h);else{const A=t.answered.size<=MAX_READ?unpacked(x,t.answered.bytes()):void 0;u=A?(0,http_store_1.keepBody)(n,A,A.length,h):{contentType:n.split(";")[0].trim().toLowerCase(),size:t.answered.size,kept:0,truncated:!1,omitted:"encoded"}}}const p=one(e.headers.host)??"localhost",m=t.path.length>MAX_PATH_CHARS?`${t.path.slice(0,MAX_PATH_CHARS)}\u2026`:t.path,w=one(e.headers["x-lensmcp-flow-id"]),b=one(e.headers["x-request-id"]),o=!s.writableFinished;return{schemaVersion:1,id:r,capturedAt:Date.now(),side:"ingress",service:emit_1.PROJECT,...w?{flowId:w}:{},...b?{requestId:b}:{},method:(e.method??"GET").toUpperCase(),url:`http://${p}${m}`,host:p.split(":")[0]??p,path:m,status:s.statusCode,...s.statusMessage?{statusText:s.statusMessage}:{},...o?{error:"the client went away before the answer ended"}:{},startedAt:t.startedAt,durationMs:Date.now()-t.startedAt,capture:t.bodies?"bodies":"headers",request:{headers:g.headers,...y.length?{query:y}:{},...c?{body:c}:{}},response:{headers:l.headers,...u?{body:u}:{}},redacted:{headers:[...new Set(i)],bodyFields:[...f.map(n=>`request.${n}`),...h.map(n=>`response.${n}`)]}}}a(exchangeOf,"exchangeOf"),d(exchangeOf,"exchangeOf");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lensmcp/node-instrumentation",
3
- "version": "1.25.3",
3
+ "version": "1.25.6",
4
4
  "main": "./index.js",
5
5
  "types": "./index.d.ts",
6
6
  "exports": {
@@ -15,9 +15,9 @@
15
15
  }
16
16
  },
17
17
  "dependencies": {
18
- "@lensmcp/core": "1.25.3",
19
- "@lensmcp/nest-instrumentation": "1.25.3",
20
- "@lensmcp/protocol-types": "1.25.3",
18
+ "@lensmcp/core": "1.25.6",
19
+ "@lensmcp/nest-instrumentation": "1.25.6",
20
+ "@lensmcp/protocol-types": "1.25.6",
21
21
  "tslib": "^2.3.0"
22
22
  },
23
23
  "optionalDependencies": {