@lensmcp/node-instrumentation 1.25.1 → 1.25.2

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.js CHANGED
@@ -1 +1 @@
1
- "use strict";var s=Object.defineProperty;var i=(t,r)=>s(t,"name",{value:r,configurable:!0});var p=Object.defineProperty,o=i((t,r)=>p(t,"name",{value:r,configurable:!0}),"o"),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 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 +1 @@
1
- "use strict";var v=Object.defineProperty;var r=(t,e)=>v(t,"name",{value:e,configurable:!0});var a=Object.defineProperty,o=r((t,e)=>a(t,"name",{value:e,configurable:!0}),"o"),i=Object.defineProperty,n=o((t,e)=>i(t,"name",{value:e,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.beginActiveWorkGeneration=beginActiveWorkGeneration,exports.activeWorkGeneration=activeWorkGeneration,exports.beginActiveWork=beginActiveWork,exports.activeWorkSnapshot=activeWorkSnapshot,exports.installActiveWorkProbe=installActiveWorkProbe,exports.resetActiveWorkForTests=resetActiveWorkForTests;const GLOBAL_KEY="__lensmcpActiveWork",running=new Set;let currentGeneration=0;function beginActiveWorkGeneration(){return++currentGeneration}r(beginActiveWorkGeneration,"beginActiveWorkGeneration"),o(beginActiveWorkGeneration,"beginActiveWorkGeneration"),n(beginActiveWorkGeneration,"beginActiveWorkGeneration");function activeWorkGeneration(){return currentGeneration}r(activeWorkGeneration,"activeWorkGeneration"),o(activeWorkGeneration,"activeWorkGeneration"),n(activeWorkGeneration,"activeWorkGeneration");function beginActiveWork(t){const e={at:Date.now(),...t===void 0?{}:{gen:t}};running.add(e);let c=!1;return()=>{c||(c=!0,running.delete(e))}}r(beginActiveWork,"beginActiveWork"),o(beginActiveWork,"beginActiveWork"),n(beginActiveWork,"beginActiveWork");function activeWorkSnapshot(t){let e,c=0;for(const s of running)t!==void 0&&s.gen!==void 0&&s.gen!==t||(c+=1,(e===void 0||s.at<e)&&(e=s.at));return{count:c,...e===void 0?{}:{oldestStartedAt:e}}}r(activeWorkSnapshot,"activeWorkSnapshot"),o(activeWorkSnapshot,"activeWorkSnapshot"),n(activeWorkSnapshot,"activeWorkSnapshot");function installActiveWorkProbe(){globalThis[GLOBAL_KEY]=activeWorkSnapshot,globalThis.__lensmcpBeginWorkGeneration=beginActiveWorkGeneration}r(installActiveWorkProbe,"installActiveWorkProbe"),o(installActiveWorkProbe,"installActiveWorkProbe"),n(installActiveWorkProbe,"installActiveWorkProbe");function resetActiveWorkForTests(){running.clear(),currentGeneration=0}r(resetActiveWorkForTests,"resetActiveWorkForTests"),o(resetActiveWorkForTests,"resetActiveWorkForTests"),n(resetActiveWorkForTests,"resetActiveWorkForTests");
1
+ "use strict";var a=Object.defineProperty;var o=(t,e)=>a(t,"name",{value:e,configurable:!0});var i=Object.defineProperty,n=o((t,e)=>i(t,"name",{value:e,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.beginActiveWorkGeneration=beginActiveWorkGeneration,exports.activeWorkGeneration=activeWorkGeneration,exports.beginActiveWork=beginActiveWork,exports.activeWorkSnapshot=activeWorkSnapshot,exports.installActiveWorkProbe=installActiveWorkProbe,exports.resetActiveWorkForTests=resetActiveWorkForTests;const GLOBAL_KEY="__lensmcpActiveWork",running=new Set;let currentGeneration=0;function beginActiveWorkGeneration(){return++currentGeneration}o(beginActiveWorkGeneration,"beginActiveWorkGeneration"),n(beginActiveWorkGeneration,"beginActiveWorkGeneration");function activeWorkGeneration(){return currentGeneration}o(activeWorkGeneration,"activeWorkGeneration"),n(activeWorkGeneration,"activeWorkGeneration");function beginActiveWork(t){const e={at:Date.now(),...t===void 0?{}:{gen:t}};running.add(e);let r=!1;return()=>{r||(r=!0,running.delete(e))}}o(beginActiveWork,"beginActiveWork"),n(beginActiveWork,"beginActiveWork");function activeWorkSnapshot(t){let e,r=0;for(const c of running)t!==void 0&&c.gen!==void 0&&c.gen!==t||(r+=1,(e===void 0||c.at<e)&&(e=c.at));return{count:r,...e===void 0?{}:{oldestStartedAt:e}}}o(activeWorkSnapshot,"activeWorkSnapshot"),n(activeWorkSnapshot,"activeWorkSnapshot");function installActiveWorkProbe(){globalThis[GLOBAL_KEY]=activeWorkSnapshot,globalThis.__lensmcpBeginWorkGeneration=beginActiveWorkGeneration}o(installActiveWorkProbe,"installActiveWorkProbe"),n(installActiveWorkProbe,"installActiveWorkProbe");function resetActiveWorkForTests(){running.clear(),currentGeneration=0}o(resetActiveWorkForTests,"resetActiveWorkForTests"),n(resetActiveWorkForTests,"resetActiveWorkForTests");
@@ -1,16 +1,16 @@
1
- "use strict";var z=Object.defineProperty;var _=(t,e)=>z(t,"name",{value:e,configurable:!0});var j=Object.defineProperty,d=_((t,e)=>j(t,"name",{value:e,configurable:!0}),"d"),M=Object.defineProperty,u=d((t,e)=>M(t,"name",{value:e,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseExtraHosts=parseExtraHosts,exports.matchTarget=matchTarget,exports.flattenContent=flattenContent,exports.normalizeRequest=normalizeRequest,exports.mapUsage=mapUsage,exports.normalizeResponse=normalizeResponse,exports.createStreamAccumulator=createStreamAccumulator;const isObj=u(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),"isObj"),asArr=u(t=>Array.isArray(t)?t:[],"asArr"),asStr=u(t=>typeof t=="string"?t:void 0,"asStr"),asNum=u(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"asNum"),MAX_ACCUMULATED_CHARS=512*1024,MAX_EVENT_BUFFER_CHARS=1024*1024,MAX_BLOCK_JSON_CHARS=2e3,KNOWN_HOSTS=[{test:/^api\.openai\.com$/i,provider:"openai"},{test:/\.openai\.azure\.com$/i,provider:"openai"},{test:/^api\.anthropic\.com$/i,provider:"anthropic"}],authorityOf=u(t=>t.trim().toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//,"").replace(/[/?#].*$/,""),"authorityOf");function parseExtraHosts(t){const e=new Map;for(const o of(t??"").split(",")){const a=o.lastIndexOf("=");if(a===-1)continue;const n=authorityOf(o.slice(0,a)),i=o.slice(a+1).trim().toLowerCase();n&&(i==="openai"||i==="anthropic")&&e.set(n,i)}return e}_(parseExtraHosts,"parseExtraHosts"),d(parseExtraHosts,"parseExtraHosts"),u(parseExtraHosts,"parseExtraHosts");function apiFor(t,e){const o=e.replace(/\/+$/,"").toLowerCase();if(t==="anthropic")return o.endsWith("/messages")?"messages":void 0;if(o.endsWith("/chat/completions"))return"chat";if(o.endsWith("/responses"))return"responses";if(o.endsWith("/embeddings"))return"embeddings"}_(apiFor,"apiFor"),d(apiFor,"apiFor"),u(apiFor,"apiFor");function matchTarget(t,e,o,a){const n=t.toLowerCase(),i=a.get(e?`${n}:${e}`:n)??a.get(n)??KNOWN_HOSTS.find(p=>p.test.test(n))?.provider;if(!i)return;const c=apiFor(i,o);return c?{provider:i,api:c}:void 0}_(matchTarget,"matchTarget"),d(matchTarget,"matchTarget"),u(matchTarget,"matchTarget");function jsonText(t,e=MAX_BLOCK_JSON_CHARS){try{const o=JSON.stringify(t);return o===void 0?"":o.length>e?`${o.slice(0,e)}\u2026`:o}catch{return""}}_(jsonText,"jsonText"),d(jsonText,"jsonText"),u(jsonText,"jsonText");const argsText=u(t=>typeof t=="string"?t:t==null?void 0:jsonText(t,8192),"argsText");function flattenContent(t){if(t==null)return"";if(typeof t=="string")return t;if(!Array.isArray(t))return jsonText(t);const e=[];for(const o of t){if(typeof o=="string"){e.push(o);continue}if(!isObj(o))continue;const a=asStr(o.type)??"";switch(a){case"text":case"input_text":case"output_text":e.push(asStr(o.text)??"");break;case"refusal":e.push(`[refusal] ${asStr(o.refusal)??""}`);break;case"image_url":case"image":case"input_image":e.push("[image]");break;case"input_audio":case"audio":e.push("[audio]");break;case"file":case"input_file":case"document":e.push("[file]");break;case"tool_use":e.push(`[tool_use ${asStr(o.name)??""} ${jsonText(o.input)}]`);break;case"tool_result":e.push(`[tool_result ${flattenContent(o.content)}]`);break;case"thinking":e.push(`[thinking] ${asStr(o.thinking)??""}`);break;case"redacted_thinking":e.push("[redacted_thinking]");break;default:e.push(asStr(o.text)??`[${a||"part"}]`)}}return e.filter(o=>o!=="").join(`
2
- `)}_(flattenContent,"flattenContent"),d(flattenContent,"flattenContent"),u(flattenContent,"flattenContent");const SCALAR_PARAMS={chat:["temperature","top_p","max_tokens","max_completion_tokens","n","seed","presence_penalty","frequency_penalty","tool_choice","reasoning_effort","service_tier"],responses:["temperature","top_p","max_output_tokens","tool_choice","parallel_tool_calls","service_tier"],messages:["max_tokens","temperature","top_p","top_k"],embeddings:["dimensions","encoding_format"]};function scalarParams(t,e){const o={};for(const p of SCALAR_PARAMS[e]){const h=t[p];(typeof h=="string"||typeof h=="number"||typeof h=="boolean")&&(o[p]=h)}const a=t.reasoning;isObj(a)&&typeof a.effort=="string"&&(o.reasoning_effort=a.effort);const n=t.thinking;isObj(n)&&(typeof n.type=="string"&&(o.thinking=n.type),typeof n.budget_tokens=="number"&&(o.thinking_budget_tokens=n.budget_tokens));const i=t.response_format;isObj(i)&&typeof i.type=="string"&&(o.response_format=i.type);const c=t.tool_choice;return isObj(c)&&typeof c.type=="string"&&(o.tool_choice=c.type),o}_(scalarParams,"scalarParams"),d(scalarParams,"scalarParams"),u(scalarParams,"scalarParams");function toolsOf(t){const e=[];for(const o of asArr(t.tools)){if(!isObj(o))continue;const a=isObj(o.function)?o.function:void 0,n=asStr(a?.name)??asStr(o.name)??asStr(o.type);if(!n)continue;const i=asStr(a?.description)??asStr(o.description);e.push(i?{name:n,description:i}:{name:n})}return e}_(toolsOf,"toolsOf"),d(toolsOf,"toolsOf"),u(toolsOf,"toolsOf");function chatMessage(t){let e=flattenContent(t.content);for(const o of asArr(t.tool_calls)){if(!isObj(o))continue;const a=isObj(o.function)?o.function:{};e+=`${e?`
3
- `:""}[tool_call ${asStr(a.name)??""} ${asStr(a.arguments)??""}]`}return{role:asStr(t.role)??"unknown",content:e}}_(chatMessage,"chatMessage"),d(chatMessage,"chatMessage"),u(chatMessage,"chatMessage");function responsesInput(t){if(typeof t=="string")return[{role:"user",content:t}];const e=[];for(const o of asArr(t)){if(!isObj(o))continue;const a=asStr(o.type);a==="function_call_output"?e.push({role:"tool",content:flattenContent(o.output)}):a==="function_call"?e.push({role:"assistant",content:`[tool_call ${asStr(o.name)??""} ${asStr(o.arguments)??""}]`}):e.push({role:asStr(o.role)??a??"user",content:flattenContent(o.content)})}return e}_(responsesInput,"responsesInput"),d(responsesInput,"responsesInput"),u(responsesInput,"responsesInput");function normalizeRequest(t,e){const o={messages:[],tools:[],params:{},stream:!1};if(!isObj(e))return o;const a={...o,...asStr(e.model)?{model:asStr(e.model)}:{},stream:e.stream===!0,params:scalarParams(e,t.api),tools:toolsOf(e)};switch(t.api){case"chat":a.messages=asArr(e.messages).filter(isObj).map(chatMessage);break;case"responses":{const n=asStr(e.instructions);n&&(a.system=n),a.messages=responsesInput(e.input);break}case"messages":{const n=e.system,i=typeof n=="string"?n:flattenContent(n);i&&(a.system=i),a.messages=asArr(e.messages).filter(isObj).map(c=>({role:asStr(c.role)??"unknown",content:flattenContent(c.content)}));break}case"embeddings":{const n=e.input;a.inputCount=Array.isArray(n)?n.length:n===void 0?0:1;break}}return a}_(normalizeRequest,"normalizeRequest"),d(normalizeRequest,"normalizeRequest"),u(normalizeRequest,"normalizeRequest");function mapUsage(t,e=!0){if(!isObj(t))return{};const o=isObj(t.prompt_tokens_details)?t.prompt_tokens_details:isObj(t.input_tokens_details)?t.input_tokens_details:{},a=isObj(t.completion_tokens_details)?t.completion_tokens_details:isObj(t.output_tokens_details)?t.output_tokens_details:{},n={},i=asNum(t.prompt_tokens)??asNum(t.input_tokens),c=asNum(t.completion_tokens)??asNum(t.output_tokens),p=asNum(o.cached_tokens)??asNum(t.cache_read_input_tokens),h=asNum(a.reasoning_tokens);i!==void 0&&(n.promptTokens=i),c!==void 0&&(n.completionTokens=c),p!==void 0&&(n.cachedTokens=p),h!==void 0&&(n.reasoningTokens=h);const m=asNum(t.total_tokens);return m!==void 0?n.totalTokens=m:e&&i!==void 0&&c!==void 0&&(n.totalTokens=i+c),n}_(mapUsage,"mapUsage"),d(mapUsage,"mapUsage"),u(mapUsage,"mapUsage");const withTotal=u(t=>t.totalTokens===void 0&&t.promptTokens!==void 0&&t.completionTokens!==void 0?{...t,totalTokens:t.promptTokens+t.completionTokens}:t,"withTotal");function errorMessage(t){const e=t.error;if(typeof e=="string")return e;if(isObj(e))return asStr(e.message)??asStr(e.type)??asStr(e.code)}_(errorMessage,"errorMessage"),d(errorMessage,"errorMessage"),u(errorMessage,"errorMessage");function normalizeResponse(t,e){const o={completion:"",toolCalls:[],usage:{}};if(!isObj(e))return o;const a=asStr(e.id),n=asStr(e.model);a&&(o.id=a),n&&(o.model=n);const i=errorMessage(e);switch(i&&(o.error=i),o.usage=mapUsage(e.usage),t.api){case"chat":{const c=asArr(e.choices).find(isObj),p=c&&isObj(c.message)?c.message:void 0;if(p){o.completion=flattenContent(p.content);const m=asStr(p.refusal);m&&(o.completion+=`${o.completion?`
4
- `:""}[refusal] ${m}`);const k=asStr(p.reasoning_content)??asStr(p.reasoning);k&&(o.reasoning=k);for(const y of asArr(p.tool_calls)){if(!isObj(y))continue;const v=isObj(y.function)?y.function:{},C=argsText(v.arguments);o.toolCalls.push({...asStr(y.id)?{id:asStr(y.id)}:{},name:asStr(v.name)??"tool",...C!==void 0?{arguments:C}:{}})}const f=isObj(p.function_call)?p.function_call:void 0;if(f){const y=argsText(f.arguments);o.toolCalls.push({name:asStr(f.name)??"tool",...y!==void 0?{arguments:y}:{}})}}const h=asStr(c?.finish_reason);h&&(o.finishReason=h);break}case"responses":{const c=[],p=[];for(const f of asArr(e.output)){if(!isObj(f))continue;const y=asStr(f.type);if(y==="message")c.push(flattenContent(f.content));else if(y==="function_call")o.toolCalls.push({...asStr(f.call_id)??asStr(f.id)?{id:asStr(f.call_id)??asStr(f.id)}:{},name:asStr(f.name)??"tool",...asStr(f.arguments)!==void 0?{arguments:asStr(f.arguments)}:{}});else if(y==="reasoning")for(const v of asArr(f.summary))isObj(v)&&asStr(v.text)&&p.push(asStr(v.text))}o.completion=c.filter(Boolean).join(`
1
+ "use strict";var j=Object.defineProperty;var d=(t,e)=>j(t,"name",{value:e,configurable:!0});var M=Object.defineProperty,u=d((t,e)=>M(t,"name",{value:e,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseExtraHosts=parseExtraHosts,exports.matchTarget=matchTarget,exports.flattenContent=flattenContent,exports.normalizeRequest=normalizeRequest,exports.mapUsage=mapUsage,exports.normalizeResponse=normalizeResponse,exports.createStreamAccumulator=createStreamAccumulator;const isObj=u(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),"isObj"),asArr=u(t=>Array.isArray(t)?t:[],"asArr"),asStr=u(t=>typeof t=="string"?t:void 0,"asStr"),asNum=u(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"asNum"),MAX_ACCUMULATED_CHARS=512*1024,MAX_EVENT_BUFFER_CHARS=1024*1024,MAX_BLOCK_JSON_CHARS=2e3,KNOWN_HOSTS=[{test:/^api\.openai\.com$/i,provider:"openai"},{test:/\.openai\.azure\.com$/i,provider:"openai"},{test:/^api\.anthropic\.com$/i,provider:"anthropic"}],authorityOf=u(t=>t.trim().toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//,"").replace(/[/?#].*$/,""),"authorityOf");function parseExtraHosts(t){const e=new Map;for(const o of(t??"").split(",")){const a=o.lastIndexOf("=");if(a===-1)continue;const n=authorityOf(o.slice(0,a)),r=o.slice(a+1).trim().toLowerCase();n&&(r==="openai"||r==="anthropic")&&e.set(n,r)}return e}d(parseExtraHosts,"parseExtraHosts"),u(parseExtraHosts,"parseExtraHosts");function apiFor(t,e){const o=e.replace(/\/+$/,"").toLowerCase();if(t==="anthropic")return o.endsWith("/messages")?"messages":void 0;if(o.endsWith("/chat/completions"))return"chat";if(o.endsWith("/responses"))return"responses";if(o.endsWith("/embeddings"))return"embeddings"}d(apiFor,"apiFor"),u(apiFor,"apiFor");function matchTarget(t,e,o,a){const n=t.toLowerCase(),r=a.get(e?`${n}:${e}`:n)??a.get(n)??KNOWN_HOSTS.find(p=>p.test.test(n))?.provider;if(!r)return;const c=apiFor(r,o);return c?{provider:r,api:c}:void 0}d(matchTarget,"matchTarget"),u(matchTarget,"matchTarget");function jsonText(t,e=MAX_BLOCK_JSON_CHARS){try{const o=JSON.stringify(t);return o===void 0?"":o.length>e?`${o.slice(0,e)}\u2026`:o}catch{return""}}d(jsonText,"jsonText"),u(jsonText,"jsonText");const argsText=u(t=>typeof t=="string"?t:t==null?void 0:jsonText(t,8192),"argsText");function flattenContent(t){if(t==null)return"";if(typeof t=="string")return t;if(!Array.isArray(t))return jsonText(t);const e=[];for(const o of t){if(typeof o=="string"){e.push(o);continue}if(!isObj(o))continue;const a=asStr(o.type)??"";switch(a){case"text":case"input_text":case"output_text":e.push(asStr(o.text)??"");break;case"refusal":e.push(`[refusal] ${asStr(o.refusal)??""}`);break;case"image_url":case"image":case"input_image":e.push("[image]");break;case"input_audio":case"audio":e.push("[audio]");break;case"file":case"input_file":case"document":e.push("[file]");break;case"tool_use":e.push(`[tool_use ${asStr(o.name)??""} ${jsonText(o.input)}]`);break;case"tool_result":e.push(`[tool_result ${flattenContent(o.content)}]`);break;case"thinking":e.push(`[thinking] ${asStr(o.thinking)??""}`);break;case"redacted_thinking":e.push("[redacted_thinking]");break;default:e.push(asStr(o.text)??`[${a||"part"}]`)}}return e.filter(o=>o!=="").join(`
2
+ `)}d(flattenContent,"flattenContent"),u(flattenContent,"flattenContent");const SCALAR_PARAMS={chat:["temperature","top_p","max_tokens","max_completion_tokens","n","seed","presence_penalty","frequency_penalty","tool_choice","reasoning_effort","service_tier"],responses:["temperature","top_p","max_output_tokens","tool_choice","parallel_tool_calls","service_tier"],messages:["max_tokens","temperature","top_p","top_k"],embeddings:["dimensions","encoding_format"]};function scalarParams(t,e){const o={};for(const p of SCALAR_PARAMS[e]){const _=t[p];(typeof _=="string"||typeof _=="number"||typeof _=="boolean")&&(o[p]=_)}const a=t.reasoning;isObj(a)&&typeof a.effort=="string"&&(o.reasoning_effort=a.effort);const n=t.thinking;isObj(n)&&(typeof n.type=="string"&&(o.thinking=n.type),typeof n.budget_tokens=="number"&&(o.thinking_budget_tokens=n.budget_tokens));const r=t.response_format;isObj(r)&&typeof r.type=="string"&&(o.response_format=r.type);const c=t.tool_choice;return isObj(c)&&typeof c.type=="string"&&(o.tool_choice=c.type),o}d(scalarParams,"scalarParams"),u(scalarParams,"scalarParams");function toolsOf(t){const e=[];for(const o of asArr(t.tools)){if(!isObj(o))continue;const a=isObj(o.function)?o.function:void 0,n=asStr(a?.name)??asStr(o.name)??asStr(o.type);if(!n)continue;const r=asStr(a?.description)??asStr(o.description);e.push(r?{name:n,description:r}:{name:n})}return e}d(toolsOf,"toolsOf"),u(toolsOf,"toolsOf");function chatMessage(t){let e=flattenContent(t.content);for(const o of asArr(t.tool_calls)){if(!isObj(o))continue;const a=isObj(o.function)?o.function:{};e+=`${e?`
3
+ `:""}[tool_call ${asStr(a.name)??""} ${asStr(a.arguments)??""}]`}return{role:asStr(t.role)??"unknown",content:e}}d(chatMessage,"chatMessage"),u(chatMessage,"chatMessage");function responsesInput(t){if(typeof t=="string")return[{role:"user",content:t}];const e=[];for(const o of asArr(t)){if(!isObj(o))continue;const a=asStr(o.type);a==="function_call_output"?e.push({role:"tool",content:flattenContent(o.output)}):a==="function_call"?e.push({role:"assistant",content:`[tool_call ${asStr(o.name)??""} ${asStr(o.arguments)??""}]`}):e.push({role:asStr(o.role)??a??"user",content:flattenContent(o.content)})}return e}d(responsesInput,"responsesInput"),u(responsesInput,"responsesInput");function normalizeRequest(t,e){const o={messages:[],tools:[],params:{},stream:!1};if(!isObj(e))return o;const a={...o,...asStr(e.model)?{model:asStr(e.model)}:{},stream:e.stream===!0,params:scalarParams(e,t.api),tools:toolsOf(e)};switch(t.api){case"chat":a.messages=asArr(e.messages).filter(isObj).map(chatMessage);break;case"responses":{const n=asStr(e.instructions);n&&(a.system=n),a.messages=responsesInput(e.input);break}case"messages":{const n=e.system,r=typeof n=="string"?n:flattenContent(n);r&&(a.system=r),a.messages=asArr(e.messages).filter(isObj).map(c=>({role:asStr(c.role)??"unknown",content:flattenContent(c.content)}));break}case"embeddings":{const n=e.input;a.inputCount=Array.isArray(n)?n.length:n===void 0?0:1;break}}return a}d(normalizeRequest,"normalizeRequest"),u(normalizeRequest,"normalizeRequest");function mapUsage(t,e=!0){if(!isObj(t))return{};const o=isObj(t.prompt_tokens_details)?t.prompt_tokens_details:isObj(t.input_tokens_details)?t.input_tokens_details:{},a=isObj(t.completion_tokens_details)?t.completion_tokens_details:isObj(t.output_tokens_details)?t.output_tokens_details:{},n={},r=asNum(t.prompt_tokens)??asNum(t.input_tokens),c=asNum(t.completion_tokens)??asNum(t.output_tokens),p=asNum(o.cached_tokens)??asNum(t.cache_read_input_tokens),_=asNum(a.reasoning_tokens);r!==void 0&&(n.promptTokens=r),c!==void 0&&(n.completionTokens=c),p!==void 0&&(n.cachedTokens=p),_!==void 0&&(n.reasoningTokens=_);const f=asNum(t.total_tokens);return f!==void 0?n.totalTokens=f:e&&r!==void 0&&c!==void 0&&(n.totalTokens=r+c),n}d(mapUsage,"mapUsage"),u(mapUsage,"mapUsage");const withTotal=u(t=>t.totalTokens===void 0&&t.promptTokens!==void 0&&t.completionTokens!==void 0?{...t,totalTokens:t.promptTokens+t.completionTokens}:t,"withTotal");function errorMessage(t){const e=t.error;if(typeof e=="string")return e;if(isObj(e))return asStr(e.message)??asStr(e.type)??asStr(e.code)}d(errorMessage,"errorMessage"),u(errorMessage,"errorMessage");function normalizeResponse(t,e){const o={completion:"",toolCalls:[],usage:{}};if(!isObj(e))return o;const a=asStr(e.id),n=asStr(e.model);a&&(o.id=a),n&&(o.model=n);const r=errorMessage(e);switch(r&&(o.error=r),o.usage=mapUsage(e.usage),t.api){case"chat":{const c=asArr(e.choices).find(isObj),p=c&&isObj(c.message)?c.message:void 0;if(p){o.completion=flattenContent(p.content);const f=asStr(p.refusal);f&&(o.completion+=`${o.completion?`
4
+ `:""}[refusal] ${f}`);const h=asStr(p.reasoning_content)??asStr(p.reasoning);h&&(o.reasoning=h);for(const k of asArr(p.tool_calls)){if(!isObj(k))continue;const y=isObj(k.function)?k.function:{},b=argsText(y.arguments);o.toolCalls.push({...asStr(k.id)?{id:asStr(k.id)}:{},name:asStr(y.name)??"tool",...b!==void 0?{arguments:b}:{}})}const m=isObj(p.function_call)?p.function_call:void 0;if(m){const k=argsText(m.arguments);o.toolCalls.push({name:asStr(m.name)??"tool",...k!==void 0?{arguments:k}:{}})}}const _=asStr(c?.finish_reason);_&&(o.finishReason=_);break}case"responses":{const c=[],p=[];for(const m of asArr(e.output)){if(!isObj(m))continue;const k=asStr(m.type);if(k==="message")c.push(flattenContent(m.content));else if(k==="function_call")o.toolCalls.push({...asStr(m.call_id)??asStr(m.id)?{id:asStr(m.call_id)??asStr(m.id)}:{},name:asStr(m.name)??"tool",...asStr(m.arguments)!==void 0?{arguments:asStr(m.arguments)}:{}});else if(k==="reasoning")for(const y of asArr(m.summary))isObj(y)&&asStr(y.text)&&p.push(asStr(y.text))}o.completion=c.filter(Boolean).join(`
5
5
  `),p.length&&(o.reasoning=p.join(`
6
- `));const h=isObj(e.incomplete_details)?asStr(e.incomplete_details.reason):void 0,m=asStr(e.status),k=h??m;k&&(o.finishReason=k),!o.error&&isObj(e.error)&&(o.error=errorMessage(e));break}case"messages":{const c=[],p=[];for(const m of asArr(e.content)){if(!isObj(m))continue;const k=asStr(m.type);k==="text"?c.push(asStr(m.text)??""):k==="thinking"?p.push(asStr(m.thinking)??""):(k==="tool_use"||k==="server_tool_use"||k==="mcp_tool_use")&&o.toolCalls.push({...asStr(m.id)?{id:asStr(m.id)}:{},name:asStr(m.name)??"tool",arguments:jsonText(m.input)})}o.completion=c.filter(Boolean).join(`
6
+ `));const _=isObj(e.incomplete_details)?asStr(e.incomplete_details.reason):void 0,f=asStr(e.status),h=_??f;h&&(o.finishReason=h),!o.error&&isObj(e.error)&&(o.error=errorMessage(e));break}case"messages":{const c=[],p=[];for(const f of asArr(e.content)){if(!isObj(f))continue;const h=asStr(f.type);h==="text"?c.push(asStr(f.text)??""):h==="thinking"?p.push(asStr(f.thinking)??""):(h==="tool_use"||h==="server_tool_use"||h==="mcp_tool_use")&&o.toolCalls.push({...asStr(f.id)?{id:asStr(f.id)}:{},name:asStr(f.name)??"tool",arguments:jsonText(f.input)})}o.completion=c.filter(Boolean).join(`
7
7
  `),p.length&&(o.reasoning=p.filter(Boolean).join(`
8
- `));const h=asStr(e.stop_reason);h&&(o.finishReason=h);break}case"embeddings":o.vectorCount=asArr(e.data).length;break}return o}_(normalizeResponse,"normalizeResponse"),d(normalizeResponse,"normalizeResponse"),u(normalizeResponse,"normalizeResponse");function createStreamAccumulator(t){let e="",o=0,a,n,i="",c="",p="",h,m={},k,f;const y=new Map,v=u((r,s)=>{s&&(r==="text"?i.length<MAX_ACCUMULATED_CHARS&&(i+=s):r==="reasoning"?c.length<MAX_ACCUMULATED_CHARS&&(c+=s):p.length<MAX_ACCUMULATED_CHARS&&(p+=s))},"append"),C=u(r=>{let s=y.get(r);return s||(s={name:"",args:""},y.set(r,s)),s},"tool");function $(r){const s=asArr(r.choices).find(isObj),g=s&&isObj(s.delta)?s.delta:void 0;if(g){v("text",asStr(g.content)??""),v("refusal",asStr(g.refusal)??""),v("reasoning",asStr(g.reasoning_content)??asStr(g.reasoning)??"");const x=isObj(g.function_call)?g.function_call:void 0;if(x){const b=C(-1);asStr(x.name)&&(b.name+=asStr(x.name)),asStr(x.arguments)&&(b.args+=asStr(x.arguments))}for(const b of asArr(g.tool_calls)){if(!isObj(b))continue;const w=C(asNum(b.index)??0);asStr(b.id)&&(w.id=asStr(b.id));const T=isObj(b.function)?b.function:{};asStr(T.name)&&(w.name+=asStr(T.name)),asStr(T.arguments)&&(w.args+=asStr(T.arguments))}}const l=asStr(s?.finish_reason);l&&(h=l),isObj(r.usage)&&(m={...m,...mapUsage(r.usage,!1)})}_($,"$"),d($,"R"),u($,"onChat");function O(r){const s=asStr(r.type)??"";s==="response.output_text.delta"?v("text",asStr(r.delta)??""):s==="response.completed"||s==="response.incomplete"||s==="response.failed"?f=normalizeResponse(t,r.response):s==="error"&&(k=asStr(r.message)??k)}_(O,"O"),d(O,"O"),u(O,"onResponses");function R(r){const s=asStr(r.type)??"",g=asNum(r.index)??0;if(s==="message_start"){const l=isObj(r.message)?r.message:{};a=asStr(l.id)??a,n=asStr(l.model)??n,m={...m,...mapUsage(l.usage,!1)}}else if(s==="content_block_start"){const l=isObj(r.content_block)?r.content_block:{};if(asStr(l.type)==="tool_use"||asStr(l.type)==="server_tool_use"||asStr(l.type)==="mcp_tool_use"){const x=C(g);x.id=asStr(l.id),x.name=asStr(l.name)??"tool"}else asStr(l.type)==="text"&&v("text",asStr(l.text)??"")}else if(s==="content_block_delta"){const l=isObj(r.delta)?r.delta:{},x=asStr(l.type);x==="text_delta"?v("text",asStr(l.text)??""):x==="thinking_delta"?v("reasoning",asStr(l.thinking)??""):x==="input_json_delta"&&(C(g).args+=asStr(l.partial_json)??"")}else if(s==="message_delta"){const l=isObj(r.delta)?r.delta:{};asStr(l.stop_reason)&&(h=asStr(l.stop_reason)),m={...m,...mapUsage(r.usage,!1)}}else s==="error"&&(k=errorMessage(r)??k)}_(R,"R"),d(R,"S"),u(R,"onAnthropic");function S(r){o+=1,a=asStr(r.id)??a,n=asStr(r.model)??n,t.api==="messages"?R(r):t.api==="responses"?O(r):$(r);const s=t.api==="messages"?void 0:errorMessage(r);s&&(k=s)}_(S,"S"),d(S,"b"),u(S,"onEvent");function A(r){const s=[];for(const l of r.split(`
8
+ `));const _=asStr(e.stop_reason);_&&(o.finishReason=_);break}case"embeddings":o.vectorCount=asArr(e.data).length;break}return o}d(normalizeResponse,"normalizeResponse"),u(normalizeResponse,"normalizeResponse");function createStreamAccumulator(t){let e="",o=0,a,n,r="",c="",p="",_,f={},h,m;const k=new Map,y=u((i,s)=>{s&&(i==="text"?r.length<MAX_ACCUMULATED_CHARS&&(r+=s):i==="reasoning"?c.length<MAX_ACCUMULATED_CHARS&&(c+=s):p.length<MAX_ACCUMULATED_CHARS&&(p+=s))},"append"),b=u(i=>{let s=k.get(i);return s||(s={name:"",args:""},k.set(i,s)),s},"tool");function $(i){const s=asArr(i.choices).find(isObj),g=s&&isObj(s.delta)?s.delta:void 0;if(g){y("text",asStr(g.content)??""),y("refusal",asStr(g.refusal)??""),y("reasoning",asStr(g.reasoning_content)??asStr(g.reasoning)??"");const x=isObj(g.function_call)?g.function_call:void 0;if(x){const v=b(-1);asStr(x.name)&&(v.name+=asStr(x.name)),asStr(x.arguments)&&(v.args+=asStr(x.arguments))}for(const v of asArr(g.tool_calls)){if(!isObj(v))continue;const T=b(asNum(v.index)??0);asStr(v.id)&&(T.id=asStr(v.id));const C=isObj(v.function)?v.function:{};asStr(C.name)&&(T.name+=asStr(C.name)),asStr(C.arguments)&&(T.args+=asStr(C.arguments))}}const l=asStr(s?.finish_reason);l&&(_=l),isObj(i.usage)&&(f={...f,...mapUsage(i.usage,!1)})}d($,"R"),u($,"onChat");function O(i){const s=asStr(i.type)??"";s==="response.output_text.delta"?y("text",asStr(i.delta)??""):s==="response.completed"||s==="response.incomplete"||s==="response.failed"?m=normalizeResponse(t,i.response):s==="error"&&(h=asStr(i.message)??h)}d(O,"O"),u(O,"onResponses");function R(i){const s=asStr(i.type)??"",g=asNum(i.index)??0;if(s==="message_start"){const l=isObj(i.message)?i.message:{};a=asStr(l.id)??a,n=asStr(l.model)??n,f={...f,...mapUsage(l.usage,!1)}}else if(s==="content_block_start"){const l=isObj(i.content_block)?i.content_block:{};if(asStr(l.type)==="tool_use"||asStr(l.type)==="server_tool_use"||asStr(l.type)==="mcp_tool_use"){const x=b(g);x.id=asStr(l.id),x.name=asStr(l.name)??"tool"}else asStr(l.type)==="text"&&y("text",asStr(l.text)??"")}else if(s==="content_block_delta"){const l=isObj(i.delta)?i.delta:{},x=asStr(l.type);x==="text_delta"?y("text",asStr(l.text)??""):x==="thinking_delta"?y("reasoning",asStr(l.thinking)??""):x==="input_json_delta"&&(b(g).args+=asStr(l.partial_json)??"")}else if(s==="message_delta"){const l=isObj(i.delta)?i.delta:{};asStr(l.stop_reason)&&(_=asStr(l.stop_reason)),f={...f,...mapUsage(i.usage,!1)}}else s==="error"&&(h=errorMessage(i)??h)}d(R,"S"),u(R,"onAnthropic");function S(i){o+=1,a=asStr(i.id)??a,n=asStr(i.model)??n,t.api==="messages"?R(i):t.api==="responses"?O(i):$(i);const s=t.api==="messages"?void 0:errorMessage(i);s&&(h=s)}d(S,"b"),u(S,"onEvent");function A(i){const s=[];for(const l of i.split(`
9
9
  `))l.startsWith("data:")&&s.push(l.slice(5).replace(/^ /,""));if(!s.length)return;const g=s.join(`
10
- `);if(g!=="[DONE]")try{const l=JSON.parse(g);isObj(l)&&S(l)}catch{}}return _(A,"A"),d(A,"$"),u(A,"parseEvent"),{push(r){e=(e+r).replace(/\r\n/g,`
10
+ `);if(g!=="[DONE]")try{const l=JSON.parse(g);isObj(l)&&S(l)}catch{}}return d(A,"$"),u(A,"parseEvent"),{push(i){e=(e+i).replace(/\r\n/g,`
11
11
  `);let s=e.indexOf(`
12
12
 
13
13
  `);for(;s!==-1;)A(e.slice(0,s)),e=e.slice(s+2),s=e.indexOf(`
14
14
 
15
- `);e.length>MAX_EVENT_BUFFER_CHARS&&(e="")},end(){e.trim()&&A(e),e="";const r=[...y.entries()].sort((g,l)=>g[0]-l[0]).map(([,g])=>({...g.id?{id:g.id}:{},name:g.name||"tool",...g.args?{arguments:g.args}:{}})),s={...a?{id:a}:{},...n?{model:n}:{},completion:p?`${i}${i?`
16
- `:""}[refusal] ${p}`:i,...c?{reasoning:c}:{},toolCalls:r,...h?{finishReason:h}:{},usage:withTotal(m),...k?{error:k}:{}};return f?{...s,...f,completion:f.completion||s.completion,toolCalls:f.toolCalls.length?f.toolCalls:s.toolCalls,usage:{...s.usage,...f.usage}}:s},get eventCount(){return o}}}_(createStreamAccumulator,"createStreamAccumulator"),d(createStreamAccumulator,"createStreamAccumulator"),u(createStreamAccumulator,"createStreamAccumulator");
15
+ `);e.length>MAX_EVENT_BUFFER_CHARS&&(e="")},end(){e.trim()&&A(e),e="";const i=[...k.entries()].sort((g,l)=>g[0]-l[0]).map(([,g])=>({...g.id?{id:g.id}:{},name:g.name||"tool",...g.args?{arguments:g.args}:{}})),s={...a?{id:a}:{},...n?{model:n}:{},completion:p?`${r}${r?`
16
+ `:""}[refusal] ${p}`:r,...c?{reasoning:c}:{},toolCalls:i,..._?{finishReason:_}:{},usage:withTotal(f),...h?{error:h}:{}};return m?{...s,...m,completion:m.completion||s.completion,toolCalls:m.toolCalls.length?m.toolCalls:s.toolCalls,usage:{...s.usage,...m.usage}}:s},get eventCount(){return o}}}d(createStreamAccumulator,"createStreamAccumulator"),u(createStreamAccumulator,"createStreamAccumulator");
package/lib/ai-store.js CHANGED
@@ -1 +1 @@
1
- "use strict";var E=Object.defineProperty;var d=(e,n)=>E(e,"name",{value:n,configurable:!0});var p=Object.defineProperty,u=d((e,n)=>p(e,"name",{value:n,configurable:!0}),"u"),f=Object.defineProperty,i=u((e,n)=>f(e,"name",{value:n,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.redactAiText=redactAiText,exports.newAiCallId=newAiCallId,exports.fitAiContent=fitAiContent,exports.removeAiContent=removeAiContent,exports.writeAiContent=writeAiContent;const tslib_1=require("tslib"),nodeFs=tslib_1.__importStar(require("node:fs")),ai_content_1=require("@lensmcp/core/ai-content"),redact_1=require("@lensmcp/core/redact"),emit_1=require("./emit"),mkdirSync=nodeFs.mkdirSync,writeFileSync=nodeFs.writeFileSync,renameSync=nodeFs.renameSync,readdirSync=nodeFs.readdirSync,unlinkSync=nodeFs.unlinkSync,AI_SECRET_PATTERNS=[/\bsk-(?:ant-|proj-|live-|test-)?[A-Za-z0-9_-]{20,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/\bgh[pousr]_[A-Za-z0-9]{30,}/g,/\bxox[abprs]-[A-Za-z0-9-]{10,}/g,/\bAIza[0-9A-Za-z_-]{35}\b/g],PEM_BEGIN="-----BEGIN ",PEM_UNTERMINATED_BODY_CHARS=4096;function redactPrivateKeys(e){if(!e.includes("PRIVATE KEY-----"))return e;let n="",t=0,r=!1;for(;;){const s=e.indexOf(PEM_BEGIN,t);if(s===-1)break;const o=e.indexOf("-----",s+PEM_BEGIN.length);if(o===-1)break;const m=e.slice(s+PEM_BEGIN.length,o);if(!/^[A-Z ]{0,30}PRIVATE KEY$/.test(m)){n+=e.slice(t,o+5),t=o+5;continue}n+=e.slice(t,s);const a=r?-1:e.indexOf("-----END ",o+5);let l;if(a===-1)r=!0,l=Math.min(e.length,o+5+PEM_UNTERMINATED_BODY_CHARS);else{const c=e.indexOf("-----",a+9);l=c===-1?e.length:c+5}n+=redact_1.REDACTED,t=l}return n+e.slice(t)}d(redactPrivateKeys,"redactPrivateKeys"),u(redactPrivateKeys,"redactPrivateKeys"),i(redactPrivateKeys,"redactPrivateKeys");const JSON_PAIR_RE=/"([A-Za-z0-9_.-]{1,64})"\s*:\s*"((?:[^"\\]|\\.){1,8192})"/g,ASSIGNMENT_RE=/\b([A-Za-z][A-Za-z0-9_-]{1,40})(\s*[:=]\s*)([^\s"'`,;&)}\]]{8,200})/g,CREDENTIAL_NAME_RE=/(token|secret|pass(?:word|wd)?|pwd|api[-_]?key|apikey|credential|authorization|bearer)/i;function redactStructured(e){return e.replace(JSON_PAIR_RE,(n,t)=>(0,redact_1.isSecretParam)(t)?`"${t}": "${redact_1.REDACTED}"`:n).replace(ASSIGNMENT_RE,(n,t,r)=>CREDENTIAL_NAME_RE.test(t)&&(0,redact_1.isSecretParam)(t)?`${t}${r}${redact_1.REDACTED}`:n)}d(redactStructured,"redactStructured"),u(redactStructured,"redactStructured"),i(redactStructured,"redactStructured");function redactAiText(e){let n=redactStructured((0,redact_1.redactText)(redactPrivateKeys(e)));for(const t of AI_SECRET_PATTERNS)n=n.replace(t,redact_1.REDACTED);return n}d(redactAiText,"redactAiText"),u(redactAiText,"redactAiText"),i(redactAiText,"redactAiText");const intEnv=i((e,n,t,r)=>{const s=Number(process.env[e]);return Number.isFinite(s)&&s>=t&&s<=r?Math.floor(s):n},"intEnv"),maxFieldChars=i(()=>intEnv("LENSMCP_AI_MAX_CHARS",32*1024,256,4*1024*1024),"maxFieldChars"),maxFileBytes=i(()=>intEnv("LENSMCP_AI_MAX_BYTES",256*1024,4*1024,16*1024*1024),"maxFileBytes"),maxFiles=i(()=>intEnv("LENSMCP_AI_MAX_FILES",200,1,1e4),"maxFiles");function newAiCallId(){const e=Date.now().toString(36).padStart(9,"0"),n=Math.random().toString(36).slice(2,8).padEnd(6,"0");return`ai_${e}${n}`}d(newAiCallId,"newAiCallId"),u(newAiCallId,"newAiCallId"),i(newAiCallId,"newAiCallId");const PRE_CLIP_FACTOR=4,MAX_MESSAGES=400;function sanitize(e,n){const t={cut:e.truncated===!0},r=i((o,m=n)=>{if(o===void 0)return;const a=m*PRE_CLIP_FACTOR;let l=o;return l.length>a&&(t.cut=!0,l=l.slice(0,a)),redactAiText(l)},"clean"),s={...e,request:{...e.request,...e.request.system!==void 0?{system:r(e.request.system)}:{},messages:e.request.messages.slice(0,MAX_MESSAGES*4).map(o=>({role:o.role,content:r(o.content)})),...e.request.tools?{tools:e.request.tools.map(o=>({name:r(o.name,200),...o.description?{description:r(o.description,512)}:{}}))}:{}},...e.response?{response:{...e.response,...e.response.completion!==void 0?{completion:r(e.response.completion)}:{},...e.response.reasoning!==void 0?{reasoning:r(e.response.reasoning)}:{},...e.response.error!==void 0?{error:r(e.response.error,2048)}:{},...e.response.toolCalls?{toolCalls:e.response.toolCalls.map(o=>({...o.id?{id:o.id}:{},name:r(o.name,200),...o.arguments!==void 0?{arguments:r(o.arguments,8192)}:{}}))}:{}}}:{}};return e.request.messages.length>MAX_MESSAGES*4&&(t.cut=!0),t.cut&&(s.truncated=!0),s}d(sanitize,"sanitize"),u(sanitize,"sanitize"),i(sanitize,"sanitize");function clipTo(e,n,t){const r={cut:e.truncated===!0},s=i((c,A=n)=>{if(c!==void 0)return c.length>A&&(r.cut=!0),(0,redact_1.clip)(c,A)},"c"),o=e.request.messages;let m=o;if(o.length>t){const c=Math.min(2,t);m=[...o.slice(0,c),...o.slice(o.length-(t-c))],r.cut=!0}const a=e.response,l={...e,request:{...e.request,...e.request.system!==void 0?{system:s(e.request.system)}:{},messages:m.map(c=>({role:c.role,content:s(c.content)}))},...a?{response:{...a,...a.completion!==void 0?{completion:s(a.completion)}:{},...a.reasoning!==void 0?{reasoning:s(a.reasoning)}:{},...a.toolCalls?{toolCalls:a.toolCalls.map(c=>({...c,...c.arguments!==void 0?{arguments:s(c.arguments,Math.min(n,8192))}:{}}))}:{}}}:{}};return r.cut?l.truncated=!0:delete l.truncated,l}d(clipTo,"clipTo"),u(clipTo,"clipTo"),i(clipTo,"clipTo");function fitAiContent(e){const n=maxFileBytes();let t=maxFieldChars(),r=MAX_MESSAGES;const s=sanitize(e,t);let o=clipTo(s,t,r),m=JSON.stringify(o);for(;m.length>n&&(t>256||r>2);)t>256?t=Math.max(256,Math.floor(t/2)):r=Math.max(2,Math.floor(r/2)),o=clipTo(s,t,r),m=JSON.stringify(o);return{json:m,content:o}}d(fitAiContent,"fitAiContent"),u(fitAiContent,"fitAiContent"),i(fitAiContent,"fitAiContent");let writes=0;function prune(e){try{const n=readdirSync(e).filter(r=>/^ai_[0-9a-z]+\.json$/.test(r)).sort(),t=n.length-maxFiles();for(let r=0;r<t;r+=1)try{unlinkSync(`${e}/${n[r]}`)}catch{}}catch{}}d(prune,"prune"),u(prune,"prune"),i(prune,"prune");function removeAiContent(e){try{unlinkSync((0,ai_content_1.aiContentFile)(emit_1.EVENT_FILE,e))}catch{}}d(removeAiContent,"removeAiContent"),u(removeAiContent,"removeAiContent"),i(removeAiContent,"removeAiContent");function writeAiContent(e){try{const n=(0,ai_content_1.aiContentDir)(emit_1.EVENT_FILE);mkdirSync(n,{recursive:!0,mode:448});const{json:t,content:r}=fitAiContent(e),s=`${n}/${e.id}.json`;return writeFileSync(`${s}.tmp`,t,{mode:384}),renameSync(`${s}.tmp`,s),writes+=1,(writes===1||writes%20===0)&&prune(n),{id:e.id,truncated:r.truncated===!0}}catch{return}}d(writeAiContent,"writeAiContent"),u(writeAiContent,"writeAiContent"),i(writeAiContent,"writeAiContent");
1
+ "use strict";var p=Object.defineProperty;var u=(e,n)=>p(e,"name",{value:n,configurable:!0});var f=Object.defineProperty,i=u((e,n)=>f(e,"name",{value:n,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.redactAiText=redactAiText,exports.newAiCallId=newAiCallId,exports.fitAiContent=fitAiContent,exports.removeAiContent=removeAiContent,exports.writeAiContent=writeAiContent;const tslib_1=require("tslib"),nodeFs=tslib_1.__importStar(require("node:fs")),ai_content_1=require("@lensmcp/core/ai-content"),redact_1=require("@lensmcp/core/redact"),emit_1=require("./emit"),mkdirSync=nodeFs.mkdirSync,writeFileSync=nodeFs.writeFileSync,renameSync=nodeFs.renameSync,readdirSync=nodeFs.readdirSync,unlinkSync=nodeFs.unlinkSync,AI_SECRET_PATTERNS=[/\bsk-(?:ant-|proj-|live-|test-)?[A-Za-z0-9_-]{20,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/\bgh[pousr]_[A-Za-z0-9]{30,}/g,/\bxox[abprs]-[A-Za-z0-9-]{10,}/g,/\bAIza[0-9A-Za-z_-]{35}\b/g],PEM_BEGIN="-----BEGIN ",PEM_UNTERMINATED_BODY_CHARS=4096;function redactPrivateKeys(e){if(!e.includes("PRIVATE KEY-----"))return e;let n="",t=0,r=!1;for(;;){const o=e.indexOf(PEM_BEGIN,t);if(o===-1)break;const s=e.indexOf("-----",o+PEM_BEGIN.length);if(s===-1)break;const d=e.slice(o+PEM_BEGIN.length,s);if(!/^[A-Z ]{0,30}PRIVATE KEY$/.test(d)){n+=e.slice(t,s+5),t=s+5;continue}n+=e.slice(t,o);const c=r?-1:e.indexOf("-----END ",s+5);let l;if(c===-1)r=!0,l=Math.min(e.length,s+5+PEM_UNTERMINATED_BODY_CHARS);else{const a=e.indexOf("-----",c+9);l=a===-1?e.length:a+5}n+=redact_1.REDACTED,t=l}return n+e.slice(t)}u(redactPrivateKeys,"redactPrivateKeys"),i(redactPrivateKeys,"redactPrivateKeys");const JSON_PAIR_RE=/"([A-Za-z0-9_.-]{1,64})"\s*:\s*"((?:[^"\\]|\\.){1,8192})"/g,ASSIGNMENT_RE=/\b([A-Za-z][A-Za-z0-9_-]{1,40})(\s*[:=]\s*)([^\s"'`,;&)}\]]{8,200})/g,CREDENTIAL_NAME_RE=/(token|secret|pass(?:word|wd)?|pwd|api[-_]?key|apikey|credential|authorization|bearer)/i;function redactStructured(e){return e.replace(JSON_PAIR_RE,(n,t)=>(0,redact_1.isSecretParam)(t)?`"${t}": "${redact_1.REDACTED}"`:n).replace(ASSIGNMENT_RE,(n,t,r)=>CREDENTIAL_NAME_RE.test(t)&&(0,redact_1.isSecretParam)(t)?`${t}${r}${redact_1.REDACTED}`:n)}u(redactStructured,"redactStructured"),i(redactStructured,"redactStructured");function redactAiText(e){let n=redactStructured((0,redact_1.redactText)(redactPrivateKeys(e)));for(const t of AI_SECRET_PATTERNS)n=n.replace(t,redact_1.REDACTED);return n}u(redactAiText,"redactAiText"),i(redactAiText,"redactAiText");const intEnv=i((e,n,t,r)=>{const o=Number(process.env[e]);return Number.isFinite(o)&&o>=t&&o<=r?Math.floor(o):n},"intEnv"),maxFieldChars=i(()=>intEnv("LENSMCP_AI_MAX_CHARS",32*1024,256,4*1024*1024),"maxFieldChars"),maxFileBytes=i(()=>intEnv("LENSMCP_AI_MAX_BYTES",256*1024,4*1024,16*1024*1024),"maxFileBytes"),maxFiles=i(()=>intEnv("LENSMCP_AI_MAX_FILES",200,1,1e4),"maxFiles");function newAiCallId(){const e=Date.now().toString(36).padStart(9,"0"),n=Math.random().toString(36).slice(2,8).padEnd(6,"0");return`ai_${e}${n}`}u(newAiCallId,"newAiCallId"),i(newAiCallId,"newAiCallId");const PRE_CLIP_FACTOR=4,MAX_MESSAGES=400;function sanitize(e,n){const t={cut:e.truncated===!0},r=i((s,d=n)=>{if(s===void 0)return;const c=d*PRE_CLIP_FACTOR;let l=s;return l.length>c&&(t.cut=!0,l=l.slice(0,c)),redactAiText(l)},"clean"),o={...e,request:{...e.request,...e.request.system!==void 0?{system:r(e.request.system)}:{},messages:e.request.messages.slice(0,MAX_MESSAGES*4).map(s=>({role:s.role,content:r(s.content)})),...e.request.tools?{tools:e.request.tools.map(s=>({name:r(s.name,200),...s.description?{description:r(s.description,512)}:{}}))}:{}},...e.response?{response:{...e.response,...e.response.completion!==void 0?{completion:r(e.response.completion)}:{},...e.response.reasoning!==void 0?{reasoning:r(e.response.reasoning)}:{},...e.response.error!==void 0?{error:r(e.response.error,2048)}:{},...e.response.toolCalls?{toolCalls:e.response.toolCalls.map(s=>({...s.id?{id:s.id}:{},name:r(s.name,200),...s.arguments!==void 0?{arguments:r(s.arguments,8192)}:{}}))}:{}}}:{}};return e.request.messages.length>MAX_MESSAGES*4&&(t.cut=!0),t.cut&&(o.truncated=!0),o}u(sanitize,"sanitize"),i(sanitize,"sanitize");function clipTo(e,n,t){const r={cut:e.truncated===!0},o=i((a,m=n)=>{if(a!==void 0)return a.length>m&&(r.cut=!0),(0,redact_1.clip)(a,m)},"c"),s=e.request.messages;let d=s;if(s.length>t){const a=Math.min(2,t);d=[...s.slice(0,a),...s.slice(s.length-(t-a))],r.cut=!0}const c=e.response,l={...e,request:{...e.request,...e.request.system!==void 0?{system:o(e.request.system)}:{},messages:d.map(a=>({role:a.role,content:o(a.content)}))},...c?{response:{...c,...c.completion!==void 0?{completion:o(c.completion)}:{},...c.reasoning!==void 0?{reasoning:o(c.reasoning)}:{},...c.toolCalls?{toolCalls:c.toolCalls.map(a=>({...a,...a.arguments!==void 0?{arguments:o(a.arguments,Math.min(n,8192))}:{}}))}:{}}}:{}};return r.cut?l.truncated=!0:delete l.truncated,l}u(clipTo,"clipTo"),i(clipTo,"clipTo");function fitAiContent(e){const n=maxFileBytes();let t=maxFieldChars(),r=MAX_MESSAGES;const o=sanitize(e,t);let s=clipTo(o,t,r),d=JSON.stringify(s);for(;d.length>n&&(t>256||r>2);)t>256?t=Math.max(256,Math.floor(t/2)):r=Math.max(2,Math.floor(r/2)),s=clipTo(o,t,r),d=JSON.stringify(s);return{json:d,content:s}}u(fitAiContent,"fitAiContent"),i(fitAiContent,"fitAiContent");let writes=0;function prune(e){try{const n=readdirSync(e).filter(r=>/^ai_[0-9a-z]+\.json$/.test(r)).sort(),t=n.length-maxFiles();for(let r=0;r<t;r+=1)try{unlinkSync(`${e}/${n[r]}`)}catch{}}catch{}}u(prune,"prune"),i(prune,"prune");function removeAiContent(e){try{unlinkSync((0,ai_content_1.aiContentFile)(emit_1.EVENT_FILE,e))}catch{}}u(removeAiContent,"removeAiContent"),i(removeAiContent,"removeAiContent");function writeAiContent(e){try{const n=(0,ai_content_1.aiContentDir)(emit_1.EVENT_FILE);mkdirSync(n,{recursive:!0,mode:448});const{json:t,content:r}=fitAiContent(e),o=`${n}/${e.id}.json`;return writeFileSync(`${o}.tmp`,t,{mode:384}),renameSync(`${o}.tmp`,o),writes+=1,(writes===1||writes%20===0)&&prune(n),{id:e.id,truncated:r.truncated===!0}}catch{return}}u(writeAiContent,"writeAiContent"),i(writeAiContent,"writeAiContent");
package/lib/emit.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var x=Object.defineProperty;var a=(t,s)=>x(t,"name",{value:s,configurable:!0});var m=Object.defineProperty,p=a((t,s)=>m(t,"name",{value:s,configurable:!0}),"p"),d=Object.defineProperty,i=p((t,s)=>d(t,"name",{value:s,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.EVENT_FILE=exports.PROJECT=exports.EVENT_MAX_FILES=exports.EVENT_MAX_BYTES=void 0,exports.maybeRotateEventFile=maybeRotateEventFile,exports.isLensWriting=isLensWriting,exports.lensEmit=lensEmit,exports.lensEmitOutcome=lensEmitOutcome,exports.lensLog=lensLog;const tslib_1=require("tslib"),nodeFs=tslib_1.__importStar(require("node:fs")),node_path_1=require("node:path"),bus_rotation_1=require("@lensmcp/core/bus-rotation"),flood_guard_1=require("./flood-guard"),flow_context_1=require("./flow-context"),appendFileSync=nodeFs.appendFileSync,mkdirSync=nodeFs.mkdirSync,statSync=nodeFs.statSync,renameSync=nodeFs.renameSync,unlinkSync=nodeFs.unlinkSync,openSync=nodeFs.openSync,closeSync=nodeFs.closeSync,BUS_CAPS=(0,bus_rotation_1.busCapsFromEnv)();exports.EVENT_MAX_BYTES=BUS_CAPS.maxBytes,exports.EVENT_MAX_FILES=BUS_CAPS.maxFiles;const rotators=new Map,BUS_FS={statSync,renameSync,unlinkSync,openSync,closeSync};function maybeRotateEventFile(t,s,e){if(e!==void 0){const n=e.maxBytes??exports.EVENT_MAX_BYTES,r=e.maxFiles??exports.EVENT_MAX_FILES;(0,bus_rotation_1.createBusRotator)(t,{maxBytes:n,maxFiles:r,fs:BUS_FS,checkEveryBytes:0})(s);return}let o=rotators.get(t);o||(o=(0,bus_rotation_1.createBusRotator)(t,{maxBytes:exports.EVENT_MAX_BYTES,maxFiles:exports.EVENT_MAX_FILES,fs:BUS_FS}),rotators.set(t,o)),o(s)}a(maybeRotateEventFile,"maybeRotateEventFile"),p(maybeRotateEventFile,"maybeRotateEventFile"),i(maybeRotateEventFile,"maybeRotateEventFile"),exports.PROJECT=process.env.LENSMCP_PROJECT||process.env.SERVICE_NAME||"app",exports.EVENT_FILE=process.env.LENSMCP_EVENT_FILE||`${process.cwd()}/.lensmcp/events.jsonl`;let writing=!1,dirReady=!1;const emitGuard=(0,flood_guard_1.createEventFloodGuard)({burst:30,perSec:5}),logGuard=(0,flood_guard_1.createEventFloodGuard)({burst:120,perSec:20});function isLensWriting(){return writing}a(isLensWriting,"isLensWriting"),p(isLensWriting,"isLensWriting"),i(isLensWriting,"isLensWriting");function lensEmit(t,s,e,o,n,r,c="cluster"){return lensEmitOutcome(t,s,e,o,n,r,c)==="written"}a(lensEmit,"lensEmit"),p(lensEmit,"lensEmit"),i(lensEmit,"lensEmit");function lensEmitOutcome(t,s,e,o,n,r,c="cluster",g=emitGuard){try{writing=!0;const E=n??`${t}:${String(o.name??t)}`,l=g.admit(E);if(!l.ok)return"suppressed";dirReady||(mkdirSync((0,node_path_1.dirname)(exports.EVENT_FILE),{recursive:!0}),dirReady=!0);const u=JSON.stringify({id:Date.now().toString(36)+Math.random().toString(36).slice(2,10),sessionId:"pending",timestamp:Date.now(),source:t,category:c,severity:s,context:{sessionId:"pending",projectName:exports.PROJECT,...r?.flowId?{flowId:r.flowId}:{},...r?.requestId?{requestId:r.requestId}:{},...r?.originNodeId?{originNodeId:r.originNodeId}:{},...r?.originType?{originType:r.originType}:{}},fingerprint:E,title:e,raw:{project:exports.PROJECT,...o,...l.suppressed>0?{floodSuppressed:l.suppressed}:{}}})+`
2
- `;return maybeRotateEventFile(exports.EVENT_FILE,u.length),appendFileSync(exports.EVENT_FILE,u),"written"}catch{return"failed"}finally{writing=!1}}a(lensEmitOutcome,"lensEmitOutcome"),p(lensEmitOutcome,"lensEmitOutcome"),i(lensEmitOutcome,"lensEmitOutcome");function lensLog(t,s,e){try{writing=!0;const o=e?.bucket!==void 0?`log:${exports.PROJECT}:${e.bucket}`:t==="error"||t==="fatal"?`log:error:${exports.PROJECT}`:`log:${exports.PROJECT}`,n=e?.bucket!==void 0?{ok:!0,suppressed:e.suppressed??0}:logGuard.admit(o);if(!n.ok)return!1;dirReady||(mkdirSync((0,node_path_1.dirname)(exports.EVENT_FILE),{recursive:!0}),dirReady=!0);const r=(0,flow_context_1.flowContext)(),c=JSON.stringify({id:Date.now().toString(36)+Math.random().toString(36).slice(2,10),sessionId:"pending",timestamp:Date.now(),source:"nestjs",category:"runtime",severity:t,context:{sessionId:"pending",projectName:exports.PROJECT,...r?.flowId?{flowId:r.flowId}:{},...r?.requestId?{requestId:r.requestId}:{}},fingerprint:o,title:s,raw:{project:exports.PROJECT,kind:"log",...e?.stack?{request:{error:{message:s,stack:e.stack}}}:{},...e?.text?{text:e.text}:{},...e?.continues?{continues:!0}:{},...e?.stream?{stream:e.stream}:{},...e?.level?{level:e.level}:{},...e?.logger?{logger:e.logger}:{},...n.suppressed>0?{floodSuppressed:n.suppressed}:{}}})+`
3
- `;return maybeRotateEventFile(exports.EVENT_FILE,c.length),appendFileSync(exports.EVENT_FILE,c),!0}catch{return!1}finally{writing=!1}}a(lensLog,"lensLog"),p(lensLog,"lensLog"),i(lensLog,"lensLog");
1
+ "use strict";var m=Object.defineProperty;var p=(t,s)=>m(t,"name",{value:s,configurable:!0});var d=Object.defineProperty,i=p((t,s)=>d(t,"name",{value:s,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.EVENT_FILE=exports.PROJECT=exports.EVENT_MAX_FILES=exports.EVENT_MAX_BYTES=void 0,exports.maybeRotateEventFile=maybeRotateEventFile,exports.isLensWriting=isLensWriting,exports.lensEmit=lensEmit,exports.lensEmitOutcome=lensEmitOutcome,exports.lensLog=lensLog;const tslib_1=require("tslib"),nodeFs=tslib_1.__importStar(require("node:fs")),node_path_1=require("node:path"),bus_rotation_1=require("@lensmcp/core/bus-rotation"),flood_guard_1=require("./flood-guard"),flow_context_1=require("./flow-context"),appendFileSync=nodeFs.appendFileSync,mkdirSync=nodeFs.mkdirSync,statSync=nodeFs.statSync,renameSync=nodeFs.renameSync,unlinkSync=nodeFs.unlinkSync,openSync=nodeFs.openSync,closeSync=nodeFs.closeSync,BUS_CAPS=(0,bus_rotation_1.busCapsFromEnv)();exports.EVENT_MAX_BYTES=BUS_CAPS.maxBytes,exports.EVENT_MAX_FILES=BUS_CAPS.maxFiles;const rotators=new Map,BUS_FS={statSync,renameSync,unlinkSync,openSync,closeSync};function maybeRotateEventFile(t,s,e){if(e!==void 0){const n=e.maxBytes??exports.EVENT_MAX_BYTES,r=e.maxFiles??exports.EVENT_MAX_FILES;(0,bus_rotation_1.createBusRotator)(t,{maxBytes:n,maxFiles:r,fs:BUS_FS,checkEveryBytes:0})(s);return}let o=rotators.get(t);o||(o=(0,bus_rotation_1.createBusRotator)(t,{maxBytes:exports.EVENT_MAX_BYTES,maxFiles:exports.EVENT_MAX_FILES,fs:BUS_FS}),rotators.set(t,o)),o(s)}p(maybeRotateEventFile,"maybeRotateEventFile"),i(maybeRotateEventFile,"maybeRotateEventFile"),exports.PROJECT=process.env.LENSMCP_PROJECT||process.env.SERVICE_NAME||"app",exports.EVENT_FILE=process.env.LENSMCP_EVENT_FILE||`${process.cwd()}/.lensmcp/events.jsonl`;let writing=!1,dirReady=!1;const emitGuard=(0,flood_guard_1.createEventFloodGuard)({burst:30,perSec:5}),logGuard=(0,flood_guard_1.createEventFloodGuard)({burst:120,perSec:20});function isLensWriting(){return writing}p(isLensWriting,"isLensWriting"),i(isLensWriting,"isLensWriting");function lensEmit(t,s,e,o,n,r,a="cluster"){return lensEmitOutcome(t,s,e,o,n,r,a)==="written"}p(lensEmit,"lensEmit"),i(lensEmit,"lensEmit");function lensEmitOutcome(t,s,e,o,n,r,a="cluster",u=emitGuard){try{writing=!0;const E=n??`${t}:${String(o.name??t)}`,c=u.admit(E);if(!c.ok)return"suppressed";dirReady||(mkdirSync((0,node_path_1.dirname)(exports.EVENT_FILE),{recursive:!0}),dirReady=!0);const l=JSON.stringify({id:Date.now().toString(36)+Math.random().toString(36).slice(2,10),sessionId:"pending",timestamp:Date.now(),source:t,category:a,severity:s,context:{sessionId:"pending",projectName:exports.PROJECT,...r?.flowId?{flowId:r.flowId}:{},...r?.requestId?{requestId:r.requestId}:{},...r?.originNodeId?{originNodeId:r.originNodeId}:{},...r?.originType?{originType:r.originType}:{}},fingerprint:E,title:e,raw:{project:exports.PROJECT,...o,...c.suppressed>0?{floodSuppressed:c.suppressed}:{}}})+`
2
+ `;return maybeRotateEventFile(exports.EVENT_FILE,l.length),appendFileSync(exports.EVENT_FILE,l),"written"}catch{return"failed"}finally{writing=!1}}p(lensEmitOutcome,"lensEmitOutcome"),i(lensEmitOutcome,"lensEmitOutcome");function lensLog(t,s,e){try{writing=!0;const o=e?.bucket!==void 0?`log:${exports.PROJECT}:${e.bucket}`:t==="error"||t==="fatal"?`log:error:${exports.PROJECT}`:`log:${exports.PROJECT}`,n=e?.bucket!==void 0?{ok:!0,suppressed:e.suppressed??0}:logGuard.admit(o);if(!n.ok)return!1;dirReady||(mkdirSync((0,node_path_1.dirname)(exports.EVENT_FILE),{recursive:!0}),dirReady=!0);const r=(0,flow_context_1.flowContext)(),a=JSON.stringify({id:Date.now().toString(36)+Math.random().toString(36).slice(2,10),sessionId:"pending",timestamp:Date.now(),source:"nestjs",category:"runtime",severity:t,context:{sessionId:"pending",projectName:exports.PROJECT,...r?.flowId?{flowId:r.flowId}:{},...r?.requestId?{requestId:r.requestId}:{}},fingerprint:o,title:s,raw:{project:exports.PROJECT,kind:"log",...e?.stack?{request:{error:{message:s,stack:e.stack}}}:{},...e?.text?{text:e.text}:{},...e?.continues?{continues:!0}:{},...e?.stream?{stream:e.stream}:{},...e?.level?{level:e.level}:{},...e?.logger?{logger:e.logger}:{},...n.suppressed>0?{floodSuppressed:n.suppressed}:{}}})+`
3
+ `;return maybeRotateEventFile(exports.EVENT_FILE,a.length),appendFileSync(exports.EVENT_FILE,a),!0}catch{return!1}finally{writing=!1}}p(lensLog,"lensLog"),i(lensLog,"lensLog");
@@ -1 +1 @@
1
- "use strict";var u=Object.defineProperty;var c=(r,t)=>u(r,"name",{value:t,configurable:!0});var n=Object.defineProperty,a=c((r,t)=>n(r,"name",{value:t,configurable:!0}),"a"),o=Object.defineProperty,e=a((r,t)=>o(r,"name",{value:t,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createEventFloodGuard=void 0;var protocol_types_1=require("@lensmcp/protocol-types");Object.defineProperty(exports,"createEventFloodGuard",{enumerable:!0,get:e(function(){return protocol_types_1.createEventFloodGuard},"get")});
1
+ "use strict";var n=Object.defineProperty;var a=(r,t)=>n(r,"name",{value:t,configurable:!0});var o=Object.defineProperty,e=a((r,t)=>o(r,"name",{value:t,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createEventFloodGuard=void 0;var protocol_types_1=require("@lensmcp/protocol-types");Object.defineProperty(exports,"createEventFloodGuard",{enumerable:!0,get:e(function(){return protocol_types_1.createEventFloodGuard},"get")});
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var r=(e,t)=>f(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,o=r((e,t)=>d(e,"name",{value:t,configurable:!0}),"o"),l=Object.defineProperty,n=o((e,t)=>l(e,"name",{value:t,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.CONTEXT_END=void 0,exports.flowContextStatus=flowContextStatus,exports.resetFlowContextForTests=resetFlowContextForTests,exports.isRequireEsmError=isRequireEsmError,exports.isModuleNotFoundError=isModuleNotFoundError,exports.primeFlowContext=primeFlowContext,exports.attachContextEnd=attachContextEnd,exports.contextEndOf=contextEndOf,exports.runInFlowContext=runInFlowContext,exports.liveFlowContext=liveFlowContext,exports.flowContext=flowContext;let getCtx=null,runWith=null,status={state:"not-primed"},warned=!1;function flowContextStatus(){return status}r(flowContextStatus,"flowContextStatus"),o(flowContextStatus,"flowContextStatus"),n(flowContextStatus,"flowContextStatus");function resetFlowContextForTests(){getCtx=null,runWith=null,status={state:"not-primed"},warned=!1}r(resetFlowContextForTests,"resetFlowContextForTests"),o(resetFlowContextForTests,"resetFlowContextForTests"),n(resetFlowContextForTests,"resetFlowContextForTests");function isRequireEsmError(e){const t=e?.code;return t==="ERR_REQUIRE_ESM"||t==="ERR_REQUIRE_ASYNC_MODULE"}r(isRequireEsmError,"isRequireEsmError"),o(isRequireEsmError,"isRequireEsmError"),n(isRequireEsmError,"isRequireEsmError");function isModuleNotFoundError(e){const t=e;return t?.code!=="MODULE_NOT_FOUND"&&t?.code!=="ERR_MODULE_NOT_FOUND"?!1:String(t?.message??"").includes("@lensmcp/nest-instrumentation")}r(isModuleNotFoundError,"isModuleNotFoundError"),o(isModuleNotFoundError,"isModuleNotFoundError"),n(isModuleNotFoundError,"isModuleNotFoundError");function requireNestInstrumentation(){return require("@lensmcp/nest-instrumentation")}r(requireNestInstrumentation,"requireNestInstrumentation"),o(requireNestInstrumentation,"requireNestInstrumentation"),n(requireNestInstrumentation,"requireNestInstrumentation");function primeFlowContext(e=requireNestInstrumentation){try{const t=e();getCtx=t.currentLensmcpContext,runWith=t.runInLensmcpContext,status={state:"ready"}}catch(t){if(getCtx=null,runWith=null,isModuleNotFoundError(t)){status={state:"absent"};return}const s=t instanceof Error?t.message:String(t);if(status=isRequireEsmError(t)?{state:"runtime-too-old",detail:s}:{state:"failed",detail:s},!warned){warned=!0;const i=status.state==="runtime-too-old"?`this Node (${process.version}) cannot require an ESM package; @lensmcp/node-instrumentation needs >=20.19`:s;console.warn(`[lensmcp] flow correlation is OFF \u2014 could not load @lensmcp/nest-instrumentation: ${i}`)}}}r(primeFlowContext,"primeFlowContext"),o(primeFlowContext,"primeFlowContext"),n(primeFlowContext,"primeFlowContext"),exports.CONTEXT_END=Symbol.for("lensmcp.contextEnd");function attachContextEnd(e){let t=!1;const s=[],i={get ended(){return t},onEnd(u){t?runEndListener(u):s.push(u)}};return Object.defineProperty(e,exports.CONTEXT_END,{value:i}),()=>{if(!t){t=!0;for(const u of s.splice(0))runEndListener(u)}}}r(attachContextEnd,"attachContextEnd"),o(attachContextEnd,"attachContextEnd"),n(attachContextEnd,"attachContextEnd");function runEndListener(e){try{e()}catch{}}r(runEndListener,"runEndListener"),o(runEndListener,"runEndListener"),n(runEndListener,"runEndListener");function contextEndOf(e){const t=e?.[exports.CONTEXT_END];return t&&typeof t.onEnd=="function"?t:void 0}r(contextEndOf,"contextEndOf"),o(contextEndOf,"contextEndOf"),n(contextEndOf,"contextEndOf");function runInFlowContext(e,t){if(!runWith)return t();const s={sessionId:"pending",requestId:e.requestId,...e.flowId?{flowId:e.flowId}:{}},i=attachContextEnd(s);let u;try{u=runWith(s,t)}catch{return i(),t()}const c=u;return c&&typeof c.then=="function"?c.then(a=>(i(),a),a=>{throw i(),a}):(i(),u)}r(runInFlowContext,"runInFlowContext"),o(runInFlowContext,"runInFlowContext"),n(runInFlowContext,"runInFlowContext");function liveFlowContext(){try{return getCtx?.()}catch{return}}r(liveFlowContext,"liveFlowContext"),o(liveFlowContext,"liveFlowContext"),n(liveFlowContext,"liveFlowContext");function flowContext(){const e=liveFlowContext();if(e)return{...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},...e.originNodeId?{originNodeId:e.originNodeId}:{}}}r(flowContext,"flowContext"),o(flowContext,"flowContext"),n(flowContext,"flowContext");
1
+ "use strict";var d=Object.defineProperty;var o=(e,t)=>d(e,"name",{value:t,configurable:!0});var l=Object.defineProperty,n=o((e,t)=>l(e,"name",{value:t,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.CONTEXT_END=void 0,exports.flowContextStatus=flowContextStatus,exports.resetFlowContextForTests=resetFlowContextForTests,exports.isRequireEsmError=isRequireEsmError,exports.isModuleNotFoundError=isModuleNotFoundError,exports.primeFlowContext=primeFlowContext,exports.attachContextEnd=attachContextEnd,exports.contextEndOf=contextEndOf,exports.runInFlowContext=runInFlowContext,exports.liveFlowContext=liveFlowContext,exports.flowContext=flowContext;let getCtx=null,runWith=null,status={state:"not-primed"},warned=!1;function flowContextStatus(){return status}o(flowContextStatus,"flowContextStatus"),n(flowContextStatus,"flowContextStatus");function resetFlowContextForTests(){getCtx=null,runWith=null,status={state:"not-primed"},warned=!1}o(resetFlowContextForTests,"resetFlowContextForTests"),n(resetFlowContextForTests,"resetFlowContextForTests");function isRequireEsmError(e){const t=e?.code;return t==="ERR_REQUIRE_ESM"||t==="ERR_REQUIRE_ASYNC_MODULE"}o(isRequireEsmError,"isRequireEsmError"),n(isRequireEsmError,"isRequireEsmError");function isModuleNotFoundError(e){const t=e;return t?.code!=="MODULE_NOT_FOUND"&&t?.code!=="ERR_MODULE_NOT_FOUND"?!1:String(t?.message??"").includes("@lensmcp/nest-instrumentation")}o(isModuleNotFoundError,"isModuleNotFoundError"),n(isModuleNotFoundError,"isModuleNotFoundError");function requireNestInstrumentation(){return require("@lensmcp/nest-instrumentation")}o(requireNestInstrumentation,"requireNestInstrumentation"),n(requireNestInstrumentation,"requireNestInstrumentation");function primeFlowContext(e=requireNestInstrumentation){try{const t=e();getCtx=t.currentLensmcpContext,runWith=t.runInLensmcpContext,status={state:"ready"}}catch(t){if(getCtx=null,runWith=null,isModuleNotFoundError(t)){status={state:"absent"};return}const r=t instanceof Error?t.message:String(t);if(status=isRequireEsmError(t)?{state:"runtime-too-old",detail:r}:{state:"failed",detail:r},!warned){warned=!0;const s=status.state==="runtime-too-old"?`this Node (${process.version}) cannot require an ESM package; @lensmcp/node-instrumentation needs >=20.19`:r;console.warn(`[lensmcp] flow correlation is OFF \u2014 could not load @lensmcp/nest-instrumentation: ${s}`)}}}o(primeFlowContext,"primeFlowContext"),n(primeFlowContext,"primeFlowContext"),exports.CONTEXT_END=Symbol.for("lensmcp.contextEnd");function attachContextEnd(e){let t=!1;const r=[],s={get ended(){return t},onEnd(u){t?runEndListener(u):r.push(u)}};return Object.defineProperty(e,exports.CONTEXT_END,{value:s}),()=>{if(!t){t=!0;for(const u of r.splice(0))runEndListener(u)}}}o(attachContextEnd,"attachContextEnd"),n(attachContextEnd,"attachContextEnd");function runEndListener(e){try{e()}catch{}}o(runEndListener,"runEndListener"),n(runEndListener,"runEndListener");function contextEndOf(e){const t=e?.[exports.CONTEXT_END];return t&&typeof t.onEnd=="function"?t:void 0}o(contextEndOf,"contextEndOf"),n(contextEndOf,"contextEndOf");function runInFlowContext(e,t){if(!runWith)return t();const r={sessionId:"pending",requestId:e.requestId,...e.flowId?{flowId:e.flowId}:{}},s=attachContextEnd(r);let u;try{u=runWith(r,t)}catch{return s(),t()}const i=u;return i&&typeof i.then=="function"?i.then(c=>(s(),c),c=>{throw s(),c}):(s(),u)}o(runInFlowContext,"runInFlowContext"),n(runInFlowContext,"runInFlowContext");function liveFlowContext(){try{return getCtx?.()}catch{return}}o(liveFlowContext,"liveFlowContext"),n(liveFlowContext,"liveFlowContext");function flowContext(){const e=liveFlowContext();if(e)return{...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},...e.originNodeId?{originNodeId:e.originNodeId}:{}}}o(flowContext,"flowContext"),n(flowContext,"flowContext");
@@ -1,2 +1,2 @@
1
- "use strict";var j=Object.defineProperty;var m=(e,t)=>j(e,"name",{value:t,configurable:!0});var q=Object.defineProperty,g=m((e,t)=>q(e,"name",{value:t,configurable:!0}),"g"),k=Object.defineProperty,l=g((e,t)=>k(e,"name",{value:t,configurable:!0}),"l");Object.defineProperty(exports,"__esModule",{value:!0}),exports.takeRequest=takeRequest,exports.readResponse=readResponse,exports.requestPart=requestPart;const node_crypto_1=require("node:crypto"),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,MAX_STREAM_MS=300*1e3,MAX_HASH_BYTES=1024*1024,pairs=l(e=>{try{if(!e)return[];if(typeof e.forEach=="function"&&typeof e.get=="function"){const t=[];return e.forEach((a,n)=>t.push([n,a])),t}return Array.isArray(e)?e.map(([t,a])=>[String(t),String(a)]):Object.entries(e).map(([t,a])=>[t,Array.isArray(a)?a.join(", "):String(a)])}catch{return[]}},"pairs");function takeRequest(e,t,a){const n=typeof e=="object"&&e!==null&&!(e instanceof URL)?e:void 0,i=[...pairs(n?.headers),...pairs(t?.headers)],c=i.find(([s])=>s.toLowerCase()==="content-type")?.[1]??"",o={headers:i,contentType:c};if(!a)return o;const r=t?.body,d=l(s=>new TextEncoder().encode(s),"enc");if(typeof r=="string")return{...o,bytes:d(r),size:Buffer.byteLength(r)};if(r instanceof URLSearchParams)return{...o,contentType:c||"application/x-www-form-urlencoded",bytes:d(r.toString())};if(r instanceof ArrayBuffer)return{...o,bytes:new Uint8Array(r),size:r.byteLength};if(ArrayBuffer.isView(r))return{...o,bytes:new Uint8Array(r.buffer,r.byteOffset,r.byteLength),size:r.byteLength};if(typeof Blob<"u"&&r instanceof Blob)return{...o,size:r.size,...r.size<=http_store_1.MAX_KEPT_BYTES*32?{pending:r.arrayBuffer().then(s=>new Uint8Array(s)).catch(()=>{})}:{}};if(typeof FormData<"u"&&r instanceof FormData)return{...o,omitted:"form-data"};if(r!=null)return{...o,omitted:"stream"};if(n&&!n.bodyUsed&&n.body)try{return{...o,pending:n.clone().arrayBuffer().then(s=>new Uint8Array(s)).catch(()=>{})}}catch{return o}return o}m(takeRequest,"takeRequest"),g(takeRequest,"takeRequest"),l(takeRequest,"takeRequest");function sseEvent(e){let t="message";const a=[];for(const n of e.split(/\r?\n/)){if(!n||n.startsWith(":"))continue;const i=n.indexOf(":"),c=i<0?n:n.slice(0,i),o=i<0?"":n.slice(i+1).replace(/^ /,"");c==="event"?t=o||"message":c==="data"&&a.push(o)}return a.length||t!=="message"?{event:t,data:a.join(`
2
- `)}:void 0}m(sseEvent,"sseEvent"),g(sseEvent,"sseEvent"),l(sseEvent,"sseEvent");function readResponse(e,t,a,n){const i=(()=>{try{return e.headers.get("content-type")??""}catch{return""}})(),c=Number((()=>{try{return e.headers.get("content-length")??""}catch{return""}})()),o=t.body;if(!o)return Promise.resolve({endedAt:Date.now(),...Number.isFinite(c)&&c===0?{}:{}});const r=o.getReader(),d=/text\/event-stream/i.test(i);return(async()=>{let s=0;const A=[];let f=0;const L=(0,node_crypto_1.createHash)("sha256");let T=!/json|^text\/|xml|form/i.test(i);const _=[];let x=0,B=0,w,v=!1,y="";const z=new TextDecoder,M=l(p=>{const u=sseEvent(p);if(!u)return;x++;const h=Date.now()-a;if(w??=h,_.length>=MAX_EVENTS||B>=MAX_STREAM_KEPT){v=!0;return}const b=n.ai?void 0:(0,ai_store_1.redactAiText)(u.data).slice(0,MAX_EVENT_DATA);b&&(B+=b.length),_.push({atMs:h,event:u.event,bytes:Buffer.byteLength(p),...b!==void 0?{data:b}:{}})},"take");try{for(;;){const{done:p,value:u}=await r.read();if(p)break;if(s+=u.byteLength,d){y+=z.decode(u,{stream:!0});let h;for(;(h=y.search(/\r?\n\r?\n/))>=0;){const b=/\r?\n\r?\n/.exec(y.slice(h));M(y.slice(0,h)),y=y.slice(h+b[0].length)}}else n.ai||(f<http_store_1.MAX_KEPT_BYTES*32&&(A.push(u),f+=u.byteLength),T&&(s<=MAX_HASH_BYTES?L.update(u):T=!1));if(Date.now()-a>MAX_STREAM_MS){v=!0,await r.cancel().catch(()=>{});break}}d&&y.trim()&&M(y)}catch{v=!0}const E=Date.now();if(d)return{endedAt:E,stream:{protocol:"sse",...w!==void 0?{firstEventMs:w}:{},events:_,bytes:s,total:x,...v?{cut:!0}:{}}};if(n.ai)return{endedAt:E,body:{contentType:i.split(";")[0].trim(),size:s,kept:0,truncated:!1,omitted:"ai"}};const R=new Uint8Array(f);let S=0;for(const p of A)R.set(p,S),S+=p.byteLength;const P=T&&s<=MAX_HASH_BYTES?L.digest("hex"):void 0;return{endedAt:E,body:(0,http_store_1.keepBody)(i,R,s,n.paths,P)}})()}m(readResponse,"readResponse"),g(readResponse,"readResponse"),l(readResponse,"readResponse");async function requestPart(e,t,a,n,i,c){const{headers:o,redacted:r}=(0,http_store_1.redactHeaders)(e.headers);c.push(...r);const d=a==="bodies"&&t.length>1?(0,http_store_1.redactQuery)(t):[];let s;if(a==="bodies"){const A=e.contentType.split(";")[0].trim().toLowerCase();if(n)s={contentType:A,size:e.size??e.bytes?.byteLength??0,kept:0,truncated:!1,omitted:"ai"};else if(e.omitted)s={contentType:A,size:e.size??0,kept:0,truncated:!1,omitted:e.omitted};else{const f=e.bytes??await e.pending;f&&f.byteLength&&(s=(0,http_store_1.keepBody)(e.contentType,f,e.size??f.byteLength,i))}}return{headers:o,...d.length?{query:d}:{},...s?{body:s}:{}}}m(requestPart,"requestPart"),g(requestPart,"requestPart"),l(requestPart,"requestPart");
1
+ "use strict";var q=Object.defineProperty;var g=(e,r)=>q(e,"name",{value:r,configurable:!0});var k=Object.defineProperty,l=g((e,r)=>k(e,"name",{value:r,configurable:!0}),"l");Object.defineProperty(exports,"__esModule",{value:!0}),exports.takeRequest=takeRequest,exports.readResponse=readResponse,exports.requestPart=requestPart;const node_crypto_1=require("node:crypto"),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,MAX_STREAM_MS=300*1e3,MAX_HASH_BYTES=1024*1024,pairs=l(e=>{try{if(!e)return[];if(typeof e.forEach=="function"&&typeof e.get=="function"){const r=[];return e.forEach((o,n)=>r.push([n,o])),r}return Array.isArray(e)?e.map(([r,o])=>[String(r),String(o)]):Object.entries(e).map(([r,o])=>[r,Array.isArray(o)?o.join(", "):String(o)])}catch{return[]}},"pairs");function takeRequest(e,r,o){const n=typeof e=="object"&&e!==null&&!(e instanceof URL)?e:void 0,i=[...pairs(n?.headers),...pairs(r?.headers)],c=i.find(([s])=>s.toLowerCase()==="content-type")?.[1]??"",a={headers:i,contentType:c};if(!o)return a;const t=r?.body,d=l(s=>new TextEncoder().encode(s),"enc");if(typeof t=="string")return{...a,bytes:d(t),size:Buffer.byteLength(t)};if(t instanceof URLSearchParams)return{...a,contentType:c||"application/x-www-form-urlencoded",bytes:d(t.toString())};if(t instanceof ArrayBuffer)return{...a,bytes:new Uint8Array(t),size:t.byteLength};if(ArrayBuffer.isView(t))return{...a,bytes:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),size:t.byteLength};if(typeof Blob<"u"&&t instanceof Blob)return{...a,size:t.size,...t.size<=http_store_1.MAX_KEPT_BYTES*32?{pending:t.arrayBuffer().then(s=>new Uint8Array(s)).catch(()=>{})}:{}};if(typeof FormData<"u"&&t instanceof FormData)return{...a,omitted:"form-data"};if(t!=null)return{...a,omitted:"stream"};if(n&&!n.bodyUsed&&n.body)try{return{...a,pending:n.clone().arrayBuffer().then(s=>new Uint8Array(s)).catch(()=>{})}}catch{return a}return a}g(takeRequest,"takeRequest"),l(takeRequest,"takeRequest");function sseEvent(e){let r="message";const o=[];for(const n of e.split(/\r?\n/)){if(!n||n.startsWith(":"))continue;const i=n.indexOf(":"),c=i<0?n:n.slice(0,i),a=i<0?"":n.slice(i+1).replace(/^ /,"");c==="event"?r=a||"message":c==="data"&&o.push(a)}return o.length||r!=="message"?{event:r,data:o.join(`
2
+ `)}:void 0}g(sseEvent,"sseEvent"),l(sseEvent,"sseEvent");function readResponse(e,r,o,n){const i=(()=>{try{return e.headers.get("content-type")??""}catch{return""}})(),c=Number((()=>{try{return e.headers.get("content-length")??""}catch{return""}})()),a=r.body;if(!a)return Promise.resolve({endedAt:Date.now(),...Number.isFinite(c)&&c===0?{}:{}});const t=a.getReader(),d=/text\/event-stream/i.test(i);return(async()=>{let s=0;const m=[];let f=0;const E=(0,node_crypto_1.createHash)("sha256");let v=!/json|^text\/|xml|form/i.test(i);const T=[];let L=0,x=0,_,A=!1,y="";const z=new TextDecoder,B=l(p=>{const u=sseEvent(p);if(!u)return;L++;const h=Date.now()-o;if(_??=h,T.length>=MAX_EVENTS||x>=MAX_STREAM_KEPT){A=!0;return}const b=n.ai?void 0:(0,ai_store_1.redactAiText)(u.data).slice(0,MAX_EVENT_DATA);b&&(x+=b.length),T.push({atMs:h,event:u.event,bytes:Buffer.byteLength(p),...b!==void 0?{data:b}:{}})},"take");try{for(;;){const{done:p,value:u}=await t.read();if(p)break;if(s+=u.byteLength,d){y+=z.decode(u,{stream:!0});let h;for(;(h=y.search(/\r?\n\r?\n/))>=0;){const b=/\r?\n\r?\n/.exec(y.slice(h));B(y.slice(0,h)),y=y.slice(h+b[0].length)}}else n.ai||(f<http_store_1.MAX_KEPT_BYTES*32&&(m.push(u),f+=u.byteLength),v&&(s<=MAX_HASH_BYTES?E.update(u):v=!1));if(Date.now()-o>MAX_STREAM_MS){A=!0,await t.cancel().catch(()=>{});break}}d&&y.trim()&&B(y)}catch{A=!0}const w=Date.now();if(d)return{endedAt:w,stream:{protocol:"sse",..._!==void 0?{firstEventMs:_}:{},events:T,bytes:s,total:L,...A?{cut:!0}:{}}};if(n.ai)return{endedAt:w,body:{contentType:i.split(";")[0].trim(),size:s,kept:0,truncated:!1,omitted:"ai"}};const M=new Uint8Array(f);let S=0;for(const p of m)M.set(p,S),S+=p.byteLength;const R=v&&s<=MAX_HASH_BYTES?E.digest("hex"):void 0;return{endedAt:w,body:(0,http_store_1.keepBody)(i,M,s,n.paths,R)}})()}g(readResponse,"readResponse"),l(readResponse,"readResponse");async function requestPart(e,r,o,n,i,c){const{headers:a,redacted:t}=(0,http_store_1.redactHeaders)(e.headers);c.push(...t);const d=o==="bodies"&&r.length>1?(0,http_store_1.redactQuery)(r):[];let s;if(o==="bodies"){const m=e.contentType.split(";")[0].trim().toLowerCase();if(n)s={contentType:m,size:e.size??e.bytes?.byteLength??0,kept:0,truncated:!1,omitted:"ai"};else if(e.omitted)s={contentType:m,size:e.size??0,kept:0,truncated:!1,omitted:e.omitted};else{const f=e.bytes??await e.pending;f&&f.byteLength&&(s=(0,http_store_1.keepBody)(e.contentType,f,e.size??f.byteLength,i))}}return{headers:a,...d.length?{query:d}:{},...s?{body:s}:{}}}g(requestPart,"requestPart"),l(requestPart,"requestPart");
package/lib/http-store.js CHANGED
@@ -1 +1 @@
1
- "use strict";var l=Object.defineProperty;var d=(e,t)=>l(e,"name",{value:t,configurable:!0});var x=Object.defineProperty,u=d((e,t)=>x(e,"name",{value:t,configurable:!0}),"u"),f=Object.defineProperty,s=u((e,t)=>f(e,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.newExchangeId=exports.MAX_KEPT_BYTES=exports.REMOVED=void 0,exports.httpCaptureMode=httpCaptureMode,exports.redactHeaders=redactHeaders,exports.redactQuery=redactQuery,exports.keepBody=keepBody,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"}d(httpCaptureMode,"httpCaptureMode"),u(httpCaptureMode,"httpCaptureMode"),s(httpCaptureMode,"httpCaptureMode"),exports.REMOVED="\u2022\u2022\u2022\u2022 redacted",exports.MAX_KEPT_BYTES=64*1024;const MAX_PARSE_BYTES=2*1024*1024,newExchangeId=s(()=>`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(o=>r[o]!==void 0).map(o=>`${o}=${o==="exp"&&typeof r[o]=="number"?new Date(r[o]*1e3).toISOString():String(r[o]).slice(0,80)}`).join(" \xB7 ")||"no claims"} \xB7 ${exports.REMOVED.split(" ")[0]} signature`}catch{return}}d(jwtClaims,"jwtClaims"),u(jwtClaims,"jwtClaims"),s(jwtClaims,"jwtClaims");function redactHeaders(e){const t=[],r=[];for(const[o,p]of e){const n=o.toLowerCase();if(CREDENTIAL_HEADERS.test(n)||(0,redact_1.isSecretParam)(n)){r.push(n);const a=/^bearer\s+(\S+)$/i.exec(p.trim()),i=a?jwtClaims(a[1]):void 0,c=/^(\w+)\s+\S/.exec(p.trim())?.[1];t.push([n,i?`Bearer ${i}`:c&&n.endsWith("authorization")?`${c} ${exports.REMOVED}`:exports.REMOVED])}else t.push([n,(0,ai_store_1.redactAiText)(p).slice(0,2048)])}return{headers:t,redacted:r}}d(redactHeaders,"redactHeaders"),u(redactHeaders,"redactHeaders"),s(redactHeaders,"redactHeaders");function redactQuery(e){const t=[];try{for(const[r,o]of new URLSearchParams(e))t.push([r,(0,redact_1.isSecretParam)(r)||CREDENTIAL_FIELD.test(r)?exports.REMOVED:(0,ai_store_1.redactAiText)(o).slice(0,1024)])}catch{}return t.slice(0,100)}d(redactQuery,"redactQuery"),u(redactQuery,"redactQuery"),s(redactQuery,"redactQuery");function redactJson(e,t,r,o=0){if(o>32||e===null||typeof e!="object")return typeof e=="string"?(0,ai_store_1.redactAiText)(e):e;if(Array.isArray(e))return e.map((n,a)=>redactJson(n,`${t}[${a}]`,r,o+1));const p={};for(const[n,a]of Object.entries(e)){const i=t?`${t}.${n}`:n;CREDENTIAL_FIELD.test(n)&&a!==null&&typeof a!="object"?(p[n]=exports.REMOVED,r.length<50&&r.push(i)):p[n]=redactJson(a,i,r,o+1)}return p}d(redactJson,"redactJson"),u(redactJson,"redactJson"),s(redactJson,"redactJson");const textual=s(e=>/json|^text\/|x-www-form-urlencoded|xml|javascript|graphql|event-stream/i.test(e)||e==="","textual");function keepBody(e,t,r,o,p){const n=e.split(";")[0].trim().toLowerCase();if(!textual(n))return{contentType:n||"application/octet-stream",size:r,kept:0,truncated:!1,omitted:"binary",...p?{sha256:p}:{}};const a=t.byteLength>=r&&r<=MAX_PARSE_BYTES,i=Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8");let c=i;if(a&&/json/.test(n))try{c=JSON.stringify(redactJson(JSON.parse(i),"",o))}catch{c=(0,ai_store_1.redactAiText)(i)}else a&&/x-www-form-urlencoded/.test(n)?c=new URLSearchParams(redactQuery(i)).toString():c=(0,ai_store_1.redactAiText)(i);const h=Buffer.byteLength(c)>exports.MAX_KEPT_BYTES?Buffer.from(c).subarray(0,exports.MAX_KEPT_BYTES).toString("utf8"):c;return{contentType:n,size:r,kept:Buffer.byteLength(h),text:h,truncated:r>t.byteLength||h.length<c.length}}d(keepBody,"keepBody"),u(keepBody,"keepBody"),s(keepBody,"keepBody");const maxFiles=s(()=>{const e=Number(process.env.LENSMCP_HTTP_MAX_FILES);return Number.isInteger(e)&&e>=10?e:500},"maxFiles");let writes=0;function prune(e){try{const t=readdirSync(e).filter(r=>/^hx_[0-9a-z]+\.json$/.test(r)).sort();for(let r=0;r<t.length-maxFiles();r+=1)try{unlinkSync(`${e}/${t[r]}`)}catch{}}catch{}}d(prune,"prune"),u(prune,"prune"),s(prune,"prune");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);return writeFileSync(`${r}.tmp`,JSON.stringify(e),{mode:384}),renameSync(`${r}.tmp`,r),writes+=1,(writes===1||writes%25===0)&&prune(t),!0}catch{return!1}}d(writeHttpExchange,"writeHttpExchange"),u(writeHttpExchange,"writeHttpExchange"),s(writeHttpExchange,"writeHttpExchange");
1
+ "use strict";var x=Object.defineProperty;var u=(e,t)=>x(e,"name",{value:t,configurable:!0});var f=Object.defineProperty,s=u((e,t)=>f(e,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.newExchangeId=exports.MAX_KEPT_BYTES=exports.REMOVED=void 0,exports.httpCaptureMode=httpCaptureMode,exports.redactHeaders=redactHeaders,exports.redactQuery=redactQuery,exports.keepBody=keepBody,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"),s(httpCaptureMode,"httpCaptureMode"),exports.REMOVED="\u2022\u2022\u2022\u2022 redacted",exports.MAX_KEPT_BYTES=64*1024;const MAX_PARSE_BYTES=2*1024*1024,newExchangeId=s(()=>`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(o=>r[o]!==void 0).map(o=>`${o}=${o==="exp"&&typeof r[o]=="number"?new Date(r[o]*1e3).toISOString():String(r[o]).slice(0,80)}`).join(" \xB7 ")||"no claims"} \xB7 ${exports.REMOVED.split(" ")[0]} signature`}catch{return}}u(jwtClaims,"jwtClaims"),s(jwtClaims,"jwtClaims");function redactHeaders(e){const t=[],r=[];for(const[o,p]of e){const n=o.toLowerCase();if(CREDENTIAL_HEADERS.test(n)||(0,redact_1.isSecretParam)(n)){r.push(n);const i=/^bearer\s+(\S+)$/i.exec(p.trim()),c=i?jwtClaims(i[1]):void 0,a=/^(\w+)\s+\S/.exec(p.trim())?.[1];t.push([n,c?`Bearer ${c}`:a&&n.endsWith("authorization")?`${a} ${exports.REMOVED}`:exports.REMOVED])}else t.push([n,(0,ai_store_1.redactAiText)(p).slice(0,2048)])}return{headers:t,redacted:r}}u(redactHeaders,"redactHeaders"),s(redactHeaders,"redactHeaders");function redactQuery(e){const t=[];try{for(const[r,o]of new URLSearchParams(e))t.push([r,(0,redact_1.isSecretParam)(r)||CREDENTIAL_FIELD.test(r)?exports.REMOVED:(0,ai_store_1.redactAiText)(o).slice(0,1024)])}catch{}return t.slice(0,100)}u(redactQuery,"redactQuery"),s(redactQuery,"redactQuery");function redactJson(e,t,r,o=0){if(o>32||e===null||typeof e!="object")return typeof e=="string"?(0,ai_store_1.redactAiText)(e):e;if(Array.isArray(e))return e.map((n,i)=>redactJson(n,`${t}[${i}]`,r,o+1));const p={};for(const[n,i]of Object.entries(e)){const c=t?`${t}.${n}`:n;CREDENTIAL_FIELD.test(n)&&i!==null&&typeof i!="object"?(p[n]=exports.REMOVED,r.length<50&&r.push(c)):p[n]=redactJson(i,c,r,o+1)}return p}u(redactJson,"redactJson"),s(redactJson,"redactJson");const textual=s(e=>/json|^text\/|x-www-form-urlencoded|xml|javascript|graphql|event-stream/i.test(e)||e==="","textual");function keepBody(e,t,r,o,p){const n=e.split(";")[0].trim().toLowerCase();if(!textual(n))return{contentType:n||"application/octet-stream",size:r,kept:0,truncated:!1,omitted:"binary",...p?{sha256:p}:{}};const i=t.byteLength>=r&&r<=MAX_PARSE_BYTES,c=Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8");let a=c;if(i&&/json/.test(n))try{a=JSON.stringify(redactJson(JSON.parse(c),"",o))}catch{a=(0,ai_store_1.redactAiText)(c)}else i&&/x-www-form-urlencoded/.test(n)?a=new URLSearchParams(redactQuery(c)).toString():a=(0,ai_store_1.redactAiText)(c);const d=Buffer.byteLength(a)>exports.MAX_KEPT_BYTES?Buffer.from(a).subarray(0,exports.MAX_KEPT_BYTES).toString("utf8"):a;return{contentType:n,size:r,kept:Buffer.byteLength(d),text:d,truncated:r>t.byteLength||d.length<a.length}}u(keepBody,"keepBody"),s(keepBody,"keepBody");const maxFiles=s(()=>{const e=Number(process.env.LENSMCP_HTTP_MAX_FILES);return Number.isInteger(e)&&e>=10?e:500},"maxFiles");let writes=0;function prune(e){try{const t=readdirSync(e).filter(r=>/^hx_[0-9a-z]+\.json$/.test(r)).sort();for(let r=0;r<t.length-maxFiles();r+=1)try{unlinkSync(`${e}/${t[r]}`)}catch{}}catch{}}u(prune,"prune"),s(prune,"prune");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);return writeFileSync(`${r}.tmp`,JSON.stringify(e),{mode:384}),renameSync(`${r}.tmp`,r),writes+=1,(writes===1||writes%25===0)&&prune(t),!0}catch{return!1}}u(writeHttpExchange,"writeHttpExchange"),s(writeHttpExchange,"writeHttpExchange");
package/lib/install.js CHANGED
@@ -1 +1 @@
1
- "use strict";var o=Object.defineProperty;var n=(t,r)=>o(t,"name",{value:r,configurable:!0});var p=Object.defineProperty,a=n((t,r)=>p(t,"name",{value:r,configurable:!0}),"a"),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{}}}n(installLensmcpNodeInstrumentation,"installLensmcpNodeInstrumentation"),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_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 +1 @@
1
- "use strict";var f=Object.defineProperty;var u=(e,o)=>f(e,"name",{value:o,configurable:!0});var l=Object.defineProperty,s=u((e,o)=>l(e,"name",{value:o,configurable:!0}),"s"),a=Object.defineProperty,r=s((e,o)=>a(e,"name",{value:o,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installRequireHook=installRequireHook;const tapped=new Set;function runTap(e,o,d){try{o(d)!==!1&&tapped.add(e)}catch{tapped.add(e)}}u(runTap,"runTap"),s(runTap,"runTap"),r(runTap,"runTap");function installRequireHook(e){const o=require("node:module"),d=o._load;o._load=function(n,...i){const c=d.call(this,n,...i),t=e[n];return t&&!tapped.has(n)&&runTap(n,t,c),c};for(const n of Object.keys(e)){if(tapped.has(n))continue;const i=e[n];if(i)try{const c=require.resolve(n),t=require.cache[c];t&&runTap(n,i,t.exports)}catch{}}}u(installRequireHook,"installRequireHook"),s(installRequireHook,"installRequireHook"),r(installRequireHook,"installRequireHook");
1
+ "use strict";var l=Object.defineProperty;var s=(e,n)=>l(e,"name",{value:n,configurable:!0});var a=Object.defineProperty,r=s((e,n)=>a(e,"name",{value:n,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installRequireHook=installRequireHook;const tapped=new Set;function runTap(e,n,u){try{n(u)!==!1&&tapped.add(e)}catch{tapped.add(e)}}s(runTap,"runTap"),r(runTap,"runTap");function installRequireHook(e){const n=require("node:module"),u=n._load;n._load=function(t,...c){const i=u.call(this,t,...c),o=e[t];return o&&!tapped.has(t)&&runTap(t,o,i),i};for(const t of Object.keys(e)){if(tapped.has(t))continue;const c=e[t];if(c)try{const i=require.resolve(t),o=require.cache[i];o&&runTap(t,c,o.exports)}catch{}}}s(installRequireHook,"installRequireHook"),r(installRequireHook,"installRequireHook");
@@ -1 +1 @@
1
- "use strict";var u=Object.defineProperty;var r=(e,t)=>u(e,"name",{value:t,configurable:!0});var a=Object.defineProperty,n=r((e,t)=>a(e,"name",{value:t,configurable:!0}),"n"),f=Object.defineProperty,s=n((e,t)=>f(e,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SQL_ACCOUNT_SETTLE_MS=exports.SQL_ACCOUNT_KIND=void 0,exports.beginSqlStatement=beginSqlStatement,exports.endSqlStatement=endSqlStatement,exports.abandonSqlStatement=abandonSqlStatement;const flood_guard_1=require("./flood-guard"),emit_1=require("./emit"),flow_context_1=require("./flow-context");exports.SQL_ACCOUNT_KIND="db-request-account",exports.SQL_ACCOUNT_SETTLE_MS=1e3;const accountGuard=(0,flood_guard_1.createEventFloodGuard)({burst:120,perSec:20}),accounts=new WeakMap;let accountSeq=0;function newAccountId(){return accountSeq=(accountSeq+1)%16777215,`${Date.now().toString(36)}${accountSeq.toString(36)}${Math.random().toString(36).slice(2,6)}`}r(newAccountId,"newAccountId"),n(newAccountId,"newAccountId"),s(newAccountId,"newAccountId");function beginSqlStatement(e,t,d){if(!e||!t?.flowId||!t.requestId)return;let o=accounts.get(e);if(!o){o={accountId:newAccountId(),ctx:t,seq:0,inFlight:0,statements:0,failed:0,workMs:0,recorded:0,recordedWorkMs:0,suppressed:0,unwritten:0,firstStartedAt:d,lastEndedAt:d,awaitsEnd:!1,ended:!1},accounts.set(e,o);const i=(0,flow_context_1.contextEndOf)(e);if(i&&!i.ended){const c=o;c.awaitsEnd=!0,i.onEnd(()=>endSqlAccount(c))}}return o.inFlight+=1,o.timer&&(clearTimeout(o.timer),o.timer=void 0),o}r(beginSqlStatement,"beginSqlStatement"),n(beginSqlStatement,"beginSqlStatement"),s(beginSqlStatement,"beginSqlStatement");function endSqlStatement(e,t){e&&(e.inFlight=Math.max(0,e.inFlight-1),e.statements+=1,e.workMs+=t.durationMs,t.failed&&(e.failed+=1),t.emitted==="written"?(e.recorded+=1,e.recordedWorkMs+=t.durationMs):t.emitted==="suppressed"?e.suppressed+=1:e.unwritten+=1,e.lastEndedAt=Math.max(e.lastEndedAt,Date.now()),writeWhenDue(e))}r(endSqlStatement,"endSqlStatement"),n(endSqlStatement,"endSqlStatement"),s(endSqlStatement,"endSqlStatement");function abandonSqlStatement(e){e&&(e.inFlight=Math.max(0,e.inFlight-1),writeWhenDue(e))}r(abandonSqlStatement,"abandonSqlStatement"),n(abandonSqlStatement,"abandonSqlStatement"),s(abandonSqlStatement,"abandonSqlStatement");function endSqlAccount(e){e.ended=!0,writeWhenDue(e)}r(endSqlAccount,"endSqlAccount"),n(endSqlAccount,"endSqlAccount"),s(endSqlAccount,"endSqlAccount");function writeWhenDue(e){if(!(e.inFlight>0||e.statements===0)&&!(e.awaitsEnd&&!e.ended)){if(e.ended&&e.seq===0){writeAccount(e);return}settleLater(e)}}r(writeWhenDue,"writeWhenDue"),n(writeWhenDue,"writeWhenDue"),s(writeWhenDue,"writeWhenDue");function settleLater(e){e.timer&&clearTimeout(e.timer);const t=setTimeout(()=>writeAccount(e),exports.SQL_ACCOUNT_SETTLE_MS);t.unref?.(),e.timer=t}r(settleLater,"settleLater"),n(settleLater,"settleLater"),s(settleLater,"settleLater");function writeAccount(e){e.timer&&clearTimeout(e.timer),e.timer=void 0,e.seq+=1;const t=e.suppressed+e.unwritten,d=e.ended?"end":"settled";(0,emit_1.lensEmitOutcome)("lens","info",`SQL account: ${e.statements} statement${e.statements===1?"":"s"}`+(t>0?`, ${t} not on the bus`:", all on the bus"),{kind:exports.SQL_ACCOUNT_KIND,accountId:e.accountId,seq:e.seq,basis:d,statements:e.statements,failed:e.failed,workMs:e.workMs,recorded:e.recorded,recordedWorkMs:e.recordedWorkMs,suppressed:e.suppressed,unwritten:e.unwritten,firstStartedAt:e.firstStartedAt,lastEndedAt:e.lastEndedAt},`lens:sql-account:${emit_1.PROJECT}`,e.ctx,"db",accountGuard)}r(writeAccount,"writeAccount"),n(writeAccount,"writeAccount"),s(writeAccount,"writeAccount");
1
+ "use strict";var a=Object.defineProperty;var n=(t,e)=>a(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,s=n((t,e)=>f(t,"name",{value:e,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SQL_ACCOUNT_SETTLE_MS=exports.SQL_ACCOUNT_KIND=void 0,exports.beginSqlStatement=beginSqlStatement,exports.endSqlStatement=endSqlStatement,exports.abandonSqlStatement=abandonSqlStatement;const flood_guard_1=require("./flood-guard"),emit_1=require("./emit"),flow_context_1=require("./flow-context");exports.SQL_ACCOUNT_KIND="db-request-account",exports.SQL_ACCOUNT_SETTLE_MS=1e3;const accountGuard=(0,flood_guard_1.createEventFloodGuard)({burst:120,perSec:20}),accounts=new WeakMap;let accountSeq=0;function newAccountId(){return accountSeq=(accountSeq+1)%16777215,`${Date.now().toString(36)}${accountSeq.toString(36)}${Math.random().toString(36).slice(2,6)}`}n(newAccountId,"newAccountId"),s(newAccountId,"newAccountId");function beginSqlStatement(t,e,d){if(!t||!e?.flowId||!e.requestId)return;let r=accounts.get(t);if(!r){r={accountId:newAccountId(),ctx:e,seq:0,inFlight:0,statements:0,failed:0,workMs:0,recorded:0,recordedWorkMs:0,suppressed:0,unwritten:0,firstStartedAt:d,lastEndedAt:d,awaitsEnd:!1,ended:!1},accounts.set(t,r);const o=(0,flow_context_1.contextEndOf)(t);if(o&&!o.ended){const i=r;i.awaitsEnd=!0,o.onEnd(()=>endSqlAccount(i))}}return r.inFlight+=1,r.timer&&(clearTimeout(r.timer),r.timer=void 0),r}n(beginSqlStatement,"beginSqlStatement"),s(beginSqlStatement,"beginSqlStatement");function endSqlStatement(t,e){t&&(t.inFlight=Math.max(0,t.inFlight-1),t.statements+=1,t.workMs+=e.durationMs,e.failed&&(t.failed+=1),e.emitted==="written"?(t.recorded+=1,t.recordedWorkMs+=e.durationMs):e.emitted==="suppressed"?t.suppressed+=1:t.unwritten+=1,t.lastEndedAt=Math.max(t.lastEndedAt,Date.now()),writeWhenDue(t))}n(endSqlStatement,"endSqlStatement"),s(endSqlStatement,"endSqlStatement");function abandonSqlStatement(t){t&&(t.inFlight=Math.max(0,t.inFlight-1),writeWhenDue(t))}n(abandonSqlStatement,"abandonSqlStatement"),s(abandonSqlStatement,"abandonSqlStatement");function endSqlAccount(t){t.ended=!0,writeWhenDue(t)}n(endSqlAccount,"endSqlAccount"),s(endSqlAccount,"endSqlAccount");function writeWhenDue(t){if(!(t.inFlight>0||t.statements===0)&&!(t.awaitsEnd&&!t.ended)){if(t.ended&&t.seq===0){writeAccount(t);return}settleLater(t)}}n(writeWhenDue,"writeWhenDue"),s(writeWhenDue,"writeWhenDue");function settleLater(t){t.timer&&clearTimeout(t.timer);const e=setTimeout(()=>writeAccount(t),exports.SQL_ACCOUNT_SETTLE_MS);e.unref?.(),t.timer=e}n(settleLater,"settleLater"),s(settleLater,"settleLater");function writeAccount(t){t.timer&&clearTimeout(t.timer),t.timer=void 0,t.seq+=1;const e=t.suppressed+t.unwritten,d=t.ended?"end":"settled";(0,emit_1.lensEmitOutcome)("lens","info",`SQL account: ${t.statements} statement${t.statements===1?"":"s"}`+(e>0?`, ${e} not on the bus`:", all on the bus"),{kind:exports.SQL_ACCOUNT_KIND,accountId:t.accountId,seq:t.seq,basis:d,statements:t.statements,failed:t.failed,workMs:t.workMs,recorded:t.recorded,recordedWorkMs:t.recordedWorkMs,suppressed:t.suppressed,unwritten:t.unwritten,firstStartedAt:t.firstStartedAt,lastEndedAt:t.lastEndedAt},`lens:sql-account:${emit_1.PROJECT}`,t.ctx,"db",accountGuard)}n(writeAccount,"writeAccount"),s(writeAccount,"writeAccount");
package/lib/tap-ai.js CHANGED
@@ -1 +1 @@
1
- "use strict";var E=Object.defineProperty;var u=(e,t)=>E(e,"name",{value:t,configurable:!0});var R=Object.defineProperty,c=u((e,t)=>R(e,"name",{value:t,configurable:!0}),"c"),x=Object.defineProperty,d=c((e,t)=>x(e,"name",{value:t,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.aiCaptureMode=aiCaptureMode,exports.flushAiTapForTests=flushAiTapForTests,exports.resetAiTapForTests=resetAiTapForTests,exports.tapAi=tapAi;const emit_1=require("./emit"),flow_context_1=require("./flow-context"),ai_providers_1=require("./ai-providers"),ai_store_1=require("./ai-store");function aiCaptureMode(e=process.env){const t=(e.LENSMCP_AI_CAPTURE??"").trim().toLowerCase();return t==="content"?"content":t==="metadata"||t==="1"||t==="true"||t==="on"?"metadata":"off"}u(aiCaptureMode,"aiCaptureMode"),c(aiCaptureMode,"aiCaptureMode"),d(aiCaptureMode,"aiCaptureMode");const MAX_REQUEST_PARSE_BYTES=2*1024*1024,MAX_RESPONSE_PARSE_BYTES=8*1024*1024,MAX_STREAM_BYTES=8*1024*1024,MAX_STREAM_MS=300*1e3,MAX_ENDPOINT_CHARS=256;function locate(e){try{const t=new URL(typeof e=="string"?e:e instanceof URL?e.href:e.url);return{host:t.hostname,port:t.port,pathname:t.pathname}}catch{return}}u(locate,"locate"),c(locate,"locate"),d(locate,"locate");const methodOf=d((e,t)=>{const r=typeof e=="object"&&e!==null&&!(e instanceof URL)?e.method:void 0;return String(t?.method??r??"GET").toUpperCase()},"methodOf"),decode=d(e=>({bytes:e.byteLength,...e.byteLength<=MAX_REQUEST_PARSE_BYTES?{text:Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}:{}}),"decode");function takeRequestBody(e,t){const r=t?.body;if(typeof r=="string")return{text:r,bytes:Buffer.byteLength(r)};if(r instanceof ArrayBuffer)return decode(new Uint8Array(r));if(ArrayBuffer.isView(r))return decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));if(typeof Blob<"u"&&r instanceof Blob)return{bytes:r.size,...r.size<=MAX_REQUEST_PARSE_BYTES?{pending:r.text().catch(()=>{})}:{}};if(r==null&&typeof e=="object"&&e!==null&&!(e instanceof URL)){const n=e;if(!n.bodyUsed&&n.body)try{return{pending:n.clone().text().catch(()=>{})}}catch{return{}}}return{}}u(takeRequestBody,"takeRequestBody"),c(takeRequestBody,"takeRequestBody"),d(takeRequestBody,"takeRequestBody");const sum=d(e=>e.reduce((t,r)=>t+r,0),"sum");function parseJson(e){if(e)try{return JSON.parse(e)}catch{return}}u(parseJson,"parseJson"),c(parseJson,"parseJson"),d(parseJson,"parseJson");function headerOf(e,t){try{return e?.headers?.get?.(t)??""}catch{return""}}u(headerOf,"headerOf"),c(headerOf,"headerOf"),d(headerOf,"headerOf");const statusOf=d(e=>typeof e?.status=="number"?e.status:void 0,"statusOf");function failureKind(e,t){const r=e?.name,n=r==="TimeoutError";return{timedOut:n,aborted:!n&&(r==="AbortError"||t?.aborted===!0)}}u(failureKind,"failureKind"),c(failureKind,"failureKind"),d(failureKind,"failureKind");async function readStream(e,t,r){const n=(0,ai_providers_1.createStreamAccumulator)(t);let i,o=!1;const a=e.body;if(a){const p=a.getReader(),s=new TextDecoder;let m=0;try{for(;;){const{done:g,value:y}=await p.read();if(g)break;if(m+=y.byteLength,n.push(s.decode(y,{stream:!0})),i===void 0&&n.eventCount>0&&(i=Date.now()-r),m>MAX_STREAM_BYTES||Date.now()-r>MAX_STREAM_MS){o=!0,await p.cancel().catch(()=>{});break}}}catch{o=!0}}return{response:n.end(),sse:!0,cut:o,...i!==void 0?{firstEventMs:i}:{}}}u(readStream,"readStream"),c(readStream,"readStream"),d(readStream,"readStream");async function readBody(e){const t={completion:"",toolCalls:[],usage:{}};if(!e.res||!e.clone)return{response:t,sse:!1,cut:!1};try{if(headerOf(e.res,"content-type").includes("text/event-stream"))return await readStream(e.clone,e.target,e.startedAt);const r=Number(headerOf(e.res,"content-length"));if(Number.isFinite(r)&&r>MAX_RESPONSE_PARSE_BYTES)return{response:t,sse:!1,cut:!1};const n=await e.clone.text().catch(()=>{});if(n&&/^\s*(?:event|data):/.test(n)){const i=(0,ai_providers_1.createStreamAccumulator)(e.target);return i.push(n),{response:i.end(),sse:!0,cut:!1}}return{response:(0,ai_providers_1.normalizeResponse)(e.target,parseJson(n)),sse:!1,cut:!1}}catch{return{response:t,sse:!1,cut:!1}}}u(readBody,"readBody"),c(readBody,"readBody"),d(readBody,"readBody");async function capture(e){const t=readBody(e),r=e.request.text??await e.request.pending,n=e.request.bytes??(r?Buffer.byteLength(r):void 0),i=n!==void 0&&n>MAX_REQUEST_PARSE_BYTES,o=(0,ai_providers_1.normalizeRequest)(e.target,i?void 0:parseJson(r)),a=statusOf(e.res),p=await t;let s=p.response;const m=o.stream||p.sse,g=p.firstEventMs,y=p.cut,{aborted:v,timedOut:_}=e.failure!==void 0?failureKind(e.failure,e.signal):{aborted:!1,timedOut:!1};e.failure!==void 0&&(s={...s,error:String(e.failure?.message??e.failure)});const A=v||y,T=Date.now()-e.startedAt,l=s.model??o.model,w=sum(o.messages.map(S=>S.content.length))+(o.system?.length??0);let f,h=!1;if(e.mode==="content"&&e.target.api!=="embeddings"){const S={schemaVersion:1,id:(0,ai_store_1.newAiCallId)(),capturedAt:Date.now(),...e.ctx?.flowId?{flowId:e.ctx.flowId}:{},...e.ctx?.requestId?{requestId:e.ctx.requestId}:{},provider:e.target.provider,api:e.target.api,...l?{model:l}:{},host:e.host,endpoint:e.endpoint,stream:m,...a!==void 0?{status:a}:{},request:{...o.system?{system:o.system}:{},messages:o.messages,...o.tools.length?{tools:o.tools}:{},...Object.keys(o.params).length?{params:o.params}:{}},response:{completion:s.completion,...s.reasoning?{reasoning:s.reasoning}:{},...s.toolCalls.length?{toolCalls:s.toolCalls}:{},...s.finishReason?{finishReason:s.finishReason}:{},usage:s.usage,...s.error?{error:s.error}:{}}},M=(0,ai_store_1.writeAiContent)(S);M&&(f=M.id,h=M.truncated)}const b=a!==void 0&&a>=400||e.failure!==void 0&&!v,C=l??"?";!(0,emit_1.lensEmit)("ai",e.failure!==void 0&&!v?"error":"info",a!==void 0?`ai ${e.target.provider}/${C} ${e.target.api} \u2192 ${a}`:`ai ${e.target.provider}/${C} ${e.target.api} ${v?"aborted":"failed"}`,{name:e.target.provider,kind:"ai-call",provider:e.target.provider,api:e.target.api,...l?{model:l}:{},...o.model&&l&&o.model!==l?{requestedModel:o.model}:{},host:e.host,endpoint:e.endpoint,method:e.method,...a!==void 0?{status:a}:{},stream:m,startedAt:e.startedAt,durationMs:T,...e.ttfbMs!==void 0?{ttfbMs:e.ttfbMs}:{},...g!==void 0?{firstEventMs:g}:{},...Object.keys(s.usage).length?{usage:s.usage}:{},...s.finishReason?{finishReason:s.finishReason}:{},toolCallCount:s.toolCalls.length,sizes:{messageCount:o.messages.length,toolCount:o.tools.length,promptChars:w,completionChars:s.completion.length,...n!==void 0?{requestBytes:n}:{}},...o.inputCount!==void 0?{inputCount:o.inputCount}:{},...s.vectorCount!==void 0?{vectorCount:s.vectorCount}:{},contentCaptured:f!==void 0,...f?{contentRef:f}:{},...h?{truncated:!0}:{},...A?{aborted:!0}:{},..._?{timedOut:!0}:{},...s.error?{error:(0,ai_store_1.redactAiText)(s.error).slice(0,300)}:{}},b?`ai:error:${e.target.provider}:${C}`:`ai:${e.target.provider}:${C}`,e.ctx,"ai")&&f&&(0,ai_store_1.removeAiContent)(f)}u(capture,"capture"),c(capture,"capture"),d(capture,"capture");let savedFetch;const pending=new Set;async function flushAiTapForTests(){await Promise.allSettled([...pending])}u(flushAiTapForTests,"flushAiTapForTests"),c(flushAiTapForTests,"flushAiTapForTests"),d(flushAiTapForTests,"flushAiTapForTests");function resetAiTapForTests(){const e=globalThis;savedFetch&&(e.fetch=savedFetch),delete e.__lensmcpAiTap,savedFetch=void 0,pending.clear()}u(resetAiTapForTests,"resetAiTapForTests"),c(resetAiTapForTests,"resetAiTapForTests"),d(resetAiTapForTests,"resetAiTapForTests");function tapAi(){const e=aiCaptureMode();if(e==="off")return;const t=globalThis;if(typeof t.fetch!="function"||t.__lensmcpAiTap)return;t.__lensmcpAiTap=!0;const r=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS),n=t.fetch.bind(globalThis);savedFetch=t.fetch,t.fetch=(async(i,o)=>{const a=locate(i),p=methodOf(i,o),s=a&&p==="POST"?(0,ai_providers_1.matchTarget)(a.host,a.port,a.pathname,r):void 0;if(!a||!s)return n(i,o);const m=Date.now(),g=(0,flow_context_1.flowContext)(),y=a.pathname.length>MAX_ENDPOINT_CHARS?`${a.pathname.slice(0,MAX_ENDPOINT_CHARS)}\u2026`:a.pathname,v=takeRequestBody(i,o),_=o?.signal??(typeof i=="object"&&i!==null&&!(i instanceof URL)?i.signal:void 0),A=d(h=>{const b=capture(h).catch(()=>{});pending.add(b),b.finally(()=>pending.delete(b))},"track"),T={mode:e,target:s,host:a.host,endpoint:y,method:p,startedAt:m,ctx:g,signal:_,request:v};let l;try{l=await n(i,o)}catch(h){throw A({...T,failure:h}),h}const w=Date.now()-m;let f;try{f=l.clone()}catch{f=void 0}return A({...T,ttfbMs:w,res:l,...f?{clone:f}:{}}),l})}u(tapAi,"tapAi"),c(tapAi,"tapAi"),d(tapAi,"tapAi");
1
+ "use strict";var R=Object.defineProperty;var c=(t,e)=>R(t,"name",{value:e,configurable:!0});var x=Object.defineProperty,d=c((t,e)=>x(t,"name",{value:e,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.aiCaptureMode=aiCaptureMode,exports.flushAiTapForTests=flushAiTapForTests,exports.resetAiTapForTests=resetAiTapForTests,exports.tapAi=tapAi;const emit_1=require("./emit"),flow_context_1=require("./flow-context"),ai_providers_1=require("./ai-providers"),ai_store_1=require("./ai-store");function aiCaptureMode(t=process.env){const e=(t.LENSMCP_AI_CAPTURE??"").trim().toLowerCase();return e==="content"?"content":e==="metadata"||e==="1"||e==="true"||e==="on"?"metadata":"off"}c(aiCaptureMode,"aiCaptureMode"),d(aiCaptureMode,"aiCaptureMode");const MAX_REQUEST_PARSE_BYTES=2*1024*1024,MAX_RESPONSE_PARSE_BYTES=8*1024*1024,MAX_STREAM_BYTES=8*1024*1024,MAX_STREAM_MS=300*1e3,MAX_ENDPOINT_CHARS=256;function locate(t){try{const e=new URL(typeof t=="string"?t:t instanceof URL?t.href:t.url);return{host:e.hostname,port:e.port,pathname:e.pathname}}catch{return}}c(locate,"locate"),d(locate,"locate");const methodOf=d((t,e)=>{const o=typeof t=="object"&&t!==null&&!(t instanceof URL)?t.method:void 0;return String(e?.method??o??"GET").toUpperCase()},"methodOf"),decode=d(t=>({bytes:t.byteLength,...t.byteLength<=MAX_REQUEST_PARSE_BYTES?{text:Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8")}:{}}),"decode");function takeRequestBody(t,e){const o=e?.body;if(typeof o=="string")return{text:o,bytes:Buffer.byteLength(o)};if(o instanceof ArrayBuffer)return decode(new Uint8Array(o));if(ArrayBuffer.isView(o))return decode(new Uint8Array(o.buffer,o.byteOffset,o.byteLength));if(typeof Blob<"u"&&o instanceof Blob)return{bytes:o.size,...o.size<=MAX_REQUEST_PARSE_BYTES?{pending:o.text().catch(()=>{})}:{}};if(o==null&&typeof t=="object"&&t!==null&&!(t instanceof URL)){const s=t;if(!s.bodyUsed&&s.body)try{return{pending:s.clone().text().catch(()=>{})}}catch{return{}}}return{}}c(takeRequestBody,"takeRequestBody"),d(takeRequestBody,"takeRequestBody");const sum=d(t=>t.reduce((e,o)=>e+o,0),"sum");function parseJson(t){if(t)try{return JSON.parse(t)}catch{return}}c(parseJson,"parseJson"),d(parseJson,"parseJson");function headerOf(t,e){try{return t?.headers?.get?.(e)??""}catch{return""}}c(headerOf,"headerOf"),d(headerOf,"headerOf");const statusOf=d(t=>typeof t?.status=="number"?t.status:void 0,"statusOf");function failureKind(t,e){const o=t?.name,s=o==="TimeoutError";return{timedOut:s,aborted:!s&&(o==="AbortError"||e?.aborted===!0)}}c(failureKind,"failureKind"),d(failureKind,"failureKind");async function readStream(t,e,o){const s=(0,ai_providers_1.createStreamAccumulator)(e);let i,r=!1;const a=t.body;if(a){const f=a.getReader(),n=new TextDecoder;let p=0;try{for(;;){const{done:m,value:g}=await f.read();if(m)break;if(p+=g.byteLength,s.push(n.decode(g,{stream:!0})),i===void 0&&s.eventCount>0&&(i=Date.now()-o),p>MAX_STREAM_BYTES||Date.now()-o>MAX_STREAM_MS){r=!0,await f.cancel().catch(()=>{});break}}}catch{r=!0}}return{response:s.end(),sse:!0,cut:r,...i!==void 0?{firstEventMs:i}:{}}}c(readStream,"readStream"),d(readStream,"readStream");async function readBody(t){const e={completion:"",toolCalls:[],usage:{}};if(!t.res||!t.clone)return{response:e,sse:!1,cut:!1};try{if(headerOf(t.res,"content-type").includes("text/event-stream"))return await readStream(t.clone,t.target,t.startedAt);const o=Number(headerOf(t.res,"content-length"));if(Number.isFinite(o)&&o>MAX_RESPONSE_PARSE_BYTES)return{response:e,sse:!1,cut:!1};const s=await t.clone.text().catch(()=>{});if(s&&/^\s*(?:event|data):/.test(s)){const i=(0,ai_providers_1.createStreamAccumulator)(t.target);return i.push(s),{response:i.end(),sse:!0,cut:!1}}return{response:(0,ai_providers_1.normalizeResponse)(t.target,parseJson(s)),sse:!1,cut:!1}}catch{return{response:e,sse:!1,cut:!1}}}c(readBody,"readBody"),d(readBody,"readBody");async function capture(t){const e=readBody(t),o=t.request.text??await t.request.pending,s=t.request.bytes??(o?Buffer.byteLength(o):void 0),i=s!==void 0&&s>MAX_REQUEST_PARSE_BYTES,r=(0,ai_providers_1.normalizeRequest)(t.target,i?void 0:parseJson(o)),a=statusOf(t.res),f=await e;let n=f.response;const p=r.stream||f.sse,m=f.firstEventMs,g=f.cut,{aborted:y,timedOut:T}=t.failure!==void 0?failureKind(t.failure,t.signal):{aborted:!1,timedOut:!1};t.failure!==void 0&&(n={...n,error:String(t.failure?.message??t.failure)});const b=y||g,A=Date.now()-t.startedAt,u=n.model??r.model,_=sum(r.messages.map(w=>w.content.length))+(r.system?.length??0);let l,h=!1;if(t.mode==="content"&&t.target.api!=="embeddings"){const w={schemaVersion:1,id:(0,ai_store_1.newAiCallId)(),capturedAt:Date.now(),...t.ctx?.flowId?{flowId:t.ctx.flowId}:{},...t.ctx?.requestId?{requestId:t.ctx.requestId}:{},provider:t.target.provider,api:t.target.api,...u?{model:u}:{},host:t.host,endpoint:t.endpoint,stream:p,...a!==void 0?{status:a}:{},request:{...r.system?{system:r.system}:{},messages:r.messages,...r.tools.length?{tools:r.tools}:{},...Object.keys(r.params).length?{params:r.params}:{}},response:{completion:n.completion,...n.reasoning?{reasoning:n.reasoning}:{},...n.toolCalls.length?{toolCalls:n.toolCalls}:{},...n.finishReason?{finishReason:n.finishReason}:{},usage:n.usage,...n.error?{error:n.error}:{}}},S=(0,ai_store_1.writeAiContent)(w);S&&(l=S.id,h=S.truncated)}const v=a!==void 0&&a>=400||t.failure!==void 0&&!y,C=u??"?";!(0,emit_1.lensEmit)("ai",t.failure!==void 0&&!y?"error":"info",a!==void 0?`ai ${t.target.provider}/${C} ${t.target.api} \u2192 ${a}`:`ai ${t.target.provider}/${C} ${t.target.api} ${y?"aborted":"failed"}`,{name:t.target.provider,kind:"ai-call",provider:t.target.provider,api:t.target.api,...u?{model:u}:{},...r.model&&u&&r.model!==u?{requestedModel:r.model}:{},host:t.host,endpoint:t.endpoint,method:t.method,...a!==void 0?{status:a}:{},stream:p,startedAt:t.startedAt,durationMs:A,...t.ttfbMs!==void 0?{ttfbMs:t.ttfbMs}:{},...m!==void 0?{firstEventMs:m}:{},...Object.keys(n.usage).length?{usage:n.usage}:{},...n.finishReason?{finishReason:n.finishReason}:{},toolCallCount:n.toolCalls.length,sizes:{messageCount:r.messages.length,toolCount:r.tools.length,promptChars:_,completionChars:n.completion.length,...s!==void 0?{requestBytes:s}:{}},...r.inputCount!==void 0?{inputCount:r.inputCount}:{},...n.vectorCount!==void 0?{vectorCount:n.vectorCount}:{},contentCaptured:l!==void 0,...l?{contentRef:l}:{},...h?{truncated:!0}:{},...b?{aborted:!0}:{},...T?{timedOut:!0}:{},...n.error?{error:(0,ai_store_1.redactAiText)(n.error).slice(0,300)}:{}},v?`ai:error:${t.target.provider}:${C}`:`ai:${t.target.provider}:${C}`,t.ctx,"ai")&&l&&(0,ai_store_1.removeAiContent)(l)}c(capture,"capture"),d(capture,"capture");let savedFetch;const pending=new Set;async function flushAiTapForTests(){await Promise.allSettled([...pending])}c(flushAiTapForTests,"flushAiTapForTests"),d(flushAiTapForTests,"flushAiTapForTests");function resetAiTapForTests(){const t=globalThis;savedFetch&&(t.fetch=savedFetch),delete t.__lensmcpAiTap,savedFetch=void 0,pending.clear()}c(resetAiTapForTests,"resetAiTapForTests"),d(resetAiTapForTests,"resetAiTapForTests");function tapAi(){const t=aiCaptureMode();if(t==="off")return;const e=globalThis;if(typeof e.fetch!="function"||e.__lensmcpAiTap)return;e.__lensmcpAiTap=!0;const o=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS),s=e.fetch.bind(globalThis);savedFetch=e.fetch,e.fetch=(async(i,r)=>{const a=locate(i),f=methodOf(i,r),n=a&&f==="POST"?(0,ai_providers_1.matchTarget)(a.host,a.port,a.pathname,o):void 0;if(!a||!n)return s(i,r);const p=Date.now(),m=(0,flow_context_1.flowContext)(),g=a.pathname.length>MAX_ENDPOINT_CHARS?`${a.pathname.slice(0,MAX_ENDPOINT_CHARS)}\u2026`:a.pathname,y=takeRequestBody(i,r),T=r?.signal??(typeof i=="object"&&i!==null&&!(i instanceof URL)?i.signal:void 0),b=d(h=>{const v=capture(h).catch(()=>{});pending.add(v),v.finally(()=>pending.delete(v))},"track"),A={mode:t,target:n,host:a.host,endpoint:g,method:f,startedAt:p,ctx:m,signal:T,request:y};let u;try{u=await s(i,r)}catch(h){throw b({...A,failure:h}),h}const _=Date.now()-p;let l;try{l=u.clone()}catch{l=void 0}return b({...A,ttfbMs:_,res:u,...l?{clone:l}:{}}),u})}c(tapAi,"tapAi"),d(tapAi,"tapAi");
package/lib/tap-bullmq.js CHANGED
@@ -1 +1 @@
1
- "use strict";var y=Object.defineProperty;var f=(t,e)=>y(t,"name",{value:e,configurable:!0});var b=Object.defineProperty,a=f((t,e)=>b(t,"name",{value:e,configurable:!0}),"a"),g=Object.defineProperty,i=a((t,e)=>g(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.bullmqTap=bullmqTap,exports.stopWorkIntake=stopWorkIntake,exports.workIntakeReport=workIntakeReport,exports.resetQueueStatePublishersForTests=resetQueueStatePublishersForTests,exports.resetWorkIntakeForTests=resetWorkIntakeForTests;const active_work_1=require("./active-work"),workerGeneration=new WeakMap,headless_flow_1=require("@lensmcp/core/headless-flow"),emit_1=require("./emit"),flow_context_1=require("./flow-context");function jobFlow(t){const e=t?.opts?.__lensmcpFlow;return e&&typeof e=="object"?e:void 0}f(jobFlow,"jobFlow"),a(jobFlow,"jobFlow"),i(jobFlow,"jobFlow");const jobLegId=i((t,e)=>`job:${t}#${e?.id??"?"}`,"jobLegId");function flowOfJob(t,e){const o=jobFlow(e)?.flowId;if(o)return{flowId:o,own:!1};if((0,headless_flow_1.headlessFlowsEnabled)())return{flowId:(0,headless_flow_1.headlessJobFlowId)(t,e?.id),own:!0}}f(flowOfJob,"flowOfJob"),a(flowOfJob,"flowOfJob"),i(flowOfJob,"flowOfJob");const publishers=new Map,sources=new Map,sourceFor=i(t=>{let e=sources.get(t);return e||sources.set(t,e={}),e},"sourceFor"),usable=i(t=>!!t&&t.closing===void 0,"usable"),currentQueue=i(t=>{const e=sources.get(t),o=e?.app?.deref();return usable(o)?o:e?.own},"currentQueue");function ownConnection(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.duplicate=="function")try{return e.duplicate()}catch{return}return Object.fromEntries(Object.entries(e).filter(([,o])=>typeof o!="function"))}f(ownConnection,"ownConnection"),a(ownConnection,"ownConnection"),i(ownConnection,"ownConnection");function bullmqTap(t){const e=t;if(typeof e?.Queue!="function"||typeof e?.Worker!="function")return!1;tappedQueue=e.Queue;try{tapQueueAdd(e)}catch{}try{tapWorkerEmit(e)}catch{}try{tapWorkerProcess(e)}catch{}try{tapWorkerStamp(e)}catch{}try{tapWorkerIntake(e)}catch{}try{tapWorkerConstruct(e)}catch{}try{installWorkIntakeControl()}catch{}return!0}f(bullmqTap,"bullmqTap"),a(bullmqTap,"bullmqTap"),i(bullmqTap,"bullmqTap");function stampWorker(t){try{if(workerGeneration.has(t))return;workerGeneration.set(t,(0,active_work_1.activeWorkGeneration)()),knownWorkers.add(new WeakRef(t))}catch{}}f(stampWorker,"stampWorker"),a(stampWorker,"stampWorker"),i(stampWorker,"stampWorker");function tapWorkerConstruct(t){const e=t.Worker;if(typeof e!="function"||e.__lensmcpGen)return;const o=new Proxy(e,{construct(r,n,s){const p=Reflect.construct(r,n,s);return stampWorker(p),p}});Object.defineProperty(e,"__lensmcpGen",{value:!0,enumerable:!1}),t.Worker=o}f(tapWorkerConstruct,"tapWorkerConstruct"),a(tapWorkerConstruct,"tapWorkerConstruct"),i(tapWorkerConstruct,"tapWorkerConstruct");function tapWorkerStamp(t){const e=t.Worker?.prototype;if(e)for(const o of["createLockManager","run"]){const r=e[o];if(typeof r!="function"||r.__lensmcpStamp)continue;const n=i(function(...s){return stampWorker(this),r.apply(this,s)},"wrapped");n.__lensmcpStamp=!0,e[o]=n}}f(tapWorkerStamp,"tapWorkerStamp"),a(tapWorkerStamp,"tapWorkerStamp"),i(tapWorkerStamp,"tapWorkerStamp");const knownWorkers=new Set,stoppedWorkers=new WeakSet,intake=new Map,INTAKE_GENERATIONS_KEPT=64;function intakeOf(t){let e=intake.get(t);if(!e){intake.set(t,e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0});for(const o of intake.keys()){if(intake.size<=INTAKE_GENERATIONS_KEPT)break;intake.delete(o)}}return e}f(intakeOf,"intakeOf"),a(intakeOf,"intakeOf"),i(intakeOf,"intakeOf");function beginIntake(t,e){if(e===void 0)return()=>{};const o=intakeOf(e);return o.running+=1,stoppedWorkers.has(t)&&(o.takenAfterStop+=1),()=>{o.running-=1,o.stoppedAt!==void 0&&(o.finishedAfterStop+=1)}}f(beginIntake,"beginIntake"),a(beginIntake,"beginIntake"),i(beginIntake,"beginIntake");function stopWorkIntake(t){const e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0},o=Date.now();for(const r of knownWorkers){const n=r.deref();if(!n){knownWorkers.delete(r);continue}const s=workerGeneration.get(n);if(s===void 0||s>=t||stoppedWorkers.has(n))continue;const p=n.pause;if(typeof p!="function")continue;stoppedWorkers.add(n),knownWorkers.delete(r);try{Promise.resolve(p.call(n,!0)).catch(()=>{})}catch{}const u=intakeOf(s);u.stoppedAt===void 0&&(u.stoppedAt=o,u.runningAtStop=u.running,e.running+=u.running,e.runningAtStop+=u.running),u.workers+=1,e.workers+=1}return e}f(stopWorkIntake,"stopWorkIntake"),a(stopWorkIntake,"stopWorkIntake"),i(stopWorkIntake,"stopWorkIntake");function workIntakeReport(t){const e=intake.get(t);if(!(!e||e.stoppedAt===void 0))return{workers:e.workers,running:e.running,runningAtStop:e.runningAtStop,takenAfterStop:e.takenAfterStop,finishedAfterStop:e.finishedAfterStop}}f(workIntakeReport,"workIntakeReport"),a(workIntakeReport,"workIntakeReport"),i(workIntakeReport,"workIntakeReport");function tapWorkerIntake(t){const e=t.Worker?.prototype;if(!e)return;const o=e.moveToActive;if(typeof o=="function"&&!o.__lensmcpIntake){const n=i(function(...s){return stoppedWorkers.has(this)?Promise.resolve(void 0):o.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.moveToActive=n}const r=e.resume;if(typeof r=="function"&&!r.__lensmcpIntake){const n=i(function(...s){if(!stoppedWorkers.has(this))return r.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.resume=n}}f(tapWorkerIntake,"tapWorkerIntake"),a(tapWorkerIntake,"tapWorkerIntake"),i(tapWorkerIntake,"tapWorkerIntake");function installWorkIntakeControl(){const t=globalThis;t.__lensmcpStopWorkIntake=stopWorkIntake,t.__lensmcpWorkIntakeReport=workIntakeReport}f(installWorkIntakeControl,"installWorkIntakeControl"),a(installWorkIntakeControl,"installWorkIntakeControl"),i(installWorkIntakeControl,"installWorkIntakeControl");function tapWorkerProcess(t){const e=t.Worker?.prototype,o=e?.callProcessJob;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const p=workerGeneration.get(this),u=(0,active_work_1.beginActiveWork)(p),l=beginIntake(this,p),c=i(()=>{u(),l()},"endWork"),d=String(this?.name??n?.queueName??"queue"),w=flowOfJob(d,n);if(!w)return o.call(this,n,...s).finally(c);const h=jobLegId(d,n),k=Date.now(),I={flowId:w.flowId,requestId:h};if(w.own){const m=`job:${d}/${n?.name??"job"}`;(0,emit_1.lensEmit)("queue","info",`job ${n?.name??""}#${n?.id??"?"} \xB7 ${d}`,{queue:d,kind:"flow-origin",job:n?.name,jobId:n?.id,originNodeId:m},`queue-origin:${d}`,{...I,originType:"job",originNodeId:m})}return(0,flow_context_1.runInFlowContext)(I,async()=>{try{const m=await o.call(this,n,...s);return(0,emit_1.lensEmit)("queue","info",`process ${n?.name}#${n?.id} (${Date.now()-k}ms)`,{queue:d,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:k,durationMs:Date.now()-k,status:"ok"},`queue:${d}`,I),m}catch(m){throw(0,emit_1.lensEmit)("queue","error",`process ${n?.name}#${n?.id} failed (${Date.now()-k}ms)`,{queue:d,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:k,durationMs:Date.now()-k,status:"error",error:String(m?.message??m)},`queue:${d}`,I),m}finally{c()}})},"wrapped");r.__lensmcp=!0,e.callProcessJob=r}f(tapWorkerProcess,"tapWorkerProcess"),a(tapWorkerProcess,"tapWorkerProcess"),i(tapWorkerProcess,"tapWorkerProcess");function tapQueueAdd(t){const e=t.Queue?.prototype,o=e?.add;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const p=Date.now(),u=(0,flow_context_1.flowContext)();if(u?.flowId){const c=s[1]??{};s[1]={...c,__lensmcpFlow:{flowId:u.flowId,...u.requestId?{originRequestId:u.requestId}:{}}}}const l=await o.call(this,n,...s);try{const c=String(this?.name??"queue"),d=s[0];let w;try{const k=JSON.stringify(d);w=k&&k!=="undefined"?k.length>300?k.slice(0,299)+"\u2026":k:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`enqueued ${n}#${l?.id} \u2192 ${c}`,{queue:c,kind:"queue-enqueued",job:n,jobId:l?.id,...w?{data:w}:{},startedAt:p,durationMs:Date.now()-p},`queue:${c}`,u);const h=sourceFor(c);h.app?.deref()!==this&&(h.app=new WeakRef(this)),ensureStatePublisher(c)}catch{}return l},"wrapped");r.__lensmcp=!0,e.add=r}f(tapQueueAdd,"tapQueueAdd"),a(tapQueueAdd,"tapQueueAdd"),i(tapQueueAdd,"tapQueueAdd");function tapWorkerEmit(t){const e=t.Worker?.prototype,o=e?.emit;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(function(n,...s){try{observeWorkerEvent(this,String(n),s)}catch{}return o.call(this,n,...s)},"wrapped");r.__lensmcp=!0,e.emit=r}f(tapWorkerEmit,"tapWorkerEmit"),a(tapWorkerEmit,"tapWorkerEmit"),i(tapWorkerEmit,"tapWorkerEmit");function observeWorkerEvent(t,e,o){if(e!=="active"&&e!=="completed"&&e!=="failed")return;const r=String(t.name??"queue"),n=o[0],s=flowOfJob(r,n),p=s?{flowId:s.flowId,requestId:jobLegId(r,n)}:void 0;if(e==="active")(0,emit_1.lensEmit)("queue","info",`processing ${n?.name}#${n?.id}`,{queue:r,kind:"queue-active",jobId:n?.id},`queue:${r}`,p);else if(e==="completed"){let u;try{const l=n?.returnvalue??o[1],c=JSON.stringify(l);u=c&&c!=="undefined"?c.length>160?c.slice(0,159)+"\u2026":c:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`completed ${n?.name}#${n?.id}`,{queue:r,kind:"queue-completed",jobId:n?.id,...u?{returned:u}:{}},`queue:${r}`,p)}else{const u=o[1];(0,emit_1.lensEmit)("queue","error",`job ${n?.id} failed: ${u?.message}`,{queue:r,kind:"queue-failed",jobId:n?.id,error:String(u?.message??u)},`queue:${r}`,p)}if(!currentQueue(r))try{const u=t.opts,l=ownConnection(u?.connection);if(l){const c=snapshotQueueClass();c&&(sourceFor(r).own=new c(r,{connection:l}))}}catch{}ensureStatePublisher(r)}f(observeWorkerEvent,"observeWorkerEvent"),a(observeWorkerEvent,"observeWorkerEvent"),i(observeWorkerEvent,"observeWorkerEvent");let tappedQueue;function snapshotQueueClass(){if(tappedQueue)return tappedQueue;try{return require("bullmq").Queue}catch{return}}f(snapshotQueueClass,"snapshotQueueClass"),a(snapshotQueueClass,"snapshotQueueClass"),i(snapshotQueueClass,"snapshotQueueClass");function ensureStatePublisher(t){if(publishers.has(t))return;let e="";const o=setInterval(()=>{(async()=>{try{const r=currentQueue(t);if(!r)return;const n=await r.getJobCounts(),s=[];for(const l of["active","waiting","failed","completed","delayed"])for(const c of await r.getJobs([l],0,7)){const d=c?.data?.to;s.push({id:String(c.id),name:c.name,state:l,timestamp:c.timestamp??0,...typeof d=="string"?{to:d}:{}})}s.sort((l,c)=>Number(c.timestamp)-Number(l.timestamp));const p=s.slice(0,8),u=JSON.stringify([n,p.map(l=>`${l.id}${l.state}`)]);if(u===e)return;e=u,(0,emit_1.lensEmit)("queue","info",`queue state: ${n.active??0} active \xB7 ${n.waiting??0} waiting \xB7 ${n.failed??0} failed`,{queue:t,kind:"queue-state",counts:n,recent:p},`queue:${t}`)}catch{}})()},2e3);o.unref?.(),publishers.set(t,o)}f(ensureStatePublisher,"ensureStatePublisher"),a(ensureStatePublisher,"ensureStatePublisher"),i(ensureStatePublisher,"ensureStatePublisher");function resetQueueStatePublishersForTests(){for(const t of publishers.values())clearInterval(t);publishers.clear(),sources.clear()}f(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests"),a(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests"),i(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests");function resetWorkIntakeForTests(){knownWorkers.clear(),intake.clear()}f(resetWorkIntakeForTests,"resetWorkIntakeForTests"),a(resetWorkIntakeForTests,"resetWorkIntakeForTests"),i(resetWorkIntakeForTests,"resetWorkIntakeForTests");
1
+ "use strict";var b=Object.defineProperty;var a=(t,e)=>b(t,"name",{value:e,configurable:!0});var g=Object.defineProperty,i=a((t,e)=>g(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.bullmqTap=bullmqTap,exports.stopWorkIntake=stopWorkIntake,exports.workIntakeReport=workIntakeReport,exports.resetQueueStatePublishersForTests=resetQueueStatePublishersForTests,exports.resetWorkIntakeForTests=resetWorkIntakeForTests;const active_work_1=require("./active-work"),workerGeneration=new WeakMap,headless_flow_1=require("@lensmcp/core/headless-flow"),emit_1=require("./emit"),flow_context_1=require("./flow-context");function jobFlow(t){const e=t?.opts?.__lensmcpFlow;return e&&typeof e=="object"?e:void 0}a(jobFlow,"jobFlow"),i(jobFlow,"jobFlow");const jobLegId=i((t,e)=>`job:${t}#${e?.id??"?"}`,"jobLegId");function flowOfJob(t,e){const o=jobFlow(e)?.flowId;if(o)return{flowId:o,own:!1};if((0,headless_flow_1.headlessFlowsEnabled)())return{flowId:(0,headless_flow_1.headlessJobFlowId)(t,e?.id),own:!0}}a(flowOfJob,"flowOfJob"),i(flowOfJob,"flowOfJob");const publishers=new Map,sources=new Map,sourceFor=i(t=>{let e=sources.get(t);return e||sources.set(t,e={}),e},"sourceFor"),usable=i(t=>!!t&&t.closing===void 0,"usable"),currentQueue=i(t=>{const e=sources.get(t),o=e?.app?.deref();return usable(o)?o:e?.own},"currentQueue");function ownConnection(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.duplicate=="function")try{return e.duplicate()}catch{return}return Object.fromEntries(Object.entries(e).filter(([,o])=>typeof o!="function"))}a(ownConnection,"ownConnection"),i(ownConnection,"ownConnection");function bullmqTap(t){const e=t;if(typeof e?.Queue!="function"||typeof e?.Worker!="function")return!1;tappedQueue=e.Queue;try{tapQueueAdd(e)}catch{}try{tapWorkerEmit(e)}catch{}try{tapWorkerProcess(e)}catch{}try{tapWorkerStamp(e)}catch{}try{tapWorkerIntake(e)}catch{}try{tapWorkerConstruct(e)}catch{}try{installWorkIntakeControl()}catch{}return!0}a(bullmqTap,"bullmqTap"),i(bullmqTap,"bullmqTap");function stampWorker(t){try{if(workerGeneration.has(t))return;workerGeneration.set(t,(0,active_work_1.activeWorkGeneration)()),knownWorkers.add(new WeakRef(t))}catch{}}a(stampWorker,"stampWorker"),i(stampWorker,"stampWorker");function tapWorkerConstruct(t){const e=t.Worker;if(typeof e!="function"||e.__lensmcpGen)return;const o=new Proxy(e,{construct(r,n,s){const f=Reflect.construct(r,n,s);return stampWorker(f),f}});Object.defineProperty(e,"__lensmcpGen",{value:!0,enumerable:!1}),t.Worker=o}a(tapWorkerConstruct,"tapWorkerConstruct"),i(tapWorkerConstruct,"tapWorkerConstruct");function tapWorkerStamp(t){const e=t.Worker?.prototype;if(e)for(const o of["createLockManager","run"]){const r=e[o];if(typeof r!="function"||r.__lensmcpStamp)continue;const n=i(function(...s){return stampWorker(this),r.apply(this,s)},"wrapped");n.__lensmcpStamp=!0,e[o]=n}}a(tapWorkerStamp,"tapWorkerStamp"),i(tapWorkerStamp,"tapWorkerStamp");const knownWorkers=new Set,stoppedWorkers=new WeakSet,intake=new Map,INTAKE_GENERATIONS_KEPT=64;function intakeOf(t){let e=intake.get(t);if(!e){intake.set(t,e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0});for(const o of intake.keys()){if(intake.size<=INTAKE_GENERATIONS_KEPT)break;intake.delete(o)}}return e}a(intakeOf,"intakeOf"),i(intakeOf,"intakeOf");function beginIntake(t,e){if(e===void 0)return()=>{};const o=intakeOf(e);return o.running+=1,stoppedWorkers.has(t)&&(o.takenAfterStop+=1),()=>{o.running-=1,o.stoppedAt!==void 0&&(o.finishedAfterStop+=1)}}a(beginIntake,"beginIntake"),i(beginIntake,"beginIntake");function stopWorkIntake(t){const e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0},o=Date.now();for(const r of knownWorkers){const n=r.deref();if(!n){knownWorkers.delete(r);continue}const s=workerGeneration.get(n);if(s===void 0||s>=t||stoppedWorkers.has(n))continue;const f=n.pause;if(typeof f!="function")continue;stoppedWorkers.add(n),knownWorkers.delete(r);try{Promise.resolve(f.call(n,!0)).catch(()=>{})}catch{}const u=intakeOf(s);u.stoppedAt===void 0&&(u.stoppedAt=o,u.runningAtStop=u.running,e.running+=u.running,e.runningAtStop+=u.running),u.workers+=1,e.workers+=1}return e}a(stopWorkIntake,"stopWorkIntake"),i(stopWorkIntake,"stopWorkIntake");function workIntakeReport(t){const e=intake.get(t);if(!(!e||e.stoppedAt===void 0))return{workers:e.workers,running:e.running,runningAtStop:e.runningAtStop,takenAfterStop:e.takenAfterStop,finishedAfterStop:e.finishedAfterStop}}a(workIntakeReport,"workIntakeReport"),i(workIntakeReport,"workIntakeReport");function tapWorkerIntake(t){const e=t.Worker?.prototype;if(!e)return;const o=e.moveToActive;if(typeof o=="function"&&!o.__lensmcpIntake){const n=i(function(...s){return stoppedWorkers.has(this)?Promise.resolve(void 0):o.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.moveToActive=n}const r=e.resume;if(typeof r=="function"&&!r.__lensmcpIntake){const n=i(function(...s){if(!stoppedWorkers.has(this))return r.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.resume=n}}a(tapWorkerIntake,"tapWorkerIntake"),i(tapWorkerIntake,"tapWorkerIntake");function installWorkIntakeControl(){const t=globalThis;t.__lensmcpStopWorkIntake=stopWorkIntake,t.__lensmcpWorkIntakeReport=workIntakeReport}a(installWorkIntakeControl,"installWorkIntakeControl"),i(installWorkIntakeControl,"installWorkIntakeControl");function tapWorkerProcess(t){const e=t.Worker?.prototype,o=e?.callProcessJob;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const f=workerGeneration.get(this),u=(0,active_work_1.beginActiveWork)(f),p=beginIntake(this,f),c=i(()=>{u(),p()},"endWork"),l=String(this?.name??n?.queueName??"queue"),m=flowOfJob(l,n);if(!m)return o.call(this,n,...s).finally(c);const w=jobLegId(l,n),d=Date.now(),h={flowId:m.flowId,requestId:w};if(m.own){const k=`job:${l}/${n?.name??"job"}`;(0,emit_1.lensEmit)("queue","info",`job ${n?.name??""}#${n?.id??"?"} \xB7 ${l}`,{queue:l,kind:"flow-origin",job:n?.name,jobId:n?.id,originNodeId:k},`queue-origin:${l}`,{...h,originType:"job",originNodeId:k})}return(0,flow_context_1.runInFlowContext)(h,async()=>{try{const k=await o.call(this,n,...s);return(0,emit_1.lensEmit)("queue","info",`process ${n?.name}#${n?.id} (${Date.now()-d}ms)`,{queue:l,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:d,durationMs:Date.now()-d,status:"ok"},`queue:${l}`,h),k}catch(k){throw(0,emit_1.lensEmit)("queue","error",`process ${n?.name}#${n?.id} failed (${Date.now()-d}ms)`,{queue:l,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:d,durationMs:Date.now()-d,status:"error",error:String(k?.message??k)},`queue:${l}`,h),k}finally{c()}})},"wrapped");r.__lensmcp=!0,e.callProcessJob=r}a(tapWorkerProcess,"tapWorkerProcess"),i(tapWorkerProcess,"tapWorkerProcess");function tapQueueAdd(t){const e=t.Queue?.prototype,o=e?.add;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const f=Date.now(),u=(0,flow_context_1.flowContext)();if(u?.flowId){const c=s[1]??{};s[1]={...c,__lensmcpFlow:{flowId:u.flowId,...u.requestId?{originRequestId:u.requestId}:{}}}}const p=await o.call(this,n,...s);try{const c=String(this?.name??"queue"),l=s[0];let m;try{const d=JSON.stringify(l);m=d&&d!=="undefined"?d.length>300?d.slice(0,299)+"\u2026":d:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`enqueued ${n}#${p?.id} \u2192 ${c}`,{queue:c,kind:"queue-enqueued",job:n,jobId:p?.id,...m?{data:m}:{},startedAt:f,durationMs:Date.now()-f},`queue:${c}`,u);const w=sourceFor(c);w.app?.deref()!==this&&(w.app=new WeakRef(this)),ensureStatePublisher(c)}catch{}return p},"wrapped");r.__lensmcp=!0,e.add=r}a(tapQueueAdd,"tapQueueAdd"),i(tapQueueAdd,"tapQueueAdd");function tapWorkerEmit(t){const e=t.Worker?.prototype,o=e?.emit;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(function(n,...s){try{observeWorkerEvent(this,String(n),s)}catch{}return o.call(this,n,...s)},"wrapped");r.__lensmcp=!0,e.emit=r}a(tapWorkerEmit,"tapWorkerEmit"),i(tapWorkerEmit,"tapWorkerEmit");function observeWorkerEvent(t,e,o){if(e!=="active"&&e!=="completed"&&e!=="failed")return;const r=String(t.name??"queue"),n=o[0],s=flowOfJob(r,n),f=s?{flowId:s.flowId,requestId:jobLegId(r,n)}:void 0;if(e==="active")(0,emit_1.lensEmit)("queue","info",`processing ${n?.name}#${n?.id}`,{queue:r,kind:"queue-active",jobId:n?.id},`queue:${r}`,f);else if(e==="completed"){let u;try{const p=n?.returnvalue??o[1],c=JSON.stringify(p);u=c&&c!=="undefined"?c.length>160?c.slice(0,159)+"\u2026":c:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`completed ${n?.name}#${n?.id}`,{queue:r,kind:"queue-completed",jobId:n?.id,...u?{returned:u}:{}},`queue:${r}`,f)}else{const u=o[1];(0,emit_1.lensEmit)("queue","error",`job ${n?.id} failed: ${u?.message}`,{queue:r,kind:"queue-failed",jobId:n?.id,error:String(u?.message??u)},`queue:${r}`,f)}if(!currentQueue(r))try{const u=t.opts,p=ownConnection(u?.connection);if(p){const c=snapshotQueueClass();c&&(sourceFor(r).own=new c(r,{connection:p}))}}catch{}ensureStatePublisher(r)}a(observeWorkerEvent,"observeWorkerEvent"),i(observeWorkerEvent,"observeWorkerEvent");let tappedQueue;function snapshotQueueClass(){if(tappedQueue)return tappedQueue;try{return require("bullmq").Queue}catch{return}}a(snapshotQueueClass,"snapshotQueueClass"),i(snapshotQueueClass,"snapshotQueueClass");function ensureStatePublisher(t){if(publishers.has(t))return;let e="";const o=setInterval(()=>{(async()=>{try{const r=currentQueue(t);if(!r)return;const n=await r.getJobCounts(),s=[];for(const p of["active","waiting","failed","completed","delayed"])for(const c of await r.getJobs([p],0,7)){const l=c?.data?.to;s.push({id:String(c.id),name:c.name,state:p,timestamp:c.timestamp??0,...typeof l=="string"?{to:l}:{}})}s.sort((p,c)=>Number(c.timestamp)-Number(p.timestamp));const f=s.slice(0,8),u=JSON.stringify([n,f.map(p=>`${p.id}${p.state}`)]);if(u===e)return;e=u,(0,emit_1.lensEmit)("queue","info",`queue state: ${n.active??0} active \xB7 ${n.waiting??0} waiting \xB7 ${n.failed??0} failed`,{queue:t,kind:"queue-state",counts:n,recent:f},`queue:${t}`)}catch{}})()},2e3);o.unref?.(),publishers.set(t,o)}a(ensureStatePublisher,"ensureStatePublisher"),i(ensureStatePublisher,"ensureStatePublisher");function resetQueueStatePublishersForTests(){for(const t of publishers.values())clearInterval(t);publishers.clear(),sources.clear()}a(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests"),i(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests");function resetWorkIntakeForTests(){knownWorkers.clear(),intake.clear()}a(resetWorkIntakeForTests,"resetWorkIntakeForTests"),i(resetWorkIntakeForTests,"resetWorkIntakeForTests");
package/lib/tap-egress.js CHANGED
@@ -1 +1 @@
1
- "use strict";var M=Object.defineProperty;var u=(e,t)=>M(e,"name",{value:t,configurable:!0});var F=Object.defineProperty,l=u((e,t)=>F(e,"name",{value:t,configurable:!0}),"l"),C=Object.defineProperty,i=l((e,t)=>C(e,"name",{value:t,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(e=>e===""||INTERNAL.some(t=>t.test(e)),"isInternal"),CAPTURE_QUERY=process.env.LENSMCP_EGRESS_QUERY==="1",MAX_PATH_CHARS=256,clipPath=i(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}`)}u(capturePath,"capturePath"),l(capturePath,"capturePath"),i(capturePath,"capturePath");const fingerprintFor=i((e,t)=>t?`external:error:${e}`:`external:${e}`,"fingerprintFor"),pendingExchanges=new Set;async function flushEgressCaptureForTests(){await Promise.allSettled([...pendingExchanges])}u(flushEgressCaptureForTests,"flushEgressCaptureForTests"),l(flushEgressCaptureForTests,"flushEgressCaptureForTests"),i(flushEgressCaptureForTests,"flushEgressCaptureForTests");const headerPairs=i(e=>{const t=[];try{e?.headers?.forEach?.((s,p)=>t.push([p,s]))}catch{}return t},"headerPairs");async function finishExchange(e){const t=[],s=[],p=await(0,http_capture_1.requestPart)(e.request,e.url.search,e.mode,!!e.ai,s,t),r=e.reading?await e.reading.catch(()=>{}):void 0,{headers:c,redacted:a}=(0,http_store_1.redactHeaders)(headerPairs(e.res));t.push(...a);const o=typeof e.res?.status=="number"?e.res.status:void 0,d={schemaVersion:1,id:e.id,capturedAt:Date.now(),side:"egress",service:emit_1.PROJECT,...e.ctx?.flowId?{flowId:e.ctx.flowId}:{},...e.ctx?.requestId?{requestId:e.ctx.requestId}:{},method:e.method,url:`${e.url.protocol}//${e.url.host}${e.path}`,host:e.url.hostname,path:e.path,...o!==void 0?{status:o}:{},...e.res?.statusText?{statusText:e.res.statusText}:{},...e.error?{error:e.error}:{},startedAt:e.startedAt,...e.ttfbMs!==void 0?{ttfbMs:e.ttfbMs}:{},durationMs:(r?.endedAt??Date.now())-e.startedAt,capture:e.mode==="bodies"?"bodies":"headers",request:p,response:{headers:c,...r?.body?{body:r.body}:{},...r?.stream?{stream:r.stream}:{}},redacted:{headers:[...new Set(t)],bodyFields:[...s.map(n=>`request.${n}`),...e.responseFields.map(n=>`response.${n}`)]},...e.ai?{ai:{provider:e.ai}}:{}};(0,http_store_1.writeHttpExchange)(d)}u(finishExchange,"finishExchange"),l(finishExchange,"finishExchange"),i(finishExchange,"finishExchange");function trackExchange(e){const t=finishExchange(e).catch(()=>{});pendingExchanges.add(t),t.finally(()=>pendingExchanges.delete(t))}u(trackExchange,"trackExchange"),l(trackExchange,"trackExchange"),i(trackExchange,"trackExchange");function tapEgress(){tapFetch(),tapHttpModule("http"),tapHttpModule("https")}u(tapEgress,"tapEgress"),l(tapEgress,"tapEgress"),i(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}u(resetEgressTapForTests,"resetEgressTapForTests"),l(resetEgressTapForTests,"resetEgressTapForTests"),i(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)}u(restoreHttp,"restoreHttp"),l(restoreHttp,"restoreHttp"),i(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 a="",o="/",d=!1,n;try{const h=new URL(typeof r=="string"?r:r instanceof URL?r.href:r.url);n=h,a=h.hostname,d=h.search.length>1,o=capturePath(h.pathname,h.search)}catch{}if(isInternal(a))return t(r,c);const g=Date.now(),f=(0,flow_context_1.flowContext)(),T=(0,flow_context_1.liveFlowContext)();T&&(T.externalCallCount=(T.externalCallCount??0)+1);const $=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.method:void 0,x=String(c?.method??$??"GET").toUpperCase(),m=s!=="off"&&n?(0,http_store_1.newExchangeId)():void 0,q=m?(0,http_capture_1.takeRequest)(r,c,s==="bodies"):void 0,w=m&&n&&x==="POST"?(0,ai_providers_1.matchTarget)(a,n.port,n.pathname,p)?.provider:void 0,_=i(h=>({id:m,mode:s,method:x,url:n,path:n.pathname.length>256?`${n.pathname.slice(0,256)}\u2026`:n.pathname,startedAt:g,ctx:f,request:q,...w?{ai:w}:{},responseFields:[],...h}),"job");try{const h=await t(r,c),y=Date.now()-g,v=h.status>=500,b=[];let E;if(m&&s==="bodies")try{E=(0,http_capture_1.readResponse)(h,h.clone(),g,{ai:!!w,paths:b})}catch{E=void 0}const P=(0,emit_1.lensEmit)("external","info",`egress ${x} ${a} \u2192 ${h.status}`,{name:a,kind:"egress",method:x,host:a,path:o,status:h.status,...d?{hasQuery:!0}:{},startedAt:g,durationMs:y,...m?{exchangeId:m}:{}},fingerprintFor(a,v),f);return m&&P&&trackExchange(_({res:h,ttfbMs:y,responseFields:b,...E?{reading:E}:{}})),h}catch(h){const y=String(h?.message??h),v=(0,emit_1.lensEmit)("external","error",`egress ${x} ${a} failed`,{name:a,kind:"egress",method:x,host:a,path:o,...d?{hasQuery:!0}:{},error:y,startedAt:g,durationMs:Date.now()-g,...m?{exchangeId:m}:{}},fingerprintFor(a,!0),f);throw m&&v&&trackExchange(_({error:y})),h}})}u(tapFetch,"tapFetch"),l(tapFetch,"tapFetch"),i(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=i(function(...r){const c=s.apply(this,r);try{observe(r,c)}catch{}return c},"wrapped");p.__lensmcp=!0,t.request=p,typeof t.get=="function"&&(t.get=function(...r){const c=p.apply(this,r);return c.end(),c})}u(tapHttpModule,"tapHttpModule"),l(tapHttpModule,"tapHttpModule"),i(tapHttpModule,"tapHttpModule");function observe(e,t){const{host:s,method:p,path:r,hasQuery:c}=parseTarget(e);if(isInternal(s))return;const a=Date.now(),o=(0,flow_context_1.flowContext)(),d=(0,flow_context_1.liveFlowContext)();d&&(d.externalCallCount=(d.externalCallCount??0)+1);let n=!1;t.once("response",(...g)=>{if(n)return;n=!0;const f=g[0]?.statusCode;(0,emit_1.lensEmit)("external","info",`egress ${p} ${s} \u2192 ${f??"?"}`,{name:s,kind:"egress",method:p,host:s,path:r,...f!=null?{status:f}:{},...c?{hasQuery:!0}:{},startedAt:a,durationMs:Date.now()-a},fingerprintFor(s,f!=null&&f>=500),o)}),t.once("error",(...g)=>{if(n)return;n=!0;const f=g[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(f?.message??f),startedAt:a,durationMs:Date.now()-a},fingerprintFor(s,!0),o)})}u(observe,"observe"),l(observe,"observe"),i(observe,"observe");function parseTarget(e){let t="",s="GET",p="/",r=!1;const c=i((a,o)=>{r=o.length>1,p=capturePath(a,o)},"take");for(const a of e)if(typeof a=="string")try{const o=new URL(a);t=o.hostname,c(o.pathname,o.search)}catch{}else if(a instanceof URL)t=a.hostname,c(a.pathname,a.search);else if(a&&typeof a=="object"){const o=a;if(typeof o.method=="string"&&(s=o.method.toUpperCase()),typeof o.socketPath=="string")return{host:"",method:s,path:p,hasQuery:r};if(typeof o.path=="string"){const d=o.path,n=d.indexOf("?");c(n===-1?d:d.slice(0,n),n===-1?"":d.slice(n))}typeof o.hostname=="string"&&o.hostname?t=o.hostname:typeof o.host=="string"&&o.host&&(t=o.host.split(":")[0]??"")}return{host:t,method:s,path:p,hasQuery:r}}u(parseTarget,"parseTarget"),l(parseTarget,"parseTarget"),i(parseTarget,"parseTarget");
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 +1 @@
1
- "use strict";var v=Object.defineProperty;var s=(e,o)=>v(e,"name",{value:o,configurable:!0});var m=Object.defineProperty,r=s((e,o)=>m(e,"name",{value:o,configurable:!0}),"r"),a=Object.defineProperty,n=r((e,o)=>a(e,"name",{value:o,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.tapEventLoop=tapEventLoop,exports.stopEventLoopTapForTests=stopEventLoopTapForTests;const node_perf_hooks_1=require("node:perf_hooks"),emit_1=require("./emit"),SAMPLE_MS=(()=>{const e=Number(process.env.LENSMCP_EVENT_LOOP_SAMPLE_MS);return Number.isFinite(e)&&e>=1e3?e:3e4})(),REPORT_ABOVE_MS=(()=>{const e=Number(process.env.LENSMCP_EVENT_LOOP_MIN_MS);return Number.isFinite(e)&&e>=0?e:50})(),RESOLUTION_MS=20;let timer,published=!1;function tapEventLoop(){if(process.env.LENSMCP_EVENT_LOOP==="0"||timer)return;const e=(0,node_perf_hooks_1.monitorEventLoopDelay)({resolution:RESOLUTION_MS});e.enable(),timer=setInterval(()=>{const o=RESOLUTION_MS,p=e.mean/1e6;if(!Number.isFinite(p))return;const i=Math.max(0,p-o),t=Math.max(0,e.max/1e6-o),u=Math.max(0,e.percentile(99)/1e6-o);e.reset(),!(published&&t<REPORT_ABOVE_MS)&&(published=!0,(0,emit_1.lensEmit)("perf",t>=1e3?"error":"info",`event loop lag ${i.toFixed(1)}ms mean / ${t.toFixed(1)}ms max`,{kind:"event-loop-lag",lagMs:Number(i.toFixed(2)),maxMs:Number(t.toFixed(2)),p99Ms:Number(u.toFixed(2)),windowMs:SAMPLE_MS},"perf:event-loop-lag",void 0,"performance"))},SAMPLE_MS),timer.unref?.()}s(tapEventLoop,"tapEventLoop"),r(tapEventLoop,"tapEventLoop"),n(tapEventLoop,"tapEventLoop");function stopEventLoopTapForTests(){timer&&clearInterval(timer),timer=void 0,published=!1}s(stopEventLoopTapForTests,"stopEventLoopTapForTests"),r(stopEventLoopTapForTests,"stopEventLoopTapForTests"),n(stopEventLoopTapForTests,"stopEventLoopTapForTests");
1
+ "use strict";var m=Object.defineProperty;var r=(e,o)=>m(e,"name",{value:o,configurable:!0});var a=Object.defineProperty,n=r((e,o)=>a(e,"name",{value:o,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.tapEventLoop=tapEventLoop,exports.stopEventLoopTapForTests=stopEventLoopTapForTests;const node_perf_hooks_1=require("node:perf_hooks"),emit_1=require("./emit"),SAMPLE_MS=(()=>{const e=Number(process.env.LENSMCP_EVENT_LOOP_SAMPLE_MS);return Number.isFinite(e)&&e>=1e3?e:3e4})(),REPORT_ABOVE_MS=(()=>{const e=Number(process.env.LENSMCP_EVENT_LOOP_MIN_MS);return Number.isFinite(e)&&e>=0?e:50})(),RESOLUTION_MS=20;let timer,published=!1;function tapEventLoop(){if(process.env.LENSMCP_EVENT_LOOP==="0"||timer)return;const e=(0,node_perf_hooks_1.monitorEventLoopDelay)({resolution:RESOLUTION_MS});e.enable(),timer=setInterval(()=>{const o=RESOLUTION_MS,s=e.mean/1e6;if(!Number.isFinite(s))return;const i=Math.max(0,s-o),t=Math.max(0,e.max/1e6-o),p=Math.max(0,e.percentile(99)/1e6-o);e.reset(),!(published&&t<REPORT_ABOVE_MS)&&(published=!0,(0,emit_1.lensEmit)("perf",t>=1e3?"error":"info",`event loop lag ${i.toFixed(1)}ms mean / ${t.toFixed(1)}ms max`,{kind:"event-loop-lag",lagMs:Number(i.toFixed(2)),maxMs:Number(t.toFixed(2)),p99Ms:Number(p.toFixed(2)),windowMs:SAMPLE_MS},"perf:event-loop-lag",void 0,"performance"))},SAMPLE_MS),timer.unref?.()}r(tapEventLoop,"tapEventLoop"),n(tapEventLoop,"tapEventLoop");function stopEventLoopTapForTests(){timer&&clearInterval(timer),timer=void 0,published=!1}r(stopEventLoopTapForTests,"stopEventLoopTapForTests"),n(stopEventLoopTapForTests,"stopEventLoopTapForTests");
package/lib/tap-exec.js CHANGED
@@ -1 +1 @@
1
- "use strict";var m=Object.defineProperty;var d=(n,e)=>m(n,"name",{value:e,configurable:!0});var f=Object.defineProperty,l=d((n,e)=>f(n,"name",{value:e,configurable:!0}),"l"),x=Object.defineProperty,u=l((n,e)=>x(n,"name",{value:e,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.tapExec=tapExec;const emit_1=require("./emit"),fmtCmd=u((n,e)=>{const r=Array.isArray(e)?e.map(String).slice(0,8).join(" "):"";return`${String(n)}${r?" "+r:""}`.slice(0,200)},"fmtCmd");function wrap(n,e,r){const t=n[e];if(typeof t!="function"||t.__lensmcp)return;const c=r(t);c.__lensmcp=!0,n[e]=c}d(wrap,"wrap"),l(wrap,"wrap"),u(wrap,"wrap");function observeChild(n,e,r){if(!r||typeof r.once!="function")return;const t=r;if(t.__lensmcpObserved)return;t.__lensmcpObserved=!0;const c=Date.now();r.once("exit",(...o)=>{const i=o[0],a=o[1];(0,emit_1.lensEmit)("exec",i===0?"info":"error",`exec ${e.split(" ")[0]} \u2192 ${i??a}`,{name:"exec",kind:"exec",cmd:e,via:n,...i!=null?{code:i}:{},...a?{signal:a}:{},durationMs:Date.now()-c,...r.pid?{pid:r.pid}:{}})}),r.once("error",(...o)=>{const i=o[0];(0,emit_1.lensEmit)("exec","error",`exec ${e.split(" ")[0]} failed to start`,{name:"exec",kind:"exec",cmd:e,via:n,error:String(i?.message??i),durationMs:Date.now()-c})})}d(observeChild,"observeChild"),l(observeChild,"observeChild"),u(observeChild,"observeChild");function tapExec(){const n=require("node:child_process");for(const e of["spawn","fork"])wrap(n,e,r=>function(t,...c){const o=Array.isArray(c[0])?c[0]:[],i=r.call(this,t,...c);try{observeChild(e,fmtCmd(t,o),i)}catch{}return i});wrap(n,"exec",e=>function(r,...t){const c=e.call(this,r,...t);try{observeChild("exec",String(r).slice(0,200),c)}catch{}return c}),wrap(n,"execFile",e=>function(r,...t){const c=Array.isArray(t[0])?t[0]:[],o=e.call(this,r,...t);try{observeChild("execFile",fmtCmd(r,c),o)}catch{}return o});for(const e of["execSync","execFileSync","spawnSync"])wrap(n,e,r=>function(t,...c){const o=Array.isArray(c[0])?c[0]:[],i=e==="execSync"?String(t).slice(0,200):fmtCmd(t,o),a=Date.now();try{const s=r.call(this,t,...c),p=s&&typeof s=="object"&&"status"in s?s.status??0:0;return(0,emit_1.lensEmit)("exec",p===0?"info":"error",`exec ${i.split(" ")[0]} \u2192 ${p}`,{name:"exec",kind:"exec",cmd:i,via:e,code:p,durationMs:Date.now()-a,sync:!0}),s}catch(s){throw(0,emit_1.lensEmit)("exec","error",`exec ${i.split(" ")[0]} failed`,{name:"exec",kind:"exec",cmd:i,via:e,error:String(s?.message??s),durationMs:Date.now()-a,sync:!0}),s}})}d(tapExec,"tapExec"),l(tapExec,"tapExec"),u(tapExec,"tapExec");
1
+ "use strict";var f=Object.defineProperty;var l=(t,e)=>f(t,"name",{value:e,configurable:!0});var x=Object.defineProperty,u=l((t,e)=>x(t,"name",{value:e,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.tapExec=tapExec;const emit_1=require("./emit"),fmtCmd=u((t,e)=>{const c=Array.isArray(e)?e.map(String).slice(0,8).join(" "):"";return`${String(t)}${c?" "+c:""}`.slice(0,200)},"fmtCmd");function wrap(t,e,c){const n=t[e];if(typeof n!="function"||n.__lensmcp)return;const r=c(n);r.__lensmcp=!0,t[e]=r}l(wrap,"wrap"),u(wrap,"wrap");function observeChild(t,e,c){if(!c||typeof c.once!="function")return;const n=c;if(n.__lensmcpObserved)return;n.__lensmcpObserved=!0;const r=Date.now();c.once("exit",(...s)=>{const i=s[0],a=s[1];(0,emit_1.lensEmit)("exec",i===0?"info":"error",`exec ${e.split(" ")[0]} \u2192 ${i??a}`,{name:"exec",kind:"exec",cmd:e,via:t,...i!=null?{code:i}:{},...a?{signal:a}:{},durationMs:Date.now()-r,...c.pid?{pid:c.pid}:{}})}),c.once("error",(...s)=>{const i=s[0];(0,emit_1.lensEmit)("exec","error",`exec ${e.split(" ")[0]} failed to start`,{name:"exec",kind:"exec",cmd:e,via:t,error:String(i?.message??i),durationMs:Date.now()-r})})}l(observeChild,"observeChild"),u(observeChild,"observeChild");function tapExec(){const t=require("node:child_process");for(const e of["spawn","fork"])wrap(t,e,c=>function(n,...r){const s=Array.isArray(r[0])?r[0]:[],i=c.call(this,n,...r);try{observeChild(e,fmtCmd(n,s),i)}catch{}return i});wrap(t,"exec",e=>function(c,...n){const r=e.call(this,c,...n);try{observeChild("exec",String(c).slice(0,200),r)}catch{}return r}),wrap(t,"execFile",e=>function(c,...n){const r=Array.isArray(n[0])?n[0]:[],s=e.call(this,c,...n);try{observeChild("execFile",fmtCmd(c,r),s)}catch{}return s});for(const e of["execSync","execFileSync","spawnSync"])wrap(t,e,c=>function(n,...r){const s=Array.isArray(r[0])?r[0]:[],i=e==="execSync"?String(n).slice(0,200):fmtCmd(n,s),a=Date.now();try{const o=c.call(this,n,...r),d=o&&typeof o=="object"&&"status"in o?o.status??0:0;return(0,emit_1.lensEmit)("exec",d===0?"info":"error",`exec ${i.split(" ")[0]} \u2192 ${d}`,{name:"exec",kind:"exec",cmd:i,via:e,code:d,durationMs:Date.now()-a,sync:!0}),o}catch(o){throw(0,emit_1.lensEmit)("exec","error",`exec ${i.split(" ")[0]} failed`,{name:"exec",kind:"exec",cmd:i,via:e,error:String(o?.message??o),durationMs:Date.now()-a,sync:!0}),o}})}l(tapExec,"tapExec"),u(tapExec,"tapExec");
package/lib/tap-fs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var y=Object.defineProperty;var u=(t,r)=>y(t,"name",{value:r,configurable:!0});var h=Object.defineProperty,l=u((t,r)=>h(t,"name",{value:r,configurable:!0}),"l"),d=Object.defineProperty,f=l((t,r)=>d(t,"name",{value:r,configurable:!0}),"f");Object.defineProperty(exports,"__esModule",{value:!0}),exports.FsWindow=void 0,exports.tapFs=tapFs;const tslib_1=require("tslib"),os=tslib_1.__importStar(require("node:os")),emit_1=require("./emit"),flow_context_1=require("./flow-context"),PATHS_KEPT=50,PATHS_SENT=20;class FsWindow{static{u(this,"FsWindow")}static{l(this,"FsWindow")}static{f(this,"FsWindow")}constructor(){this.reads=0,this.writes=0,this.bytesRead=0,this.bytesWritten=0,this.counts=new Map,this.ops=new Map}record(r,n,e,s,i,o=!1){r==="read"?(this.reads+=1,this.bytesRead+=e):(this.writes+=1,this.bytesWritten+=e),(this.counts.size<PATHS_KEPT||this.counts.has(n))&&this.counts.set(n,(this.counts.get(n)??0)+1);const a=`${r}\0${n}\0${i?.flowId??""}`,c=this.ops.get(a);c?(c.n+=1,c.bytes+=e,c.at=s,i?.requestId&&(c.requestId=i.requestId)):this.ops.size<PATHS_KEPT&&this.ops.set(a,{path:n,op:r,n:1,bytes:e,...o?{stream:!0}:{},at:s,...i?.flowId?{flowId:i.flowId}:{},...i?.requestId?{requestId:i.requestId}:{}})}drain(){const{reads:r,writes:n,bytesRead:e,bytesWritten:s}=this;if(r+n===0)return;const i=[...this.counts.entries()].sort((a,c)=>c[1]-a[1]).slice(0,3).map(([a])=>a),o=[...this.ops.values()].sort((a,c)=>c.at-a.at).slice(0,PATHS_SENT);return this.reads=this.writes=this.bytesRead=this.bytesWritten=0,this.counts.clear(),this.ops.clear(),{reads:r,writes:n,bytesRead:e,bytesWritten:s,top:i,paths:o}}}exports.FsWindow=FsWindow;const current=new FsWindow;let timer=null;const TMP=os.tmpdir(),CWD=process.cwd(),SKIP=["node_modules","/.nx/","/dist/","/.git/",".lensmcp"],CODE=/\.(?:[cm]?[jt]sx?|map|node)$/;let appending=0;function trackedPath(t){if((0,emit_1.isLensWriting)())return null;const r=typeof t=="string"?t:Buffer.isBuffer(t)?t.toString():t instanceof URL?t.pathname:null;return!r||r===emit_1.EVENT_FILE||r.startsWith(TMP)||SKIP.some(n=>r.includes(n))?null:r}u(trackedPath,"trackedPath"),l(trackedPath,"trackedPath"),f(trackedPath,"trackedPath");function record(t,r,n=0,e,s=!1){const i=trackedPath(r);if(!i||t==="read"&&CODE.test(i))return;const o=i.startsWith(CWD)?i.slice(CWD.length+1):i;current.record(t,o,n,Date.now(),e??(0,flow_context_1.flowContext)(),s),timer||(timer=setTimeout(flush,1e3),timer.unref?.())}u(record,"record"),l(record,"record"),f(record,"record");function flush(){timer=null;const t=current.drain();t&&(0,emit_1.lensEmit)("fs","info",`fs ${t.reads} reads \xB7 ${t.writes} writes`,{name:"fs",kind:"fs-ops",...t},`fs:${emit_1.PROJECT}`)}u(flush,"flush"),l(flush,"flush"),f(flush,"flush");const byteLen=f(t=>typeof t=="string"?Buffer.byteLength(t):Buffer.isBuffer(t)?t.length:0,"byteLen");function wrap(t,r,n){const e=t?.[r];if(!t||typeof e!="function"||e.__lensmcp)return;const s=n(e);s.__lensmcp=!0;try{t[r]=s}catch{}}u(wrap,"wrap"),l(wrap,"wrap"),f(wrap,"wrap");function tapFs(){const t=require("node:fs");wrap(t,"readFileSync",n=>function(e,...s){const i=n.call(this,e,...s);return record("read",e,byteLen(i)),i}),wrap(t,"writeFileSync",n=>function(e,s,...i){const o=appending>0,a=n.call(this,e,s,...i);return o||record("write",e,byteLen(s)),a}),wrap(t,"appendFileSync",n=>function(e,s,...i){appending++;let o;try{o=n.call(this,e,s,...i)}finally{appending--}return record("append",e,byteLen(s)),o}),wrap(t,"readFile",n=>function(e,...s){const i=s[s.length-1];if(typeof i=="function"){const o=(0,flow_context_1.flowContext)();s[s.length-1]=(a,c)=>{a||record("read",e,byteLen(c),o),i(a,c)}}return n.call(this,e,...s)});for(const n of["writeFile","appendFile"])wrap(t,n,e=>function(s,i,...o){const a=o[o.length-1],c=appending>0;if(typeof a=="function"){const w=(0,flow_context_1.flowContext)();o[o.length-1]=p=>{!p&&!c&&record(n==="appendFile"?"append":"write",s,byteLen(i),w),a(p)}}if(n!=="appendFile")return e.call(this,s,i,...o);appending++;try{return e.call(this,s,i,...o)}finally{appending--}});const r=t.promises;wrap(r,"readFile",n=>async function(e,...s){const i=(0,flow_context_1.flowContext)(),o=await n.call(this,e,...s);return record("read",e,byteLen(o),i),o});for(const n of["writeFile","appendFile"])wrap(r,n,e=>async function(s,i,...o){const a=(0,flow_context_1.flowContext)(),c=await e.call(this,s,i,...o);return record(n==="appendFile"?"append":"write",s,byteLen(i),a),c});wrap(t,"createReadStream",n=>function(e,...s){return record("read",e,0,(0,flow_context_1.flowContext)(),!0),n.call(this,e,...s)}),wrap(t,"createWriteStream",n=>function(e,...s){return record("write",e,0,(0,flow_context_1.flowContext)(),!0),n.call(this,e,...s)})}u(tapFs,"tapFs"),l(tapFs,"tapFs"),f(tapFs,"tapFs");
1
+ "use strict";var h=Object.defineProperty;var l=(e,i)=>h(e,"name",{value:i,configurable:!0});var d=Object.defineProperty,f=l((e,i)=>d(e,"name",{value:i,configurable:!0}),"f");Object.defineProperty(exports,"__esModule",{value:!0}),exports.FsWindow=void 0,exports.tapFs=tapFs;const tslib_1=require("tslib"),os=tslib_1.__importStar(require("node:os")),emit_1=require("./emit"),flow_context_1=require("./flow-context"),PATHS_KEPT=50,PATHS_SENT=20;class FsWindow{static{l(this,"FsWindow")}static{f(this,"FsWindow")}constructor(){this.reads=0,this.writes=0,this.bytesRead=0,this.bytesWritten=0,this.counts=new Map,this.ops=new Map}record(i,n,t,s,r,o=!1){i==="read"?(this.reads+=1,this.bytesRead+=t):(this.writes+=1,this.bytesWritten+=t),(this.counts.size<PATHS_KEPT||this.counts.has(n))&&this.counts.set(n,(this.counts.get(n)??0)+1);const c=`${i}\0${n}\0${r?.flowId??""}`,a=this.ops.get(c);a?(a.n+=1,a.bytes+=t,a.at=s,r?.requestId&&(a.requestId=r.requestId)):this.ops.size<PATHS_KEPT&&this.ops.set(c,{path:n,op:i,n:1,bytes:t,...o?{stream:!0}:{},at:s,...r?.flowId?{flowId:r.flowId}:{},...r?.requestId?{requestId:r.requestId}:{}})}drain(){const{reads:i,writes:n,bytesRead:t,bytesWritten:s}=this;if(i+n===0)return;const r=[...this.counts.entries()].sort((c,a)=>a[1]-c[1]).slice(0,3).map(([c])=>c),o=[...this.ops.values()].sort((c,a)=>a.at-c.at).slice(0,PATHS_SENT);return this.reads=this.writes=this.bytesRead=this.bytesWritten=0,this.counts.clear(),this.ops.clear(),{reads:i,writes:n,bytesRead:t,bytesWritten:s,top:r,paths:o}}}exports.FsWindow=FsWindow;const current=new FsWindow;let timer=null;const TMP=os.tmpdir(),CWD=process.cwd(),SKIP=["node_modules","/.nx/","/dist/","/.git/",".lensmcp"],CODE=/\.(?:[cm]?[jt]sx?|map|node)$/;let appending=0;function trackedPath(e){if((0,emit_1.isLensWriting)())return null;const i=typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e instanceof URL?e.pathname:null;return!i||i===emit_1.EVENT_FILE||i.startsWith(TMP)||SKIP.some(n=>i.includes(n))?null:i}l(trackedPath,"trackedPath"),f(trackedPath,"trackedPath");function record(e,i,n=0,t,s=!1){const r=trackedPath(i);if(!r||e==="read"&&CODE.test(r))return;const o=r.startsWith(CWD)?r.slice(CWD.length+1):r;current.record(e,o,n,Date.now(),t??(0,flow_context_1.flowContext)(),s),timer||(timer=setTimeout(flush,1e3),timer.unref?.())}l(record,"record"),f(record,"record");function flush(){timer=null;const e=current.drain();e&&(0,emit_1.lensEmit)("fs","info",`fs ${e.reads} reads \xB7 ${e.writes} writes`,{name:"fs",kind:"fs-ops",...e},`fs:${emit_1.PROJECT}`)}l(flush,"flush"),f(flush,"flush");const byteLen=f(e=>typeof e=="string"?Buffer.byteLength(e):Buffer.isBuffer(e)?e.length:0,"byteLen");function wrap(e,i,n){const t=e?.[i];if(!e||typeof t!="function"||t.__lensmcp)return;const s=n(t);s.__lensmcp=!0;try{e[i]=s}catch{}}l(wrap,"wrap"),f(wrap,"wrap");function tapFs(){const e=require("node:fs");wrap(e,"readFileSync",n=>function(t,...s){const r=n.call(this,t,...s);return record("read",t,byteLen(r)),r}),wrap(e,"writeFileSync",n=>function(t,s,...r){const o=appending>0,c=n.call(this,t,s,...r);return o||record("write",t,byteLen(s)),c}),wrap(e,"appendFileSync",n=>function(t,s,...r){appending++;let o;try{o=n.call(this,t,s,...r)}finally{appending--}return record("append",t,byteLen(s)),o}),wrap(e,"readFile",n=>function(t,...s){const r=s[s.length-1];if(typeof r=="function"){const o=(0,flow_context_1.flowContext)();s[s.length-1]=(c,a)=>{c||record("read",t,byteLen(a),o),r(c,a)}}return n.call(this,t,...s)});for(const n of["writeFile","appendFile"])wrap(e,n,t=>function(s,r,...o){const c=o[o.length-1],a=appending>0;if(typeof c=="function"){const p=(0,flow_context_1.flowContext)();o[o.length-1]=u=>{!u&&!a&&record(n==="appendFile"?"append":"write",s,byteLen(r),p),c(u)}}if(n!=="appendFile")return t.call(this,s,r,...o);appending++;try{return t.call(this,s,r,...o)}finally{appending--}});const i=e.promises;wrap(i,"readFile",n=>async function(t,...s){const r=(0,flow_context_1.flowContext)(),o=await n.call(this,t,...s);return record("read",t,byteLen(o),r),o});for(const n of["writeFile","appendFile"])wrap(i,n,t=>async function(s,r,...o){const c=(0,flow_context_1.flowContext)(),a=await t.call(this,s,r,...o);return record(n==="appendFile"?"append":"write",s,byteLen(r),c),a});wrap(e,"createReadStream",n=>function(t,...s){return record("read",t,0,(0,flow_context_1.flowContext)(),!0),n.call(this,t,...s)}),wrap(e,"createWriteStream",n=>function(t,...s){return record("write",t,0,(0,flow_context_1.flowContext)(),!0),n.call(this,t,...s)})}l(tapFs,"tapFs"),f(tapFs,"tapFs");
@@ -1,6 +1,6 @@
1
- "use strict";var x=Object.defineProperty;var c=(e,t)=>x(e,"name",{value:t,configurable:!0});var T=Object.defineProperty,s=c((e,t)=>T(e,"name",{value:t,configurable:!0}),"s"),S=Object.defineProperty,o=s((e,t)=>S(e,"name",{value:t,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isLoggerEcho=isLoggerEcho,exports.resetNestLoggerTapForTests=resetNestLoggerTapForTests,exports.nestLoggerTap=nestLoggerTap;const redact_1=require("@lensmcp/core/redact"),flood_guard_1=require("./flood-guard"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),LEVELS=["verbose","debug","log","warn","error","fatal"],SEVERITY={verbose:"debug",debug:"debug",log:"info",warn:"warning",error:"error",fatal:"fatal"},MAX_TEXT_CHARS=4e3,TITLE_CHARS=240,shapeGuard=(0,flood_guard_1.createEventFloodGuard)({burst:30,perSec:5}),podGuard=(0,flood_guard_1.createEventFloodGuard)({burst:400,perSec:100});let depth=0;const recent=[],ECHO_WINDOW_MS=2e3,ECHO_NEEDLE_CHARS=96,ECHO_MIN_CHARS=12,MAX_RECENT=64;function isLoggerEcho(e,t=Date.now()){for(let r=recent.length-1;r>=0;r--){const n=recent[r];if(t-n.at>ECHO_WINDOW_MS)return recent.splice(0,r+1),!1;if(e.includes(n.needle)||n.escaped!==void 0&&e.includes(n.escaped))return recent.splice(r,1),!0}return!1}c(isLoggerEcho,"isLoggerEcho"),s(isLoggerEcho,"isLoggerEcho"),o(isLoggerEcho,"isLoggerEcho");function expectEcho(e,t){const r=e.split(`
2
- `,1)[0]??"";if(r.length<ECHO_MIN_CHARS)return;const n=r.slice(0,ECHO_NEEDLE_CHARS),i=JSON.stringify(n).slice(1,-1);recent.push({needle:n,at:t,...i!==n?{escaped:i}:{}}),recent.length>MAX_RECENT&&recent.splice(0,recent.length-MAX_RECENT)}c(expectEcho,"expectEcho"),s(expectEcho,"expectEcho"),o(expectEcho,"expectEcho");function resetNestLoggerTapForTests(){recent.length=0,depth=0}c(resetNestLoggerTapForTests,"resetNestLoggerTapForTests"),s(resetNestLoggerTapForTests,"resetNestLoggerTapForTests"),o(resetNestLoggerTapForTests,"resetNestLoggerTapForTests");function textOf(e){if(typeof e=="string")return e;if(e instanceof Error)return e.stack??`${e.name}: ${e.message}`;if(e===null||typeof e!="object")return String(e);try{return JSON.stringify(e)??String(e)}catch{return Object.prototype.toString.call(e)}}c(textOf,"textOf"),s(textOf,"textOf"),o(textOf,"textOf");function openingOf(e){return typeof e=="string"?e.split(`
1
+ "use strict";var T=Object.defineProperty;var s=(e,t)=>T(e,"name",{value:t,configurable:!0});var S=Object.defineProperty,o=s((e,t)=>S(e,"name",{value:t,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isLoggerEcho=isLoggerEcho,exports.resetNestLoggerTapForTests=resetNestLoggerTapForTests,exports.nestLoggerTap=nestLoggerTap;const redact_1=require("@lensmcp/core/redact"),flood_guard_1=require("./flood-guard"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),LEVELS=["verbose","debug","log","warn","error","fatal"],SEVERITY={verbose:"debug",debug:"debug",log:"info",warn:"warning",error:"error",fatal:"fatal"},MAX_TEXT_CHARS=4e3,TITLE_CHARS=240,shapeGuard=(0,flood_guard_1.createEventFloodGuard)({burst:30,perSec:5}),podGuard=(0,flood_guard_1.createEventFloodGuard)({burst:400,perSec:100});let depth=0;const recent=[],ECHO_WINDOW_MS=2e3,ECHO_NEEDLE_CHARS=96,ECHO_MIN_CHARS=12,MAX_RECENT=64;function isLoggerEcho(e,t=Date.now()){for(let r=recent.length-1;r>=0;r--){const n=recent[r];if(t-n.at>ECHO_WINDOW_MS)return recent.splice(0,r+1),!1;if(e.includes(n.needle)||n.escaped!==void 0&&e.includes(n.escaped))return recent.splice(r,1),!0}return!1}s(isLoggerEcho,"isLoggerEcho"),o(isLoggerEcho,"isLoggerEcho");function expectEcho(e,t){const r=e.split(`
2
+ `,1)[0]??"";if(r.length<ECHO_MIN_CHARS)return;const n=r.slice(0,ECHO_NEEDLE_CHARS),c=JSON.stringify(n).slice(1,-1);recent.push({needle:n,at:t,...c!==n?{escaped:c}:{}}),recent.length>MAX_RECENT&&recent.splice(0,recent.length-MAX_RECENT)}s(expectEcho,"expectEcho"),o(expectEcho,"expectEcho");function resetNestLoggerTapForTests(){recent.length=0,depth=0}s(resetNestLoggerTapForTests,"resetNestLoggerTapForTests"),o(resetNestLoggerTapForTests,"resetNestLoggerTapForTests");function textOf(e){if(typeof e=="string")return e;if(e instanceof Error)return e.stack??`${e.name}: ${e.message}`;if(e===null||typeof e!="object")return String(e);try{return JSON.stringify(e)??String(e)}catch{return Object.prototype.toString.call(e)}}s(textOf,"textOf"),o(textOf,"textOf");function openingOf(e){return typeof e=="string"?e.split(`
3
3
  `,1)[0]??"":e instanceof Error?`${e.name}: ${e.message}`.split(`
4
- `,1)[0]??"":e===null||typeof e!="object"?String(e):"{object}"}c(openingOf,"openingOf"),s(openingOf,"openingOf"),o(openingOf,"openingOf");const looksLikeStack=o(e=>typeof e=="string"&&/\n\s+at\s/.test(e),"looksLikeStack");function shapeOf(e){return e.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"#").replace(/\b[0-9a-f]{12,}\b/gi,"#").replace(/\d+/g,"#").slice(0,80)}c(shapeOf,"shapeOf"),s(shapeOf,"shapeOf"),o(shapeOf,"shapeOf");function capture(e,t,r,n){const i=(0,flow_context_1.flowContext)();if(!i?.flowId&&!i?.requestId)return;const f=t?.context,a=n.slice();let g=typeof f=="string"&&f?f:void 0;!g&&a.length>0&&typeof a[a.length-1]=="string"&&!looksLikeStack(a[a.length-1])&&(g=a.pop());const E=openingOf(r),L=`${g??""}:${shapeOf((0,redact_1.redactText)(E.slice(0,MAX_TEXT_CHARS*2)))}`,_=Date.now(),d=shapeGuard.admit(L),y=d.ok?podGuard.admit("pod"):d;if(!d.ok||!y.ok){expectEcho(E,_);return}const b=[r,...a].filter(p=>p!==void 0).map(textOf);let h="";for(const p of b)h+=h===""?p:(looksLikeStack(p)?`
5
- `:" ")+p;const l=(0,redact_1.redactText)(h.slice(0,MAX_TEXT_CHARS*2)).slice(0,MAX_TEXT_CHARS);if(!l)return;const u=l.split(`
6
- `,1)[0]??"",O=looksLikeStack(l);(0,emit_1.lensLog)(SEVERITY[e],u.length>TITLE_CHARS?`${u.slice(0,TITLE_CHARS)}\u2026`:u,{...O?{stack:l}:l!==u||u.length>TITLE_CHARS?{text:l}:{},stream:"logger",level:e,...g?{logger:g}:{},bucket:L,suppressed:d.suppressed+y.suppressed});for(const p of b)expectEcho(p,_)}c(capture,"capture"),s(capture,"capture"),o(capture,"capture");function wrap(e,t){const r=e[t];if(typeof r!="function"||r.__lensmcpLog)return;const n=o(function(i,...f){if(depth===0)try{capture(t,this,i,f)}catch{}depth+=1;try{return r.call(this,i,...f)}finally{depth-=1}},"wrapped");n.__lensmcpLog=!0,e[t]=n}c(wrap,"wrap"),s(wrap,"wrap"),o(wrap,"wrap");function nestLoggerTap(e){if(process.env.LENSMCP_LOGS==="0")return!0;const t=e?.Logger;if(typeof t!="function"||!t.prototype)return!1;for(const r of LEVELS)wrap(t.prototype,r),wrap(t,r);return!0}c(nestLoggerTap,"nestLoggerTap"),s(nestLoggerTap,"nestLoggerTap"),o(nestLoggerTap,"nestLoggerTap");
4
+ `,1)[0]??"":e===null||typeof e!="object"?String(e):"{object}"}s(openingOf,"openingOf"),o(openingOf,"openingOf");const looksLikeStack=o(e=>typeof e=="string"&&/\n\s+at\s/.test(e),"looksLikeStack");function shapeOf(e){return e.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"#").replace(/\b[0-9a-f]{12,}\b/gi,"#").replace(/\d+/g,"#").slice(0,80)}s(shapeOf,"shapeOf"),o(shapeOf,"shapeOf");function capture(e,t,r,n){const c=(0,flow_context_1.flowContext)();if(!c?.flowId&&!c?.requestId)return;const l=t?.context,i=n.slice();let f=typeof l=="string"&&l?l:void 0;!f&&i.length>0&&typeof i[i.length-1]=="string"&&!looksLikeStack(i[i.length-1])&&(f=i.pop());const h=openingOf(r),E=`${f??""}:${shapeOf((0,redact_1.redactText)(h.slice(0,MAX_TEXT_CHARS*2)))}`,_=Date.now(),u=shapeGuard.admit(E),L=u.ok?podGuard.admit("pod"):u;if(!u.ok||!L.ok){expectEcho(h,_);return}const y=[r,...i].filter(a=>a!==void 0).map(textOf);let d="";for(const a of y)d+=d===""?a:(looksLikeStack(a)?`
5
+ `:" ")+a;const p=(0,redact_1.redactText)(d.slice(0,MAX_TEXT_CHARS*2)).slice(0,MAX_TEXT_CHARS);if(!p)return;const g=p.split(`
6
+ `,1)[0]??"",b=looksLikeStack(p);(0,emit_1.lensLog)(SEVERITY[e],g.length>TITLE_CHARS?`${g.slice(0,TITLE_CHARS)}\u2026`:g,{...b?{stack:p}:p!==g||g.length>TITLE_CHARS?{text:p}:{},stream:"logger",level:e,...f?{logger:f}:{},bucket:E,suppressed:u.suppressed+L.suppressed});for(const a of y)expectEcho(a,_)}s(capture,"capture"),o(capture,"capture");function wrap(e,t){const r=e[t];if(typeof r!="function"||r.__lensmcpLog)return;const n=o(function(c,...l){if(depth===0)try{capture(t,this,c,l)}catch{}depth+=1;try{return r.call(this,c,...l)}finally{depth-=1}},"wrapped");n.__lensmcpLog=!0,e[t]=n}s(wrap,"wrap"),o(wrap,"wrap");function nestLoggerTap(e){if(process.env.LENSMCP_LOGS==="0")return!0;const t=e?.Logger;if(typeof t!="function"||!t.prototype)return!1;for(const r of LEVELS)wrap(t.prototype,r),wrap(t,r);return!0}s(nestLoggerTap,"nestLoggerTap"),o(nestLoggerTap,"nestLoggerTap");
package/lib/tap-nest.js CHANGED
@@ -1 +1 @@
1
- "use strict";var y=Object.defineProperty;var p=(e,t)=>y(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,c=p((e,t)=>d(e,"name",{value:t,configurable:!0}),"c"),f=Object.defineProperty,s=c((e,t)=>f(e,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installChildAppBridge=installChildAppBridge,exports.nestTap=nestTap;const emit_1=require("./emit"),WRAPPED=Symbol.for("lensmcp.wrappedRoot"),captures=[],waiters=[];function pushCapture(e){const t=waiters.shift();t?(clearTimeout(t.timer),t.resolve(e)):captures.push(e)}p(pushCapture,"pushCapture"),c(pushCapture,"pushCapture"),s(pushCapture,"pushCapture");function nextCapture(e=6e4){const t=captures.shift();return t?Promise.resolve(t):new Promise((n,o)=>{const i={resolve:n,reject:o,timer:setTimeout(()=>{const r=waiters.indexOf(i);r>=0&&waiters.splice(r,1),o(new Error("[lensmcp] no NestJS app captured within 60s \u2014 does main.ts call app.listen()? (zero-touch pods boot by running your main and intercepting listen)"))},e)};i.timer.unref?.(),waiters.push(i)})}p(nextCapture,"nextCapture"),c(nextCapture,"nextCapture"),s(nextCapture,"nextCapture");function installChildAppBridge(){if(process.env.APP_RUNNER!=="1")return;const e=global,t=s(()=>nextCapture(),"factory");e.createChildApp=t,e.__lensmcpCreateChildApp=t}p(installChildAppBridge,"installChildAppBridge"),c(installChildAppBridge,"installChildAppBridge"),s(installChildAppBridge,"installChildAppBridge");function nestTap(e){const t=e,n=t?.NestFactory,o=n?.create;if(!n||typeof o!="function")return!1;if(o.__lensmcp)return!0;const i=s(async function(r,...l){let a=r;const u=r,m=!!(u?.[WRAPPED]||u?.module?.[WRAPPED]);if(process.env.LENSMCP_NEST!=="0"&&!m)try{a=await buildLensmcpRoot(r)}catch{a=r}return o.call(this??n,a,...l)},"wrapped");if(i.__lensmcp=!0,n.create=i,process.env.APP_RUNNER==="1"){const r=t?.NestApplication?.prototype,l=r?.listen;if(r&&typeof l=="function"&&!l.__lensmcp){const a=s(async function(u,...m){return captureApp(this,u).catch(h=>(console.error("[lensmcp] pod capture failed, falling back to TCP listen:",h),l.call(this,u,...m)))},"listenWrapped");a.__lensmcp=!0,r.listen=a}}return!0}p(nestTap,"nestTap"),c(nestTap,"nestTap"),s(nestTap,"nestTap");async function buildLensmcpRoot(e){const t=await import("@lensmcp/nest-instrumentation"),n=require("@nestjs/common"),o=t.LensmcpModule.forRoot({projectName:emit_1.PROJECT,trace:{autoInstrumentMethods:!0},memory:{mode:"light",scope:"all"}});class i{static{p(this,"i")}static{c(this,"n")}static{s(this,"LensmcpZeroTouchRoot")}}return i[WRAPPED]=!0,n.Module({imports:[o,e]})(i),i}p(buildLensmcpRoot,"buildLensmcpRoot"),c(buildLensmcpRoot,"buildLensmcpRoot"),s(buildLensmcpRoot,"buildLensmcpRoot");async function captureApp(e,t){await e.init();let n=e.getHttpAdapter?.()?.getInstance?.();if(typeof n!="function"){const o=n;o?.ready&&await o.ready(),typeof o?.routing=="function"&&(n=s((i,r)=>o.routing(i,r),"handler"))}if(typeof n!="function")throw new Error("[lensmcp] cannot derive a request handler from the HTTP adapter");return pushCapture({handler:n,serviceConfig:{port:t??process.env.PORT??0},close:s(()=>Promise.resolve(e.close()).then(()=>{}),"close"),app:e}),e.getHttpServer?.()}p(captureApp,"captureApp"),c(captureApp,"captureApp"),s(captureApp,"captureApp");
1
+ "use strict";var d=Object.defineProperty;var c=(e,t)=>d(e,"name",{value:t,configurable:!0});var f=Object.defineProperty,s=c((e,t)=>f(e,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installChildAppBridge=installChildAppBridge,exports.nestTap=nestTap;const emit_1=require("./emit"),WRAPPED=Symbol.for("lensmcp.wrappedRoot"),captures=[],waiters=[];function pushCapture(e){const t=waiters.shift();t?(clearTimeout(t.timer),t.resolve(e)):captures.push(e)}c(pushCapture,"pushCapture"),s(pushCapture,"pushCapture");function nextCapture(e=6e4){const t=captures.shift();return t?Promise.resolve(t):new Promise((n,r)=>{const i={resolve:n,reject:r,timer:setTimeout(()=>{const o=waiters.indexOf(i);o>=0&&waiters.splice(o,1),r(new Error("[lensmcp] no NestJS app captured within 60s \u2014 does main.ts call app.listen()? (zero-touch pods boot by running your main and intercepting listen)"))},e)};i.timer.unref?.(),waiters.push(i)})}c(nextCapture,"nextCapture"),s(nextCapture,"nextCapture");function installChildAppBridge(){if(process.env.APP_RUNNER!=="1")return;const e=global,t=s(()=>nextCapture(),"factory");e.createChildApp=t,e.__lensmcpCreateChildApp=t}c(installChildAppBridge,"installChildAppBridge"),s(installChildAppBridge,"installChildAppBridge");function nestTap(e){const t=e,n=t?.NestFactory,r=n?.create;if(!n||typeof r!="function")return!1;if(r.__lensmcp)return!0;const i=s(async function(o,...a){let p=o;const l=o,u=!!(l?.[WRAPPED]||l?.module?.[WRAPPED]);if(process.env.LENSMCP_NEST!=="0"&&!u)try{p=await buildLensmcpRoot(o)}catch{p=o}return r.call(this??n,p,...a)},"wrapped");if(i.__lensmcp=!0,n.create=i,process.env.APP_RUNNER==="1"){const o=t?.NestApplication?.prototype,a=o?.listen;if(o&&typeof a=="function"&&!a.__lensmcp){const p=s(async function(l,...u){return captureApp(this,l).catch(m=>(console.error("[lensmcp] pod capture failed, falling back to TCP listen:",m),a.call(this,l,...u)))},"listenWrapped");p.__lensmcp=!0,o.listen=p}}return!0}c(nestTap,"nestTap"),s(nestTap,"nestTap");async function buildLensmcpRoot(e){const t=await import("@lensmcp/nest-instrumentation"),n=require("@nestjs/common"),r=t.LensmcpModule.forRoot({projectName:emit_1.PROJECT,trace:{autoInstrumentMethods:!0},memory:{mode:"light",scope:"all"}});class i{static{c(this,"n")}static{s(this,"LensmcpZeroTouchRoot")}}return i[WRAPPED]=!0,n.Module({imports:[r,e]})(i),i}c(buildLensmcpRoot,"buildLensmcpRoot"),s(buildLensmcpRoot,"buildLensmcpRoot");async function captureApp(e,t){await e.init();let n=e.getHttpAdapter?.()?.getInstance?.();if(typeof n!="function"){const r=n;r?.ready&&await r.ready(),typeof r?.routing=="function"&&(n=s((i,o)=>r.routing(i,o),"handler"))}if(typeof n!="function")throw new Error("[lensmcp] cannot derive a request handler from the HTTP adapter");return pushCapture({handler:n,serviceConfig:{port:t??process.env.PORT??0},close:s(()=>Promise.resolve(e.close()).then(()=>{}),"close"),app:e}),e.getHttpServer?.()}c(captureApp,"captureApp"),s(captureApp,"captureApp");
@@ -0,0 +1,5 @@
1
+ /** Wraps the `connect` that `pg.Pool` inherits from pg-pool. True once patched (or already). */
2
+ export declare function pgPoolTap(pg: unknown): boolean;
3
+ /** Tests only: one sampling pass now, and a clean slate. */
4
+ export declare function samplePgPoolsForTests(now?: number): void;
5
+ export declare function resetPgPoolTapForTests(): void;
@@ -0,0 +1,2 @@
1
+ "use strict";var x=Object.defineProperty;var g=(e,o)=>x(e,"name",{value:o,configurable:!0});var M=Object.defineProperty,u=g((e,o)=>M(e,"name",{value:o,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.pgPoolTap=pgPoolTap,exports.samplePgPoolsForTests=samplePgPoolsForTests,exports.resetPgPoolTapForTests=resetPgPoolTapForTests;const pg_errors_1=require("@lensmcp/core/pg-errors"),active_work_1=require("./active-work"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),envMs=u((e,o,i)=>{const r=Number(process.env[e]);return Number.isFinite(r)&&r>=i?r:o},"envMs"),SAMPLE_MS=envMs("LENSMCP_PG_POOL_SAMPLE_MS",1e4,1e3),HOLD_WARN_MS=envMs("LENSMCP_PG_HOLD_WARN_MS",3e4,1e3),SLOW_WAIT_MS=250,BLOCKED_MIN_MS=1e3,WAITS_KEPT=256,SITE_FRAMES=8,stats=new WeakMap,live=[];let nextId=1,timer;const counters=u(e=>({total:e.totalCount??0,idle:e.idleCount??0,waiting:e.waitingCount??0,max:e.options?.max??10}),"counters");function whereOf(e){const o=e.options??{};let i=typeof o.host=="string"?o.host:void 0,r=typeof o.port=="number"||typeof o.port=="string"?String(o.port):void 0,t=typeof o.database=="string"?o.database:void 0;if(typeof o.connectionString=="string")try{const n=new URL(o.connectionString);i??=n.hostname||void 0,r??=n.port||void 0,t??=decodeURIComponent(n.pathname.replace(/^\//,""))||void 0}catch{}return{...t?{database:t}:{},...i?{server:`${i}:${r??5432}`}:{}}}g(whereOf,"whereOf"),u(whereOf,"whereOf");function statsOf(e){let o=stats.get(e);return o||(o={id:nextId++,gen:(0,active_work_1.activeWorkGeneration)(),ref:new WeakRef(e),createdAt:Date.now(),where:whereOf(e),out:new Map,acquires:0,waits:[],waitMax:0,peakWaiting:0,peakTotal:0,failures:0,holdMax:0},stats.set(e,o),live.push(o),startSampling()),o}g(statsOf,"statsOf"),u(statsOf,"statsOf");function siteOf(e){const o=(e.stack??"").split(`
2
+ `).slice(1).map(r=>r.trim()).filter(r=>r.startsWith("at ")&&!/tap-pg-pool\.[cm]?[jt]s:/.test(r)),i=o.filter(r=>!r.includes("node_modules")&&!r.includes("node:"));return(i.length?i:o).slice(0,SITE_FRAMES)}g(siteOf,"siteOf"),u(siteOf,"siteOf");const secs=u(e=>e>=1e4?`${Math.round(e/1e3)} s`:e>=1e3?`${(e/1e3).toFixed(1)} s`:`${Math.round(e)} ms`,"secs");function failed(e,o,i,r,t){o.failures+=1;const n=(0,pg_errors_1.pgConnectReason)(i),s=counters(e),l=e.options?.connectionTimeoutMillis??0,p=n==="pool-wait-timeout"||n==="connect-timeout",d=p&&l>0?Math.max(0,r-l):0,f=d>=Math.max(BLOCKED_MIN_MS,l*.2),a=`${s.total}/${s.max} open, ${s.idle} idle, ${s.waiting} waiting`,c=n==="pool-wait-timeout"?f?`no connection in time \u2014 waited ${secs(r)} on a ${secs(l)} limit: the process was blocked ${secs(d)} (${a})`:`pool full \u2014 no free connection within ${secs(l)} (${a})`:n==="connect-timeout"?`opening a connection took over ${secs(l)}${f?` \u2014 the process was blocked ${secs(d)}`:""} (${a})`:n?`could not get a connection: ${pg_errors_1.PG_CONNECT_MEANING[n]}`:`could not get a connection (${secs(r)})`,h=i;(0,emit_1.lensEmitOutcome)("db","error",c,{name:"postgres",kind:"db-pool-error",...n?{reason:n}:{},waitedMs:r,...l?{timeoutMs:l}:{},...p?{lateMs:d}:{},...f?{blockedMs:d}:{},...s,pool:o.id,generation:o.gen,serving:(0,active_work_1.activeWorkGeneration)(),pools:live.length,...o.where,error:String(h?.message??i),...typeof h?.code=="string"?{code:h.code}:{}},`db:pool-error:${n??"other"}`,t)}g(failed,"failed"),u(failed,"failed");function checkedOut(e,o,i,r,t,n){if(e.waits.push(n),e.waits.length>WAITS_KEPT&&e.waits.splice(0,e.waits.length-WAITS_KEPT),n>e.waitMax&&(e.waitMax=n),!o||typeof o!="object")return i;const s=o;e.out.set(s,{at:Date.now(),site:r,ctx:t});const l=u(a=>{if(!a)return;e.out.delete(s);const c=Date.now()-a.at;c>e.holdMax&&(e.holdMax=c)},"back"),p=o.release,d=u(a=>typeof a=="function"?function(...c){return l(e.out.get(s)),a.apply(this??o,c)}:a,"wrap"),f=d(p);return f&&(o.release=f),i===p?f:d(i)}g(checkedOut,"checkedOut"),u(checkedOut,"checkedOut");function percentile(e,o){if(!e.length)return 0;const i=e.slice().sort((r,t)=>r-t);return i[Math.min(i.length-1,Math.floor(i.length*o))]}g(percentile,"percentile"),u(percentile,"percentile");function sample(e=Date.now()){for(let t=live.length-1;t>=0;t--){const n=live[t],s=n.ref.deref();(!s||s.ended&&n.out.size===0)&&live.splice(t,1)}const o=(0,active_work_1.activeWorkGeneration)(),i=live.reduce((t,n)=>Math.max(t,n.gen),0),r=live.map(t=>{const n=t.ref.deref(),s=counters(n);return{pool:t.id,generation:t.gen,total:s.total,idle:s.idle,waiting:s.waiting,max:s.max,...n.ending?{ending:!0}:{}}});for(const t of live){const n=t.ref.deref();if(!n)continue;const s=[];let l=0;for(const a of t.out.values()){const c=e-a.at;if(c>l&&(l=c),c<HOLD_WARN_MS||a.warned)continue;a.warned=!0;const h=siteOf(a.site);s.push({heldMs:c,site:h}),(0,emit_1.lensEmitOutcome)("db","info",`a connection held ${secs(c)} and not given back${h[0]?` \u2014 taken ${h[0].replace(/^at /,"at ")}`:""}`,{name:"postgres",kind:"db-pool-hold",heldMs:c,site:h,pool:t.id,generation:t.gen,...counters(n),...t.where},"db:pool-hold",a.ctx)}const p=counters(n),d=t.gen<i&&p.total>0,f=t.peakWaiting>0||t.waitMax>=SLOW_WAIT_MS||t.failures>0||s.length>0;(f||d)&&(0,emit_1.lensEmit)("db","info",d&&!f?`pool of generation ${t.gen} still holds ${p.total} connection(s) \u2014 the app serving now is generation ${o}`:`pool ${p.total}/${p.max} open \xB7 ${t.acquires} checkouts \xB7 wait p95 ${secs(percentile(t.waits,.95))} max ${secs(t.waitMax)}${t.peakWaiting?` \xB7 up to ${t.peakWaiting} waiting`:""}${t.failures?` \xB7 ${t.failures} failed`:""}`,{name:"postgres",kind:"db-pool",pool:t.id,generation:t.gen,serving:o,...p,acquires:t.acquires,waitP95Ms:percentile(t.waits,.95),waitMaxMs:t.waitMax,peakWaiting:t.peakWaiting,peakTotal:t.peakTotal,failures:t.failures,holdMaxMs:t.holdMax,out:t.out.size,longestHeldMs:l,...d?{leftover:!0}:{},windowMs:SAMPLE_MS,pools:r,...t.where},"db:pool",void 0),t.acquires=0,t.waits=[],t.waitMax=0,t.failures=0,t.holdMax=0,t.peakWaiting=p.waiting,t.peakTotal=p.total}}g(sample,"sample"),u(sample,"sample");function startSampling(){timer||(timer=setInterval(()=>{try{sample()}catch{}},SAMPLE_MS),timer.unref?.())}g(startSampling,"startSampling"),u(startSampling,"startSampling");function pgPoolTap(e){let o=e?.Pool?.prototype??null;for(;o&&!Object.prototype.hasOwnProperty.call(o,"connect");)o=Object.getPrototypeOf(o);const i=o?.connect;if(!o||typeof i!="function")return!1;if(i.__lensmcp)return!0;const r=u(function(t){let n;try{n=statsOf(this)}catch{return i.call(this,t)}const s=Date.now(),l=(0,flow_context_1.flowContext)(),p=new Error("pg checkout");n.acquires+=1;const d=u(()=>{try{const a=counters(this);a.waiting>n.peakWaiting&&(n.peakWaiting=a.waiting),a.total>n.peakTotal&&(n.peakTotal=a.total)}catch{}},"note");if(typeof t=="function"){const a=i.call(this,(c,h,w)=>{let m=w;try{c?failed(this,n,c,Date.now()-s,l):m=checkedOut(n,h,w,p,l,Date.now()-s)}catch{}t(c,h,m)});return d(),a}const f=i.call(this);return d(),!f||typeof f.then!="function"?f:f.then(a=>{try{checkedOut(n,a,a?.release,p,l,Date.now()-s)}catch{}return a},a=>{try{failed(this,n,a,Date.now()-s,l)}catch{}throw a})},"wrapped");return r.__lensmcp=!0,o.connect=r,!0}g(pgPoolTap,"pgPoolTap"),u(pgPoolTap,"pgPoolTap");function samplePgPoolsForTests(e){sample(e)}g(samplePgPoolsForTests,"samplePgPoolsForTests"),u(samplePgPoolsForTests,"samplePgPoolsForTests");function resetPgPoolTapForTests(){timer&&clearInterval(timer),timer=void 0,live.splice(0,live.length),nextId=1}g(resetPgPoolTapForTests,"resetPgPoolTapForTests"),u(resetPgPoolTapForTests,"resetPgPoolTapForTests");
package/lib/tap-pg.d.ts CHANGED
@@ -1 +1,9 @@
1
+ /**
2
+ * What the connection calls itself to Postgres: the app's own name, then which service, which app generation and which
3
+ * process opened it — `foodguard lens:engine:g12:p83466` (generations count per process, so the pid tells two pods'
4
+ * apart). Every FoodGuard service connected as `foodguard`, and behind Docker's port proxy
5
+ * every client address is the same, so `pg_stat_activity` could not say whose connections were whose, nor that an
6
+ * app a hot swap replaced still held some. The suffix is kept whole; the app's part is cut to fit.
7
+ */
8
+ export declare function taggedAppName(own: string | undefined, project: string, generation: number, pid?: number): string;
1
9
  export declare function pgTap(exportsObject: unknown): boolean;
package/lib/tap-pg.js CHANGED
@@ -1 +1 @@
1
- "use strict";var k=Object.defineProperty;var u=(t,e)=>k(t,"name",{value:e,configurable:!0});var R=Object.defineProperty,p=u((t,e)=>R(t,"name",{value:e,configurable:!0}),"p"),B=Object.defineProperty,o=p((t,e)=>B(t,"name",{value:e,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.pgTap=pgTap;const redact_1=require("@lensmcp/core/redact"),sql_shape_1=require("@lensmcp/core/sql-shape"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),sql_accounting_1=require("./sql-accounting"),SKIP_OPS=new Set(["BEGIN","START","COMMIT","END","ROLLBACK","SAVEPOINT","RELEASE","SET","RESET","SHOW","DEALLOCATE","DISCARD","LISTEN","UNLISTEN"]),STATEMENT_EVERY_MS=10*6e4,STATEMENT_MAX=8*1024,statementSentAt=new Map,MAX_SHAPES_REMEMBERED=2e3,firstWord=o(t=>(/^\s*(?:(?:\/\*[\s\S]*?\*\/|--[^\n]*\n?)\s*)*(\w+)/.exec(t)?.[1]??"query").toUpperCase(),"firstWord");function parseSql(t){const e=(0,sql_shape_1.sqlShape)(t),r=(e.target??e.tables[0])?.split(".").pop();return{op:e.verb,...r?{table:r}:{},sqlId:e.id,tables:e.tables,...e.name?{name:e.name}:{}}}u(parseSql,"parseSql"),p(parseSql,"parseSql"),o(parseSql,"parseSql");const oneLine=o(t=>t.replace(/\s+/g," ").trim(),"oneLine"),clip=o((t,e)=>t.length>e?t.slice(0,e-1)+"\u2026":t,"clip");function paramPreview(t){if(!(!Array.isArray(t)||t.length===0))return t.slice(0,10).map(e=>{if(e==null)return String(e);const r=typeof e=="string"?e:(()=>{try{return JSON.stringify(e)}catch{return String(e)}})();return clip(r,80)})}u(paramPreview,"paramPreview"),p(paramPreview,"paramPreview"),o(paramPreview,"paramPreview");const rowsOf=o(t=>t?.rowCount??t?.rows?.length??0,"rowsOf");function resultPreview(t){const e=t?.rows;if(!(!Array.isArray(e)||e.length===0))try{return clip(JSON.stringify((0,redact_1.redactDeep)(e.slice(0,2))),240)}catch{return}}u(resultPreview,"resultPreview"),p(resultPreview,"resultPreview"),o(resultPreview,"resultPreview");function connectionOf(t){const e=t,r=e?.connectionParameters,S=typeof e?.database=="string"?e.database:typeof r?.database=="string"?r.database:void 0,s=typeof e?.host=="string"?e.host:typeof r?.host=="string"?r.host:void 0,a=typeof e?.port=="number"||typeof e?.port=="string"?e.port:typeof r?.port=="number"||typeof r?.port=="string"?r.port:5432;return{...S?{database:S}:{},...s?{server:`${s}:${a}`}:{}}}u(connectionOf,"connectionOf"),p(connectionOf,"connectionOf"),o(connectionOf,"connectionOf");function pgTap(t){const e=t?.Client?.prototype,r=e?.query;if(!e||typeof r!="function")return!1;if(r.__lensmcp)return!0;const S=o(function(s,a,g){const f=s,d=typeof f=="string"?f:f?.text;if(!d||f&&typeof f=="object"&&typeof f.submit=="function")return r.call(this,s,a,g);if(SKIP_OPS.has(firstWord(d)))return r.call(this,s,a,g);const{op:x,table:i,sqlId:q,tables:T,name:O}=parseSql(d),D=connectionOf(this),y=x.toLowerCase(),j=`db:${y}:${i??"query"}`,m=Date.now(),A=(0,flow_context_1.flowContext)(),h=(0,flow_context_1.liveFlowContext)();h&&(h.dbCallCount=(h.dbCallCount??0)+1);const w=(0,sql_accounting_1.beginSqlStatement)(h,A,m),C=clip(oneLine(d),500),P=paramPreview(Array.isArray(a)?a:s?.values),E=P&&(0,redact_1.redactSqlParams)(d,P),_=o((n,c)=>{const l=Date.now()-m,$=m-(statementSentAt.get(q)??-1/0)>=STATEMENT_EVERY_MS,N={sqlId:q,...T.length?{tables:T}:{},...O?{sqlName:O}:{},...D,...$?{statement:clip(d.trim(),STATEMENT_MAX)}:{}};let v;if(n)v=(0,emit_1.lensEmitOutcome)("db","error",`${y}${i?" "+i:""} failed (${l}ms)`,{name:"postgres",kind:"db-query",op:y,...i?{table:i}:{},...N,query:C,...E?{params:E}:{},startedAt:m,error:String(n?.message??n),durationMs:l},`db:error:${y}:${i??"query"}`,A);else{const I=rowsOf(c),L=resultPreview(c);v=(0,emit_1.lensEmitOutcome)("db","info",`${y} ${i??"query"} (${I} rows, ${l}ms)`,{name:"postgres",kind:"db-query",op:y,...i?{table:i}:{},...N,query:C,...E?{params:E}:{},...L?{result:L}:{},startedAt:m,rows:I,durationMs:l},j,A)}$&&v==="written"&&(statementSentAt.delete(q),statementSentAt.set(q,m),statementSentAt.size>MAX_SHAPES_REMEMBERED&&statementSentAt.delete(statementSentAt.keys().next().value)),(0,sql_accounting_1.endSqlStatement)(w,{durationMs:l,failed:!!n,emitted:v})},"done"),M=typeof g=="function"?g:typeof a=="function"?a:void 0;if(M){const n=o((c,l)=>{try{_(c,l)}catch{}M(c,l)},"wrappedCb");try{return typeof a=="function"?r.call(this,s,n):r.call(this,s,a,n)}catch(c){throw(0,sql_accounting_1.abandonSqlStatement)(w),c}}let b;try{b=r.call(this,s,a)}catch(n){throw(0,sql_accounting_1.abandonSqlStatement)(w),n}return b&&typeof b.then=="function"?b.then(n=>_(void 0,n),n=>_(n,void 0)):(0,sql_accounting_1.abandonSqlStatement)(w),b},"wrapped");return S.__lensmcp=!0,e.query=S,!0}u(pgTap,"pgTap"),p(pgTap,"pgTap"),o(pgTap,"pgTap");
1
+ "use strict";var D=Object.defineProperty;var c=(t,e)=>D(t,"name",{value:e,configurable:!0});var B=Object.defineProperty,o=c((t,e)=>B(t,"name",{value:e,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.taggedAppName=taggedAppName,exports.pgTap=pgTap;const redact_1=require("@lensmcp/core/redact"),sql_shape_1=require("@lensmcp/core/sql-shape"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),sql_accounting_1=require("./sql-accounting"),tap_pg_pool_1=require("./tap-pg-pool"),active_work_1=require("./active-work"),emit_2=require("./emit"),SKIP_OPS=new Set(["BEGIN","START","COMMIT","END","ROLLBACK","SAVEPOINT","RELEASE","SET","RESET","SHOW","DEALLOCATE","DISCARD","LISTEN","UNLISTEN"]),STATEMENT_EVERY_MS=10*6e4,STATEMENT_MAX=64*1024,statementSentAt=new Map,MAX_SHAPES_REMEMBERED=2e3,firstWord=o(t=>(/^\s*(?:(?:\/\*[\s\S]*?\*\/|--[^\n]*\n?)\s*)*(\w+)/.exec(t)?.[1]??"query").toUpperCase(),"firstWord");function parseSql(t){const e=(0,sql_shape_1.sqlShape)(t),r=(e.target??e.tables[0])?.split(".").pop();return{op:e.verb,...r?{table:r}:{},sqlId:e.id,tables:e.tables,...e.name?{name:e.name}:{}}}c(parseSql,"parseSql"),o(parseSql,"parseSql");const oneLine=o(t=>t.replace(/\s+/g," ").trim(),"oneLine"),clip=o((t,e)=>t.length>e?t.slice(0,e-1)+"\u2026":t,"clip");function paramPreview(t){if(!(!Array.isArray(t)||t.length===0))return t.slice(0,10).map(e=>{if(e==null)return String(e);const r=typeof e=="string"?e:(()=>{try{return JSON.stringify(e)}catch{return String(e)}})();return clip(r,80)})}c(paramPreview,"paramPreview"),o(paramPreview,"paramPreview");const rowsOf=o(t=>t?.rowCount??t?.rows?.length??0,"rowsOf");function resultPreview(t){const e=t?.rows;if(!(!Array.isArray(e)||e.length===0))try{return clip(JSON.stringify((0,redact_1.redactDeep)(e.slice(0,2))),240)}catch{return}}c(resultPreview,"resultPreview"),o(resultPreview,"resultPreview");function connectionOf(t){const e=t,r=e?.connectionParameters,n=typeof e?.database=="string"?e.database:typeof r?.database=="string"?r.database:void 0,a=typeof e?.host=="string"?e.host:typeof r?.host=="string"?r.host:void 0,i=typeof e?.port=="number"||typeof e?.port=="string"?e.port:typeof r?.port=="number"||typeof r?.port=="string"?r.port:5432;return{...n?{database:n}:{},...a?{server:`${a}:${i}`}:{}}}c(connectionOf,"connectionOf"),o(connectionOf,"connectionOf");const APP_NAME_MAX=63;function taggedAppName(t,e,r,n){const a=` lens:${e.replace(/[^\x21-\x7e]/g,"?").replace(/:/g,"_")}${r>0?`:g${r}`:""}${n?`:p${n}`:""}`.slice(0,APP_NAME_MAX);return`${(t??"node").replace(/[^\x20-\x7e]/g,"?").replace(/ lens:\S+$/,"").slice(0,Math.max(0,APP_NAME_MAX-a.length))}${a}`}c(taggedAppName,"taggedAppName"),o(taggedAppName,"taggedAppName");function tagApplicationName(t){if(process.env.LENSMCP_PG_APP_NAME==="0")return;const e=t.getStartupConf;if(typeof e!="function"||e.__lensmcp)return;const r=o(function(){const n=e.call(this);try{n&&typeof n=="object"&&emit_2.PROJECT&&(n.application_name=taggedAppName(typeof n.application_name=="string"?n.application_name:void 0,emit_2.PROJECT,(0,active_work_1.activeWorkGeneration)(),process.pid))}catch{}return n},"wrapped");r.__lensmcp=!0,t.getStartupConf=r}c(tagApplicationName,"tagApplicationName"),o(tagApplicationName,"tagApplicationName");function pgTap(t){const e=t?.Client?.prototype,r=e?.query;if(!e||typeof r!="function")return!1;try{(0,tap_pg_pool_1.pgPoolTap)(t)}catch{}try{tagApplicationName(e)}catch{}if(r.__lensmcp)return!0;const n=o(function(a,i,_){const f=a,d=typeof f=="string"?f:f?.text;if(!d||f&&typeof f=="object"&&typeof f.submit=="function")return r.call(this,a,i,_);if(SKIP_OPS.has(firstWord(d)))return r.call(this,a,i,_);const{op:L,table:p,sqlId:S,tables:v,name:P}=parseSql(d),I=connectionOf(this),m=L.toLowerCase(),R=`db:${m}:${p??"query"}`,g=Date.now(),E=(0,flow_context_1.flowContext)(),b=(0,flow_context_1.liveFlowContext)();b&&(b.dbCallCount=(b.dbCallCount??0)+1);const q=(0,sql_accounting_1.beginSqlStatement)(b,E,g),T=clip(oneLine(d),500),$=paramPreview(Array.isArray(i)?i:a?.values),h=$&&(0,redact_1.redactSqlParams)(d,$),w=o((s,u)=>{const l=Date.now()-g,M=g-(statementSentAt.get(S)??-1/0)>=STATEMENT_EVERY_MS,N={sqlId:S,...v.length?{tables:v}:{},...P?{sqlName:P}:{},...I,...M?{statement:clip(d.trim(),STATEMENT_MAX)}:{}};let A;if(s)A=(0,emit_1.lensEmitOutcome)("db","error",`${m}${p?" "+p:""} failed (${l}ms)`,{name:"postgres",kind:"db-query",op:m,...p?{table:p}:{},...N,query:T,...h?{params:h}:{},startedAt:g,error:String(s?.message??s),durationMs:l},`db:error:${m}:${p??"query"}`,E);else{const O=rowsOf(u),x=resultPreview(u);A=(0,emit_1.lensEmitOutcome)("db","info",`${m} ${p??"query"} (${O} rows, ${l}ms)`,{name:"postgres",kind:"db-query",op:m,...p?{table:p}:{},...N,query:T,...h?{params:h}:{},...x?{result:x}:{},startedAt:g,rows:O,durationMs:l},R,E)}M&&A==="written"&&(statementSentAt.delete(S),statementSentAt.set(S,g),statementSentAt.size>MAX_SHAPES_REMEMBERED&&statementSentAt.delete(statementSentAt.keys().next().value)),(0,sql_accounting_1.endSqlStatement)(q,{durationMs:l,failed:!!s,emitted:A})},"done"),C=typeof _=="function"?_:typeof i=="function"?i:void 0;if(C){const s=o((u,l)=>{try{w(u,l)}catch{}C(u,l)},"wrappedCb");try{return typeof i=="function"?r.call(this,a,s):r.call(this,a,i,s)}catch(u){throw(0,sql_accounting_1.abandonSqlStatement)(q),u}}let y;try{y=r.call(this,a,i)}catch(s){throw(0,sql_accounting_1.abandonSqlStatement)(q),s}return y&&typeof y.then=="function"?y.then(s=>w(void 0,s),s=>w(s,void 0)):(0,sql_accounting_1.abandonSqlStatement)(q),y},"wrapped");return n.__lensmcp=!0,e.query=n,!0}c(pgTap,"pgTap"),o(pgTap,"pgTap");
package/lib/tap-redis.js CHANGED
@@ -1 +1 @@
1
- "use strict";var v=Object.defineProperty;var l=(t,e)=>v(t,"name",{value:e,configurable:!0});var b=Object.defineProperty,a=l((t,e)=>b(t,"name",{value:e,configurable:!0}),"a"),h=Object.defineProperty,c=a((t,e)=>h(t,"name",{value:e,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.redisTap=redisTap;const emit_1=require("./emit"),flow_context_1=require("./flow-context"),HOUSEKEEPING=new Set(["info","ping","hello","auth","select","client","cluster","command","subscribe","psubscribe","unsubscribe","punsubscribe","echo","quit","wait","script","config","debug","memory","readonly","readwrite"]),MAX_PER_SEC=30;let emitted=0,windowStart=0;function isBullTraffic(t){const e=String(t.name??"").toLowerCase();if(e==="eval"||e==="evalsha")return!0;const r=t.args??[];for(let n=0;n<Math.min(r.length,4);n++){const s=String(r[n]??"");if(s.startsWith("bull:")||s.startsWith("{bull"))return!0}return!1}l(isBullTraffic,"isBullTraffic"),a(isBullTraffic,"isBullTraffic"),c(isBullTraffic,"isBullTraffic");function redisTap(t){const e=t,r=(e?.default??e)?.prototype,n=r?.sendCommand;if(!r||typeof n!="function")return!1;if(n.__lensmcp)return!0;const s=c(function(i,u){const m=n.call(this,i,u);try{observe(i)}catch{}return m},"wrapped");return s.__lensmcp=!0,r.sendCommand=s,!0}l(redisTap,"redisTap"),a(redisTap,"redisTap"),c(redisTap,"redisTap");const clip=c((t,e)=>t.length>e?t.slice(0,e-1)+"\u2026":t,"clip");function commandLine(t,e){const r=e.slice(0,6).map((n,s)=>{const i=String(n??"");return s>0&&i.length>48?`\u2026(${(i.length/1024).toFixed(1)}kb)`:clip(i,64)});return[t.toUpperCase(),...r].join(" ")}l(commandLine,"commandLine"),a(commandLine,"commandLine"),c(commandLine,"commandLine");function observe(t){const e=String(t?.name??"").toLowerCase();if(!e||HOUSEKEEPING.has(e)||isBullTraffic(t))return;const r=(0,flow_context_1.liveFlowContext)();r&&(r.redisCallCount=(r.redisCallCount??0)+1);const n=Date.now();if(n-windowStart>1e3&&(windowStart=n,emitted=0),++emitted>MAX_PER_SEC)return;const s=t?.args??[],i=String(s[0]??""),u=(0,flow_context_1.flowContext)(),m=commandLine(e,s),p={name:"cache",kind:"redis-op",op:e,key:i,command:m,startedAt:n};if(e==="get"&&t.promise&&typeof t.promise.then=="function"){const f=n;t.promise.then(d=>{const o=d!=null;(0,emit_1.lensEmit)("redis","info",`cache ${o?"hit":"miss"} ${i}`,{...p,hit:o,durationMs:Date.now()-f,...o?{value:clip(String(d),120)}:{}},"redis:cache",u)},()=>{});return}if(e==="set"){const f=s.map(g=>String(g)),d=f.findIndex(g=>g.toUpperCase()==="EX"),o=d>=0?Number(f[d+1]):void 0;(0,emit_1.lensEmit)("redis","info",o?`cache set ${i} (ttl ${o}s)`:`cache set ${i}`,{...p,...o?{ttlSec:o}:{}},"redis:cache",u);return}(0,emit_1.lensEmit)("redis","info",`cache ${e} ${i}`,p,"redis:cache",u)}l(observe,"observe"),a(observe,"observe"),c(observe,"observe");
1
+ "use strict";var b=Object.defineProperty;var a=(t,e)=>b(t,"name",{value:e,configurable:!0});var h=Object.defineProperty,c=a((t,e)=>h(t,"name",{value:e,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.redisTap=redisTap;const emit_1=require("./emit"),flow_context_1=require("./flow-context"),HOUSEKEEPING=new Set(["info","ping","hello","auth","select","client","cluster","command","subscribe","psubscribe","unsubscribe","punsubscribe","echo","quit","wait","script","config","debug","memory","readonly","readwrite"]),MAX_PER_SEC=30;let emitted=0,windowStart=0;function isBullTraffic(t){const e=String(t.name??"").toLowerCase();if(e==="eval"||e==="evalsha")return!0;const r=t.args??[];for(let n=0;n<Math.min(r.length,4);n++){const s=String(r[n]??"");if(s.startsWith("bull:")||s.startsWith("{bull"))return!0}return!1}a(isBullTraffic,"isBullTraffic"),c(isBullTraffic,"isBullTraffic");function redisTap(t){const e=t,r=(e?.default??e)?.prototype,n=r?.sendCommand;if(!r||typeof n!="function")return!1;if(n.__lensmcp)return!0;const s=c(function(i,l){const f=n.call(this,i,l);try{observe(i)}catch{}return f},"wrapped");return s.__lensmcp=!0,r.sendCommand=s,!0}a(redisTap,"redisTap"),c(redisTap,"redisTap");const clip=c((t,e)=>t.length>e?t.slice(0,e-1)+"\u2026":t,"clip");function commandLine(t,e){const r=e.slice(0,6).map((n,s)=>{const i=String(n??"");return s>0&&i.length>48?`\u2026(${(i.length/1024).toFixed(1)}kb)`:clip(i,64)});return[t.toUpperCase(),...r].join(" ")}a(commandLine,"commandLine"),c(commandLine,"commandLine");function observe(t){const e=String(t?.name??"").toLowerCase();if(!e||HOUSEKEEPING.has(e)||isBullTraffic(t))return;const r=(0,flow_context_1.liveFlowContext)();r&&(r.redisCallCount=(r.redisCallCount??0)+1);const n=Date.now();if(n-windowStart>1e3&&(windowStart=n,emitted=0),++emitted>MAX_PER_SEC)return;const s=t?.args??[],i=String(s[0]??""),l=(0,flow_context_1.flowContext)(),f=commandLine(e,s),m={name:"cache",kind:"redis-op",op:e,key:i,command:f,startedAt:n};if(e==="get"&&t.promise&&typeof t.promise.then=="function"){const d=n;t.promise.then(u=>{const o=u!=null;(0,emit_1.lensEmit)("redis","info",`cache ${o?"hit":"miss"} ${i}`,{...m,hit:o,durationMs:Date.now()-d,...o?{value:clip(String(u),120)}:{}},"redis:cache",l)},()=>{});return}if(e==="set"){const d=s.map(p=>String(p)),u=d.findIndex(p=>p.toUpperCase()==="EX"),o=u>=0?Number(d[u+1]):void 0;(0,emit_1.lensEmit)("redis","info",o?`cache set ${i} (ttl ${o}s)`:`cache set ${i}`,{...m,...o?{ttlSec:o}:{}},"redis:cache",l);return}(0,emit_1.lensEmit)("redis","info",`cache ${e} ${i}`,m,"redis:cache",l)}a(observe,"observe"),c(observe,"observe");
package/lib/tap-stdout.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var S=Object.defineProperty;var a=(t,e)=>S(t,"name",{value:e,configurable:!0});var R=Object.defineProperty,f=a((t,e)=>R(t,"name",{value:e,configurable:!0}),"f"),E=Object.defineProperty,u=f((t,e)=>E(t,"name",{value:e,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.tapStdout=tapStdout;const emit_1=require("./emit"),tap_nest_logger_1=require("./tap-nest-logger"),ANSI=new RegExp("\x1B\\[[0-9;]*m","g");function severityOf(t,e){return/\bFATAL\b/.test(t)?"fatal":/\bERROR\b/.test(t)?"error":/\bWARN\b/.test(t)?"warning":/\bDEBUG\b/.test(t)||/\bVERBOSE\b/.test(t)?"debug":/\bLOG\b/.test(t)?"info":e}a(severityOf,"severityOf"),f(severityOf,"severityOf"),u(severityOf,"severityOf");const STACK_FRAME=/^\s+(at\s|\.\.\.\s\d+\smore)/,CONTINUATION=/^(\s+\S|[}\])]+[,;]?$)/,CONTINUES_WITHIN_MS=1e3;function emitChunk(t,e,l,c,g){const o=t.split(`
2
- `).map(n=>n.replace(ANSI,"").replace(/\s+$/,""));let s=0,r=l;for(;s<o.length;){const n=o[s];if(s+=1,!n.trim())continue;const i=[];for(;s<o.length&&o[s].trim()&&CONTINUATION.test(o[s]);)i.push(o[s]),s+=1;const b=[n,...i].filter(_=>STACK_FRAME.test(_)),p=CONTINUATION.test(n)&&r&&c-r.at<=CONTINUES_WITHIN_MS?r.severity:void 0,O=severityOf(n,e),v=O!==e||/\b(?:FATAL|ERROR|WARN|DEBUG|VERBOSE|LOG)\b/.test(n),d=p??(v?O:b.length>0?"error":e),m=[n,...i];if(!p&&(0,tap_nest_logger_1.isLoggerEcho)(m.join(`
3
- `),c)){r={severity:d,at:c};continue}(0,emit_1.lensLog)(d,p?n.trim():n,{...b.length>0?{stack:m.join(`
4
- `)}:{},...i.length>0&&b.length<i.length?{text:m.join(`
5
- `)}:{},...p?{continues:!0}:{},stream:g}),r={severity:d,at:c}}return r}a(emitChunk,"emitChunk"),f(emitChunk,"emitChunk"),u(emitChunk,"emitChunk");function tapStdout(){if(process.env.LENSMCP_LOGS==="0"||process.env.APP_RUNNER!=="1")return;const t=[[process.stdout,"info","stdout"],[process.stderr,"error","stderr"]];for(const[e,l,c]of t){if(e.write.__lensmcp)continue;const g=e.write.bind(e);let o;const s=u(function(r,...n){try{if(!(0,emit_1.isLensWriting)()){const i=typeof r=="string"?r:Buffer.isBuffer(r)?r.toString("utf8"):"";i&&i.indexOf("[lensmcp]")===-1&&(o=emitChunk(i,l,o,Date.now(),c))}}catch{}return g(r,...n)},"wrapped");s.__lensmcp=!0,e.write=s}}a(tapStdout,"tapStdout"),f(tapStdout,"tapStdout"),u(tapStdout,"tapStdout");
1
+ "use strict";var R=Object.defineProperty;var f=(t,e)=>R(t,"name",{value:e,configurable:!0});var E=Object.defineProperty,u=f((t,e)=>E(t,"name",{value:e,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.tapStdout=tapStdout;const emit_1=require("./emit"),tap_nest_logger_1=require("./tap-nest-logger"),ANSI=new RegExp("\x1B\\[[0-9;]*m","g");function severityOf(t,e){return/\bFATAL\b/.test(t)?"fatal":/\bERROR\b/.test(t)?"error":/\bWARN\b/.test(t)?"warning":/\bDEBUG\b/.test(t)||/\bVERBOSE\b/.test(t)?"debug":/\bLOG\b/.test(t)?"info":e}f(severityOf,"severityOf"),u(severityOf,"severityOf");const STACK_FRAME=/^\s+(at\s|\.\.\.\s\d+\smore)/,CONTINUATION=/^(\s+\S|[}\])]+[,;]?$)/,CONTINUES_WITHIN_MS=1e3;function emitChunk(t,e,p,c,l){const o=t.split(`
2
+ `).map(r=>r.replace(ANSI,"").replace(/\s+$/,""));let s=0,n=p;for(;s<o.length;){const r=o[s];if(s+=1,!r.trim())continue;const i=[];for(;s<o.length&&o[s].trim()&&CONTINUATION.test(o[s]);)i.push(o[s]),s+=1;const g=[r,...i].filter(_=>STACK_FRAME.test(_)),a=CONTINUATION.test(r)&&n&&c-n.at<=CONTINUES_WITHIN_MS?n.severity:void 0,m=severityOf(r,e),O=m!==e||/\b(?:FATAL|ERROR|WARN|DEBUG|VERBOSE|LOG)\b/.test(r),b=a??(O?m:g.length>0?"error":e),d=[r,...i];if(!a&&(0,tap_nest_logger_1.isLoggerEcho)(d.join(`
3
+ `),c)){n={severity:b,at:c};continue}(0,emit_1.lensLog)(b,a?r.trim():r,{...g.length>0?{stack:d.join(`
4
+ `)}:{},...i.length>0&&g.length<i.length?{text:d.join(`
5
+ `)}:{},...a?{continues:!0}:{},stream:l}),n={severity:b,at:c}}return n}f(emitChunk,"emitChunk"),u(emitChunk,"emitChunk");function tapStdout(){if(process.env.LENSMCP_LOGS==="0"||process.env.APP_RUNNER!=="1")return;const t=[[process.stdout,"info","stdout"],[process.stderr,"error","stderr"]];for(const[e,p,c]of t){if(e.write.__lensmcp)continue;const l=e.write.bind(e);let o;const s=u(function(n,...r){try{if(!(0,emit_1.isLensWriting)()){const i=typeof n=="string"?n:Buffer.isBuffer(n)?n.toString("utf8"):"";i&&i.indexOf("[lensmcp]")===-1&&(o=emitChunk(i,p,o,Date.now(),c))}}catch{}return l(n,...r)},"wrapped");s.__lensmcp=!0,e.write=s}}f(tapStdout,"tapStdout"),u(tapStdout,"tapStdout");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lensmcp/node-instrumentation",
3
- "version": "1.25.1",
3
+ "version": "1.25.2",
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.1",
19
- "@lensmcp/nest-instrumentation": "1.25.1",
20
- "@lensmcp/protocol-types": "1.25.1",
18
+ "@lensmcp/core": "1.25.2",
19
+ "@lensmcp/nest-instrumentation": "1.25.2",
20
+ "@lensmcp/protocol-types": "1.25.2",
21
21
  "tslib": "^2.3.0"
22
22
  },
23
23
  "optionalDependencies": {
package/register.js CHANGED
@@ -1 +1 @@
1
- "use strict";var o=Object.defineProperty;var a=(t,n)=>o(t,"name",{value:n,configurable:!0});var i=Object.defineProperty,r=a((t,n)=>i(t,"name",{value:n,configurable:!0}),"r"),s=Object.defineProperty,e=r((t,n)=>s(t,"name",{value:n,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installLensmcpNodeInstrumentation=void 0;const install_1=require("./lib/install");Object.defineProperty(exports,"installLensmcpNodeInstrumentation",{enumerable:!0,get:e(function(){return install_1.installLensmcpNodeInstrumentation},"get")}),(0,install_1.installLensmcpNodeInstrumentation)();
1
+ "use strict";var i=Object.defineProperty;var r=(t,n)=>i(t,"name",{value:n,configurable:!0});var s=Object.defineProperty,e=r((t,n)=>s(t,"name",{value:n,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installLensmcpNodeInstrumentation=void 0;const install_1=require("./lib/install");Object.defineProperty(exports,"installLensmcpNodeInstrumentation",{enumerable:!0,get:e(function(){return install_1.installLensmcpNodeInstrumentation},"get")}),(0,install_1.installLensmcpNodeInstrumentation)();