@lensmcp/node-instrumentation 1.26.23 → 1.26.25

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.
@@ -2,8 +2,17 @@ import type { HttpExchange, HttpExchangeBody } from '@lensmcp/core/http-exchange
2
2
  import { type HttpCaptureMode } from './http-store';
3
3
  type FetchInput = Parameters<typeof fetch>[0];
4
4
  type FetchInit = Parameters<typeof fetch>[1];
5
- /** A response is read for at most this long; the `http` path also writes the exchange of one nobody reads by then. */
5
+ /**
6
+ * A response is read for at most this long FROM ITS FIRST BYTE — the time the call waited for an answer is the
7
+ * provider's, not a body being read (foodguard-302: FoodGuard's non-streamed OpenAI calls that answered after 5 to 8
8
+ * minutes were counted from the call's start, so each was cut at its first chunk, its token counts lost). The `http`
9
+ * path also writes the exchange of one nobody reads by then.
10
+ */
6
11
  export declare const MAX_STREAM_MS: number;
12
+ /** An AI provider's answer kept whole is read for longer: the provider or the caller ends it; the sizes above bound it. */
13
+ export declare const MAX_AI_STREAM_MS: number;
14
+ /** How long an answer is read from its first byte: {@link MAX_STREAM_MS}, or {@link MAX_AI_STREAM_MS} for an AI call kept whole. */
15
+ export declare const readMsOf: (large: boolean | undefined) => number;
7
16
  /** Headers as name/value pairs, whatever holds them: a `Headers`, an array of pairs, or a plain object (`http`'s). */
8
17
  export declare const headerPairs: (h: unknown) => Array<[string, string]>;
9
18
  export interface RequestSide {
@@ -55,6 +64,7 @@ export interface ResponseRead {
55
64
  */
56
65
  export declare class ResponseSink {
57
66
  private readonly contentType;
67
+ /** When the call started: what an event's time is counted from. */
58
68
  private readonly startedAt;
59
69
  private readonly opts;
60
70
  private total;
@@ -70,10 +80,14 @@ export declare class ResponseSink {
70
80
  private eventTotal;
71
81
  private eventData;
72
82
  private firstEventMs;
73
- private cut;
83
+ private cutBy;
74
84
  private pendingText;
75
85
  private readonly decoder;
76
- constructor(contentType: string, startedAt: number, opts: {
86
+ /** When the answer began — the sink is made as its headers arrive: what the read's time is counted from. */
87
+ private readonly answeredAt;
88
+ constructor(contentType: string,
89
+ /** When the call started: what an event's time is counted from. */
90
+ startedAt: number, opts: {
77
91
  ai: boolean;
78
92
  large?: boolean;
79
93
  paths: string[];
@@ -84,9 +98,15 @@ export declare class ResponseSink {
84
98
  private take;
85
99
  /** One chunk, as it arrived. False once the read has run past its 5 minutes: it is cut, and keeps nothing more. */
86
100
  push(value: Uint8Array): boolean;
101
+ /** How long this answer is read from its first byte ({@link readMsOf}). */
102
+ get readMs(): number;
87
103
  private inTime;
88
- /** What was kept. `broken`: the caller or the network cut the body short — keep what arrived, and say so. */
89
- finish(broken?: boolean, endedAt?: number): ResponseRead;
104
+ /**
105
+ * What was kept. `broken`: the caller or the network cut the body short — keep what arrived, and say so; `'time'`: its
106
+ * read ran out of time first. A body the read stopped before its end says it (`truncated`, and `cut`: why): its size
107
+ * is only what arrived.
108
+ */
109
+ finish(broken?: boolean | 'time', endedAt?: number): ResponseRead;
90
110
  }
91
111
  /**
92
112
  * Read the response from its clone. MUST be called synchronously after `res.clone()` (see above). An AI provider's
@@ -1,2 +1,2 @@
1
- "use strict";var g=Object.defineProperty;var p=(t,e)=>g(t,"name",{value:e,configurable:!0});var l=Object.defineProperty,c=p((t,e)=>l(t,"name",{value:e,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResponseSink=exports.WrittenBody=exports.headerPairs=exports.MAX_STREAM_MS=void 0,exports.takeRequest=takeRequest,exports.chunkBytes=chunkBytes,exports.unpacked=unpacked,exports.writtenRequest=writtenRequest,exports.readResponse=readResponse,exports.requestPart=requestPart;const tslib_1=require("tslib"),node_crypto_1=require("node:crypto"),zlib=tslib_1.__importStar(require("node:zlib")),ai_store_1=require("./ai-store"),http_store_1=require("./http-store"),MAX_EVENTS=2e3,MAX_EVENT_DATA=4*1024,MAX_STREAM_KEPT=256*1024;exports.MAX_STREAM_MS=300*1e3;const MAX_HASH_BYTES=1024*1024,MAX_READ=http_store_1.MAX_KEPT_BYTES*32,LIMITS={standard:{read:MAX_READ,keep:http_store_1.MAX_KEPT_BYTES,events:MAX_EVENTS,eventData:MAX_EVENT_DATA,streamKept:MAX_STREAM_KEPT},large:{read:http_store_1.MAX_AI_KEPT_BYTES,keep:http_store_1.MAX_AI_KEPT_BYTES,events:2e4,eventData:1024*1024,streamKept:8*1024*1024}},limitsOf=c(t=>t?LIMITS.large:LIMITS.standard,"limitsOf"),headerPairs=c(t=>{try{if(!t)return[];if(typeof t.forEach=="function"&&typeof t.get=="function"){const e=[];return t.forEach((s,n)=>e.push([n,s])),e}return Array.isArray(t)?t.map(([e,s])=>[String(e),String(s)]):Object.entries(t).map(([e,s])=>[e,Array.isArray(s)?s.join(", "):String(s)])}catch{return[]}},"headerPairs");exports.headerPairs=headerPairs;function takeRequest(t,e,s,n=!1){const r=typeof t=="object"&&t!==null&&!(t instanceof URL)?t:void 0,a=[...(0,exports.headerPairs)(r?.headers),...(0,exports.headerPairs)(e?.headers)],h=a.find(([d])=>d.toLowerCase()==="content-type")?.[1]??"",o={headers:a,contentType:h};if(!s)return o;const i=e?.body,u=c(d=>new TextEncoder().encode(d),"enc");if(typeof i=="string")return{...o,bytes:u(i),size:Buffer.byteLength(i)};if(i instanceof URLSearchParams)return{...o,contentType:h||"application/x-www-form-urlencoded",bytes:u(i.toString())};if(i instanceof ArrayBuffer)return{...o,bytes:new Uint8Array(i),size:i.byteLength};if(ArrayBuffer.isView(i))return{...o,bytes:new Uint8Array(i.buffer,i.byteOffset,i.byteLength),size:i.byteLength};if(typeof Blob<"u"&&i instanceof Blob)return{...o,size:i.size,...i.size<=limitsOf(n).read?{pending:i.arrayBuffer().then(d=>new Uint8Array(d)).catch(()=>{})}:{}};if(typeof FormData<"u"&&i instanceof FormData)return{...o,omitted:"form-data"};if(i!=null)return{...o,omitted:"stream"};if(r&&!r.bodyUsed&&r.body)try{return{...o,pending:r.clone().arrayBuffer().then(d=>new Uint8Array(d)).catch(()=>{})}}catch{return o}return o}p(takeRequest,"takeRequest"),c(takeRequest,"takeRequest");function chunkBytes(t,e){if(t instanceof Uint8Array)return t;if(typeof t=="string")return Buffer.from(t,typeof e=="string"&&Buffer.isEncoding(e)?e:"utf8")}p(chunkBytes,"chunkBytes"),c(chunkBytes,"chunkBytes");class WrittenBody{static{p(this,"WrittenBody")}static{c(this,"WrittenBody")}constructor(e,s=!1){this.keep=e,this.large=s,this.chunks=[],this.read=0,this.size=0}take(e,s){if(e==null||typeof e=="function")return;const n=chunkBytes(e,s);n&&(this.size+=n.byteLength,this.keep&&this.read<limitsOf(this.large).read&&(this.chunks.push(n),this.read+=n.byteLength))}get whole(){return this.read>=this.size}bytes(){return Buffer.concat(this.chunks)}}exports.WrittenBody=WrittenBody;function unpacked(t,e){try{if(t==="gzip"||t==="x-gzip")return zlib.gunzipSync(e,{maxOutputLength:MAX_READ});if(t==="br")return zlib.brotliDecompressSync(e,{maxOutputLength:MAX_READ});if(t==="deflate")return zlib.inflateSync(e,{maxOutputLength:MAX_READ})}catch{return}}p(unpacked,"unpacked"),c(unpacked,"unpacked");const encodingOf=c(t=>{const e=(t??"").trim().toLowerCase();return e==="identity"?"":e},"encodingOf");function writtenRequest(t,e){const s=(0,exports.headerPairs)(t),n=c(o=>s.find(([i])=>i.toLowerCase()===o)?.[1],"header"),r={headers:s,contentType:n("content-type")??""};if(!e||!e.size)return r;const a=encodingOf(n("content-encoding"));if(!a)return{...r,bytes:e.bytes(),size:e.size};const h=e.whole?unpacked(a,e.bytes()):void 0;return h?{...r,bytes:h,size:h.length}:{...r,size:e.size,omitted:"encoded"}}p(writtenRequest,"writtenRequest"),c(writtenRequest,"writtenRequest");function sseEvent(t){let e="message";const s=[];for(const n of t.split(/\r?\n/)){if(!n||n.startsWith(":"))continue;const r=n.indexOf(":"),a=r<0?n:n.slice(0,r),h=r<0?"":n.slice(r+1).replace(/^ /,"");a==="event"?e=h||"message":a==="data"&&s.push(h)}return s.length||e!=="message"?{event:e,data:s.join(`
2
- `)}:void 0}p(sseEvent,"sseEvent"),c(sseEvent,"sseEvent");class ResponseSink{static{p(this,"ResponseSink")}static{c(this,"ResponseSink")}constructor(e,s,n){this.contentType=e,this.startedAt=s,this.opts=n,this.total=0,this.kept=[],this.keptBytes=0,this.hash=(0,node_crypto_1.createHash)("sha256"),this.events=[],this.eventTotal=0,this.eventData=0,this.cut=!1,this.pendingText="",this.decoder=new TextDecoder,this.encoding=encodingOf(n.encoding),this.sse=!this.encoding&&/text\/event-stream/i.test(e),this.parsing=this.sse,this.hashing=!/json|^text\/|xml|form/i.test(e)}get size(){return this.total}take(e){const s=sseEvent(e);if(!s)return;this.eventTotal++;const n=Date.now()-this.startedAt;this.firstEventMs??=n;const r=limitsOf(this.opts.large);if(this.events.length>=r.events||this.eventData>=r.streamKept){this.cut=!0;return}const a=this.opts.ai?void 0:(0,ai_store_1.redactAiText)(s.data).slice(0,r.eventData);a&&(this.eventData+=a.length),this.events.push({atMs:n,event:s.event,bytes:Buffer.byteLength(e),...a!==void 0?{data:a}:{}})}push(e){if(this.total+=e.byteLength,this.sse){if(!this.parsing)return this.inTime();this.pendingText+=this.decoder.decode(e,{stream:!0});let s;for(;(s=this.pendingText.search(/\r?\n\r?\n/))>=0;){const n=/\r?\n\r?\n/.exec(this.pendingText.slice(s));this.take(this.pendingText.slice(0,s)),this.pendingText=this.pendingText.slice(s+n[0].length)}this.pendingText.length>limitsOf(this.opts.large).read&&(this.pendingText="",this.parsing=!1,this.cut=!0)}else this.opts.ai||(this.keptBytes<limitsOf(this.opts.large).read&&(this.kept.push(e),this.keptBytes+=e.byteLength),this.hashing&&!this.encoding&&(this.total<=MAX_HASH_BYTES?this.hash.update(e):this.hashing=!1));return this.inTime()}inTime(){return Date.now()-this.startedAt<=exports.MAX_STREAM_MS?!0:(this.cut=!0,!1)}finish(e=!1,s=Date.now()){e?this.cut=!0:this.parsing&&this.pendingText.trim()&&this.take(this.pendingText);const n=this.total,r=this.contentType.split(";")[0].trim();if(this.sse)return{endedAt:s,stream:{protocol:"sse",...this.firstEventMs!==void 0?{firstEventMs:this.firstEventMs}:{},events:this.events,bytes:n,total:this.eventTotal,...this.cut?{cut:!0}:{}}};if(this.opts.ai)return{endedAt:s,body:{contentType:r,size:n,kept:0,truncated:!1,omitted:"ai"}};const a=Buffer.concat(this.kept);if(this.encoding){const o=n<=MAX_READ?unpacked(this.encoding,a):void 0;if(!o)return{endedAt:s,body:{contentType:r.toLowerCase(),size:n,kept:0,truncated:!1,omitted:"encoded"}};const i=this.hashing&&o.length<=MAX_HASH_BYTES?(0,node_crypto_1.createHash)("sha256").update(o).digest("hex"):void 0;return{endedAt:s,body:(0,http_store_1.keepBody)(this.contentType,o,o.length,this.opts.paths,i,limitsOf(this.opts.large).keep)}}const h=this.hashing&&n<=MAX_HASH_BYTES?this.hash.digest("hex"):void 0;return{endedAt:s,body:(0,http_store_1.keepBody)(this.contentType,a,n,this.opts.paths,h,limitsOf(this.opts.large).keep)}}}exports.ResponseSink=ResponseSink;function readResponse(t,e,s,n){const r=(()=>{try{return t.headers.get("content-type")??""}catch{return""}})(),a=e.body;if(!a)return Promise.resolve({endedAt:Date.now()});const h=a.getReader(),o=new ResponseSink(r,s,n);return(async()=>{try{for(;;){const{done:i,value:u}=await h.read();if(i)break;if(!o.push(u)){await h.cancel().catch(()=>{});break}}}catch{return o.finish(!0)}return o.finish()})()}p(readResponse,"readResponse"),c(readResponse,"readResponse");async function requestPart(t,e,s,n,r,a,h=!1){const{headers:o,redacted:i}=(0,http_store_1.redactHeaders)(t.headers);a.push(...i);const u=s==="bodies"&&e.length>1?(0,http_store_1.redactQuery)(e):[];let d;if(s==="bodies"){const y=t.contentType.split(";")[0].trim().toLowerCase();if(n)d={contentType:y,size:t.size??t.bytes?.byteLength??0,kept:0,truncated:!1,omitted:"ai"};else if(t.omitted)d={contentType:y,size:t.size??0,kept:0,truncated:!1,omitted:t.omitted};else{const f=t.bytes??await t.pending;f&&f.byteLength&&(d=(0,http_store_1.keepBody)(t.contentType,f,t.size??f.byteLength,r,void 0,limitsOf(h).keep))}}return{headers:o,...u.length?{query:u}:{},...d?{body:d}:{}}}p(requestPart,"requestPart"),c(requestPart,"requestPart");
1
+ "use strict";var l=Object.defineProperty;var u=(t,e)=>l(t,"name",{value:e,configurable:!0});var y=Object.defineProperty,c=u((t,e)=>y(t,"name",{value:e,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResponseSink=exports.WrittenBody=exports.headerPairs=exports.readMsOf=exports.MAX_AI_STREAM_MS=exports.MAX_STREAM_MS=void 0,exports.takeRequest=takeRequest,exports.chunkBytes=chunkBytes,exports.unpacked=unpacked,exports.writtenRequest=writtenRequest,exports.readResponse=readResponse,exports.requestPart=requestPart;const tslib_1=require("tslib"),node_crypto_1=require("node:crypto"),zlib=tslib_1.__importStar(require("node:zlib")),ai_store_1=require("./ai-store"),http_store_1=require("./http-store"),MAX_EVENTS=2e3,MAX_EVENT_DATA=4*1024,MAX_STREAM_KEPT=256*1024;exports.MAX_STREAM_MS=300*1e3,exports.MAX_AI_STREAM_MS=1800*1e3;const MAX_HASH_BYTES=1024*1024,MAX_READ=http_store_1.MAX_KEPT_BYTES*32,LIMITS={standard:{read:MAX_READ,keep:http_store_1.MAX_KEPT_BYTES,events:MAX_EVENTS,eventData:MAX_EVENT_DATA,streamKept:MAX_STREAM_KEPT,readMs:exports.MAX_STREAM_MS},large:{read:http_store_1.MAX_AI_KEPT_BYTES,keep:http_store_1.MAX_AI_KEPT_BYTES,events:2e4,eventData:1024*1024,streamKept:8*1024*1024,readMs:exports.MAX_AI_STREAM_MS}},limitsOf=c(t=>t?LIMITS.large:LIMITS.standard,"limitsOf"),readMsOf=c(t=>limitsOf(t).readMs,"readMsOf");exports.readMsOf=readMsOf;const headerPairs=c(t=>{try{if(!t)return[];if(typeof t.forEach=="function"&&typeof t.get=="function"){const e=[];return t.forEach((s,n)=>e.push([n,s])),e}return Array.isArray(t)?t.map(([e,s])=>[String(e),String(s)]):Object.entries(t).map(([e,s])=>[e,Array.isArray(s)?s.join(", "):String(s)])}catch{return[]}},"headerPairs");exports.headerPairs=headerPairs;function takeRequest(t,e,s,n=!1){const r=typeof t=="object"&&t!==null&&!(t instanceof URL)?t:void 0,o=[...(0,exports.headerPairs)(r?.headers),...(0,exports.headerPairs)(e?.headers)],h=o.find(([p])=>p.toLowerCase()==="content-type")?.[1]??"",a={headers:o,contentType:h};if(!s)return a;const i=e?.body,d=c(p=>new TextEncoder().encode(p),"enc");if(typeof i=="string")return{...a,bytes:d(i),size:Buffer.byteLength(i)};if(i instanceof URLSearchParams)return{...a,contentType:h||"application/x-www-form-urlencoded",bytes:d(i.toString())};if(i instanceof ArrayBuffer)return{...a,bytes:new Uint8Array(i),size:i.byteLength};if(ArrayBuffer.isView(i))return{...a,bytes:new Uint8Array(i.buffer,i.byteOffset,i.byteLength),size:i.byteLength};if(typeof Blob<"u"&&i instanceof Blob)return{...a,size:i.size,...i.size<=limitsOf(n).read?{pending:i.arrayBuffer().then(p=>new Uint8Array(p)).catch(()=>{})}:{}};if(typeof FormData<"u"&&i instanceof FormData)return{...a,omitted:"form-data"};if(i!=null)return{...a,omitted:"stream"};if(r&&!r.bodyUsed&&r.body)try{return{...a,pending:r.clone().arrayBuffer().then(p=>new Uint8Array(p)).catch(()=>{})}}catch{return a}return a}u(takeRequest,"takeRequest"),c(takeRequest,"takeRequest");function chunkBytes(t,e){if(t instanceof Uint8Array)return t;if(typeof t=="string")return Buffer.from(t,typeof e=="string"&&Buffer.isEncoding(e)?e:"utf8")}u(chunkBytes,"chunkBytes"),c(chunkBytes,"chunkBytes");class WrittenBody{static{u(this,"WrittenBody")}static{c(this,"WrittenBody")}constructor(e,s=!1){this.keep=e,this.large=s,this.chunks=[],this.read=0,this.size=0}take(e,s){if(e==null||typeof e=="function")return;const n=chunkBytes(e,s);n&&(this.size+=n.byteLength,this.keep&&this.read<limitsOf(this.large).read&&(this.chunks.push(n),this.read+=n.byteLength))}get whole(){return this.read>=this.size}bytes(){return Buffer.concat(this.chunks)}}exports.WrittenBody=WrittenBody;function unpacked(t,e){try{if(t==="gzip"||t==="x-gzip")return zlib.gunzipSync(e,{maxOutputLength:MAX_READ});if(t==="br")return zlib.brotliDecompressSync(e,{maxOutputLength:MAX_READ});if(t==="deflate")return zlib.inflateSync(e,{maxOutputLength:MAX_READ})}catch{return}}u(unpacked,"unpacked"),c(unpacked,"unpacked");const encodingOf=c(t=>{const e=(t??"").trim().toLowerCase();return e==="identity"?"":e},"encodingOf");function writtenRequest(t,e){const s=(0,exports.headerPairs)(t),n=c(a=>s.find(([i])=>i.toLowerCase()===a)?.[1],"header"),r={headers:s,contentType:n("content-type")??""};if(!e||!e.size)return r;const o=encodingOf(n("content-encoding"));if(!o)return{...r,bytes:e.bytes(),size:e.size};const h=e.whole?unpacked(o,e.bytes()):void 0;return h?{...r,bytes:h,size:h.length}:{...r,size:e.size,omitted:"encoded"}}u(writtenRequest,"writtenRequest"),c(writtenRequest,"writtenRequest");function sseEvent(t){let e="message";const s=[];for(const n of t.split(/\r?\n/)){if(!n||n.startsWith(":"))continue;const r=n.indexOf(":"),o=r<0?n:n.slice(0,r),h=r<0?"":n.slice(r+1).replace(/^ /,"");o==="event"?e=h||"message":o==="data"&&s.push(h)}return s.length||e!=="message"?{event:e,data:s.join(`
2
+ `)}:void 0}u(sseEvent,"sseEvent"),c(sseEvent,"sseEvent");class ResponseSink{static{u(this,"ResponseSink")}static{c(this,"ResponseSink")}constructor(e,s,n){this.contentType=e,this.startedAt=s,this.opts=n,this.total=0,this.kept=[],this.keptBytes=0,this.hash=(0,node_crypto_1.createHash)("sha256"),this.events=[],this.eventTotal=0,this.eventData=0,this.pendingText="",this.decoder=new TextDecoder,this.answeredAt=Date.now(),this.encoding=encodingOf(n.encoding),this.sse=!this.encoding&&/text\/event-stream/i.test(e),this.parsing=this.sse,this.hashing=!/json|^text\/|xml|form/i.test(e)}get size(){return this.total}take(e){const s=sseEvent(e);if(!s)return;this.eventTotal++;const n=Date.now()-this.startedAt;this.firstEventMs??=n;const r=limitsOf(this.opts.large);if(this.events.length>=r.events||this.eventData>=r.streamKept){this.cutBy??="size";return}const o=this.opts.ai?void 0:(0,ai_store_1.redactAiText)(s.data).slice(0,r.eventData);o&&(this.eventData+=o.length),this.events.push({atMs:n,event:s.event,bytes:Buffer.byteLength(e),...o!==void 0?{data:o}:{}})}push(e){if(this.total+=e.byteLength,this.sse){if(!this.parsing)return this.inTime();this.pendingText+=this.decoder.decode(e,{stream:!0});let s;for(;(s=this.pendingText.search(/\r?\n\r?\n/))>=0;){const n=/\r?\n\r?\n/.exec(this.pendingText.slice(s));this.take(this.pendingText.slice(0,s)),this.pendingText=this.pendingText.slice(s+n[0].length)}this.pendingText.length>limitsOf(this.opts.large).read&&(this.pendingText="",this.parsing=!1,this.cutBy??="size")}else this.opts.ai||(this.keptBytes<limitsOf(this.opts.large).read&&(this.kept.push(e),this.keptBytes+=e.byteLength),this.hashing&&!this.encoding&&(this.total<=MAX_HASH_BYTES?this.hash.update(e):this.hashing=!1));return this.inTime()}get readMs(){return limitsOf(this.opts.large).readMs}inTime(){return Date.now()-this.answeredAt<=this.readMs?!0:(this.cutBy??="time",!1)}finish(e=!1,s=Date.now()){e?this.cutBy??=e==="time"?"time":"broken":this.parsing&&this.pendingText.trim()&&this.take(this.pendingText);const n=this.total,r=this.contentType.split(";")[0].trim(),o=this.cutBy;if(this.sse)return{endedAt:s,stream:{protocol:"sse",...this.firstEventMs!==void 0?{firstEventMs:this.firstEventMs}:{},events:this.events,bytes:n,total:this.eventTotal,...o?{cut:!0,cutBy:o}:{}}};const h=c(d=>({endedAt:s,body:o==="time"||o==="broken"?{...d,truncated:!0,cut:o}:d}),"ended");if(this.opts.ai)return{endedAt:s,body:{contentType:r,size:n,kept:0,truncated:!1,omitted:"ai"}};const a=Buffer.concat(this.kept);if(this.encoding){const d=n<=MAX_READ?unpacked(this.encoding,a):void 0;if(!d)return h({contentType:r.toLowerCase(),size:n,kept:0,truncated:!1,omitted:"encoded"});const p=this.hashing&&d.length<=MAX_HASH_BYTES?(0,node_crypto_1.createHash)("sha256").update(d).digest("hex"):void 0;return h((0,http_store_1.keepBody)(this.contentType,d,d.length,this.opts.paths,p,limitsOf(this.opts.large).keep))}const i=this.hashing&&n<=MAX_HASH_BYTES?this.hash.digest("hex"):void 0;return h((0,http_store_1.keepBody)(this.contentType,a,n,this.opts.paths,i,limitsOf(this.opts.large).keep))}}exports.ResponseSink=ResponseSink;function readResponse(t,e,s,n){const r=(()=>{try{return t.headers.get("content-type")??""}catch{return""}})(),o=e.body;if(!o)return Promise.resolve({endedAt:Date.now()});const h=o.getReader(),a=new ResponseSink(r,s,n);return(async()=>{try{for(;;){const{done:i,value:d}=await h.read();if(i)break;if(!a.push(d)){await h.cancel().catch(()=>{});break}}}catch{return a.finish(!0)}return a.finish()})()}u(readResponse,"readResponse"),c(readResponse,"readResponse");async function requestPart(t,e,s,n,r,o,h=!1){const{headers:a,redacted:i}=(0,http_store_1.redactHeaders)(t.headers);o.push(...i);const d=s==="bodies"&&e.length>1?(0,http_store_1.redactQuery)(e):[];let p;if(s==="bodies"){const g=t.contentType.split(";")[0].trim().toLowerCase();if(n)p={contentType:g,size:t.size??t.bytes?.byteLength??0,kept:0,truncated:!1,omitted:"ai"};else if(t.omitted)p={contentType:g,size:t.size??0,kept:0,truncated:!1,omitted:t.omitted};else{const f=t.bytes??await t.pending;f&&f.byteLength&&(p=(0,http_store_1.keepBody)(t.contentType,f,t.size??f.byteLength,r,void 0,limitsOf(h).keep))}}return{headers:a,...d.length?{query:d}:{},...p?{body:p}:{}}}u(requestPart,"requestPart"),c(requestPart,"requestPart");
package/lib/tap-egress.js CHANGED
@@ -1 +1 @@
1
- "use strict";var U=Object.defineProperty;var g=(e,t)=>U(e,"name",{value:t,configurable:!0});var P=Object.defineProperty,d=g((e,t)=>P(e,"name",{value:t,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.flushEgressCaptureForTests=flushEgressCaptureForTests,exports.tapEgress=tapEgress,exports.resetEgressTapForTests=resetEgressTapForTests;const redact_1=require("@lensmcp/core/redact"),http_exchange_1=require("@lensmcp/core/http-exchange"),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=d(e=>e===""||INTERNAL.some(t=>t.test(e)),"isInternal"),CAPTURE_QUERY=process.env.LENSMCP_EGRESS_QUERY==="1",MAX_PATH_CHARS=256,clipPath=d(e=>e.length>MAX_PATH_CHARS?`${e.slice(0,MAX_PATH_CHARS)}\u2026`:e,"clipPath");function capturePath(e,t){const s=e||"/";return!CAPTURE_QUERY||t.length<=1?clipPath(s):(0,redact_1.redactUrl)(`${s}${t}`)}g(capturePath,"capturePath"),d(capturePath,"capturePath");const fingerprintFor=d((e,t)=>t?`external:error:${e}`:`external:${e}`,"fingerprintFor"),PARENT_HEADER="x-lensmcp-parent-request-id",FLOW_HEADER="x-lensmcp-flow-id",ORIGIN_HEADER="x-lensmcp-origin-node-id";let hopsOutside=0;function hopHeaders(e,t){if(!e?.requestId&&!e?.flowId||t(http_exchange_1.LENS_REQUEST_ID_HEADER)||t(PARENT_HEADER)||t(FLOW_HEADER))return;const s={};if(e.requestId){const p=(0,flow_context_1.liveFlowContext)(),r=p?p.hopCount=(p.hopCount??0)+1:++hopsOutside;s[http_exchange_1.LENS_REQUEST_ID_HEADER]=`${e.requestId}.${r}`,s[PARENT_HEADER]=e.requestId}return e.flowId&&(s[FLOW_HEADER]=e.flowId),e.originNodeId&&(s[ORIGIN_HEADER]=e.originNodeId),s}g(hopHeaders,"hopHeaders"),d(hopHeaders,"hopHeaders");function isAiCall(e,t,s){return!!e&&t==="POST"&&!!(0,ai_providers_1.matchTarget)(e.hostname,e.port,e.pathname,s)}g(isAiCall,"isAiCall"),d(isAiCall,"isAiCall");function stampFetch(e,t,s){try{const p=t?.headers??(typeof e=="object"&&e!==null&&!(e instanceof URL)?e.headers:void 0),r=new Headers(p),c=hopHeaders(s,a=>r.has(a));if(!c)return{init:t};for(const[a,l]of Object.entries(c))r.set(a,l);const o=c[http_exchange_1.LENS_REQUEST_ID_HEADER];return{init:{...t,headers:r},...o?{calleeRequestId:o}:{}}}catch{return{init:t}}}g(stampFetch,"stampFetch"),d(stampFetch,"stampFetch");function stampRequest(e,t){try{if(e.headersSent||typeof e.setHeader!="function"||typeof e.getHeader!="function")return;const s=hopHeaders(t,p=>e.getHeader(p)!==void 0);if(!s)return;for(const[p,r]of Object.entries(s))e.setHeader(p,r);return s[http_exchange_1.LENS_REQUEST_ID_HEADER]}catch{return}}g(stampRequest,"stampRequest"),d(stampRequest,"stampRequest");const pendingExchanges=new Set;async function flushEgressCaptureForTests(){await Promise.allSettled([...pendingExchanges]),await(0,http_store_1.flushHttpExchanges)()}g(flushEgressCaptureForTests,"flushEgressCaptureForTests"),d(flushEgressCaptureForTests,"flushEgressCaptureForTests");async function finishExchange(e){const t=e.mode==="bodies"&&(0,http_store_1.proofBoundHeaders)(e.request.headers)?{...e,mode:"headers",responseFields:[]}:e,s=[],p=[],r=await(0,http_capture_1.requestPart)(t.request,t.url.search,t.mode,!!t.aiOpaque,p,s,!!t.ai&&!t.aiOpaque),c=t.reading?await t.reading.catch(()=>{}):void 0,{headers:o,redacted:a}=(0,http_store_1.redactHeaders)(t.responseHeaders??[]);s.push(...a);const l=typeof t.status=="number"?t.status:void 0,u={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,...l!==void 0?{status:l}:{},...t.statusText?{statusText:t.statusText}:{},...t.error?{error:t.error}:{},startedAt:t.startedAt,...t.ttfbMs!==void 0?{ttfbMs:t.ttfbMs}:{},durationMs:(c?.endedAt??Date.now())-t.startedAt,capture:t.mode==="bodies"?"bodies":"headers",request:r,response:{headers:o,...t.mode==="bodies"&&c?.body?{body:c.body}:{},...t.mode==="bodies"&&c?.stream?{stream:c.stream}:{}},redacted:{headers:[...new Set(s)],bodyFields:[...p.map(h=>`request.${h}`),...t.responseFields.map(h=>`response.${h}`)]},...t.ai?{ai:{provider:t.ai}}:{}};(0,http_store_1.queueHttpExchange)(u)}g(finishExchange,"finishExchange"),d(finishExchange,"finishExchange");function trackExchange(e){const t=(typeof e=="function"?new Promise(s=>setImmediate(s)).then(()=>finishExchange(e())):finishExchange(e)).catch(()=>{});pendingExchanges.add(t),t.finally(()=>pendingExchanges.delete(t))}g(trackExchange,"trackExchange"),d(trackExchange,"trackExchange");function tapEgress(){(0,http_store_1.primeHttpStore)(),tapFetch(),tapHttpModule("http"),tapHttpModule("https")}g(tapEgress,"tapEgress"),d(tapEgress,"tapEgress");let savedFetch;const httpOriginals=new Map;function resetEgressTapForTests(){const e=globalThis;savedFetch&&(e.fetch=savedFetch),delete e.__lensmcpFetchTap,restoreHttp("http"),restoreHttp("https"),savedFetch=void 0}g(resetEgressTapForTests,"resetEgressTapForTests"),d(resetEgressTapForTests,"resetEgressTapForTests");function restoreHttp(e){const t=httpOriginals.get(e);if(!t)return;const s=require(`node:${e}`);s.request=t.request,s.get=t.get,httpOriginals.delete(e)}g(restoreHttp,"restoreHttp"),d(restoreHttp,"restoreHttp");function tapFetch(){const e=globalThis;if(typeof e.fetch!="function"||e.__lensmcpFetchTap)return;e.__lensmcpFetchTap=!0;const t=e.fetch.bind(globalThis);savedFetch=e.fetch;const s=(0,http_store_1.httpCaptureMode)(),p=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS);e.fetch=(async(r,c)=>{let o="",a="/",l=!1,u;try{const i=new URL(typeof r=="string"?r:r instanceof URL?r.href:r.url);u=i,o=i.hostname,l=i.search.length>1,a=capturePath(i.pathname,i.search)}catch{}if(isInternal(o))return t(r,c);const h=Date.now(),f=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.method:void 0,n=String(c?.method??f??"GET").toUpperCase();isAiCall(u,n,p)&&(0,flow_context_1.startLiveFlow)();const x=(0,flow_context_1.flowContext)(),E=(0,http_exchange_1.isServiceHopHost)(o)?stampFetch(r,c,x):{init:c},_=E.init,R=E.calleeRequestId,q=(0,flow_context_1.liveFlowContext)();q&&(q.externalCallCount=(q.externalCallCount??0)+1);const y=s!=="off"&&u?(0,http_store_1.newExchangeId)():void 0,I=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.headers:void 0,$=s==="bodies"&&((0,http_store_1.proofBoundHeaders)(I)||(0,http_store_1.proofBoundHeaders)(_?.headers))?"headers":s,H=y&&u&&n==="POST"?(0,ai_providers_1.matchTarget)(o,u.port,u.pathname,p)?.provider:void 0,w=!!H&&(0,tap_ai_1.aiCaptureMode)()!=="content"&&!(0,capture_file_1.aiBodiesAsked)(),T=!!H&&!w,F=T&&!!u&&!/\/embeddings\/?$/.test(u.pathname),M=y?(0,http_capture_1.takeRequest)(r,_,$==="bodies",T):void 0,A=d(i=>({id:y,mode:$,method:n,url:u,path:u.pathname.length>256?`${u.pathname.slice(0,256)}\u2026`:u.pathname,startedAt:h,ctx:x,request:M,...H?{ai:H}:{},...w?{aiOpaque:w}:{},responseFields:[],...i}),"job");try{const i=await t(r,_),m=Date.now()-h,b=i.status>=500,S=[];let v;if(y&&$==="bodies")try{v=(0,http_capture_1.readResponse)(i,i.clone(),h,{ai:w,large:F,paths:S})}catch{v=void 0}const C=(0,emit_1.lensEmit)("external","info",`egress ${n} ${o} \u2192 ${i.status}`,{name:o,kind:"egress",method:n,host:o,path:a,status:i.status,...l?{hasQuery:!0}:{},startedAt:h,durationMs:m,...y?{exchangeId:y}:{},...R?{calleeRequestId:R}:{}},fingerprintFor(o,b),x);if(y&&C){const O={status:i.status,...i.statusText?{statusText:i.statusText}:{},responseHeaders:(0,http_capture_1.headerPairs)(i.headers)};trackExchange(A({...O,ttfbMs:m,responseFields:S,...v?{reading:v}:{}}))}return i}catch(i){const m=String(i?.message??i),b=(0,emit_1.lensEmit)("external","error",`egress ${n} ${o} failed`,{name:o,kind:"egress",method:n,host:o,path:a,...l?{hasQuery:!0}:{},error:m,startedAt:h,durationMs:Date.now()-h,...y?{exchangeId:y}:{},...R?{calleeRequestId:R}:{}},fingerprintFor(o,!0),x);throw y&&b&&trackExchange(A({error:m})),i}})}g(tapFetch,"tapFetch"),d(tapFetch,"tapFetch");function tapHttpModule(e){const t=require(`node:${e}`),s=t.request;if(typeof s!="function"||s.__lensmcp)return;httpOriginals.set(e,{request:s,get:t.get});const p=(0,http_store_1.httpCaptureMode)(),r=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS),c=d(function(...o){const a=s.apply(this,o);try{observe(e,o,a,p,r)}catch{}return a},"wrapped");c.__lensmcp=!0,t.request=c,typeof t.get=="function"&&(t.get=function(...o){const a=c.apply(this,o);return a.end(),a})}g(tapHttpModule,"tapHttpModule"),d(tapHttpModule,"tapHttpModule");const headersOf=d(e=>{try{return e.getHeaders?.()}catch{return}},"headersOf"),optionsWithProof=d(e=>!!e&&typeof e=="object"&&!(e instanceof URL)&&(0,http_store_1.proofBoundHeaders)(e.headers),"optionsWithProof"),headerOf=d((e,t)=>{const s=e?.[t];return Array.isArray(s)?s.join(", "):s??""},"headerOf");function teeRequest(e,t,s,p=!1){const r=t?new http_capture_1.WrittenBody(!s,p):void 0;let c,o=!1;const a=e.write;r&&typeof a=="function"&&(e.write=function(u,...h){try{o||r.take(u,h[0])}catch{}return a.call(this,u,...h)});const l=e.end;return e.end=function(u,...h){try{o||(o=!0,r?.take(u,h[0]),c=headersOf(e))}catch{}return l.call(this,u,...h)},()=>(0,http_capture_1.writtenRequest)(c??headersOf(e),r)}g(teeRequest,"teeRequest"),d(teeRequest,"teeRequest");function teeResponse(e,t,s){let p=!1;const r=d(a=>{if(p)return;p=!0,clearTimeout(c);const l=Date.now();s(()=>t.size?t.finish(a,l):{endedAt:l})},"finish"),c=setTimeout(()=>r(!0),http_capture_1.MAX_STREAM_MS);c.unref?.();const o=e.emit;e.emit=function(a,...l){try{return o.call(this,a,...l)}finally{try{if(a==="data"){const u=p?void 0:(0,http_capture_1.chunkBytes)(l[0],e.readableEncoding);u&&!t.push(u)&&r(!1)}else a==="end"?r(!1):(a==="aborted"||a==="error"||a==="close")&&r(!0)}catch{}}}}g(teeResponse,"teeResponse"),d(teeResponse,"teeResponse");function observe(e,t,s,p,r){const c=parseTarget(t,e),{host:o,method:a,path:l,hasQuery:u}=c;if(isInternal(o))return;const h=Date.now();isAiCall(targetUrl(c),a,r)&&(0,flow_context_1.startLiveFlow)();const f=(0,flow_context_1.flowContext)(),n=(0,http_exchange_1.isServiceHopHost)(o)?stampRequest(s,f):void 0,x=(0,flow_context_1.liveFlowContext)();x&&(x.externalCallCount=(x.externalCallCount??0)+1);const E=p!=="off"?targetUrl(c):void 0,_=E?(0,http_store_1.newExchangeId)():void 0;let R=p==="bodies"&&((0,http_store_1.proofBoundHeaders)(headersOf(s))||t.some(optionsWithProof))?"headers":p;const q=_&&E&&a==="POST"?(0,ai_providers_1.matchTarget)(o,E.port,E.pathname,r)?.provider:void 0,y=!!q&&(0,tap_ai_1.aiCaptureMode)()!=="content"&&!(0,capture_file_1.aiBodiesAsked)(),I=!!q&&!y,$=I&&!!E&&!/\/embeddings\/?$/.test(E.pathname),H=_?teeRequest(s,R==="bodies",y,I):void 0,w=d(i=>({id:_,mode:R,method:a,url:E,path:clipPath(E.pathname),startedAt:h,ctx:f,request:H(),...q?{ai:q}:{},...y?{aiOpaque:y}:{},responseFields:[],...i}),"job");let T=!1;const F=d(i=>{if(T)return;T=!0,R==="bodies"&&(0,http_store_1.proofBoundHeaders)(headersOf(s))&&(R="headers");const m=i?.statusCode,b=Date.now()-h,S=(0,emit_1.lensEmit)("external","info",`egress ${a} ${o} \u2192 ${m??"?"}`,{name:o,kind:"egress",method:a,host:o,path:l,...m!=null?{status:m}:{},...u?{hasQuery:!0}:{},startedAt:h,durationMs:b,..._?{exchangeId:_}:{},...n?{calleeRequestId:n}:{}},fingerprintFor(o,m!=null&&m>=500),f);if(!_||!S||!i||typeof i.emit!="function")return;const v={...m!=null?{status:m}:{},...i.statusMessage?{statusText:i.statusMessage}:{},responseHeaders:(0,http_capture_1.headerPairs)(i.headers),ttfbMs:b};if(R!=="bodies"){trackExchange(()=>w(v));return}const C=[],O=new http_capture_1.ResponseSink(headerOf(i.headers,"content-type"),h,{ai:y,large:$,paths:C,encoding:headerOf(i.headers,"content-encoding")});teeResponse(i,O,D=>trackExchange(()=>w({...v,responseFields:C,reading:Promise.resolve(D())})))},"onResponse"),M=d(i=>{if(T)return;T=!0;const m=String(i?.message??i),b=(0,emit_1.lensEmit)("external","error",`egress ${a} ${o} failed`,{name:o,kind:"egress",method:a,host:o,path:l,...u?{hasQuery:!0}:{},error:m,startedAt:h,durationMs:Date.now()-h,..._?{exchangeId:_}:{},...n?{calleeRequestId:n}:{}},fingerprintFor(o,!0),f);_&&b&&trackExchange(()=>w({error:m}))},"onError"),A=s.emit;s.emit=function(i,...m){try{i==="response"?F(m[0]):i==="error"&&M(m[0])}catch{}return A.call(this,i,...m)}}g(observe,"observe"),d(observe,"observe");function targetUrl(e){try{const t=e.host.includes(":")&&!e.host.startsWith("[")?`[${e.host}]`:e.host,s=e.pathname.startsWith("/")?e.pathname:`/${e.pathname}`;return new URL(`${e.protocol}//${t}${e.port?`:${e.port}`:""}${s}${e.search}`)}catch{return}}g(targetUrl,"targetUrl"),d(targetUrl,"targetUrl");function parseTarget(e,t="http"){let s="",p="GET",r="/",c=!1,o=`${t}:`,a="",l="/",u="";const h=d((f,n)=>{c=n.length>1,r=capturePath(f,n),l=f||"/",u=n},"take");for(const f of e)if(typeof f=="string")try{const n=new URL(f);s=n.hostname,o=n.protocol,a=n.port,h(n.pathname,n.search)}catch{}else if(f instanceof URL)s=f.hostname,o=f.protocol,a=f.port,h(f.pathname,f.search);else if(f&&typeof f=="object"){const n=f;if(typeof n.method=="string"&&(p=n.method.toUpperCase()),typeof n.socketPath=="string")return{host:"",method:p,path:r,hasQuery:c,protocol:o,port:a,pathname:l,search:u};if(typeof n.path=="string"){const x=n.path,E=x.indexOf("?");h(E===-1?x:x.slice(0,E),E===-1?"":x.slice(E))}if(typeof n.protocol=="string"&&n.protocol&&(o=n.protocol),(typeof n.port=="number"||typeof n.port=="string"&&n.port)&&(a=String(n.port)),typeof n.hostname=="string"&&n.hostname)s=n.hostname;else if(typeof n.host=="string"&&n.host){const[x,E]=n.host.split(":");s=x??"",E&&!(typeof n.port=="number"||typeof n.port=="string")&&(a=E)}}return{host:s,method:p,path:r,hasQuery:c,protocol:o,port:a,pathname:l,search:u}}g(parseTarget,"parseTarget"),d(parseTarget,"parseTarget");
1
+ "use strict";var U=Object.defineProperty;var g=(e,t)=>U(e,"name",{value:t,configurable:!0});var P=Object.defineProperty,d=g((e,t)=>P(e,"name",{value:t,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.flushEgressCaptureForTests=flushEgressCaptureForTests,exports.tapEgress=tapEgress,exports.resetEgressTapForTests=resetEgressTapForTests;const redact_1=require("@lensmcp/core/redact"),http_exchange_1=require("@lensmcp/core/http-exchange"),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=d(e=>e===""||INTERNAL.some(t=>t.test(e)),"isInternal"),CAPTURE_QUERY=process.env.LENSMCP_EGRESS_QUERY==="1",MAX_PATH_CHARS=256,clipPath=d(e=>e.length>MAX_PATH_CHARS?`${e.slice(0,MAX_PATH_CHARS)}\u2026`:e,"clipPath");function capturePath(e,t){const s=e||"/";return!CAPTURE_QUERY||t.length<=1?clipPath(s):(0,redact_1.redactUrl)(`${s}${t}`)}g(capturePath,"capturePath"),d(capturePath,"capturePath");const fingerprintFor=d((e,t)=>t?`external:error:${e}`:`external:${e}`,"fingerprintFor"),PARENT_HEADER="x-lensmcp-parent-request-id",FLOW_HEADER="x-lensmcp-flow-id",ORIGIN_HEADER="x-lensmcp-origin-node-id";let hopsOutside=0;function hopHeaders(e,t){if(!e?.requestId&&!e?.flowId||t(http_exchange_1.LENS_REQUEST_ID_HEADER)||t(PARENT_HEADER)||t(FLOW_HEADER))return;const s={};if(e.requestId){const p=(0,flow_context_1.liveFlowContext)(),r=p?p.hopCount=(p.hopCount??0)+1:++hopsOutside;s[http_exchange_1.LENS_REQUEST_ID_HEADER]=`${e.requestId}.${r}`,s[PARENT_HEADER]=e.requestId}return e.flowId&&(s[FLOW_HEADER]=e.flowId),e.originNodeId&&(s[ORIGIN_HEADER]=e.originNodeId),s}g(hopHeaders,"hopHeaders"),d(hopHeaders,"hopHeaders");function isAiCall(e,t,s){return!!e&&t==="POST"&&!!(0,ai_providers_1.matchTarget)(e.hostname,e.port,e.pathname,s)}g(isAiCall,"isAiCall"),d(isAiCall,"isAiCall");function stampFetch(e,t,s){try{const p=t?.headers??(typeof e=="object"&&e!==null&&!(e instanceof URL)?e.headers:void 0),r=new Headers(p),c=hopHeaders(s,a=>r.has(a));if(!c)return{init:t};for(const[a,l]of Object.entries(c))r.set(a,l);const o=c[http_exchange_1.LENS_REQUEST_ID_HEADER];return{init:{...t,headers:r},...o?{calleeRequestId:o}:{}}}catch{return{init:t}}}g(stampFetch,"stampFetch"),d(stampFetch,"stampFetch");function stampRequest(e,t){try{if(e.headersSent||typeof e.setHeader!="function"||typeof e.getHeader!="function")return;const s=hopHeaders(t,p=>e.getHeader(p)!==void 0);if(!s)return;for(const[p,r]of Object.entries(s))e.setHeader(p,r);return s[http_exchange_1.LENS_REQUEST_ID_HEADER]}catch{return}}g(stampRequest,"stampRequest"),d(stampRequest,"stampRequest");const pendingExchanges=new Set;async function flushEgressCaptureForTests(){await Promise.allSettled([...pendingExchanges]),await(0,http_store_1.flushHttpExchanges)()}g(flushEgressCaptureForTests,"flushEgressCaptureForTests"),d(flushEgressCaptureForTests,"flushEgressCaptureForTests");async function finishExchange(e){const t=e.mode==="bodies"&&(0,http_store_1.proofBoundHeaders)(e.request.headers)?{...e,mode:"headers",responseFields:[]}:e,s=[],p=[],r=await(0,http_capture_1.requestPart)(t.request,t.url.search,t.mode,!!t.aiOpaque,p,s,!!t.ai&&!t.aiOpaque),c=t.reading?await t.reading.catch(()=>{}):void 0,{headers:o,redacted:a}=(0,http_store_1.redactHeaders)(t.responseHeaders??[]);s.push(...a);const l=typeof t.status=="number"?t.status:void 0,u={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,...l!==void 0?{status:l}:{},...t.statusText?{statusText:t.statusText}:{},...t.error?{error:t.error}:{},startedAt:t.startedAt,...t.ttfbMs!==void 0?{ttfbMs:t.ttfbMs}:{},durationMs:(c?.endedAt??Date.now())-t.startedAt,capture:t.mode==="bodies"?"bodies":"headers",request:r,response:{headers:o,...t.mode==="bodies"&&c?.body?{body:c.body}:{},...t.mode==="bodies"&&c?.stream?{stream:c.stream}:{}},redacted:{headers:[...new Set(s)],bodyFields:[...p.map(h=>`request.${h}`),...t.responseFields.map(h=>`response.${h}`)]},...t.ai?{ai:{provider:t.ai}}:{}};(0,http_store_1.queueHttpExchange)(u)}g(finishExchange,"finishExchange"),d(finishExchange,"finishExchange");function trackExchange(e){const t=(typeof e=="function"?new Promise(s=>setImmediate(s)).then(()=>finishExchange(e())):finishExchange(e)).catch(()=>{});pendingExchanges.add(t),t.finally(()=>pendingExchanges.delete(t))}g(trackExchange,"trackExchange"),d(trackExchange,"trackExchange");function tapEgress(){(0,http_store_1.primeHttpStore)(),tapFetch(),tapHttpModule("http"),tapHttpModule("https")}g(tapEgress,"tapEgress"),d(tapEgress,"tapEgress");let savedFetch;const httpOriginals=new Map;function resetEgressTapForTests(){const e=globalThis;savedFetch&&(e.fetch=savedFetch),delete e.__lensmcpFetchTap,restoreHttp("http"),restoreHttp("https"),savedFetch=void 0}g(resetEgressTapForTests,"resetEgressTapForTests"),d(resetEgressTapForTests,"resetEgressTapForTests");function restoreHttp(e){const t=httpOriginals.get(e);if(!t)return;const s=require(`node:${e}`);s.request=t.request,s.get=t.get,httpOriginals.delete(e)}g(restoreHttp,"restoreHttp"),d(restoreHttp,"restoreHttp");function tapFetch(){const e=globalThis;if(typeof e.fetch!="function"||e.__lensmcpFetchTap)return;e.__lensmcpFetchTap=!0;const t=e.fetch.bind(globalThis);savedFetch=e.fetch;const s=(0,http_store_1.httpCaptureMode)(),p=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS);e.fetch=(async(r,c)=>{let o="",a="/",l=!1,u;try{const i=new URL(typeof r=="string"?r:r instanceof URL?r.href:r.url);u=i,o=i.hostname,l=i.search.length>1,a=capturePath(i.pathname,i.search)}catch{}if(isInternal(o))return t(r,c);const h=Date.now(),f=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.method:void 0,n=String(c?.method??f??"GET").toUpperCase();isAiCall(u,n,p)&&(0,flow_context_1.startLiveFlow)();const x=(0,flow_context_1.flowContext)(),E=(0,http_exchange_1.isServiceHopHost)(o)?stampFetch(r,c,x):{init:c},_=E.init,q=E.calleeRequestId,R=(0,flow_context_1.liveFlowContext)();R&&(R.externalCallCount=(R.externalCallCount??0)+1);const y=s!=="off"&&u?(0,http_store_1.newExchangeId)():void 0,I=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.headers:void 0,$=s==="bodies"&&((0,http_store_1.proofBoundHeaders)(I)||(0,http_store_1.proofBoundHeaders)(_?.headers))?"headers":s,H=y&&u&&n==="POST"?(0,ai_providers_1.matchTarget)(o,u.port,u.pathname,p)?.provider:void 0,w=!!H&&(0,tap_ai_1.aiCaptureMode)()!=="content"&&!(0,capture_file_1.aiBodiesAsked)(),T=!!H&&!w,F=T&&!!u&&!/\/embeddings\/?$/.test(u.pathname),M=y?(0,http_capture_1.takeRequest)(r,_,$==="bodies",T):void 0,A=d(i=>({id:y,mode:$,method:n,url:u,path:u.pathname.length>256?`${u.pathname.slice(0,256)}\u2026`:u.pathname,startedAt:h,ctx:x,request:M,...H?{ai:H}:{},...w?{aiOpaque:w}:{},responseFields:[],...i}),"job");try{const i=await t(r,_),m=Date.now()-h,b=i.status>=500,C=[];let v;if(y&&$==="bodies")try{v=(0,http_capture_1.readResponse)(i,i.clone(),h,{ai:w,large:F,paths:C})}catch{v=void 0}const S=(0,emit_1.lensEmit)("external","info",`egress ${n} ${o} \u2192 ${i.status}`,{name:o,kind:"egress",method:n,host:o,path:a,status:i.status,...l?{hasQuery:!0}:{},startedAt:h,durationMs:m,...y?{exchangeId:y}:{},...q?{calleeRequestId:q}:{}},fingerprintFor(o,b),x);if(y&&S){const O={status:i.status,...i.statusText?{statusText:i.statusText}:{},responseHeaders:(0,http_capture_1.headerPairs)(i.headers)};trackExchange(A({...O,ttfbMs:m,responseFields:C,...v?{reading:v}:{}}))}return i}catch(i){const m=String(i?.message??i),b=(0,emit_1.lensEmit)("external","error",`egress ${n} ${o} failed`,{name:o,kind:"egress",method:n,host:o,path:a,...l?{hasQuery:!0}:{},error:m,startedAt:h,durationMs:Date.now()-h,...y?{exchangeId:y}:{},...q?{calleeRequestId:q}:{}},fingerprintFor(o,!0),x);throw y&&b&&trackExchange(A({error:m})),i}})}g(tapFetch,"tapFetch"),d(tapFetch,"tapFetch");function tapHttpModule(e){const t=require(`node:${e}`),s=t.request;if(typeof s!="function"||s.__lensmcp)return;httpOriginals.set(e,{request:s,get:t.get});const p=(0,http_store_1.httpCaptureMode)(),r=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS),c=d(function(...o){const a=s.apply(this,o);try{observe(e,o,a,p,r)}catch{}return a},"wrapped");c.__lensmcp=!0,t.request=c,typeof t.get=="function"&&(t.get=function(...o){const a=c.apply(this,o);return a.end(),a})}g(tapHttpModule,"tapHttpModule"),d(tapHttpModule,"tapHttpModule");const headersOf=d(e=>{try{return e.getHeaders?.()}catch{return}},"headersOf"),optionsWithProof=d(e=>!!e&&typeof e=="object"&&!(e instanceof URL)&&(0,http_store_1.proofBoundHeaders)(e.headers),"optionsWithProof"),headerOf=d((e,t)=>{const s=e?.[t];return Array.isArray(s)?s.join(", "):s??""},"headerOf");function teeRequest(e,t,s,p=!1){const r=t?new http_capture_1.WrittenBody(!s,p):void 0;let c,o=!1;const a=e.write;r&&typeof a=="function"&&(e.write=function(u,...h){try{o||r.take(u,h[0])}catch{}return a.call(this,u,...h)});const l=e.end;return e.end=function(u,...h){try{o||(o=!0,r?.take(u,h[0]),c=headersOf(e))}catch{}return l.call(this,u,...h)},()=>(0,http_capture_1.writtenRequest)(c??headersOf(e),r)}g(teeRequest,"teeRequest"),d(teeRequest,"teeRequest");function teeResponse(e,t,s){let p=!1;const r=d(a=>{if(p)return;p=!0,clearTimeout(c);const l=Date.now();s(()=>t.size?t.finish(a,l):{endedAt:l})},"finish"),c=setTimeout(()=>r("time"),t.readMs);c.unref?.();const o=e.emit;e.emit=function(a,...l){try{return o.call(this,a,...l)}finally{try{if(a==="data"){const u=p?void 0:(0,http_capture_1.chunkBytes)(l[0],e.readableEncoding);u&&!t.push(u)&&r(!1)}else a==="end"?r(!1):(a==="aborted"||a==="error"||a==="close")&&r(!0)}catch{}}}}g(teeResponse,"teeResponse"),d(teeResponse,"teeResponse");function observe(e,t,s,p,r){const c=parseTarget(t,e),{host:o,method:a,path:l,hasQuery:u}=c;if(isInternal(o))return;const h=Date.now();isAiCall(targetUrl(c),a,r)&&(0,flow_context_1.startLiveFlow)();const f=(0,flow_context_1.flowContext)(),n=(0,http_exchange_1.isServiceHopHost)(o)?stampRequest(s,f):void 0,x=(0,flow_context_1.liveFlowContext)();x&&(x.externalCallCount=(x.externalCallCount??0)+1);const E=p!=="off"?targetUrl(c):void 0,_=E?(0,http_store_1.newExchangeId)():void 0;let q=p==="bodies"&&((0,http_store_1.proofBoundHeaders)(headersOf(s))||t.some(optionsWithProof))?"headers":p;const R=_&&E&&a==="POST"?(0,ai_providers_1.matchTarget)(o,E.port,E.pathname,r)?.provider:void 0,y=!!R&&(0,tap_ai_1.aiCaptureMode)()!=="content"&&!(0,capture_file_1.aiBodiesAsked)(),I=!!R&&!y,$=I&&!!E&&!/\/embeddings\/?$/.test(E.pathname),H=_?teeRequest(s,q==="bodies",y,I):void 0,w=d(i=>({id:_,mode:q,method:a,url:E,path:clipPath(E.pathname),startedAt:h,ctx:f,request:H(),...R?{ai:R}:{},...y?{aiOpaque:y}:{},responseFields:[],...i}),"job");let T=!1;const F=d(i=>{if(T)return;T=!0,q==="bodies"&&(0,http_store_1.proofBoundHeaders)(headersOf(s))&&(q="headers");const m=i?.statusCode,b=Date.now()-h,C=(0,emit_1.lensEmit)("external","info",`egress ${a} ${o} \u2192 ${m??"?"}`,{name:o,kind:"egress",method:a,host:o,path:l,...m!=null?{status:m}:{},...u?{hasQuery:!0}:{},startedAt:h,durationMs:b,..._?{exchangeId:_}:{},...n?{calleeRequestId:n}:{}},fingerprintFor(o,m!=null&&m>=500),f);if(!_||!C||!i||typeof i.emit!="function")return;const v={...m!=null?{status:m}:{},...i.statusMessage?{statusText:i.statusMessage}:{},responseHeaders:(0,http_capture_1.headerPairs)(i.headers),ttfbMs:b};if(q!=="bodies"){trackExchange(()=>w(v));return}const S=[],O=new http_capture_1.ResponseSink(headerOf(i.headers,"content-type"),h,{ai:y,large:$,paths:S,encoding:headerOf(i.headers,"content-encoding")});teeResponse(i,O,D=>trackExchange(()=>w({...v,responseFields:S,reading:Promise.resolve(D())})))},"onResponse"),M=d(i=>{if(T)return;T=!0;const m=String(i?.message??i),b=(0,emit_1.lensEmit)("external","error",`egress ${a} ${o} failed`,{name:o,kind:"egress",method:a,host:o,path:l,...u?{hasQuery:!0}:{},error:m,startedAt:h,durationMs:Date.now()-h,..._?{exchangeId:_}:{},...n?{calleeRequestId:n}:{}},fingerprintFor(o,!0),f);_&&b&&trackExchange(()=>w({error:m}))},"onError"),A=s.emit;s.emit=function(i,...m){try{i==="response"?F(m[0]):i==="error"&&M(m[0])}catch{}return A.call(this,i,...m)}}g(observe,"observe"),d(observe,"observe");function targetUrl(e){try{const t=e.host.includes(":")&&!e.host.startsWith("[")?`[${e.host}]`:e.host,s=e.pathname.startsWith("/")?e.pathname:`/${e.pathname}`;return new URL(`${e.protocol}//${t}${e.port?`:${e.port}`:""}${s}${e.search}`)}catch{return}}g(targetUrl,"targetUrl"),d(targetUrl,"targetUrl");function parseTarget(e,t="http"){let s="",p="GET",r="/",c=!1,o=`${t}:`,a="",l="/",u="";const h=d((f,n)=>{c=n.length>1,r=capturePath(f,n),l=f||"/",u=n},"take");for(const f of e)if(typeof f=="string")try{const n=new URL(f);s=n.hostname,o=n.protocol,a=n.port,h(n.pathname,n.search)}catch{}else if(f instanceof URL)s=f.hostname,o=f.protocol,a=f.port,h(f.pathname,f.search);else if(f&&typeof f=="object"){const n=f;if(typeof n.method=="string"&&(p=n.method.toUpperCase()),typeof n.socketPath=="string")return{host:"",method:p,path:r,hasQuery:c,protocol:o,port:a,pathname:l,search:u};if(typeof n.path=="string"){const x=n.path,E=x.indexOf("?");h(E===-1?x:x.slice(0,E),E===-1?"":x.slice(E))}if(typeof n.protocol=="string"&&n.protocol&&(o=n.protocol),(typeof n.port=="number"||typeof n.port=="string"&&n.port)&&(a=String(n.port)),typeof n.hostname=="string"&&n.hostname)s=n.hostname;else if(typeof n.host=="string"&&n.host){const[x,E]=n.host.split(":");s=x??"",E&&!(typeof n.port=="number"||typeof n.port=="string")&&(a=E)}}return{host:s,method:p,path:r,hasQuery:c,protocol:o,port:a,pathname:l,search:u}}g(parseTarget,"parseTarget"),d(parseTarget,"parseTarget");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lensmcp/node-instrumentation",
3
- "version": "1.26.23",
3
+ "version": "1.26.25",
4
4
  "main": "./index.js",
5
5
  "types": "./index.d.ts",
6
6
  "exports": {
@@ -19,9 +19,9 @@
19
19
  }
20
20
  },
21
21
  "dependencies": {
22
- "@lensmcp/core": "1.26.23",
23
- "@lensmcp/nest-instrumentation": "1.26.23",
24
- "@lensmcp/protocol-types": "1.26.23",
22
+ "@lensmcp/core": "1.26.25",
23
+ "@lensmcp/nest-instrumentation": "1.26.25",
24
+ "@lensmcp/protocol-types": "1.26.25",
25
25
  "tslib": "^2.3.0"
26
26
  },
27
27
  "optionalDependencies": {