clawpro-diagnostics-metrics-cls 3.0.4 → 3.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +7 -17
- package/package.json +6 -5
package/dist/index.js
CHANGED
|
@@ -1,17 +1,7 @@
|
|
|
1
|
-
var jl=Object.create;var bn=Object.defineProperty;var Ul=Object.getOwnPropertyDescriptor;var ql=Object.getOwnPropertyNames;var Fl=Object.getPrototypeOf,Kl=Object.prototype.hasOwnProperty;var ne=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var A=(t,e)=>()=>(t&&(e=t(t=0)),e);var B=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Gl=(t,e)=>{for(var n in e)bn(t,n,{get:e[n],enumerable:!0})},xo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ql(e))!Kl.call(t,s)&&s!==n&&bn(t,s,{get:()=>e[s],enumerable:!(r=Ul(e,s))||r.enumerable});return t};var Oo=(t,e,n)=>(n=t!=null?jl(Fl(t)):{},xo(e||!t||!t.__esModule?bn(n,"default",{value:t,enumerable:!0}):n,t)),Vl=t=>xo(bn({},"__esModule",{value:!0}),t);var Ce=B(Re=>{"use strict";Re.getValueAsString=function(e){return Number.isNaN(e)?"Nan":Number.isFinite(e)?`${e}`:e<0?"-Inf":"+Inf"};Re.removeLabels=function(e,n,r){let s=yr(n,r);delete e[s]};Re.setValue=function(e,n,r){let s=yr(r);return e[s]={value:typeof n=="number"?n:0,labels:r||{}},e};Re.setValueDelta=function(e,n,r,s=""){let o=typeof n=="number"?n:0;return e[s]?e[s].value+=o:e[s]={value:o,labels:r},e};Re.getLabels=function(t,e){if(typeof e[0]=="object")return e[0];if(t.length!==e.length)throw new Error(`Invalid number of arguments (${e.length}): "${e.join(", ")}" for label names (${t.length}): "${t.join(", ")}".`);let n={};for(let r=0;r<t.length;r++)n[t[r]]=e[r];return n};function Po(t,e){if(t.length===0)return"";let n="";for(let r=0;r<t.length;r++){let s=t[r],o=e[s];o!==void 0&&(n+=`${s}:${o},`)}return n}function yr(t,e){if(e)return Po(e,t);let n=Object.keys(t);return n.length>1&&n.sort(),Po(n,t)}Re.hashObject=yr;Re.isObject=function(e){return e!==null&&typeof e=="object"};Re.nowTimestamp=function(){return Date.now()/1e3};var hr=class extends Map{add(e,n){this.has(e)?this.get(e).push(n):this.set(e,[n])}};Re.Grouper=hr});var ct=B((xf,wr)=>{"use strict";var{getValueAsString:Ao}=Ce(),wn=class t{static get PROMETHEUS_CONTENT_TYPE(){return"text/plain; version=0.0.4; charset=utf-8"}static get OPENMETRICS_CONTENT_TYPE(){return"application/openmetrics-text; version=1.0.0; charset=utf-8"}constructor(e=t.PROMETHEUS_CONTENT_TYPE){if(this._metrics={},this._collectors=[],this._defaultLabels={},e!==t.PROMETHEUS_CONTENT_TYPE&&e!==t.OPENMETRICS_CONTENT_TYPE)throw new TypeError(`Content type ${e} is unsupported`);this._contentType=e}getMetricsAsArray(){return Object.values(this._metrics)}async getMetricsAsString(e){let n=typeof e.getForPromString=="function"?await e.getForPromString():await e.get(),r=br(n.name),s=`# HELP ${r} ${br(n.help)}`,o=`# TYPE ${r} ${n.type}`,i=[s,o],c=Object.keys(this._defaultLabels).length>0?this._defaultLabels:null,u=this.contentType===t.OPENMETRICS_CONTENT_TYPE;for(let f of n.values||[]){let{metricName:h=r,labels:_={}}=f,{sharedLabels:T={}}=f;u&&n.type==="counter"&&(h=`${h}_total`),c&&(_={..._,...c,..._});let M=_r(_,T),R=zl(T),k=[...M,R].filter(Boolean),y=k.length?`{${k.join(",")}}`:"",$=`${h}${y} ${Ao(f.value)}`,{exemplar:P}=f;if(P&&u){let L=_r(P.labelSet);$+=` # {${L.join(",")}} ${Ao(P.value)} ${P.timestamp}`}i.push($)}return i.join(`
|
|
2
|
-
`)}
|
|
3
|
-
`)}
|
|
4
|
-
# EOF
|
|
5
|
-
`:`${r.join(`
|
|
6
|
-
|
|
7
|
-
`)}
|
|
8
|
-
`}registerMetric(e){if(this._metrics[e.name]&&this._metrics[e.name]!==e)throw new Error(`A metric with the name ${e.name} has already been registered.`);this._metrics[e.name]=e}clear(){this._metrics={},this._defaultLabels={}}async getMetricsAsJSON(){let e=[],n=Object.keys(this._defaultLabels),r=[];for(let o of this.getMetricsAsArray())r.push(o.get());let s=await Promise.all(r);for(let o of s){if(o.values&&n.length>0)for(let i of o.values){i.labels=Object.assign({},i.labels);for(let c of n)i.labels[c]=i.labels[c]||this._defaultLabels[c]}e.push(o)}return e}removeSingleMetric(e){delete this._metrics[e]}getSingleMetricAsString(e){return this.getMetricsAsString(this._metrics[e])}getSingleMetric(e){return this._metrics[e]}setDefaultLabels(e){this._defaultLabels=e}resetMetrics(){for(let e in this._metrics)this._metrics[e].reset()}get contentType(){return this._contentType}setContentType(e){if(e===t.OPENMETRICS_CONTENT_TYPE||e===t.PROMETHEUS_CONTENT_TYPE)this._contentType=e;else throw new Error(`Content type ${e} is unsupported`)}static merge(e){let n=e[0].contentType;for(let o of e)if(o.contentType!==n)throw new Error("Registers can only be merged if they have the same content type");let r=new t(n);return e.reduce((o,i)=>o.concat(i.getMetricsAsArray()),[]).forEach(r.registerMetric,r),r}};function _r(t,e){let{hasOwnProperty:n}=Object.prototype,r=[];for(let[s,o]of Object.entries(t))(!e||!n.call(e,s))&&r.push(`${s}="${Jl(o)}"`);return r}var $o=new WeakMap;function zl(t){let e=$o.get(t);if(e)return e;let r=_r(t).join(",");return $o.set(t,r),r}function Jl(t){return typeof t!="string"?t:br(t).replace(/"/g,'\\"')}function br(t){return t.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function Wl(t){return t.replace(/_total$/,"")}wr.exports=wn;wr.exports.globalRegistry=new wn});var He=B(In=>{"use strict";var Hl=ne("util"),Xl=/^[a-zA-Z_:][a-zA-Z0-9_:]*$/,Yl=/^[a-zA-Z_][a-zA-Z0-9_]*$/;In.validateMetricName=function(t){return Xl.test(t)};In.validateLabelName=function(t=[]){return t.every(e=>Yl.test(e))};In.validateLabel=function(e,n){for(let r in n)if(!e.includes(r))throw new Error(`Added label "${r}" is not included in initial labelset: ${Hl.inspect(e)}`)}});var Pt=B((Pf,Lo)=>{"use strict";var Ir=ct(),{isObject:Ql}=Ce(),{validateMetricName:Zl,validateLabelName:eu}=He(),Tr=class{constructor(e,n={}){if(!Ql(e))throw new TypeError("constructor expected a config object");if(Object.assign(this,{labelNames:[],registers:[Ir.globalRegistry],aggregator:"sum",enableExemplars:!1},n,e),this.registers||(this.registers=[Ir.globalRegistry]),!this.help)throw new Error("Missing mandatory help parameter");if(!this.name)throw new Error("Missing mandatory name parameter");if(!Zl(this.name))throw new Error("Invalid metric name");if(!eu(this.labelNames))throw new Error("Invalid label name");if(this.collect&&typeof this.collect!="function")throw new Error('Optional "collect" parameter must be a function');this.labelNames?this.sortedLabelNames=[...this.labelNames].sort():this.sortedLabelNames=[],this.reset();for(let r of this.registers){if(this.enableExemplars&&r.contentType===Ir.PROMETHEUS_CONTENT_TYPE)throw new TypeError("Exemplars are supported only on OpenMetrics registries");r.registerMetric(this)}}reset(){}};Lo.exports={Metric:Tr}});var vr=B((Af,Do)=>{"use strict";var Sr=class{constructor(e={},n=null){this.labelSet=e,this.value=n}validateExemplarLabelSet(e){let n="";for(let[r,s]of Object.entries(e))n+=`${r}${s}`;if(n.length>128)throw new RangeError("Label set size must be smaller than 128 UTF-8 chars")}};Do.exports=Sr});var Rr=B(($f,Fo)=>{"use strict";var tu=ne("util"),{hashObject:nu,isObject:Bo,getLabels:jo,removeLabels:ru,nowTimestamp:su}=Ce(),{validateLabel:Uo}=He(),{Metric:ou}=Pt(),iu=vr(),Er=class extends ou{constructor(e){super(e),this.type="counter",this.defaultLabels={},this.defaultValue=1,this.defaultExemplarLabelSet={},e.enableExemplars?(this.enableExemplars=!0,this.inc=this.incWithExemplar):this.inc=this.incWithoutExemplar}incWithoutExemplar(e,n){let r="";if(Bo(e)?(r=nu(e,this.sortedLabelNames),Uo(this.labelNames,e)):(n=e,e={}),n&&!Number.isFinite(n))throw new TypeError(`Value is not a valid number: ${tu.format(n)}`);if(n<0)throw new Error("It is not possible to decrease a counter");return n==null&&(n=1),qo(this.hashMap,n,e,r),{labelHash:r}}incWithExemplar({labels:e=this.defaultLabels,value:n=this.defaultValue,exemplarLabels:r=this.defaultExemplarLabelSet}={}){let s=this.incWithoutExemplar(e,n);this.updateExemplar(r,n,s.labelHash)}updateExemplar(e,n,r){e!==this.defaultExemplarLabelSet&&(Bo(this.hashMap[r].exemplar)||(this.hashMap[r].exemplar=new iu),this.hashMap[r].exemplar.validateExemplarLabelSet(e),this.hashMap[r].exemplar.labelSet=e,this.hashMap[r].exemplar.value=n||1,this.hashMap[r].exemplar.timestamp=su())}reset(){this.hashMap={},this.labelNames.length===0&&qo(this.hashMap,0)}async get(){if(this.collect){let e=this.collect();e instanceof Promise&&await e}return{help:this.help,name:this.name,type:this.type,values:Object.values(this.hashMap),aggregator:this.aggregator}}labels(...e){let n=jo(this.labelNames,e)||{};return{inc:this.inc.bind(this,n)}}remove(...e){let n=jo(this.labelNames,e)||{};return Uo(this.labelNames,n),ru.call(this,this.hashMap,n,this.sortedLabelNames)}};function qo(t,e,n={},r=""){return t[r]?t[r].value+=e:t[r]={value:e,labels:n},t}Fo.exports=Er});var de=B((Lf,Ho)=>{"use strict";var Vo=ne("util"),{setValue:zo,setValueDelta:au,getLabels:Ko,hashObject:Jo,isObject:Wo,removeLabels:cu}=Ce(),{validateLabel:Tn}=He(),{Metric:lu}=Pt(),kr=class extends lu{constructor(e){super(e),this.type="gauge"}set(e,n){n=Nr(e,n),e=Cr(e),uu(this,e,n)}reset(){this.hashMap={},this.labelNames.length===0&&zo(this.hashMap,0,{})}inc(e,n){n=Nr(e,n),e=Cr(e),n===void 0&&(n=1),Go(this,e,n)}dec(e,n){n=Nr(e,n),e=Cr(e),n===void 0&&(n=1),Go(this,e,-n)}setToCurrentTime(e){let n=Date.now()/1e3;e===void 0?this.set(n):this.set(e,n)}startTimer(e){let n=process.hrtime();return r=>{let s=process.hrtime(n),o=s[0]+s[1]/1e9;return this.set(Object.assign({},e,r),o),o}}async get(){if(this.collect){let e=this.collect();e instanceof Promise&&await e}return{help:this.help,name:this.name,type:this.type,values:Object.values(this.hashMap),aggregator:this.aggregator}}_getValue(e){let n=Jo(e||{},this.sortedLabelNames);return this.hashMap[n]?this.hashMap[n].value:0}labels(...e){let n=Ko(this.labelNames,e);return Tn(this.labelNames,n),{inc:this.inc.bind(this,n),dec:this.dec.bind(this,n),set:this.set.bind(this,n),setToCurrentTime:this.setToCurrentTime.bind(this,n),startTimer:this.startTimer.bind(this,n)}}remove(...e){let n=Ko(this.labelNames,e);Tn(this.labelNames,n),cu.call(this,this.hashMap,n,this.sortedLabelNames)}};function uu(t,e,n){if(typeof n!="number")throw new TypeError(`Value is not a valid number: ${Vo.format(n)}`);Tn(t.labelNames,e),zo(t.hashMap,n,e)}function Go(t,e,n){if(typeof n!="number")throw new TypeError(`Delta is not a valid number: ${Vo.format(n)}`);Tn(t.labelNames,e);let r=Jo(e,t.sortedLabelNames);au(t.hashMap,n,e,r)}function Cr(t){return Wo(t)?t:{}}function Nr(t,e){return Wo(t)?e:t}Ho.exports=kr});var Ar=B((Df,ei)=>{"use strict";var du=ne("util"),{getLabels:Xo,hashObject:Sn,isObject:Qo,removeLabels:pu,nowTimestamp:fu}=Ce(),{validateLabel:xr}=He(),{Metric:mu}=Pt(),gu=vr(),Or=class extends mu{constructor(e){super(e,{buckets:[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10]}),this.type="histogram",this.defaultLabels={},this.defaultExemplarLabelSet={},this.enableExemplars=!1;for(let n of this.labelNames)if(n==="le")throw new Error("le is a reserved label keyword");this.upperBounds=this.buckets,this.bucketValues=this.upperBounds.reduce((n,r)=>(n[r]=0,n),{}),e.enableExemplars?(this.enableExemplars=!0,this.bucketExemplars=this.upperBounds.reduce((n,r)=>(n[r]=null,n),{}),Object.freeze(this.bucketExemplars),this.observe=this.observeWithExemplar):this.observe=this.observeWithoutExemplar,Object.freeze(this.bucketValues),Object.freeze(this.upperBounds),this.labelNames.length===0&&(this.hashMap={[Sn({})]:Pr({},this.bucketValues,this.bucketExemplars)})}observeWithoutExemplar(e,n){Mr.call(this,e===0?0:e||{})(n)}observeWithExemplar({labels:e=this.defaultLabels,value:n,exemplarLabels:r=this.defaultExemplarLabelSet}={}){Mr.call(this,e===0?0:e||{})(n),this.updateExemplar(e,n,r)}updateExemplar(e,n,r){if(Object.keys(r).length===0)return;let s=Sn(e,this.sortedLabelNames),o=Zo(this.upperBounds,n),{bucketExemplars:i}=this.hashMap[s],c=i[o];Qo(c)||(c=new gu,i[o]=c),c.validateExemplarLabelSet(r),c.labelSet=r,c.value=n,c.timestamp=fu()}async get(){let e=await this.getForPromString();return e.values=e.values.map(wu),e}async getForPromString(){if(this.collect){let r=this.collect();r instanceof Promise&&await r}let n=Object.values(this.hashMap).map(_u(this)).reduce(bu(this),[]);return{name:this.name,help:this.help,type:this.type,values:n,aggregator:this.aggregator}}reset(){this.hashMap={}}zero(e){let n=Sn(e,this.sortedLabelNames);this.hashMap[n]=Pr(e,this.bucketValues,this.bucketExemplars)}startTimer(e,n){return this.enableExemplars?hu.call(this,e,n)():Yo.call(this,e)()}labels(...e){let n=Xo(this.labelNames,e);return xr(this.labelNames,n),{observe:Mr.call(this,n),startTimer:Yo.call(this,n)}}remove(...e){let n=Xo(this.labelNames,e);xr(this.labelNames,n),pu.call(this,this.hashMap,n,this.sortedLabelNames)}};function Yo(t){return()=>{let e=process.hrtime();return n=>{let r=process.hrtime(e),s=r[0]+r[1]/1e9;return this.observe(Object.assign({},t,n),s),s}}}function hu(t,e){return()=>{let n=process.hrtime();return(r,s)=>{let o=process.hrtime(n),i=o[0]+o[1]/1e9;return this.observe({labels:Object.assign({},t,r),value:i,exemplarLabels:Object.assign({},e,s)}),i}}}function vn(t,e,n,r,s={}){return{labels:t,sharedLabels:s,value:e,metricName:n,exemplar:r}}function Zo(t,e){for(let n=0;n<t.length;n++){let r=t[n];if(e<=r)return r}return-1}function Mr(t){return e=>{let n=yu(t,e);if(xr(this.labelNames,n.labels),!Number.isFinite(n.value))throw new TypeError(`Value is not a valid number: ${du.format(n.value)}`);let r=Sn(n.labels,this.sortedLabelNames),s=this.hashMap[r];s||(s=Pr(n.labels,this.bucketValues,this.bucketExemplars));let o=Zo(this.upperBounds,n.value);s.sum+=n.value,s.count+=1,Object.prototype.hasOwnProperty.call(s.bucketValues,o)&&(s.bucketValues[o]+=1),this.hashMap[r]=s}}function Pr(t,e,n){let r={labels:t,bucketValues:{...e},sum:0,count:0};return n&&(r.bucketExemplars={...n}),r}function yu(t,e){return Qo(t)?{labels:t,value:e}:{value:t,labels:{}}}function _u(t){let e=`${t.name}_bucket`;return n=>{let r=0;return{buckets:t.upperBounds.map(o=>(r+=n.bucketValues[o],vn({le:o},r,e,n.bucketExemplars?n.bucketExemplars[o]:null,n.labels))),data:n}}}function bu(t){return(e,n)=>{e.push(...n.buckets);let r={le:"+Inf"};return e.push(vn(r,n.data.count,`${t.name}_bucket`,n.data.bucketExemplars?n.data.bucketExemplars[-1]:null,n.data.labels),vn({},n.data.sum,`${t.name}_sum`,void 0,n.data.labels),vn({},n.data.count,`${t.name}_count`,void 0,n.data.labels)),e}}function wu(t){let{sharedLabels:e,labels:n,...r}=t;for(let s of Object.keys(e))n[s]=e[s];return r.labels=n,r}ei.exports=Or});var $r=B((Bf,ti)=>{function be(){}be.prototype.clear=function(){this._root=null,this.size=0};be.prototype.find=function(t){for(var e=this._root;e!==null;){var n=this._comparator(t,e.data);if(n===0)return e.data;e=e.get_child(n>0)}return null};be.prototype.findIter=function(t){for(var e=this._root,n=this.iterator();e!==null;){var r=this._comparator(t,e.data);if(r===0)return n._cursor=e,n;n._ancestors.push(e),e=e.get_child(r>0)}return null};be.prototype.lowerBound=function(t){for(var e=this._root,n=this.iterator(),r=this._comparator;e!==null;){var s=r(t,e.data);if(s===0)return n._cursor=e,n;n._ancestors.push(e),e=e.get_child(s>0)}for(var o=n._ancestors.length-1;o>=0;--o)if(e=n._ancestors[o],r(t,e.data)<0)return n._cursor=e,n._ancestors.length=o,n;return n._ancestors.length=0,n};be.prototype.upperBound=function(t){for(var e=this.lowerBound(t),n=this._comparator;e.data()!==null&&n(e.data(),t)===0;)e.next();return e};be.prototype.min=function(){var t=this._root;if(t===null)return null;for(;t.left!==null;)t=t.left;return t.data};be.prototype.max=function(){var t=this._root;if(t===null)return null;for(;t.right!==null;)t=t.right;return t.data};be.prototype.iterator=function(){return new lt(this)};be.prototype.each=function(t){for(var e=this.iterator(),n;(n=e.next())!==null;)if(t(n)===!1)return};be.prototype.reach=function(t){for(var e=this.iterator(),n;(n=e.prev())!==null;)if(t(n)===!1)return};function lt(t){this._tree=t,this._ancestors=[],this._cursor=null}lt.prototype.data=function(){return this._cursor!==null?this._cursor.data:null};lt.prototype.next=function(){if(this._cursor===null){var t=this._tree._root;t!==null&&this._minNode(t)}else if(this._cursor.right===null){var e;do if(e=this._cursor,this._ancestors.length)this._cursor=this._ancestors.pop();else{this._cursor=null;break}while(this._cursor.right===e)}else this._ancestors.push(this._cursor),this._minNode(this._cursor.right);return this._cursor!==null?this._cursor.data:null};lt.prototype.prev=function(){if(this._cursor===null){var t=this._tree._root;t!==null&&this._maxNode(t)}else if(this._cursor.left===null){var e;do if(e=this._cursor,this._ancestors.length)this._cursor=this._ancestors.pop();else{this._cursor=null;break}while(this._cursor.left===e)}else this._ancestors.push(this._cursor),this._maxNode(this._cursor.left);return this._cursor!==null?this._cursor.data:null};lt.prototype._minNode=function(t){for(;t.left!==null;)this._ancestors.push(t),t=t.left;this._cursor=t};lt.prototype._maxNode=function(t){for(;t.right!==null;)this._ancestors.push(t),t=t.right;this._cursor=t};ti.exports=be});var si=B((jf,ri)=>{var Iu=$r();function ut(t){this.data=t,this.left=null,this.right=null,this.red=!0}ut.prototype.get_child=function(t){return t?this.right:this.left};ut.prototype.set_child=function(t,e){t?this.right=e:this.left=e};function En(t){this._root=null,this._comparator=t,this.size=0}En.prototype=new Iu;En.prototype.insert=function(t){var e=!1;if(this._root===null)this._root=new ut(t),e=!0,this.size++;else{var n=new ut(void 0),r=0,s=0,o=null,i=n,c=null,u=this._root;for(i.right=this._root;;){if(u===null?(u=new ut(t),c.set_child(r,u),e=!0,this.size++):he(u.left)&&he(u.right)&&(u.red=!0,u.left.red=!1,u.right.red=!1),he(u)&&he(c)){var f=i.right===o;u===c.get_child(s)?i.set_child(f,At(o,!s)):i.set_child(f,ni(o,!s))}var h=this._comparator(u.data,t);if(h===0)break;s=r,r=h<0,o!==null&&(i=o),o=c,c=u,u=u.get_child(r)}this._root=n.right}return this._root.red=!1,e};En.prototype.remove=function(t){if(this._root===null)return!1;var e=new ut(void 0),n=e;n.right=this._root;for(var r=null,s=null,o=null,i=1;n.get_child(i)!==null;){var c=i;s=r,r=n,n=n.get_child(i);var u=this._comparator(t,n.data);if(i=u>0,u===0&&(o=n),!he(n)&&!he(n.get_child(i))){if(he(n.get_child(!i))){var f=At(n,i);r.set_child(c,f),r=f}else if(!he(n.get_child(!i))){var h=r.get_child(!c);if(h!==null)if(!he(h.get_child(!c))&&!he(h.get_child(c)))r.red=!1,h.red=!0,n.red=!0;else{var _=s.right===r;he(h.get_child(c))?s.set_child(_,ni(r,c)):he(h.get_child(!c))&&s.set_child(_,At(r,c));var T=s.get_child(_);T.red=!0,n.red=!0,T.left.red=!1,T.right.red=!1}}}}return o!==null&&(o.data=n.data,r.set_child(r.right===n,n.get_child(n.left===null)),this.size--),this._root=e.right,this._root!==null&&(this._root.red=!1),o!==null};function he(t){return t!==null&&t.red}function At(t,e){var n=t.get_child(!e);return t.set_child(!e,n.get_child(e)),n.set_child(e,t),t.red=!0,n.red=!1,n}function ni(t,e){return t.set_child(!e,At(t.get_child(!e),!e)),At(t,e)}ri.exports=En});var ii=B((Uf,oi)=>{var Tu=$r();function $t(t){this.data=t,this.left=null,this.right=null}$t.prototype.get_child=function(t){return t?this.right:this.left};$t.prototype.set_child=function(t,e){t?this.right=e:this.left=e};function Rn(t){this._root=null,this._comparator=t,this.size=0}Rn.prototype=new Tu;Rn.prototype.insert=function(t){if(this._root===null)return this._root=new $t(t),this.size++,!0;for(var e=0,n=null,r=this._root;;){if(r===null)return r=new $t(t),n.set_child(e,r),ret=!0,this.size++,!0;if(this._comparator(r.data,t)===0)return!1;e=this._comparator(r.data,t)<0,n=r,r=r.get_child(e)}};Rn.prototype.remove=function(t){if(this._root===null)return!1;var e=new $t(void 0),n=e;n.right=this._root;for(var r=null,s=null,o=1;n.get_child(o)!==null;){r=n,n=n.get_child(o);var i=this._comparator(t,n.data);o=i>0,i===0&&(s=n)}return s!==null?(s.data=n.data,r.set_child(r.right===n,n.get_child(n.left===null)),this._root=e.right,this.size--,!0):!1};oi.exports=Rn});var ci=B((qf,ai)=>{ai.exports={RBTree:si(),BinTree:ii()}});var di=B((Ff,ui)=>{var Su=ci().RBTree;function W(t,e,n){this.discrete=t===!1,this.delta=t||.01,this.K=e===void 0?25:e,this.CX=n===void 0?1.1:n,this.centroids=new Su(li),this.nreset=0,this.reset()}W.prototype.reset=function(){this.centroids.clear(),this.n=0,this.nreset+=1,this.last_cumulate=0};W.prototype.size=function(){return this.centroids.size};W.prototype.toArray=function(t){var e=[];return t?(this._cumulate(!0),this.centroids.each(function(n){e.push(n)})):this.centroids.each(function(n){e.push({mean:n.mean,n:n.n})}),e};W.prototype.summary=function(){var t=this.discrete?"exact ":"approximating ",e=[t+this.n+" samples using "+this.size()+" centroids","min = "+this.percentile(0),"Q1 = "+this.percentile(.25),"Q2 = "+this.percentile(.5),"Q3 = "+this.percentile(.75),"max = "+this.percentile(1)];return e.join(`
|
|
9
|
-
`)};function li(t,e){return t.mean>e.mean?1:t.mean<e.mean?-1:0}function vu(t,e){return t.mean_cumn-e.mean_cumn}W.prototype.push=function(t,e){e=e||1,t=Array.isArray(t)?t:[t];for(var n=0;n<t.length;n++)this._digest(t[n],e)};W.prototype.push_centroid=function(t){t=Array.isArray(t)?t:[t];for(var e=0;e<t.length;e++)this._digest(t[e].mean,t[e].n)};W.prototype._cumulate=function(t){if(!(this.n===this.last_cumulate||!t&&this.CX&&this.CX>this.n/this.last_cumulate)){var e=0;this.centroids.each(function(n){n.mean_cumn=e+n.n/2,e=n.cumn=e+n.n}),this.n=this.last_cumulate=e}};W.prototype.find_nearest=function(t){if(this.size()===0)return null;var e=this.centroids.lowerBound({mean:t}),n=e.data()===null?e.prev():e.data();if(n.mean===t||this.discrete)return n;var r=e.prev();return r&&Math.abs(r.mean-t)<Math.abs(n.mean-t)?r:n};W.prototype._new_centroid=function(t,e,n){var r={mean:t,n:e,cumn:n};return this.centroids.insert(r),this.n+=e,r};W.prototype._addweight=function(t,e,n){e!==t.mean&&(t.mean+=n*(e-t.mean)/(t.n+n)),t.cumn+=n,t.mean_cumn+=n/2,t.n+=n,this.n+=n};W.prototype._digest=function(t,e){var n=this.centroids.min(),r=this.centroids.max(),s=this.find_nearest(t);if(s&&s.mean===t)this._addweight(s,t,e);else if(s===n)this._new_centroid(t,e,0);else if(s===r)this._new_centroid(t,e,this.n);else if(this.discrete)this._new_centroid(t,e,s.cumn);else{var o=s.mean_cumn/this.n,i=Math.floor(4*this.n*this.delta*o*(1-o));i-s.n>=e?this._addweight(s,t,e):this._new_centroid(t,e,s.cumn)}this._cumulate(!1),!this.discrete&&this.K&&this.size()>this.K/this.delta&&this.compress()};W.prototype.bound_mean=function(t){var e=this.centroids.upperBound({mean:t}),n=e.prev(),r=n.mean===t?n:e.next();return[n,r]};W.prototype.p_rank=function(t){var e=Array.isArray(t)?t:[t],n=e.map(this._p_rank,this);return Array.isArray(t)?n:n[0]};W.prototype._p_rank=function(t){if(this.size()!==0){{if(t<this.centroids.min().mean)return 0;if(t>this.centroids.max().mean)return 1}this._cumulate(!0);var e=this.bound_mean(t),n=e[0],r=e[1];if(this.discrete)return n.cumn/this.n;var s=n.mean_cumn;return n!==r&&(s+=(t-n.mean)*(r.mean_cumn-n.mean_cumn)/(r.mean-n.mean)),s/this.n}};W.prototype.bound_mean_cumn=function(t){this.centroids._comparator=vu;var e=this.centroids.upperBound({mean_cumn:t});this.centroids._comparator=li;var n=e.prev(),r=n&&n.mean_cumn===t?n:e.next();return[n,r]};W.prototype.percentile=function(t){var e=Array.isArray(t)?t:[t],n=e.map(this._percentile,this);return Array.isArray(t)?n:n[0]};W.prototype._percentile=function(t){if(this.size()!==0){this._cumulate(!0);var e=this.n*t,n=this.bound_mean_cumn(e),r=n[0],s=n[1];return s===r||r===null||s===null?(r||s).mean:this.discrete?e<=r.cumn?r.mean:s.mean:r.mean+(e-r.mean_cumn)*(s.mean-r.mean)/(s.mean_cumn-r.mean_cumn)}};function Eu(t){var e=Math.floor(Math.random()*t.length);return t.splice(e,1)[0]}W.prototype.compress=function(){if(!this.compressing){var t=this.toArray();for(this.reset(),this.compressing=!0;t.length>0;)this.push_centroid(Eu(t));this._cumulate(!0),this.compressing=!1}};function qe(t){this.config=t||{},this.mode=this.config.mode||"auto",W.call(this,this.mode==="cont"?t.delta:!1),this.digest_ratio=this.config.ratio||.9,this.digest_thresh=this.config.thresh||1e3,this.n_unique=0}qe.prototype=Object.create(W.prototype);qe.prototype.constructor=qe;qe.prototype.push=function(t){W.prototype.push.call(this,t),this.check_continuous()};qe.prototype._new_centroid=function(t,e,n){this.n_unique+=1,W.prototype._new_centroid.call(this,t,e,n)};qe.prototype._addweight=function(t,e,n){t.n===1&&(this.n_unique-=1),W.prototype._addweight.call(this,t,e,n)};qe.prototype.check_continuous=function(){return this.mode!=="auto"||this.size()<this.digest_thresh?!1:this.n_unique/this.size()>this.digest_ratio?(this.mode="cont",this.discrete=!1,this.delta=this.config.delta||.01,this.compress(),!0):!1};ui.exports={TDigest:W,Digest:qe}});var mi=B((Kf,fi)=>{"use strict";var{TDigest:pi}=di(),Dr=class{constructor(e,n){this.maxAgeSeconds=e||0,this.ageBuckets=n||0,this.shouldRotate=e&&n,this.ringBuffer=Array(n).fill(new pi),this.currentBuffer=0,this.lastRotateTimestampMillis=Date.now(),this.durationBetweenRotatesMillis=e*1e3/n||1/0}size(){return Lr.call(this).size()}percentile(e){return Lr.call(this).percentile(e)}push(e){Lr.call(this),this.ringBuffer.forEach(n=>{n.push(e)})}reset(){this.ringBuffer.forEach(e=>{e.reset()})}compress(){this.ringBuffer.forEach(e=>{e.compress()})}};function Lr(){let t=Date.now()-this.lastRotateTimestampMillis;for(;t>this.durationBetweenRotatesMillis&&this.shouldRotate;)this.ringBuffer[this.currentBuffer]=new pi,++this.currentBuffer>=this.ringBuffer.length&&(this.currentBuffer=0),t-=this.durationBetweenRotatesMillis,this.lastRotateTimestampMillis+=this.durationBetweenRotatesMillis;return this.ringBuffer[this.currentBuffer]}fi.exports=Dr});var Ii=B((Gf,wi)=>{"use strict";var Ru=ne("util"),{getLabels:gi,hashObject:_i,removeLabels:Cu}=Ce(),{validateLabel:Br}=He(),{Metric:Nu}=Pt(),bi=mi(),ku=1e3,jr=class extends Nu{constructor(e){super(e,{percentiles:[.01,.05,.5,.9,.95,.99,.999],compressCount:ku,hashMap:{}}),this.type="summary";for(let n of this.labelNames)if(n==="quantile")throw new Error("quantile is a reserved label keyword");this.labelNames.length===0&&(this.hashMap={[_i({})]:{labels:{},td:new bi(this.maxAgeSeconds,this.ageBuckets),count:0,sum:0}})}observe(e,n){yi.call(this,e===0?0:e||{})(n)}async get(){if(this.collect){let r=this.collect();r instanceof Promise&&await r}let e=Object.keys(this.hashMap),n=[];return e.forEach(r=>{let s=this.hashMap[r];s&&(this.pruneAgedBuckets&&s.td.size()===0?delete this.hashMap[r]:(Mu(s,this.percentiles).forEach(o=>{n.push(o)}),n.push(Ou(s,this)),n.push(xu(s,this))))}),{name:this.name,help:this.help,type:this.type,values:n,aggregator:this.aggregator}}reset(){Object.values(this.hashMap).forEach(n=>{n.td.reset(),n.count=0,n.sum=0})}startTimer(e){return hi.call(this,e)()}labels(...e){let n=gi(this.labelNames,e);return Br(this.labelNames,n),{observe:yi.call(this,n),startTimer:hi.call(this,n)}}remove(...e){let n=gi(this.labelNames,e);Br(this.labelNames,n),Cu.call(this,this.hashMap,n,this.sortedLabelNames)}};function Mu(t,e){return t.td.compress(),e.map(n=>{let r=t.td.percentile(n);return{labels:Object.assign({quantile:n},t.labels),value:r||0}})}function xu(t,e){return{metricName:`${e.name}_count`,labels:t.labels,value:t.count}}function Ou(t,e){return{metricName:`${e.name}_sum`,labels:t.labels,value:t.sum}}function hi(t){return()=>{let e=process.hrtime();return n=>{let r=process.hrtime(e),s=r[0]+r[1]/1e9;return this.observe(Object.assign({},t,n),s),s}}}function yi(t){return e=>{let n=Pu(t,e);if(Br(this.labelNames,t),!Number.isFinite(n.value))throw new TypeError(`Value is not a valid number: ${Ru.format(n.value)}`);let r=_i(n.labels,this.sortedLabelNames),s=this.hashMap[r];s||(s={labels:n.labels,td:new bi(this.maxAgeSeconds,this.ageBuckets),count:0,sum:0}),s.td.push(n.value),s.count++,s.count%this.compressCount===0&&s.td.compress(),s.sum+=n.value,this.hashMap[r]=s}}function Pu(t,e){return e===void 0?{value:t,labels:{}}:{labels:t,value:e}}wi.exports=jr});var Si=B((Vf,Ti)=>{"use strict";var Ur=ne("url"),Au=ne("http"),$u=ne("https"),{gzipSync:Lu}=ne("zlib"),{globalRegistry:Du}=ct(),Fr=class{constructor(e,n,r){r||(r=Du),this.registry=r,this.gatewayUrl=e;let{requireJobName:s,...o}={requireJobName:!0,...n};this.requireJobName=s,this.requestOptions=o}pushAdd(e={}){if(this.requireJobName&&!e.jobName)throw new Error("Missing jobName parameter");return qr.call(this,"POST",e.jobName,e.groupings)}push(e={}){if(this.requireJobName&&!e.jobName)throw new Error("Missing jobName parameter");return qr.call(this,"PUT",e.jobName,e.groupings)}delete(e={}){if(this.requireJobName&&!e.jobName)throw new Error("Missing jobName parameter");return qr.call(this,"DELETE",e.jobName,e.groupings)}};async function qr(t,e,n){let r=Ur.parse(this.gatewayUrl),s=r.pathname&&r.pathname!=="/"?r.pathname:"",o=e?`/job/${encodeURIComponent(e)}${Bu(n)}`:"",i=`${s}/metrics${o}`,c=Ur.resolve(this.gatewayUrl,i),u=Ur.parse(c),f=ju(u.href)?$u:Au,h=Object.assign(u,this.requestOptions,{method:t});return new Promise((_,T)=>{t==="DELETE"&&h.headers&&delete h.headers["Content-Encoding"];let M=f.request(h,R=>{let k="";R.setEncoding("utf8"),R.on("data",y=>{k+=y}),R.on("end",()=>{R.statusCode>=400?T(new Error(`push failed with status ${R.statusCode}, ${k}`)):_({resp:R,body:k})})});M.on("error",R=>{T(R)}),M.on("timeout",()=>{M.destroy(new Error("Pushgateway request timed out"))}),t!=="DELETE"?this.registry.metrics().then(R=>{h.headers&&h.headers["Content-Encoding"]==="gzip"&&(R=Lu(R)),M.write(R),M.end()}).catch(R=>{T(R)}):M.end()})}function Bu(t){return t?Object.keys(t).map(e=>`/${encodeURIComponent(e)}/${encodeURIComponent(t[e])}`).join(""):""}function ju(t){return t.search(/^https/)!==-1}Ti.exports=Fr});var Gr=B(Kr=>{"use strict";Kr.linearBuckets=(t,e,n)=>{if(n<1)throw new Error("Linear buckets needs a positive count");let r=new Array(n);for(let s=0;s<n;s++)r[s]=t+s*e;return r};Kr.exponentialBuckets=(t,e,n)=>{if(t<=0)throw new Error("Exponential buckets needs a positive start");if(n<1)throw new Error("Exponential buckets needs a positive count");if(e<=1)throw new Error("Exponential buckets needs a factor greater than 1");let r=new Array(n);for(let s=0;s<n;s++)r[s]=t,t*=e;return r}});var Ae,Vr=A(()=>{Ae="1.9.1"});function Uu(t){let e=new Set([t]),n=new Set,r=t.match(vi);if(!r)return()=>!1;let s={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(s.prerelease!=null)return function(u){return u===t};function o(c){return n.add(c),!1}function i(c){return e.add(c),!0}return function(u){if(e.has(u))return!0;if(n.has(u))return!1;let f=u.match(vi);if(!f)return o(u);let h={major:+f[1],minor:+f[2],patch:+f[3],prerelease:f[4]};return h.prerelease!=null||s.major!==h.major?o(u):s.major===0?s.minor===h.minor&&s.patch<=h.patch?i(u):o(u):s.minor<=h.minor?i(u):o(u)}}var vi,Ei,Ri=A(()=>{Vr();vi=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;Ei=Uu(Ae)});function Ne(t,e,n,r=!1){var s;let o=Dt[Lt]=(s=Dt[Lt])!==null&&s!==void 0?s:{version:Ae};if(!r&&o[t]){let i=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return n.error(i.stack||i.message),!1}if(o.version!==Ae){let i=new Error(`@opentelemetry/api: Registration of version v${o.version} for ${t} does not match previously registered API v${Ae}`);return n.error(i.stack||i.message),!1}return o[t]=e,n.debug(`@opentelemetry/api: Registered a global for ${t} v${Ae}.`),!0}function ge(t){var e,n;let r=(e=Dt[Lt])===null||e===void 0?void 0:e.version;if(!(!r||!Ei(r)))return(n=Dt[Lt])===null||n===void 0?void 0:n[t]}function ke(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${Ae}.`);let n=Dt[Lt];n&&delete n[t]}var qu,Lt,Dt,Xe=A(()=>{Vr();Ri();qu=Ae.split(".")[0],Lt=Symbol.for(`opentelemetry.js.api.${qu}`),Dt=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function Bt(t,e,n){let r=ge("diag");if(r)return r[t](e,...n)}var Cn,Ci=A(()=>{Xe();Cn=class{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return Bt("debug",this._namespace,e)}error(...e){return Bt("error",this._namespace,e)}info(...e){return Bt("info",this._namespace,e)}warn(...e){return Bt("warn",this._namespace,e)}verbose(...e){return Bt("verbose",this._namespace,e)}}});var re,Nn=A(()=>{(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(re||(re={}))});function Ni(t,e){t<re.NONE?t=re.NONE:t>re.ALL&&(t=re.ALL),e=e||{};function n(r,s){let o=e[r];return typeof o=="function"&&t>=s?o.bind(e):function(){}}return{error:n("error",re.ERROR),warn:n("warn",re.WARN),info:n("info",re.INFO),debug:n("debug",re.DEBUG),verbose:n("verbose",re.VERBOSE)}}var ki=A(()=>{Nn()});var Fu,ee,Ye=A(()=>{Ci();ki();Nn();Xe();Fu="diag",ee=class t{static instance(){return this._instance||(this._instance=new t),this._instance}constructor(){function e(s){return function(...o){let i=ge("diag");if(i)return i[s](...o)}}let n=this,r=(s,o={logLevel:re.INFO})=>{var i,c,u;if(s===n){let _=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((i=_.stack)!==null&&i!==void 0?i:_.message),!1}typeof o=="number"&&(o={logLevel:o});let f=ge("diag"),h=Ni((c=o.logLevel)!==null&&c!==void 0?c:re.INFO,s);if(f&&!o.suppressOverrideMessage){let _=(u=new Error().stack)!==null&&u!==void 0?u:"<failed to generate stacktrace>";f.warn(`Current logger will be overwritten from ${_}`),h.warn(`Current logger will overwrite one already registered from ${_}`)}return Ne("diag",h,n,!0)};n.setLogger=r,n.disable=()=>{ke(Fu,n)},n.createComponentLogger=s=>new Cn(s),n.verbose=e("verbose"),n.debug=e("debug"),n.info=e("info"),n.warn=e("warn"),n.error=e("error")}}});var kn,Mi=A(()=>{kn=class t{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let n=this._entries.get(e);if(n)return Object.assign({},n)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,n){let r=new t(this._entries);return r._entries.set(e,n),r}removeEntry(e){let n=new t(this._entries);return n._entries.delete(e),n}removeEntries(...e){let n=new t(this._entries);for(let r of e)n._entries.delete(r);return n}clear(){return new t}}});var xi,Oi=A(()=>{xi=Symbol("BaggageEntryMetadata")});function Pi(t={}){return new kn(new Map(Object.entries(t)))}function Ai(t){return typeof t!="string"&&(Ku.error(`Cannot create baggage metadata from unknown type: ${typeof t}`),t=""),{__TYPE__:xi,toString(){return t}}}var Ku,zr=A(()=>{Ye();Mi();Oi();Ku=ee.instance()});function dt(t){return Symbol.for(t)}var Jr,Mn,jt=A(()=>{Jr=class t{constructor(e){let n=this;n._currentContext=e?new Map(e):new Map,n.getValue=r=>n._currentContext.get(r),n.setValue=(r,s)=>{let o=new t(n._currentContext);return o._currentContext.set(r,s),o},n.deleteValue=r=>{let s=new t(n._currentContext);return s._currentContext.delete(r),s}}},Mn=new Jr});var Wr,Hr,xn,$i=A(()=>{Wr=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],Hr={};if(typeof console<"u"){let t=["error","warn","info","debug","trace","log"];for(let e of t)typeof console[e]=="function"&&(Hr[e]=console[e])}xn=class{constructor(){function e(n){return function(...r){let s=Hr[n];if(typeof s!="function"&&(s=Hr.log),typeof s!="function"&&console&&(s=console[n],typeof s!="function"&&(s=console.log)),typeof s=="function")return s.apply(console,r)}}for(let n=0;n<Wr.length;n++)this[Wr[n].n]=e(Wr[n].c)}}});function Li(){return ss}var Xr,pt,Yr,Qr,Zr,es,Ut,ts,ns,rs,ss,Gu,Vu,zu,Ju,Wu,Hu,Xu,os=A(()=>{Xr=class{constructor(){}createGauge(e,n){return Vu}createHistogram(e,n){return zu}createCounter(e,n){return Gu}createUpDownCounter(e,n){return Ju}createObservableGauge(e,n){return Hu}createObservableCounter(e,n){return Wu}createObservableUpDownCounter(e,n){return Xu}addBatchObservableCallback(e,n){}removeBatchObservableCallback(e){}},pt=class{},Yr=class extends pt{add(e,n){}},Qr=class extends pt{add(e,n){}},Zr=class extends pt{record(e,n){}},es=class extends pt{record(e,n){}},Ut=class{addCallback(e){}removeCallback(e){}},ts=class extends Ut{},ns=class extends Ut{},rs=class extends Ut{},ss=new Xr,Gu=new Yr,Vu=new Zr,zu=new es,Ju=new Qr,Wu=new ts,Hu=new ns,Xu=new rs});var On,Di=A(()=>{(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(On||(On={}))});var Pn,An,is=A(()=>{Pn={get(t,e){if(t!=null)return t[e]},keys(t){return t==null?[]:Object.keys(t)}},An={set(t,e,n){t!=null&&(t[e]=n)}}});var $n,Bi=A(()=>{jt();$n=class{active(){return Mn}with(e,n,r,...s){return n.call(r,...s)}bind(e,n){return n}enable(){return this}disable(){return this}}});var as,Yu,Me,qt=A(()=>{Bi();Xe();Ye();as="context",Yu=new $n,Me=class t{constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalContextManager(e){return Ne(as,e,ee.instance())}active(){return this._getContextManager().active()}with(e,n,r,...s){return this._getContextManager().with(e,n,r,...s)}bind(e,n){return this._getContextManager().bind(e,n)}_getContextManager(){return ge(as)||Yu}disable(){this._getContextManager().disable(),ke(as,ee.instance())}}});var ft,cs=A(()=>{(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(ft||(ft={}))});var Ft,Kt,Ln,Dn=A(()=>{cs();Ft="0000000000000000",Kt="00000000000000000000000000000000",Ln={traceId:Kt,spanId:Ft,traceFlags:ft.NONE}});var xe,Bn=A(()=>{Dn();xe=class{constructor(e=Ln){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,n){return this}setAttributes(e){return this}addEvent(e,n){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,n){}}});function jn(t){return t.getValue(ls)||void 0}function ji(){return jn(Me.getInstance().active())}function Gt(t,e){return t.setValue(ls,e)}function Ui(t){return t.deleteValue(ls)}function qi(t,e){return Gt(t,new xe(e))}function Un(t){var e;return(e=jn(t))===null||e===void 0?void 0:e.spanContext()}var ls,us=A(()=>{jt();Bn();qt();ls=dt("OpenTelemetry Context Key SPAN")});function Fi(t,e){if(typeof t!="string"||t.length!==e)return!1;let n=0;for(let r=0;r<t.length;r+=4)n+=(qn[t.charCodeAt(r)]|0)+(qn[t.charCodeAt(r+1)]|0)+(qn[t.charCodeAt(r+2)]|0)+(qn[t.charCodeAt(r+3)]|0);return n===e}function ds(t){return Fi(t,32)&&t!==Kt}function ps(t){return Fi(t,16)&&t!==Ft}function mt(t){return ds(t.traceId)&&ps(t.spanId)}function Ki(t){return new xe(t)}var qn,Fn=A(()=>{Dn();Bn();qn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1])});function Qu(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}var fs,gt,ms=A(()=>{qt();us();Bn();Fn();fs=Me.getInstance(),gt=class{startSpan(e,n,r=fs.active()){if(!!n?.root)return new xe;let o=r&&Un(r);return Qu(o)&&mt(o)?new xe(o):new xe}startActiveSpan(e,n,r,s){let o,i,c;if(arguments.length<2)return;arguments.length===2?c=n:arguments.length===3?(o=n,c=r):(o=n,i=r,c=s);let u=i??fs.active(),f=this.startSpan(e,o,u),h=Gt(u,f);return fs.with(h,c,void 0,f)}}});var Zu,ht,gs=A(()=>{ms();Zu=new gt,ht=class{constructor(e,n,r,s){this._provider=e,this.name=n,this.version=r,this.options=s}startSpan(e,n,r){return this._getTracer().startSpan(e,n,r)}startActiveSpan(e,n,r,s){let o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):Zu}}});var Kn,Gi=A(()=>{ms();Kn=class{getTracer(e,n,r){return new gt}}});var ed,Qe,hs=A(()=>{gs();Gi();ed=new Kn,Qe=class{getTracer(e,n,r){var s;return(s=this.getDelegateTracer(e,n,r))!==null&&s!==void 0?s:new ht(this,e,n,r)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:ed}setDelegate(e){this._delegate=e}getDelegateTracer(e,n,r){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,n,r)}}});var Gn,Vi=A(()=>{(function(t){t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(Gn||(Gn={}))});var Vn,zi=A(()=>{(function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"})(Vn||(Vn={}))});var zn,Ji=A(()=>{(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(zn||(zn={}))});function Wi(t){return rd.test(t)}function Hi(t){return sd.test(t)&&!od.test(t)}var ys,td,nd,rd,sd,od,Xi=A(()=>{ys="[_0-9a-z-*/]",td=`[a-z]${ys}{0,255}`,nd=`[a-z0-9]${ys}{0,240}@[a-z]${ys}{0,13}`,rd=new RegExp(`^(?:${td}|${nd})$`),sd=/^[ -~]{0,255}[!-~]$/,od=/,|=/});var Yi,id,Qi,Zi,Jn,ea=A(()=>{Xi();Yi=32,id=512,Qi=",",Zi="=",Jn=class t{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,n){let r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,n),r}unset(e){let n=this._clone();return n._internalState.delete(e),n}get(e){return this._internalState.get(e)}serialize(){return Array.from(this._internalState.keys()).reduceRight((e,n)=>(e.push(n+Zi+this.get(n)),e),[]).join(Qi)}_parse(e){e.length>id||(this._internalState=e.split(Qi).reduceRight((n,r)=>{let s=r.trim(),o=s.indexOf(Zi);if(o!==-1){let i=s.slice(0,o),c=s.slice(o+1,r.length);Wi(i)&&Hi(c)&&n.set(i,c)}return n},new Map),this._internalState.size>Yi&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Yi))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}}});function ta(t){return new Jn(t)}var na=A(()=>{ea()});var _s,ra=A(()=>{qt();_s=Me.getInstance()});var bs,sa=A(()=>{Ye();bs=ee.instance()});var ws,oa,ia=A(()=>{os();ws=class{getMeter(e,n,r){return ss}},oa=new ws});var Is,Wn,aa=A(()=>{ia();Xe();Ye();Is="metrics",Wn=class t{constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalMeterProvider(e){return Ne(Is,e,ee.instance())}getMeterProvider(){return ge(Is)||oa}getMeter(e,n,r){return this.getMeterProvider().getMeter(e,n,r)}disable(){ke(Is,ee.instance())}}});var Ts,ca=A(()=>{aa();Ts=Wn.getInstance()});var Hn,la=A(()=>{Hn=class{inject(e,n){}extract(e,n){return e}fields(){return[]}}});function vs(t){return t.getValue(Ss)||void 0}function ua(){return vs(Me.getInstance().active())}function da(t,e){return t.setValue(Ss,e)}function pa(t){return t.deleteValue(Ss)}var Ss,fa=A(()=>{qt();jt();Ss=dt("OpenTelemetry Baggage Key")});var Es,ad,Xn,ma=A(()=>{Xe();la();is();fa();zr();Ye();Es="propagation",ad=new Hn,Xn=class t{constructor(){this.createBaggage=Pi,this.getBaggage=vs,this.getActiveBaggage=ua,this.setBaggage=da,this.deleteBaggage=pa}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalPropagator(e){return Ne(Es,e,ee.instance())}inject(e,n,r=An){return this._getGlobalPropagator().inject(e,n,r)}extract(e,n,r=Pn){return this._getGlobalPropagator().extract(e,n,r)}fields(){return this._getGlobalPropagator().fields()}disable(){ke(Es,ee.instance())}_getGlobalPropagator(){return ge(Es)||ad}}});var Rs,ga=A(()=>{ma();Rs=Xn.getInstance()});var Cs,Yn,ha=A(()=>{Xe();hs();Fn();us();Ye();Cs="trace",Yn=class t{constructor(){this._proxyTracerProvider=new Qe,this.wrapSpanContext=Ki,this.isSpanContextValid=mt,this.deleteSpan=Ui,this.getSpan=jn,this.getActiveSpan=ji,this.getSpanContext=Un,this.setSpan=Gt,this.setSpanContext=qi}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalTracerProvider(e){let n=Ne(Cs,this._proxyTracerProvider,ee.instance());return n&&this._proxyTracerProvider.setDelegate(e),n}getTracerProvider(){return ge(Cs)||this._proxyTracerProvider}getTracer(e,n){return this.getTracerProvider().getTracer(e,n)}disable(){ke(Cs,ee.instance()),this._proxyTracerProvider=new Qe}}});var Ns,ya=A(()=>{ha();Ns=Yn.getInstance()});var _a={};Gl(_a,{DiagConsoleLogger:()=>xn,DiagLogLevel:()=>re,INVALID_SPANID:()=>Ft,INVALID_SPAN_CONTEXT:()=>Ln,INVALID_TRACEID:()=>Kt,ProxyTracer:()=>ht,ProxyTracerProvider:()=>Qe,ROOT_CONTEXT:()=>Mn,SamplingDecision:()=>Gn,SpanKind:()=>Vn,SpanStatusCode:()=>zn,TraceFlags:()=>ft,ValueType:()=>On,baggageEntryMetadataFromString:()=>Ai,context:()=>_s,createContextKey:()=>dt,createNoopMeter:()=>Li,createTraceState:()=>ta,default:()=>cd,defaultTextMapGetter:()=>Pn,defaultTextMapSetter:()=>An,diag:()=>bs,isSpanContextValid:()=>mt,isValidSpanId:()=>ps,isValidTraceId:()=>ds,metrics:()=>Ts,propagation:()=>Rs,trace:()=>Ns});var cd,ba=A(()=>{zr();jt();$i();Nn();os();Di();is();gs();hs();Vi();zi();Ji();cs();na();Fn();Dn();ra();sa();ca();ga();ya();cd={context:_s,diag:bs,metrics:Ts,propagation:Rs,trace:Ns}});var va=B((sh,Ms)=>{"use strict";var wa=(ba(),Vl(_a)),ks=Rr(),Ia="process_cpu_user_seconds_total",Ta="process_cpu_system_seconds_total",Sa="process_cpu_seconds_total";Ms.exports=(t,e={})=>{let n=t?[t]:void 0,r=e.prefix?e.prefix:"",s=e.labels?e.labels:{},o=e.enableExemplars?e.enableExemplars:!1,i=Object.keys(s),c=process.cpuUsage(),u=new ks({name:r+Ia,help:"Total user CPU time spent in seconds.",enableExemplars:o,registers:n,labelNames:i,collect(){let _=process.cpuUsage(),T=_.user-c.user,M=_.system-c.system;if(c=_,this.enableExemplars){let R={},k=wa.trace.getSpan(wa.context.active());k&&(R={traceId:k.spanContext().traceId,spanId:k.spanContext().spanId}),u.inc({labels:s,value:T/1e6,exemplarLabels:R}),f.inc({labels:s,value:M/1e6,exemplarLabels:R}),h.inc({labels:s,value:(T+M)/1e6,exemplarLabels:R})}else u.inc(s,T/1e6),f.inc(s,M/1e6),h.inc(s,(T+M)/1e6)}}),f=new ks({name:r+Ta,help:"Total system CPU time spent in seconds.",enableExemplars:o,registers:n,labelNames:i}),h=new ks({name:r+Sa,help:"Total user and system CPU time spent in seconds.",enableExemplars:o,registers:n,labelNames:i})};Ms.exports.metricNames=[Ia,Ta,Sa]});var Ra=B((oh,xs)=>{"use strict";var ld=de(),ud=Math.round(Date.now()/1e3-process.uptime()),Ea="process_start_time_seconds";xs.exports=(t,e={})=>{let n=e.prefix?e.prefix:"",r=e.labels?e.labels:{},s=Object.keys(r);new ld({name:n+Ea,help:"Start time of the process since unix epoch in seconds.",registers:t?[t]:void 0,labelNames:s,aggregator:"omit",collect(){this.set(r,ud)}})};xs.exports.metricNames=[Ea]});var Ma=B((ih,Ps)=>{"use strict";var Os=de(),dd=ne("fs"),pd=["VmSize","VmRSS","VmData"],Ca="process_resident_memory_bytes",Na="process_virtual_memory_bytes",ka="process_heap_bytes";function fd(t){return t.split(`
|
|
10
|
-
`).reduce((e,n)=>{if(!pd.some(o=>n.startsWith(o)))return e;let r=n.split(":"),s=r[1].trim();return s=s.substr(0,s.length-3),s=Number(s)*1024,e[r[0]]=s,e},{})}Ps.exports=(t,e={})=>{let n=t?[t]:void 0,r=e.prefix?e.prefix:"",s=e.labels?e.labels:{},o=Object.keys(s),i=new Os({name:r+Ca,help:"Resident memory size in bytes.",registers:n,labelNames:o,collect(){try{let f=dd.readFileSync("/proc/self/status","utf8"),h=fd(f);i.set(s,h.VmRSS),c.set(s,h.VmSize),u.set(s,h.VmData)}catch{}}}),c=new Os({name:r+Na,help:"Virtual memory size in bytes.",registers:n,labelNames:o}),u=new Os({name:r+ka,help:"Process heap size in bytes.",registers:n,labelNames:o})};Ps.exports.metricNames=[Ca,Na,ka]});var As=B((ah,xa)=>{"use strict";function md(){try{return process.memoryUsage()}catch{return}}xa.exports=md});var Aa=B((ch,$s)=>{"use strict";var gd=de(),Oa=Ma(),hd=As(),Pa="process_resident_memory_bytes";function yd(t,e={}){let n=e.prefix?e.prefix:"",r=e.labels?e.labels:{},s=Object.keys(r);new gd({name:n+Pa,help:"Resident memory size in bytes.",registers:t?[t]:void 0,labelNames:s,collect(){let o=hd();o&&this.set(r,o.rss)}})}$s.exports=(t,e)=>process.platform==="linux"?Oa(t,e):yd(t,e);$s.exports.metricNames=process.platform==="linux"?Oa.metricNames:[Pa]});var La=B((lh,Ls)=>{"use strict";var _d=de(),bd=ne("fs"),wd=ne("process"),$a="process_open_fds";Ls.exports=(t,e={})=>{if(wd.platform!=="linux")return;let n=e.prefix?e.prefix:"",r=e.labels?e.labels:{},s=Object.keys(r);new _d({name:n+$a,help:"Number of open file descriptors.",registers:t?[t]:void 0,labelNames:s,collect(){try{let o=bd.readdirSync("/proc/self/fd");this.set(r,o.length-1)}catch{}}})};Ls.exports.metricNames=[$a]});var Ba=B((uh,Ds)=>{"use strict";var Id=de(),Td=ne("fs"),Da="process_max_fds",Vt;Ds.exports=(t,e={})=>{if(Vt===void 0)try{let i=Td.readFileSync("/proc/self/limits","utf8").split(`
|
|
11
|
-
`);for(let c of i)if(c.startsWith("Max open files")){let u=c.split(/ +/);Vt=Number(u[1]);break}}catch{return}if(Vt===void 0)return;let n=e.prefix?e.prefix:"",r=e.labels?e.labels:{},s=Object.keys(r);new Id({name:n+Da,help:"Maximum number of open file descriptors.",registers:t?[t]:void 0,labelNames:s,collect(){Vt!==void 0&&this.set(r,Vt)}})};Ds.exports.metricNames=[Da]});var Wa=B((dh,Bs)=>{"use strict";var Fe=de(),Qn;try{Qn=ne("perf_hooks")}catch{}var Ua="nodejs_eventloop_lag_seconds",qa="nodejs_eventloop_lag_min_seconds",Fa="nodejs_eventloop_lag_max_seconds",Ka="nodejs_eventloop_lag_mean_seconds",Ga="nodejs_eventloop_lag_stddev_seconds",Va="nodejs_eventloop_lag_p50_seconds",za="nodejs_eventloop_lag_p90_seconds",Ja="nodejs_eventloop_lag_p99_seconds";function ja(t,e,n){let r=process.hrtime(t),o=(r[0]*1e9+r[1])/1e9;e.set(n,o)}Bs.exports=(t,e={})=>{let n=e.prefix?e.prefix:"",r=e.labels?e.labels:{},s=Object.keys(r),o=t?[t]:void 0,i=()=>{let k=process.hrtime();setImmediate(ja,k,c,r)};if(Qn&&Qn.monitorEventLoopDelay)try{let k=Qn.monitorEventLoopDelay({resolution:e.eventLoopMonitoringPrecision});k.enable(),i=()=>{let y=process.hrtime();setImmediate(ja,y,c,r),u.set(r,k.min/1e9),f.set(r,k.max/1e9),h.set(r,k.mean/1e9),_.set(r,k.stddev/1e9),T.set(r,k.percentile(50)/1e9),M.set(r,k.percentile(90)/1e9),R.set(r,k.percentile(99)/1e9),k.reset()}}catch(k){if(k.code==="ERR_NOT_IMPLEMENTED")return;throw k}let c=new Fe({name:n+Ua,help:"Lag of event loop in seconds.",registers:o,labelNames:s,aggregator:"average",collect:i}),u=new Fe({name:n+qa,help:"The minimum recorded event loop delay.",registers:o,labelNames:s,aggregator:"min"}),f=new Fe({name:n+Fa,help:"The maximum recorded event loop delay.",registers:o,labelNames:s,aggregator:"max"}),h=new Fe({name:n+Ka,help:"The mean of the recorded event loop delays.",registers:o,labelNames:s,aggregator:"average"}),_=new Fe({name:n+Ga,help:"The standard deviation of the recorded event loop delays.",registers:o,labelNames:s,aggregator:"average"}),T=new Fe({name:n+Va,help:"The 50th percentile of the recorded event loop delays.",registers:o,labelNames:s,aggregator:"average"}),M=new Fe({name:n+za,help:"The 90th percentile of the recorded event loop delays.",registers:o,labelNames:s,aggregator:"average"}),R=new Fe({name:n+Ja,help:"The 99th percentile of the recorded event loop delays.",registers:o,labelNames:s,aggregator:"average"})};Bs.exports.metricNames=[Ua,qa,Fa,Ka,Ga,Va,za,Ja]});var yt=B((ph,Ha)=>{"use strict";function Sd(t){let e={};for(let n=0;n<t.length;n++){let r=t[n];!r||typeof r.constructor>"u"||(Object.hasOwnProperty.call(e,r.constructor.name)?e[r.constructor.name]+=1:e[r.constructor.name]=1)}return e}function vd(t,e,n){t.reset();for(let r in e)t.set(Object.assign({type:r},n||{}),e[r])}Ha.exports={aggregateByObjectName:Sd,updateMetrics:vd}});var Za=B((fh,js)=>{"use strict";var{aggregateByObjectName:Ed}=yt(),{updateMetrics:Rd}=yt(),Xa=de(),Ya="nodejs_active_handles",Qa="nodejs_active_handles_total";js.exports=(t,e={})=>{if(typeof process._getActiveHandles!="function")return;let n=t?[t]:void 0,r=e.prefix?e.prefix:"",s=e.labels?e.labels:{},o=Object.keys(s);new Xa({name:r+Ya,help:"Number of active libuv handles grouped by handle type. Every handle type is C++ class name.",labelNames:["type",...o],registers:n,collect(){let i=process._getActiveHandles();Rd(this,Ed(i),s)}}),new Xa({name:r+Qa,help:"Total number of active handles.",registers:n,labelNames:o,collect(){let i=process._getActiveHandles();this.set(s,i.length)}})};js.exports.metricNames=[Ya,Qa]});var rc=B((mh,Us)=>{"use strict";var ec=de(),{aggregateByObjectName:Cd}=yt(),{updateMetrics:Nd}=yt(),tc="nodejs_active_requests",nc="nodejs_active_requests_total";Us.exports=(t,e={})=>{if(typeof process._getActiveRequests!="function")return;let n=e.prefix?e.prefix:"",r=e.labels?e.labels:{},s=Object.keys(r);new ec({name:n+tc,help:"Number of active libuv requests grouped by request type. Every request type is C++ class name.",labelNames:["type",...s],registers:t?[t]:void 0,collect(){let o=process._getActiveRequests();Nd(this,Cd(o),r)}}),new ec({name:n+nc,help:"Total number of active requests.",registers:t?[t]:void 0,labelNames:s,collect(){let o=process._getActiveRequests();this.set(r,o.length)}})};Us.exports.metricNames=[tc,nc]});var ac=B((gh,qs)=>{"use strict";var sc=de(),{updateMetrics:kd}=yt(),oc="nodejs_active_resources",ic="nodejs_active_resources_total";qs.exports=(t,e={})=>{if(typeof process.getActiveResourcesInfo!="function")return;let n=e.prefix?e.prefix:"",r=e.labels?e.labels:{},s=Object.keys(r);new sc({name:n+oc,help:"Number of active resources that are currently keeping the event loop alive, grouped by async resource type.",labelNames:["type",...s],registers:t?[t]:void 0,collect(){let o=process.getActiveResourcesInfo(),i={};for(let c=0;c<o.length;c++){let u=o[c];Object.hasOwn(i,u)?i[u]+=1:i[u]=1}kd(this,i,r)}}),new sc({name:n+ic,help:"Total number of active resources.",registers:t?[t]:void 0,labelNames:s,collect(){let o=process.getActiveResourcesInfo();this.set(r,o.length)}})};qs.exports.metricNames=[oc,ic]});var dc=B((hh,Ks)=>{"use strict";var Fs=de(),Md=As(),cc="nodejs_heap_size_total_bytes",lc="nodejs_heap_size_used_bytes",uc="nodejs_external_memory_bytes";Ks.exports=(t,e={})=>{if(typeof process.memoryUsage!="function")return;let n=e.labels?e.labels:{},r=Object.keys(n),s=t?[t]:void 0,o=e.prefix?e.prefix:"",i=()=>{let h=Md();h&&(c.set(n,h.heapTotal),u.set(n,h.heapUsed),h.external!==void 0&&f.set(n,h.external))},c=new Fs({name:o+cc,help:"Process heap size from Node.js in bytes.",registers:s,labelNames:r,collect:i}),u=new Fs({name:o+lc,help:"Process heap size used from Node.js in bytes.",registers:s,labelNames:r}),f=new Fs({name:o+uc,help:"Node.js external memory size in bytes.",registers:s,labelNames:r})};Ks.exports.metricNames=[cc,lc,uc]});var mc=B((yh,Vs)=>{"use strict";var xd=de(),pc=ne("v8"),fc=["total","used","available"],Gs={};fc.forEach(t=>{Gs[t]=`nodejs_heap_space_size_${t}_bytes`});Vs.exports=(t,e={})=>{try{pc.getHeapSpaceStatistics()}catch(c){if(c.code==="ERR_NOT_IMPLEMENTED")return;throw c}let n=t?[t]:void 0,r=e.prefix?e.prefix:"",s=e.labels?e.labels:{},o=["space",...Object.keys(s)],i={};fc.forEach(c=>{i[c]=new xd({name:r+Gs[c],help:`Process heap space size ${c} from Node.js in bytes.`,labelNames:o,registers:n})}),i.total.collect=()=>{for(let c of pc.getHeapSpaceStatistics()){let u=c.space_name.substr(0,c.space_name.indexOf("_space"));i.total.set({space:u,...s},c.space_size),i.used.set({space:u,...s},c.space_used_size),i.available.set({space:u,...s},c.space_available_size)}}};Vs.exports.metricNames=Object.values(Gs)});var yc=B((_h,Js)=>{"use strict";var Od=de(),gc=process.version,zs=gc.slice(1).split(".").map(Number),hc="nodejs_version_info";Js.exports=(t,e={})=>{let n=e.prefix?e.prefix:"",r=e.labels?e.labels:{},s=Object.keys(r);new Od({name:n+hc,help:"Node.js version info.",labelNames:["version","major","minor","patch",...s],registers:t?[t]:void 0,aggregator:"first",collect(){this.labels(gc,zs[0],zs[1],zs[2],...Object.values(r)).set(1)}})};Js.exports.metricNames=[hc]});var bc=B((bh,Ws)=>{"use strict";var Pd=Ar(),$e;try{$e=ne("perf_hooks")}catch{}var _c="nodejs_gc_duration_seconds",Ad=[.001,.01,.1,1,2,5],_t=[];$e&&$e.constants&&(_t[$e.constants.NODE_PERFORMANCE_GC_MAJOR]="major",_t[$e.constants.NODE_PERFORMANCE_GC_MINOR]="minor",_t[$e.constants.NODE_PERFORMANCE_GC_INCREMENTAL]="incremental",_t[$e.constants.NODE_PERFORMANCE_GC_WEAKCB]="weakcb");Ws.exports=(t,e={})=>{if(!$e)return;let n=e.prefix?e.prefix:"",r=e.labels?e.labels:{},s=Object.keys(r),o=e.gcDurationBuckets?e.gcDurationBuckets:Ad,i=new Pd({name:n+_c,help:"Garbage collection duration by kind, one of major, minor, incremental or weakcb.",labelNames:["kind",...s],enableExemplars:!1,buckets:o,registers:t?[t]:void 0});new $e.PerformanceObserver(u=>{let f=u.getEntries()[0],h=f.detail?_t[f.detail.kind]:_t[f.kind];i.observe(Object.assign({kind:h},r),f.duration/1e3)}).observe({entryTypes:["gc"]})};Ws.exports.metricNames=[_c]});var Ic=B((wh,Hs)=>{"use strict";var{isObject:$d}=Ce(),Ld=va(),Dd=Ra(),Bd=Aa(),jd=La(),Ud=Ba(),qd=Wa(),Fd=Za(),Kd=rc(),Gd=ac(),Vd=dc(),zd=mc(),Jd=yc(),Wd=bc(),wc={processCpuTotal:Ld,processStartTime:Dd,osMemoryHeap:Bd,processOpenFileDescriptors:jd,processMaxFileDescriptors:Ud,eventLoopLag:qd,...typeof process.getActiveResourcesInfo=="function"?{processResources:Gd}:{},processHandles:Fd,processRequests:Kd,heapSizeAndUsed:Vd,heapSpacesSizeAndUsed:zd,version:Jd,gc:Wd},Hd=Object.keys(wc);Hs.exports=function(e){if(e!=null&&!$d(e))throw new TypeError("config must be null, undefined, or an object");e={eventLoopMonitoringPrecision:10,...e};for(let n of Object.values(wc))n(e.register,e)};Hs.exports.metricsList=Hd});var Ys=B(Xs=>{"use strict";var{Grouper:Xd,hashObject:Yd}=Ce();function bt(t){return e=>{if(e.length===0)return;let n={help:e[0].help,name:e[0].name,type:e[0].type,values:[],aggregator:e[0].aggregator},r=new Xd;return e.forEach(s=>{s.values.forEach(o=>{let i=Yd(o.labels);r.add(`${o.metricName}_${i}`,o)})}),r.forEach(s=>{if(s.length===0)return;let o={value:t(s),labels:s[0].labels};s[0].metricName&&(o.metricName=s[0].metricName),n.values.push(o)}),n}}Xs.AggregatorFactory=bt;Xs.aggregators={sum:bt(t=>t.reduce((e,n)=>e+n.value,0)),first:bt(t=>t[0].value),omit:()=>{},average:bt(t=>t.reduce((e,n)=>e+n.value,0)/t.length),min:bt(t=>t.reduce((e,n)=>Math.min(e,n.value),1/0)),max:bt(t=>t.reduce((e,n)=>Math.max(e,n.value),-1/0))}});var Rc=B((Th,Ec)=>{"use strict";var wt=ct(),{Grouper:Qd}=Ce(),{aggregators:Zd}=Ys(),Ze=()=>{let t=ne("cluster");return Ze=()=>t,t},Sc="prom-client:getMetricsReq",Qs="prom-client:getMetricsRes",vc=[wt.globalRegistry],ep=0,Tc=!1,Zs=new Map,Zn=class extends wt{constructor(e=wt.PROMETHEUS_CONTENT_TYPE){super(e),tp()}clusterMetrics(){let e=ep++;return new Promise((n,r)=>{let s=!1;function o(u,f){s||(s=!0,u?r(u):n(f))}let i={responses:[],pending:0,done:o,errorTimeout:setTimeout(()=>{let u=new Error("Operation timed out.");i.done(u)},5e3)};Zs.set(e,i);let c={type:Sc,requestId:e};for(let u in Ze().workers)Ze().workers[u].isConnected()&&(Ze().workers[u].send(c),i.pending++);i.pending===0&&(clearTimeout(i.errorTimeout),process.nextTick(()=>o(null,"")))})}get contentType(){return super.contentType}static aggregate(e,n=wt.PROMETHEUS_CONTENT_TYPE){let r=new wt,s=new Qd;return r.setContentType(n),e.forEach(o=>{o.forEach(i=>{s.add(i.name,i)})}),s.forEach(o=>{let i=o[0].aggregator,c=Zd[i];if(typeof c!="function")throw new Error(`'${i}' is not a defined aggregator.`);let u=c(o);if(u){let f=Object.assign({get:()=>u},u);r.registerMetric(f)}}),r}static setRegistries(e){Array.isArray(e)||(e=[e]),e.forEach(n=>{if(!(n instanceof wt))throw new TypeError(`Expected Registry, got ${typeof n}`)}),vc=e}};function tp(){Tc||(Tc=!0,Ze().isMaster&&Ze().on("message",(t,e)=>{if(e.type===Qs){let n=Zs.get(e.requestId);if(e.error){n.done(new Error(e.error));return}if(e.metrics.forEach(r=>n.responses.push(r)),n.pending--,n.pending===0){Zs.delete(e.requestId),clearTimeout(n.errorTimeout);let s=Zn.aggregate(n.responses).metrics();n.done(null,s)}}}),Ze().isWorker&&process.on("message",t=>{t.type===Sc&&Promise.all(vc.map(e=>e.getMetricsAsJSON())).then(e=>{process.send({type:Qs,requestId:t.requestId,metrics:e})}).catch(e=>{process.send({type:Qs,requestId:t.requestId,error:e.message})})}))}Ec.exports=Zn});var Cc=B(X=>{"use strict";X.register=ct().globalRegistry;X.Registry=ct();Object.defineProperty(X,"contentType",{configurable:!1,enumerable:!0,get(){return X.register.contentType},set(t){X.register.setContentType(t)}});X.prometheusContentType=X.Registry.PROMETHEUS_CONTENT_TYPE;X.openMetricsContentType=X.Registry.OPENMETRICS_CONTENT_TYPE;X.validateMetricName=He().validateMetricName;X.Counter=Rr();X.Gauge=de();X.Histogram=Ar();X.Summary=Ii();X.Pushgateway=Si();X.linearBuckets=Gr().linearBuckets;X.exponentialBuckets=Gr().exponentialBuckets;X.collectDefaultMetrics=Ic();X.aggregators=Ys().aggregators;X.AggregatorRegistry=Rc()});var kc=B(Nc=>{"use strict";var np=[0,255,65535,16777215,4294967295];function rp(t,e,n,r,s){var o;for(o=0;o<s;o++)n[r+o]=t[e+o]}function sp(t,e,n,r){var s;for(s=0;s<r;s++)t[e+s]=t[e-n+s]}function eo(t){this.array=t,this.pos=0}eo.prototype.readUncompressedLength=function(){for(var t=0,e=0,n,r;e<32&&this.pos<this.array.length;){if(n=this.array[this.pos],this.pos+=1,r=n&127,r<<e>>>e!==r)return-1;if(t|=r<<e,n<128)return t;e+=7}return-1};eo.prototype.uncompressToBuffer=function(t){for(var e=this.array,n=e.length,r=this.pos,s=0,o,i,c,u;r<e.length;)if(o=e[r],r+=1,(o&3)===0){if(i=(o>>>2)+1,i>60){if(r+3>=n)return!1;c=i-60,i=e[r]+(e[r+1]<<8)+(e[r+2]<<16)+(e[r+3]<<24),i=(i&np[c])+1,r+=c}if(r+i>n)return!1;rp(e,r,t,s,i),r+=i,s+=i}else{switch(o&3){case 1:i=(o>>>2&7)+4,u=e[r]+(o>>>5<<8),r+=1;break;case 2:if(r+1>=n)return!1;i=(o>>>2)+1,u=e[r]+(e[r+1]<<8),r+=2;break;case 3:if(r+3>=n)return!1;i=(o>>>2)+1,u=e[r]+(e[r+1]<<8)+(e[r+2]<<16)+(e[r+3]<<24),r+=4;break;default:break}if(u===0||u>s)return!1;sp(t,s,u,i),s+=i}return!0};Nc.SnappyDecompressor=eo});var Ac=B(Pc=>{"use strict";var op=16,ip=1<<op,Oc=14,to=new Array(Oc+1);function zt(t,e){return t*506832829>>>e}function Jt(t,e){return t[e]+(t[e+1]<<8)+(t[e+2]<<16)+(t[e+3]<<24)}function Mc(t,e,n){return t[e]===t[n]&&t[e+1]===t[n+1]&&t[e+2]===t[n+2]&&t[e+3]===t[n+3]}function ap(t,e,n,r,s){var o;for(o=0;o<s;o++)n[r+o]=t[e+o]}function xc(t,e,n,r,s){return n<=60?(r[s]=n-1<<2,s+=1):n<256?(r[s]=240,r[s+1]=n-1,s+=2):(r[s]=244,r[s+1]=n-1&255,r[s+2]=n-1>>>8,s+=3),ap(t,e,r,s,n),s+n}function no(t,e,n,r){return r<12&&n<2048?(t[e]=1+(r-4<<2)+(n>>>8<<5),t[e+1]=n&255,e+2):(t[e]=2+(r-1<<2),t[e+1]=n&255,t[e+2]=n>>>8,e+3)}function cp(t,e,n,r){for(;r>=68;)e=no(t,e,n,64),r-=64;return r>64&&(e=no(t,e,n,60),r-=60),no(t,e,n,r)}function lp(t,e,n,r,s){for(var o=1;1<<o<=n&&o<=Oc;)o+=1;o-=1;var i=32-o;typeof to[o]>"u"&&(to[o]=new Uint16Array(1<<o));var c=to[o],u;for(u=0;u<c.length;u++)c[u]=0;var f=e+n,h,_=e,T=e,M,R,k,y,$,P,L,x,I,O,j,S=!0,q=15;if(n>=q)for(h=f-q,e+=1,R=zt(Jt(t,e),i);S;){$=32,k=e;do{if(e=k,M=R,P=$>>>5,$+=1,k=e+P,e>h){S=!1;break}R=zt(Jt(t,k),i),y=_+c[M],c[M]=e-_}while(!Mc(t,e,y));if(!S)break;s=xc(t,T,e-T,r,s);do{for(L=e,x=4;e+x<f&&t[e+x]===t[y+x];)x+=1;if(e+=x,I=L-y,s=cp(r,s,I,x),T=e,e>=h){S=!1;break}O=zt(Jt(t,e-1),i),c[O]=e-1-_,j=zt(Jt(t,e),i),y=_+c[j],c[j]=e-_}while(Mc(t,e,y));if(!S)break;e+=1,R=zt(Jt(t,e),i)}return T<f&&(s=xc(t,T,f-T,r,s)),s}function up(t,e,n){do e[n]=t&127,t=t>>>7,t>0&&(e[n]+=128),n+=1;while(t>0);return n}function ro(t){this.array=t}ro.prototype.maxCompressedLength=function(){var t=this.array.length;return 32+t+Math.floor(t/6)};ro.prototype.compressToBuffer=function(t){var e=this.array,n=e.length,r=0,s=0,o;for(s=up(n,t,s);r<n;)o=Math.min(n-r,ip),s=lp(e,r,o,t,s),r+=o;return s};Pc.SnappyCompressor=ro});var Bc=B(so=>{"use strict";function $c(){return typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node<"u"}function er(t){return t instanceof Uint8Array&&(!$c()||!Buffer.isBuffer(t))}function tr(t){return t instanceof ArrayBuffer}function Lc(t){return $c()?Buffer.isBuffer(t):!1}var dp=kc().SnappyDecompressor,pp=Ac().SnappyCompressor,Dc="Argument compressed must be type of ArrayBuffer, Buffer, or Uint8Array";function fp(t,e){if(!er(t)&&!tr(t)&&!Lc(t))throw new TypeError(Dc);var n=!1,r=!1;er(t)?n=!0:tr(t)&&(r=!0,t=new Uint8Array(t));var s=new dp(t),o=s.readUncompressedLength();if(o===-1)throw new Error("Invalid Snappy bitstream");if(o>e)throw new Error(`The uncompressed length of ${o} is too big, expect at most ${e}`);var i,c;if(n){if(i=new Uint8Array(o),!s.uncompressToBuffer(i))throw new Error("Invalid Snappy bitstream")}else if(r){if(i=new ArrayBuffer(o),c=new Uint8Array(i),!s.uncompressToBuffer(c))throw new Error("Invalid Snappy bitstream")}else if(i=Buffer.alloc(o),!s.uncompressToBuffer(i))throw new Error("Invalid Snappy bitstream");return i}function mp(t){if(!er(t)&&!tr(t)&&!Lc(t))throw new TypeError(Dc);var e=!1,n=!1;er(t)?e=!0:tr(t)&&(n=!0,t=new Uint8Array(t));var r=new pp(t),s=r.maxCompressedLength(),o,i,c;if(e?(o=new Uint8Array(s),c=r.compressToBuffer(o)):n?(o=new ArrayBuffer(s),i=new Uint8Array(o),c=r.compressToBuffer(i)):(o=Buffer.alloc(s),c=r.compressToBuffer(o)),!o.slice){var u=new Uint8Array(Array.prototype.slice.call(o,0,c));if(e)return u;if(n)return u.buffer;throw new Error("Not implemented")}return o.slice(0,c)}so.uncompress=fp;so.compress=mp});var G=Oo(Cc(),1);var ao=Oo(Bc(),1);import Ht from"node:fs";import Fc from"node:fs/promises";import Ep from"node:http";import Rp from"node:https";function Uc(t){let e=[],n=t>>>0;for(;n>127;)e.push(n&127|128),n>>>=7;return e.push(n&127),e}function gp(t){let e=[],n=BigInt.asUintN(64,t);for(;n>0x7fn;)e.push(Number(n&0x7fn)|128),n>>=7n;return e.push(Number(n&0x7fn)),e}function hp(t){return gp(BigInt(Math.trunc(t)))}var yp=new TextEncoder;function jc(t){return yp.encode(t)}function _p(t){let e=new ArrayBuffer(8);return new Float64Array(e)[0]=t,new Uint8Array(e)}function oo(t,e){return Uc(t<<3|e)}var bp=0,wp=1,Ip=2;function Wt(t,e){let n=oo(t,Ip),r=Uc(e.length),s=new Uint8Array(n.length+r.length+e.length);return s.set(n,0),s.set(r,n.length),s.set(e,n.length+r.length),s}function nr(t){let e=0;for(let s of t)e+=s.length;let n=new Uint8Array(e),r=0;for(let s of t)n.set(s,r),r+=s.length;return n}function Tp(t){let e=[];if(t.name.length>0){let n=jc(t.name);e.push(Wt(1,n))}if(t.value.length>0){let n=jc(t.value);e.push(Wt(2,n))}return nr(e)}function Sp(t){let e=[];{let n=oo(1,wp),r=_p(t.value),s=new Uint8Array(n.length+8);s.set(n,0),s.set(r,n.length),e.push(s)}{let n=oo(2,bp),r=hp(t.timestampMs),s=new Uint8Array(n.length+r.length);s.set(n,0),s.set(r,n.length),e.push(s)}return nr(e)}function vp(t){let e=[];for(let n of t.labels)e.push(Wt(1,Tp(n)));for(let n of t.samples)e.push(Wt(2,Sp(n)));return nr(e)}function qc(t){let e=[];for(let n of t.timeseries)e.push(Wt(1,vp(n)));return nr(e)}var Cp=64*1024;function Np(t){return t.map(e=>({source_labels:e.source_labels??["__name__"],regex:new RegExp(e.regex??"(.*)"),action:e.action??"keep"}))}function kp(t,e){for(let n of e){let r=n.source_labels.map(o=>t.find(i=>i.name===o)?.value??"").join(";"),s=n.regex.test(r);if(n.action==="keep"&&!s||n.action==="drop"&&s)return null}return t}var et=class{constructor(e,n,r){this.buffer=[];this.flushTimer=null;this.stopped=!1;this.flushing=!1;this.consecutiveFailures=0;this.circuitOpen=!1;this.lastCircuitWarnMs=0;this.config=e,this.logger=n,this.onUnauthorized=r;let s=e.queue_config??{};this.capacity=s.capacity??2500,this.maxSamplesPerSend=s.max_samples_per_send??500,this.batchDeadlineMs=s.batch_send_deadline_ms??5e3,this.maxRetries=s.max_retries??3,this.minBackoffMs=s.min_backoff_ms??30,this.maxBackoffMs=s.max_backoff_ms??5e3,this.timeoutMs=e.remote_timeout_ms??3e4,this.maxConsecutiveFailures=s.max_consecutive_failures??3,this.compiledRelabelConfigs=Np(e.write_relabel_configs??[]);let o=e.tls_config;if(o?.ca_file)try{this.cachedTlsCa=Ht.readFileSync(o.ca_file)}catch(i){n.warn(`diagnostics-prometheus: \u8BFB\u53D6 TLS ca_file \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}if(o?.cert_file)try{this.cachedTlsCert=Ht.readFileSync(o.cert_file)}catch(i){n.warn(`diagnostics-prometheus: \u8BFB\u53D6 TLS cert_file \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}if(o?.key_file)try{this.cachedTlsKey=Ht.readFileSync(o.key_file)}catch(i){n.warn(`diagnostics-prometheus: \u8BFB\u53D6 TLS key_file \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}enqueue(e){if(this.stopped)return;if(this.circuitOpen){let r=Date.now();r-this.lastCircuitWarnMs>=6e5&&(this.lastCircuitWarnMs=r,this.logger.warn(`diagnostics-prometheus: \u7194\u65AD\u5668\u5DF2\u6253\u5F00\uFF08\u8FDE\u7EED ${this.consecutiveFailures} \u6279\u6B21\u53D1\u9001\u5931\u8D25\uFF09\uFF0C\u6570\u636E\u4E0A\u62A5\u5DF2\u6682\u505C\u3002\u8BF7\u68C0\u67E5\u91C7\u96C6\u5668\u914D\u7F6E\uFF08endpoint/\u8BA4\u8BC1\u4FE1\u606F\u7B49\uFF09\uFF0C\u914D\u7F6E\u4FEE\u6B63\u540E\u5C06\u81EA\u52A8\u6062\u590D\uFF08\u70ED\u52A0\u8F7D\u751F\u6548\u5373\u53EF\uFF09\u3002`));return}this.refreshFileCredentials();let n=this.applyRelabelFilters(e);if(n.length!==0){if(this.buffer.push(...n),this.buffer.length>this.capacity&&this.buffer.splice(0,this.buffer.length-this.capacity),this.buffer.length>=this.maxSamplesPerSend){this.flush();return}this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},this.batchDeadlineMs),typeof this.flushTimer.unref=="function"&&this.flushTimer.unref())}}async flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),!this.flushing){this.flushing=!0;try{for(;this.buffer.length>0;){let e=this.buffer.splice(0,this.maxSamplesPerSend);await this.sendBatch(e)}}finally{this.flushing=!1}}}updateConfig(e){this.config={...this.config,...e},(e.basic_auth||e.bearer_token_file)&&(this.cachedPasswordFileContent=void 0,this.cachedBearerTokenFileContent=void 0),(this.circuitOpen||this.consecutiveFailures>0)&&(this.consecutiveFailures=0,this.circuitOpen=!1,this.logger.debug("diagnostics-prometheus: \u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0C\u7194\u65AD\u5668\u5DF2\u91CD\u7F6E\uFF0C\u6570\u636E\u4E0A\u62A5\u6062\u590D\u3002"))}async stop(){this.stopped=!0,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),await this.flush().catch(()=>{})}async refreshFileCredentials(){if(this.config.basic_auth?.password_file&&this.cachedPasswordFileContent===void 0)try{this.cachedPasswordFileContent=(await Fc.readFile(this.config.basic_auth.password_file,"utf-8")).trim()}catch(e){this.logger.warn(`diagnostics-prometheus: \u5F02\u6B65\u8BFB\u53D6 password_file \u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}if(this.config.bearer_token_file&&this.cachedBearerTokenFileContent===void 0)try{this.cachedBearerTokenFileContent=(await Fc.readFile(this.config.bearer_token_file,"utf-8")).trim()}catch(e){this.logger.warn(`diagnostics-prometheus: \u5F02\u6B65\u8BFB\u53D6 bearer_token_file \u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}applyRelabelFilters(e){return this.compiledRelabelConfigs.length===0?e:e.filter(n=>kp(n.labels,this.compiledRelabelConfigs)!==null)}async sendBatch(e){if(e.length===0)return;let n=qc({timeseries:e}),r=ao.default.compress??ao.default.default?.compress;if(!r){this.logger.error(`diagnostics-prometheus: snappyjs compress \u51FD\u6570\u672A\u627E\u5230\uFF0C\u65E0\u6CD5\u538B\u7F29\u6570\u636E\uFF0Cdropping ${e.length} samples\u3002\u8BF7\u68C0\u67E5 snappyjs \u5305\u7248\u672C\u548C\u6A21\u5757\u52A0\u8F7D\u65B9\u5F0F`);return}let s=r(Buffer.from(n));for(let o=0;o<=this.maxRetries;o++)try{let{statusCode:i,body:c}=await this.httpPost(s);if(i>=200&&i<300){this.consecutiveFailures=0;return}if(i===401){if(this.onUnauthorized){this.logger.warn(`diagnostics-prometheus: remote write 401 Unauthorized, \u6B63\u5728\u68C0\u67E5\u51ED\u8BC1\u72B6\u6001 (attempt ${o+1}/${this.maxRetries}). Response: ${c}`);let u;try{u=await this.onUnauthorized()}catch(f){this.logger.error(`diagnostics-prometheus: \u51ED\u8BC1\u5237\u65B0\u5931\u8D25: ${io(f)}, dropping ${e.length} samples. Response: ${c}`),this.recordBatchFailure();return}if(!u){this.logger.error(`diagnostics-prometheus: remote write 401 Unauthorized, \u4E34\u65F6\u5BC6\u94A5\u672A\u8FC7\u671F\uFF0C\u8DF3\u8FC7\u91CD\u8BD5, dropping ${e.length} samples. Response: ${c}`),this.recordBatchFailure();return}if(o<this.maxRetries)continue;this.logger.error(`diagnostics-prometheus: remote write 401 after ${this.maxRetries} retries, dropping ${e.length} samples. Response: ${c}`),this.recordBatchFailure();return}this.logger.error(`diagnostics-prometheus: remote write 401 Unauthorized, dropping ${e.length} samples. Response: ${c}`),this.recordBatchFailure();return}if(i===400||i===415){this.logger.error(`diagnostics-prometheus: remote write rejected with ${i}, dropping ${e.length} samples. Response: ${c}`),this.recordBatchFailure();return}if(i===429||i>=500&&i<600){if(o<this.maxRetries){let u=this.calculateBackoff(o);this.logger.warn(`diagnostics-prometheus: remote write ${i}, retrying in ${u}ms (attempt ${o+1}/${this.maxRetries}). Response: ${c}`),await this.sleep(u);continue}this.logger.error(`diagnostics-prometheus: remote write failed after ${this.maxRetries} retries, dropping ${e.length} samples. Response: ${c}`),this.recordBatchFailure();return}this.logger.warn(`diagnostics-prometheus: remote write unexpected status ${i}. Response: ${c}`);return}catch(i){if(o<this.maxRetries){let c=this.calculateBackoff(o);this.logger.warn(`diagnostics-prometheus: remote write error: ${io(i)}, retrying in ${c}ms`),await this.sleep(c);continue}this.logger.error(`diagnostics-prometheus: remote write failed: ${io(i)}, dropping ${e.length} samples`),this.recordBatchFailure();return}}recordBatchFailure(){++this.consecutiveFailures,!this.circuitOpen&&this.consecutiveFailures>=this.maxConsecutiveFailures&&(this.circuitOpen=!0,this.lastCircuitWarnMs=0,this.logger.error(`diagnostics-prometheus: \u8FDE\u7EED ${this.consecutiveFailures} \u6279\u6B21\u53D1\u9001\u5931\u8D25\uFF0C\u7194\u65AD\u5668\u5DF2\u6253\u5F00\uFF0C\u6570\u636E\u4E0A\u62A5\u5DF2\u6682\u505C\u3002\u8BF7\u68C0\u67E5\u91C7\u96C6\u5668\u914D\u7F6E\uFF08endpoint/\u8BA4\u8BC1\u4FE1\u606F\u7B49\uFF09\uFF0C\u914D\u7F6E\u4FEE\u6B63\u540E\u70ED\u52A0\u8F7D\u5C06\u81EA\u52A8\u91CD\u7F6E\u7194\u65AD\u5668\u5E76\u6062\u590D\u4E0A\u62A5\u3002`))}httpPost(e){return new Promise((n,r)=>{let s=new URL(this.config.url),o=s.protocol==="https:",i=o?Rp:Ep,c={"Content-Type":"application/x-protobuf","Content-Encoding":"snappy","X-Prometheus-Remote-Write-Version":"0.1.0","User-Agent":"openclaw-diagnostics-prometheus/1.0",...this.config.headers??{}};if(this.config.basic_auth){let h=this.config.basic_auth.username??"",_=this.config.basic_auth.password??"";if(!_&&this.config.basic_auth.password_file&&(_=this.cachedPasswordFileContent??"",!_)){this.logger.warn("diagnostics-prometheus: password_file \u7F13\u5B58\u4E3A\u7A7A\uFF0C\u5C1D\u8BD5\u540C\u6B65\u8BFB\u53D6\u4F5C\u4E3A\u56DE\u9000");try{_=Ht.readFileSync(this.config.basic_auth.password_file,"utf-8").trim()}catch(T){this.logger.warn(`diagnostics-prometheus: \u8BFB\u53D6 password_file \u5931\u8D25: ${T instanceof Error?T.message:String(T)}`)}}c.Authorization=`Basic ${Buffer.from(`${h}:${_}`).toString("base64")}`}else if(this.config.bearer_token)c.Authorization=`Bearer ${this.config.bearer_token}`;else if(this.config.bearer_token_file){let h=this.cachedBearerTokenFileContent??"";if(h)c.Authorization=`Bearer ${h}`;else{this.logger.warn("diagnostics-prometheus: bearer_token_file \u7F13\u5B58\u4E3A\u7A7A\uFF0C\u5C1D\u8BD5\u540C\u6B65\u8BFB\u53D6\u4F5C\u4E3A\u56DE\u9000");try{c.Authorization=`Bearer ${Ht.readFileSync(this.config.bearer_token_file,"utf-8").trim()}`}catch(_){this.logger.warn(`diagnostics-prometheus: \u8BFB\u53D6 bearer_token_file \u5931\u8D25: ${_ instanceof Error?_.message:String(_)}`)}}}let u={method:"POST",hostname:s.hostname,port:s.port||(o?443:80),path:s.pathname+s.search,headers:c,timeout:this.timeoutMs};if(o&&this.config.tls_config){let h=this.config.tls_config;this.cachedTlsCa&&(u.ca=this.cachedTlsCa),this.cachedTlsCert&&(u.cert=this.cachedTlsCert),this.cachedTlsKey&&(u.key=this.cachedTlsKey),h.server_name&&(u.servername=h.server_name),h.insecure_skip_verify&&(u.rejectUnauthorized=!1)}let f=i.request(u,h=>{let _=[],T=0,M=!1;h.on("data",R=>{if(!M){if(T+=R.length,T>Cp){M=!0,h.destroy();let k=Buffer.concat(_).toString("utf-8");n({statusCode:h.statusCode??0,body:k+"...(truncated)"});return}_.push(R)}}),h.on("end",()=>{if(M)return;let R=Buffer.concat(_).toString("utf-8");n({statusCode:h.statusCode??0,body:R})}),h.on("error",()=>{M||n({statusCode:h.statusCode??0,body:""})})});f.on("error",r),f.on("timeout",()=>{f.destroy(new Error("remote write request timed out"))}),f.write(Buffer.isBuffer(e)?e:Buffer.from(e)),f.end()})}calculateBackoff(e){let n=this.minBackoffMs*Math.pow(2,e),r=Math.min(n,this.maxBackoffMs),s=r*.25*(Math.random()*2-1);return Math.round(r+s)}sleep(e){return new Promise(n=>setTimeout(n,e))}};function io(t){return t instanceof Error?t.stack??t.message:typeof t=="string"?t:String(t)}import Mp from"node:http";import xp from"node:https";import{URL as Op}from"node:url";import uo from"node:os";import le from"node:fs/promises";import Jc from"node:path";var Pp="http://metadata.tencentyun.com/latest/meta-data",Ap=2e3,$p=30*1e3,co=3,Kc=1024,Gc=3,Xt="clawpro-diagnostics-metrics-cls",Wc=Object.freeze({cvmInstanceId:"",cvmInstanceName:"",cvmInstanceIntraIp:"",hostName:""}),we=Wc,Yt=!1,en=!1,Le=null,Qt=0,Zt=0;function lo(t,e=0){let n=e===0?`${Pp}/${t}`:t;if(e>Gc)return Promise.reject(new Error(`Too many redirects (>${Gc}) for ${n}`));let r;try{r=new Op(n)}catch{return Promise.reject(new Error(`Invalid URL: ${n}`))}let s=r.protocol==="https:"?xp:Mp;return new Promise((o,i)=>{let c=s.get(n,{timeout:Ap},u=>{let f=u.statusCode??0;if(f>=300&&f<400&&u.headers.location){u.resume(),lo(u.headers.location,e+1).then(o,i);return}if(f!==200){u.resume(),i(new Error(`HTTP ${f} for ${n}`));return}Lp(u,n,o,i)});c.on("timeout",()=>{c.destroy(),i(new Error(`Request timeout for ${n}`))}),c.on("error",i)})}function Lp(t,e,n,r){let s=[],o=0,i=!1;t.on("data",c=>{if(!i){if(o+=c.length,o>Kc){i=!0,t.destroy(),r(new Error(`Response body too large (>${Kc} bytes) for ${e}`));return}s.push(c)}}),t.on("end",()=>{i||n(Buffer.concat(s).toString("utf-8").trim())}),t.on("error",c=>{i||r(c)})}async function Dp(t){let e={instanceId:"",instanceName:"",localIpv4:""};try{let n=Jc.join(t,"openclaw.json"),r=await le.readFile(n,"utf8"),f=JSON.parse(r).plugins?.entries?.[Xt]?.config?.instance_metadata;if(!f)return e;let h=_=>typeof _=="string"&&_.trim()?_.trim():"";return{instanceId:h(f.instance_id),instanceName:h(f.instance_name),localIpv4:h(f.local_ipv4)}}catch{return e}}var Vc=50,Bp=5e3;async function jp(t,e){let n=Date.now()+e;for(;Date.now()<n;){let r=null;try{return r=await le.open(t,le.constants.O_CREAT|le.constants.O_EXCL|le.constants.O_WRONLY),await r.writeFile(String(process.pid),"utf8"),await r.close(),r=null,!0}catch(s){if(r!==null){try{await r.close()}catch{}try{await le.unlink(t)}catch{}r=null,await new Promise(c=>setTimeout(c,Vc*10));continue}if(s.code!=="EEXIST")return!1;if(await Up(t)){try{await le.unlink(t)}catch{}continue}await new Promise(c=>setTimeout(c,Vc))}}return!1}async function Up(t){try{let e=await le.readFile(t,"utf8"),n=parseInt(e.trim(),10);if(isNaN(n)||n<=0)return!0;try{return process.kill(n,0),!1}catch(r){return r.code==="ESRCH"}}catch{return!1}}async function qp(t){try{await le.unlink(t)}catch{}}async function po(t,e,n){let r={};if(e.instanceId&&(r.instance_id=e.instanceId),e.instanceName&&(r.instance_name=e.instanceName),Object.keys(r).length===0)return;let s=Jc.join(t,"openclaw.json"),o=s+".lock",i=s+".tmp";if(!await jp(o,Bp)){n?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6 openclaw.json \u6587\u4EF6\u9501\u8D85\u65F6\uFF0C\u8DF3\u8FC7\u672C\u6B21\u5199\u5165");return}try{let u={};try{let k=await le.readFile(s,"utf8");u=JSON.parse(k)}catch{}(!u.plugins||typeof u.plugins!="object")&&(u.plugins={});let f=u.plugins;(!f.entries||typeof f.entries!="object")&&(f.entries={});let h=f.entries;(!h[Xt]||typeof h[Xt]!="object")&&(h[Xt]={});let _=h[Xt];(!_.config||typeof _.config!="object")&&(_.config={});let T=_.config,M=T.instance_metadata;T.instance_metadata={...M??{},...r};let R=JSON.stringify(u,null,2)+`
|
|
12
|
-
`;await le.writeFile(i,R,"utf8");try{await le.rename(i,s)}catch(k){if(k.code==="EXDEV"){await le.copyFile(i,s);try{await le.unlink(i)}catch{}}else throw k}n?.debug(`diagnostics-metrics/instance-metadata: \u5B9E\u4F8B\u5143\u6570\u636E\u5DF2\u6301\u4E45\u5316\u5199\u5165 openclaw.json (${Object.keys(r).join(", ")})`)}catch(u){try{await le.unlink(i)}catch{}n?.warn(`diagnostics-metrics/instance-metadata: \u5199\u5165\u5B9E\u4F8B\u5143\u6570\u636E\u5230 openclaw.json \u5931\u8D25: ${String(u)}`)}finally{await qp(o)}}function Hc(){let t;try{t=uo.networkInterfaces()}catch{return""}let e=[];for(let[r,s]of Object.entries(t))if(s)for(let o of s)o.family!=="IPv4"||o.internal||o.address.startsWith("169.254.")||e.push({iface:r,address:o.address});if(e.length===0)return"";let n=r=>r.startsWith("eth")?0:r.startsWith("en")?1:2;return e.sort((r,s)=>{let o=n(r.iface),i=n(s.iface);return o!==i?o-i:r.iface<s.iface?-1:r.iface>s.iface?1:0}),e[0].address}async function fo(t){let e=we,n=!e.cvmInstanceId,r=!e.cvmInstanceName,[s,o]=await Promise.all([n?zc(lo("instance-id")):Promise.resolve({status:"skipped"}),r?zc(lo("instance-name")):Promise.resolve({status:"skipped"})]),i=e.hostName;try{i=uo.hostname()}catch{t?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6 hostname \u5931\u8D25")}let c=Hc(),u={},f={...e,hostName:i||e.hostName};s.status==="fulfilled"&&s.value?(f.cvmInstanceId=s.value,u.instanceId=s.value):s.status==="rejected"?t?.warn(`diagnostics-metrics/instance-metadata: \u83B7\u53D6 instance-id \u5931\u8D25: ${String(s.reason)}`):s.status==="fulfilled"&&t?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6 instance-id \u5931\u8D25: empty response"),o.status==="fulfilled"&&o.value?(f.cvmInstanceName=o.value,u.instanceName=o.value):o.status==="rejected"?t?.warn(`diagnostics-metrics/instance-metadata: \u83B7\u53D6 instance-name \u5931\u8D25: ${String(o.reason)}`):o.status==="fulfilled"&&t?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6 instance-name \u5931\u8D25: empty response"),c?f.cvmInstanceIntraIp=c:t?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6\u672C\u5730\u975E\u73AF\u56DE IPv4 \u5730\u5740\u5931\u8D25: \u672A\u627E\u5230\u53EF\u7528\u7F51\u7EDC\u63A5\u53E3"),we=Object.freeze(f);let h=!!f.cvmInstanceId&&!!f.cvmInstanceName;return t?.debug(`diagnostics-metrics/instance-metadata: \u5F53\u524D\u5B9E\u4F8B\u4FE1\u606F cvm_instance_id=${we.cvmInstanceId}, cvm_instance_name=${we.cvmInstanceName}, cvm_instance_intra_ip=${we.cvmInstanceIntraIp}, host_name=${we.hostName}`),{allSuccess:h,fetched:u}}function zc(t){return t.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))}function Oe(){return we}function Xc(t,e,n){if(!Yt){e?.warn("diagnostics-metrics/instance-metadata: updateInstanceMetadata \u8C03\u7528\u65F6\u6A21\u5757\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u672C\u6B21\u70ED\u66F4\u65B0\u5DF2\u8DF3\u8FC7");return}let r=we,s=t.instanceId!==void 0?t.instanceId:r.cvmInstanceId,o=t.instanceName!==void 0?t.instanceName:r.cvmInstanceName,i=t.localIpv4!==void 0?t.localIpv4:r.cvmInstanceIntraIp;if(s===r.cvmInstanceId&&o===r.cvmInstanceName&&i===r.cvmInstanceIntraIp)return;we=Object.freeze({cvmInstanceId:s,cvmInstanceName:o,cvmInstanceIntraIp:i,hostName:r.hostName}),(!s||!o)&&(e?.debug("diagnostics-metrics/instance-metadata: \u70ED\u66F4\u65B0\u6E05\u7A7A\u4E86\u90E8\u5206\u5B57\u6BB5\uFF0C\u91CD\u65B0\u89E6\u53D1 metadata \u63A5\u53E3\u83B7\u53D6"),Qt=0,Le&&(clearTimeout(Le),Le=null),fo(e).then(({allSuccess:u,fetched:f})=>{en||(n&&(f.instanceId||f.instanceName)&&po(n,f,e),u||mo(e,n))}))}async function rr(t,e){if(Zt++,!Yt){en=!1,Yt=!0;try{let n="";try{n=uo.hostname()}catch{}let r=e?await Dp(e):{instanceId:"",instanceName:"",localIpv4:""},s=r.localIpv4||Hc();s||t?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6\u672C\u5730\u975E\u73AF\u56DE IPv4 \u5730\u5740\u5931\u8D25: \u672A\u627E\u5230\u53EF\u7528\u7F51\u7EDC\u63A5\u53E3");let o={cvmInstanceId:r.instanceId,cvmInstanceName:r.instanceName,cvmInstanceIntraIp:s,hostName:n};if(we=Object.freeze(o),o.cvmInstanceId&&o.cvmInstanceName){t?.debug(`diagnostics-metrics/instance-metadata: \u5F53\u524D\u5B9E\u4F8B\u4FE1\u606F cvm_instance_id=${o.cvmInstanceId}, cvm_instance_name=${o.cvmInstanceName}, cvm_instance_intra_ip=${o.cvmInstanceIntraIp}, host_name=${o.hostName}`);return}let{allSuccess:i,fetched:c}=await fo(t);if(e&&(c.instanceId||c.instanceName)&&await po(e,c,t),!i){t?.warn("diagnostics-metrics/instance-metadata: \u9996\u6B21\u83B7\u53D6\u5B58\u5728\u672A\u5C31\u7EEA\u5B57\u6BB5\uFF0C\u53EF\u80FD\u4E0D\u5728\u817E\u8BAF\u4E91\u73AF\u5883\uFF0C\u5C06\u5728 30 \u79D2\u540E\u91CD\u8BD5"),mo(t,e);return}}catch(n){throw Yt=!1,Zt--,n}}}function mo(t,e){if(Qt>=co){t?.warn(`diagnostics-metrics/instance-metadata: \u5DF2\u91CD\u8BD5 ${co} \u6B21\u4ECD\u672A\u6210\u529F\uFF0C\u505C\u6B62\u91CD\u8BD5`);return}Le=setTimeout(async()=>{if(en)return;Qt++,t?.debug(`diagnostics-metrics/instance-metadata: \u7B2C ${Qt}/${co} \u6B21\u91CD\u8BD5\u83B7\u53D6\u5143\u6570\u636E`);let{allSuccess:n,fetched:r}=await fo(t);if(!en&&(e&&(r.instanceId||r.instanceName)&&await po(e,r,t),!n)){mo(t,e);return}},$p),typeof Le.unref=="function"&&Le.unref()}function tn(){Zt!==0&&(Zt--,!(Zt>0)&&(en=!0,Le&&(clearTimeout(Le),Le=null),Qt=0,Yt=!1,we=Wc))}import{createCipheriv as Fp,createDecipheriv as Kp,createHash as Gp,randomBytes as Vp}from"node:crypto";var nn="ENC:",zp="openclaw-diag-metrics-cls",Yc="aes-256-cbc";function Qc(){return Gp("sha256").update(zp).digest()}function go(t){if(!t||t.startsWith(nn))return t;let e=Qc(),n=Vp(16),r=Fp(Yc,e,n),s=Buffer.concat([r.update(t,"utf8"),r.final()]),o=Buffer.concat([n,s]).toString("base64");return`${nn}${o}`}function ie(t){if(!t||!t.startsWith(nn))return t;try{let e=t.slice(nn.length),n=Buffer.from(e,"base64");if(n.length<17)return console.error(`[crypto-utils] \u89E3\u5BC6\u5931\u8D25: \u5BC6\u6587\u6570\u636E\u4E0D\u5B8C\u6574 (\u957F\u5EA6=${n.length}), \u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u52A0\u5BC6\u5B57\u6BB5\u662F\u5426\u88AB\u7BE1\u6539\u6216\u622A\u65AD`),"";let r=n.subarray(0,16),s=n.subarray(16),o=Qc(),i=Kp(Yc,o,r);return Buffer.concat([i.update(s),i.final()]).toString("utf8")}catch(e){let n=e instanceof Error?e.message:String(e);return console.error(`[crypto-utils] \u89E3\u5BC6\u5931\u8D25: ${n}, \u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u52A0\u5BC6\u5B57\u6BB5\u662F\u5426\u6B63\u786E`),""}}function ho(t){return typeof t=="string"&&t.startsWith(nn)}var It="clawpro-diagnostics-metrics-cls";import el from"node:path";import yo from"node:fs/promises";var Jp=300*1e3;function tl(t){return t?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t):!0}function Wp(t){let e=typeof t?.metricTopicId=="string"?t.metricTopicId.trim():"",n=typeof t?.endpoint=="string"?t.endpoint.trim():"",r=typeof t?.credentialMode=="string"&&t.credentialMode.trim()==="cvmRole"?"cvmRole":"static",s=typeof t?.roleName=="string"&&t.roleName.trim()?t.roleName.trim():"",o=typeof t?.secretId=="string"?ie(t.secretId.trim()):"",i=typeof t?.secretKey=="string"?ie(t.secretKey.trim()):"",c=typeof t?.token=="string"?t.token.trim():void 0;if(e&&!tl(e)&&(e=""),r==="static"&&(!o||!i)||r==="cvmRole"&&!s)return null;let u=typeof t?.credentialRefreshIntervalMs=="number"&&t.credentialRefreshIntervalMs>=6e4?t.credentialRefreshIntervalMs:Jp,f=t?.enableReport!==!1;return{metricTopicId:e,credentialMode:r,roleName:s,secretId:o,secretKey:i,token:c,endpoint:n,credentialRefreshIntervalMs:u,enableReport:f}}var Hp=1e4;async function Xp(t){try{let e=await yo.readFile(t,"utf8"),i=JSON.parse(e).plugins?.entries?.[It]?.config,c=i?.cls,u=typeof c?.metricTopicId=="string"?c.metricTopicId.trim():"",f=typeof c?.endpoint=="string"?c.endpoint.trim():"",h=c?.enableReport!==!1,_=typeof c?.secretId=="string"?ie(c.secretId.trim()):"",T=typeof c?.secretKey=="string"?ie(c.secretKey.trim()):"",M=u;u&&!tl(u)&&(M=void 0);let R=i?.instance_metadata,k=q=>typeof q!="string"?null:q.trim(),y=R?k(R.instance_id):null,$=R?k(R.instance_name):null,P=R?k(R.local_ipv4):null,L=y??"",x=$??"",I=P??"",O=i?.log,j=O?.enableLogReport===!0,S=typeof O?.logTopicId=="string"?O.logTopicId.trim():"";return{metricTopicId:M,endpoint:f,enableReport:h,secretId:_,secretKey:T,instanceId:L,instanceName:x,localIpv4:I,enableLogReport:j,logTopicId:S}}catch{return null}}function Zc(t,e){return!t||!e?"":`https://${t}/prometheus/${e}/api/v1/write`}function nl(t){return t instanceof Error?t.stack??t.message:typeof t=="string"?t:String(t)}async function Yp(t){let e=el.join(t.stateDir,"openclaw.json"),n;try{n=await yo.readFile(e,"utf8")}catch{return}let r;try{r=JSON.parse(n)}catch{return}let s=!1,o=r.diagnostics;o?.enabled!==!0&&(r.diagnostics={...o??{},enabled:!0},s=!0,t.logger.debug?.("diagnostics-metrics/prometheus: \u5DF2\u81EA\u52A8\u5199\u5165 diagnostics.enabled=true \u5230 openclaw.json\uFF0C\u91CD\u542F\u540E\u751F\u6548"));let h=r.plugins?.entries?.[It]?.config?.cls;if(h){let _=h.secretId,T=h.secretKey;typeof _=="string"&&_.trim()&&!ho(_.trim())&&(h.secretId=go(_.trim()),s=!0,t.logger.debug?.("diagnostics-metrics/prometheus: \u5DF2\u5C06 secretId \u52A0\u5BC6\u540E\u5199\u5165\u914D\u7F6E\u6587\u4EF6")),typeof T=="string"&&T.trim()&&!ho(T.trim())&&(h.secretKey=go(T.trim()),s=!0,t.logger.debug?.("diagnostics-metrics/prometheus: \u5DF2\u5C06 secretKey \u52A0\u5BC6\u540E\u5199\u5165\u914D\u7F6E\u6587\u4EF6"))}s&&await yo.writeFile(e,JSON.stringify(r,null,2)+`
|
|
13
|
-
`,"utf8")}function rl(t,e,n){let r=Wp(t),s=null,o=null,i=[],c=null,u=null,f=null,h=null,_="",T="",M=!0,R="",k="",y="",$="",P="",L=!1,x="";return{id:"clawpro-diagnostics-metrics-cls",getExports(){return u},async start(I){let O={debug:I.logger.debug??(()=>{}),info:I.logger.info.bind(I.logger),warn:I.logger.warn.bind(I.logger),error:I.logger.error.bind(I.logger)},j=t;if(j?.enabled===!1)return;let S=j?.metric_prefix??"openclaw",q={...j?.external_labels??{}};await rr(O,I.stateDir).catch(w=>{let D=w instanceof Error?w.message:String(w);I.logger.warn(`diagnostics-metrics/prometheus: \u5B9E\u4F8B\u5143\u6570\u636E\u5B9A\u65F6\u5237\u65B0\u542F\u52A8\u5931\u8D25 (${D})\uFF0C\u5C06\u4F7F\u7528 unknown \u4F5C\u4E3A\u9ED8\u8BA4\u503C`)}),await Yp(I).catch(()=>{I.logger.warn('diagnostics-metrics/prometheus: \u65E0\u6CD5\u81EA\u52A8\u5199\u5165 diagnostics.enabled\uFF0C\u8BF7\u624B\u52A8\u5728 openclaw.json \u4E2D\u6DFB\u52A0 { "diagnostics": { "enabled": true } }')}),s=new G.Registry,j?.default_metrics!==!1&&(0,G.collectDefaultMetrics)({register:s,prefix:`${S}_node_`});let V=new G.Counter({name:`${S}_tokens_total`,help:"Total tokens consumed",labelNames:["openclaw_type","openclaw_provider","openclaw_model","openclaw_channel"],registers:[s]}),Y=new G.Counter({name:`${S}_cost_usd_total`,help:"Estimated model cost in USD",labelNames:["openclaw_provider","openclaw_model","openclaw_channel"],registers:[s]}),ce=new G.Histogram({name:`${S}_run_duration_ms`,help:"Agent run duration in milliseconds",labelNames:["openclaw_provider","openclaw_model","openclaw_channel"],buckets:[100,250,500,1e3,2500,5e3,1e4,3e4,6e4],registers:[s]}),Se=new G.Histogram({name:`${S}_context_tokens`,help:"Context window token count",labelNames:["openclaw_provider","openclaw_model","openclaw_channel","openclaw_type"],buckets:[1e3,4e3,8e3,16e3,32e3,64e3,128e3,2e5],registers:[s]}),ve=new G.Counter({name:`${S}_webhook_received_total`,help:"Webhook requests received",labelNames:["openclaw_channel","openclaw_update_type"],registers:[s]}),nt=new G.Counter({name:`${S}_webhook_error_total`,help:"Webhook processing errors",labelNames:["openclaw_channel","openclaw_update_type"],registers:[s]}),C=new G.Histogram({name:`${S}_webhook_duration_ms`,help:"Webhook processing duration in milliseconds",labelNames:["openclaw_channel","openclaw_update_type"],buckets:[10,50,100,250,500,1e3,2500,5e3],registers:[s]}),rt=new G.Counter({name:`${S}_message_queued_total`,help:"Messages queued for processing",labelNames:["openclaw_channel","openclaw_source"],registers:[s]}),Ee=new G.Counter({name:`${S}_message_processed_total`,help:"Messages processed by outcome",labelNames:["openclaw_channel","openclaw_outcome"],registers:[s]}),ye=new G.Histogram({name:`${S}_message_duration_ms`,help:"Message processing duration in milliseconds",labelNames:["openclaw_channel","openclaw_outcome"],buckets:[100,500,1e3,2500,5e3,1e4,3e4,6e4],registers:[s]}),ln=new G.Gauge({name:`${S}_queue_depth`,help:"Current queue depth per lane",labelNames:["openclaw_lane"],registers:[s]}),lr=new G.Histogram({name:`${S}_queue_wait_ms`,help:"Queue wait time before execution in milliseconds",labelNames:["openclaw_lane"],buckets:[10,50,100,500,1e3,5e3,1e4],registers:[s]}),z=new G.Counter({name:`${S}_queue_lane_enqueue_total`,help:"Queue lane enqueue events",labelNames:["openclaw_lane"],registers:[s]}),st=new G.Counter({name:`${S}_queue_lane_dequeue_total`,help:"Queue lane dequeue events",labelNames:["openclaw_lane"],registers:[s]}),ur=new G.Counter({name:`${S}_session_state_total`,help:"Session state transitions",labelNames:["openclaw_state","openclaw_reason"],registers:[s]}),un=new G.Counter({name:`${S}_session_stuck_total`,help:"Sessions detected as stuck",labelNames:["openclaw_state"],registers:[s]}),dn=new G.Histogram({name:`${S}_session_stuck_age_ms`,help:"Age of stuck sessions in milliseconds",labelNames:["openclaw_state"],buckets:[1e3,5e3,1e4,3e4,6e4,12e4,3e5],registers:[s]}),pn=new G.Counter({name:`${S}_run_attempt_total`,help:"Agent run attempts",labelNames:["openclaw_attempt"],registers:[s]}),fn=new G.Gauge({name:`${S}_active_sessions`,help:"Number of currently active sessions",registers:[s]}),dr=new G.Gauge({name:`${S}_waiting_sessions`,help:"Number of sessions in waiting state",registers:[s]}),pr=new G.Gauge({name:`${S}_queued_messages`,help:"Total messages currently queued",registers:[s]}),fr=new G.Counter({name:`${S}_tool_loop_total`,help:"Tool loop detections",labelNames:["openclaw_tool","openclaw_detector","openclaw_level","openclaw_action"],registers:[s]}),Ct=w=>{try{switch(w.type){case"model.usage":{let D={openclaw_provider:w.provider??"unknown",openclaw_model:w.model??"unknown",openclaw_channel:w.channel??"unknown"},J=w.usage;if(!J)break;J.input&&V.inc({...D,openclaw_type:"input"},J.input),J.output&&V.inc({...D,openclaw_type:"output"},J.output),J.cacheRead&&V.inc({...D,openclaw_type:"cache_read"},J.cacheRead),J.cacheWrite&&V.inc({...D,openclaw_type:"cache_write"},J.cacheWrite),J.promptTokens&&V.inc({...D,openclaw_type:"prompt"},J.promptTokens),J.total&&V.inc({...D,openclaw_type:"total"},J.total),w.costUsd&&Y.inc({openclaw_provider:D.openclaw_provider,openclaw_model:D.openclaw_model,openclaw_channel:D.openclaw_channel},w.costUsd),w.durationMs&&ce.observe({openclaw_provider:D.openclaw_provider,openclaw_model:D.openclaw_model,openclaw_channel:D.openclaw_channel},w.durationMs),w.context?.limit&&Se.observe({openclaw_provider:D.openclaw_provider,openclaw_model:D.openclaw_model,openclaw_channel:D.openclaw_channel,openclaw_type:"limit"},w.context.limit),w.context?.used&&Se.observe({openclaw_provider:D.openclaw_provider,openclaw_model:D.openclaw_model,openclaw_channel:D.openclaw_channel,openclaw_type:"used"},w.context.used);break}case"webhook.received":{ve.inc({openclaw_channel:w.channel??"unknown",openclaw_update_type:w.updateType??"unknown"});break}case"webhook.processed":{typeof w.durationMs=="number"&&C.observe({openclaw_channel:w.channel??"unknown",openclaw_update_type:w.updateType??"unknown"},w.durationMs);break}case"webhook.error":{nt.inc({openclaw_channel:w.channel??"unknown",openclaw_update_type:w.updateType??"unknown"});break}case"message.queued":{rt.inc({openclaw_channel:w.channel??"unknown",openclaw_source:w.source??"unknown"});break}case"message.processed":{Ee.inc({openclaw_channel:w.channel??"unknown",openclaw_outcome:w.outcome??"unknown"}),typeof w.durationMs=="number"&&ye.observe({openclaw_channel:w.channel??"unknown",openclaw_outcome:w.outcome??"unknown"},w.durationMs);break}case"queue.lane.enqueue":{z.inc({openclaw_lane:w.lane}),ln.set({openclaw_lane:w.lane},w.queueSize??0);break}case"queue.lane.dequeue":{st.inc({openclaw_lane:w.lane}),ln.set({openclaw_lane:w.lane},w.queueSize??0),typeof w.waitMs=="number"&&lr.observe({openclaw_lane:w.lane},w.waitMs);break}case"session.state":{ur.inc({openclaw_state:w.state,openclaw_reason:w.reason??""});break}case"session.stuck":{un.inc({openclaw_state:w.state}),typeof w.ageMs=="number"&&dn.observe({openclaw_state:w.state},w.ageMs);break}case"run.attempt":{pn.inc({openclaw_attempt:String(w.attempt)});break}case"diagnostic.heartbeat":{fn.set(w.active??0),dr.set(w.waiting??0),pr.set(w.queued??0);break}case"tool.loop":{fr.inc({openclaw_tool:w.toolName,openclaw_detector:w.detector,openclaw_level:w.level,openclaw_action:w.action});break}}}catch(D){I.logger.error(`diagnostics-metrics/prometheus: event handler failed (${w.type}): ${nl(D)}`)}},mn="openclaw/plugin-sdk/diagnostics-otel",gn="openclaw/plugin-sdk/diagnostic-runtime",Ke;try{Ke=(await import(mn)).onDiagnosticEvent}catch{}if(!Ke)try{Ke=(await import(gn)).onDiagnosticEvent}catch{}Ke?o=Ke(Ct):I.logger.warn("diagnostics-metrics/prometheus: onDiagnosticEvent \u5728\u5F53\u524D openclaw \u7248\u672C\u4E2D\u4E0D\u53EF\u7528\uFF0C\u6307\u6807\u91C7\u96C6\u5DF2\u8DF3\u8FC7");let hn=r?.metricTopicId??"",Ge=r?.endpoint??"";_=hn,T=Ge,M=r?.enableReport??!0,R=r?.secretId??"",k=r?.secretKey??"",y=Oe().cvmInstanceId,$=Oe().cvmInstanceName,P=Oe().cvmInstanceIntraIp;let Ve=j?.remote_write??[],ze=r?.credentialMode??"static",ko=r?.roleName||"",Q=el.join(I.stateDir,"openclaw.json"),_e=async()=>e?(I.logger.warn("diagnostics-metrics/prometheus: \u6536\u5230 401\uFF0C\u901A\u8FC7\u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u68C0\u67E5\u5E76\u5237\u65B0\u4E34\u65F6\u5BC6\u94A5"),await e.forceRefresh()):ze==="cvmRole"?(I.logger.warn("diagnostics-metrics/prometheus: \u6536\u5230 401\uFF0C\u4F46\u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u4E0D\u53EF\u7528"),!1):(I.logger.warn("diagnostics-metrics/prometheus: \u6536\u5230 401\uFF0C\u5F53\u524D\u4E3A static \u51ED\u8BC1\u6A21\u5F0F\uFF0C\u8BF7\u68C0\u67E5 secretId/secretKey \u662F\u5426\u6B63\u786E"),!1),De=Zc(T,_),yn=Ve.some(w=>!w.url),_n=Ve.some(w=>w.url);if(De&&yn&&!_n){let w=Ve.find(D=>!D.url);w&&(i=[new et({...w,url:De},O,_e)])}else De&&Ve.length===0?i=[new et({url:De},O,_e)]:i=Ve.filter(w=>w.url).map(w=>new et(w,O,_e));let Be=j?.push_interval_ms??3e4;if(i.length>0&&M?(c=setInterval(()=>{sr(s,i,q,O)},Be),typeof c.unref=="function"&&c.unref(),I.logger.debug?.(`diagnostics-metrics/prometheus: remote write enabled for ${i.length} target(s), push interval ${Be}ms`)):i.length>0&&!M&&I.logger.debug?.("diagnostics-metrics/prometheus: remote write clients created but pushTimer not started (enableReport=false)"),ze==="static"&&r&&i.length>0&&!e){let w=r.secretKey;r.token!==void 0&&r.token!==""&&(w=w+"#"+r.token);let D={username:r.secretId,password:w};for(let J of i)J.updateConfig({basic_auth:D});I.logger.debug?.("diagnostics-metrics/prometheus: static \u51ED\u8BC1\u6A21\u5F0F\uFF08\u65E0\u5171\u4EAB\u7BA1\u7406\u5668\uFF09\uFF0C\u5DF2\u8BBE\u7F6E basic_auth")}let je=w=>{let D=w.secretKey;w.token!==void 0&&w.token!==""&&(D=D+"#"+w.token);let J={username:w.secretId,password:D};for(let it of i)it.updateConfig({basic_auth:J});i.length>0&&!c&&M&&(c=setInterval(()=>{sr(s,i,q,O)},Be),typeof c.unref=="function"&&c.unref(),I.logger.debug?.("diagnostics-metrics/prometheus: \u51ED\u8BC1\u66F4\u65B0\u6210\u529F\uFF0C\u5DF2\u6062\u590D remote write \u63A8\u9001"))};if(e&&i.length>0){let w=e.getCredentialSnapshot();w.secretId&&w.secretKey&&je(w),h=e.subscribe(D=>{je(D),I.logger.debug?.("diagnostics-metrics/prometheus: \u5171\u4EAB\u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0C\u5DF2\u540C\u6B65\u5230 RemoteWriteClient")}),I.logger.debug?.("diagnostics-metrics/prometheus: \u5DF2\u8BA2\u9605\u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u7684\u51ED\u8BC1\u53D8\u66F4\u4E8B\u4EF6")}let ot=!1;f=setInterval(()=>{(async()=>{if(!ot){ot=!0;try{let w=await Xp(Q);if(!w)return;let D=w.metricTopicId??hn,J=w.endpoint??Ge,it=w.enableReport,Nt=w.secretId,kt=w.secretKey,Mt=w.instanceId,xt=w.instanceName,a=w.localIpv4,d=D!==_,g=J!==T,p=Oe();!y&&p.cvmInstanceId&&(y=p.cvmInstanceId),!$&&p.cvmInstanceName&&($=p.cvmInstanceName),!P&&p.cvmInstanceIntraIp&&(P=p.cvmInstanceIntraIp);let l=Mt!==y||xt!==$||a!==P,m=it!==M,b=ze==="static"&&Nt&&kt&&(Nt!==R||kt!==k);if(l&&(y=Mt,$=xt,P=a,Xc({instanceId:Mt,instanceName:xt,localIpv4:a},O,I.stateDir),I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Cinstance_metadata \u5DF2\u66F4\u65B0 (instance_id=${y}, instance_name=${$}, local_ipv4=${P})`)),b){if(R=Nt,k=kt,e&&ze==="static")e.updateStaticCredential(R,k);else if(i.length>0){let v=k;r?.token!==void 0&&r.token!==""&&(v=v+"#"+r.token);let U={username:R,password:v};for(let F of i)F.updateConfig({basic_auth:U})}I.logger.debug?.("diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Cstatic \u6A21\u5F0F\u5BC6\u94A5\u5DF2\u66F4\u65B0")}if(m&&(M=it,M?(i.length>0&&!c&&(c=setInterval(()=>{sr(s,i,q,O)},Be),typeof c.unref=="function"&&c.unref()),I.logger.debug?.("diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CenableReport=true\uFF0C\u5DF2\u6062\u590D remote write \u63A8\u9001")):(c&&(clearInterval(c),c=null),I.logger.debug?.("diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CenableReport=false\uFF0C\u5DF2\u6682\u505C remote write \u63A8\u9001"))),n){let v=w.enableLogReport,U=w.logTopicId;(v!==L||U!==x)&&(L=v,x=U,n(v,U),I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Clog \u914D\u7F6E\u5DF2\u53D8\u66F4\uFF08enableLogReport=${v}\uFF0ClogTopicId=${U||"(\u7A7A)"}\uFF09`))}if(!d&&!g)return;_=D,T=J;let N=Zc(T,_);if(!N){if(i.length>0){I.logger.debug?.("diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Cendpoint \u6216 metricTopicId \u4E3A\u7A7A\uFF0Cremote write \u5DF2\u6682\u505C");for(let v of i)v.stop().catch(()=>{});i=[],c&&(clearInterval(c),c=null)}return}if(i.length>0){for(let v of i)v.updateConfig({url:N});I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0C\u5DF2\u66F4\u65B0 RemoteWriteClient url=${N}`)}else{let v=new et({url:N},O,_e);if(i=[v],e){let U=e.getCredentialSnapshot();U.secretId&&U.secretKey&&je(U)}else ze==="static"&&R&&k&&v.updateConfig({basic_auth:{username:R,password:k}});e&&!h&&(h=e.subscribe(U=>{je(U),I.logger.debug?.("diagnostics-metrics/prometheus: \u5171\u4EAB\u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0C\u5DF2\u540C\u6B65\u5230 RemoteWriteClient")})),M&&!c&&(c=setInterval(()=>{sr(s,i,q,O)},Be),typeof c.unref=="function"&&c.unref()),I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0C\u52A8\u6001\u521B\u5EFA RemoteWriteClient url=${N}`)}}finally{ot=!1}}})()},Hp),f&&typeof f.unref=="function"&&f.unref(),u=j?.pull!==!1?{registry:s}:null,I.logger.debug?.(`diagnostics-metrics/prometheus: started (pull=${j?.pull!==!1}, remote_write=${i.length} targets, metricTopicId=${_||"(\u5F85\u914D\u7F6E\u6587\u4EF6\u6CE8\u5165)"}, endpoint=${T||"(\u5F85\u914D\u7F6E\u6587\u4EF6\u6CE8\u5165)"})`)},async stop(){o?.(),o=null,f&&(clearInterval(f),f=null),h&&(h(),h=null),c&&(clearInterval(c),c=null);for(let I of i)await I.stop().catch(()=>{});i=[],tn(),s&&(s.clear(),s=null),u=null,_="",T="",M=!0,R="",k="",y="",$="",P=""}}}async function sr(t,e,n,r){if(e.length!==0)try{let s=Oe(),o={...n};o.cvm_instance_id||(o.cvm_instance_id=s.cvmInstanceId),o.cvm_instance_name||(o.cvm_instance_name=s.cvmInstanceName),o.cvm_instance_intra_ip||(o.cvm_instance_intra_ip=s.cvmInstanceIntraIp),o.host_name||(o.host_name=s.hostName);let i=await t.getMetricsAsJSON(),c=Date.now(),u=[];for(let f of i){let h=f.values;for(let _ of h){let M=[{name:"__name__",value:_.metricName??f.name}];for(let[R,k]of Object.entries(o))M.push({name:R,value:k});if(_.labels)for(let[R,k]of Object.entries(_.labels))M.push({name:R,value:String(k)});M.sort((R,k)=>R.name.localeCompare(k.name)),u.push({labels:M,samples:[{value:_.value??0,timestampMs:c}]})}}if(u.length===0)return;for(let f of e)f.enqueue(u)}catch(s){r.error(`diagnostics-metrics/prometheus: failed to collect metrics for push: ${nl(s)}`)}}import{Producer as ir}from"tencentcloud-cls-sdk-nodejs";import{hostname as El}from"node:os";import{basename as df,join as pf}from"node:path";var E="[diagnostics-metrics-cls/trace]",tt=32e5,rn=4096,_o=20,sl=3e3,bo=1200*1e3,ol=600*1e3,il=1e4,al=It,cl="__temp_run_",ll=15e3,ul=1e4,wo=300*1e3,dl=5e3;import{randomBytes as Qp}from"crypto";function ae(t=16){let e=Math.ceil(t/2);return Qp(e).toString("hex").slice(0,t)}function Ie(t){return t.length>tt?t.substring(0,tt):t}function fl(t){let e=JSON.stringify(t);if(e.length<=tt)return e;let n=To(t),r=Zp(n.length),s=64;for(let i=0;i<20;i++){let c=JSON.stringify(n);if(c.length<=tt)return c;let u=!1;for(let f of r){let h=n[f];if(h&&ef(h,s)){u=!0;break}}if(!u)break}let o=tf(n);return JSON.stringify(o)}function Zp(t){let e=[];if(t<=0)return e;let n=Math.floor(t/2);e.push(n);for(let r=1;r<=t;r++){let s=n-r,o=n+r;o<t&&e.push(o),s>=0&&e.push(s)}return e}function ef(t,e){let n=null,r=(c,u)=>{typeof c=="string"&&(c.length<=e||(!n||c.length>n.value.length)&&(n={set:u,value:c}))};if(r(t.content,c=>{t.content=c}),Array.isArray(t.tool_calls))for(let c of t.tool_calls)!c||typeof c!="object"||r(c.arguments,u=>{c.arguments=u});if(!n)return!1;let s=n,o=s.value,i=Math.max(e,Math.floor(o.length/2));return i>=o.length?!1:(s.set(o.slice(0,i)+`... [truncated, total ${o.length} chars]`),!0)}function tf(t){if(t.length<=2)return t.map(i=>pl(i,2048));let e=t[0],n=Math.min(5,t.length-1),r=null;for(;n>=1;){let i=t.slice(t.length-n),c=t.length-1-n,u=t.slice(1,t.length-n).reduce((T,M)=>T+JSON.stringify(M).length,0),f={role:"system",content:`[...omitted ${c} messages, total ${u} chars]`},h=[e,f,...i];if(JSON.stringify(h).length<=tt)return h;r=h,n--}let s=r??[e,t[t.length-1]],o=Math.max(1024,Math.floor((tt-256)/Math.max(1,s.length)));return s.map(i=>pl(i,o))}function pl(t,e){let n={...t};return typeof n.content=="string"&&n.content.length>e&&(n.content=n.content.slice(0,e)+`... [truncated, total ${n.content.length} chars]`),Array.isArray(n.tool_calls)&&(n.tool_calls=n.tool_calls.map(r=>{if(!r||typeof r!="object")return r;let s={...r};return typeof s.arguments=="string"&&s.arguments.length>e&&(s.arguments=s.arguments.slice(0,e)+`... [truncated, total ${s.arguments.length} chars]`),s})),n}function Io(t,e=rn){return t?t.length<=e?t:t.slice(0,e)+`... [truncated, total ${t.length} chars]`:""}function To(t){return typeof globalThis.structuredClone=="function"?globalThis.structuredClone(t):Tt(t)}function Tt(t,e=new WeakMap){if(t===null||typeof t!="object")return t;let n=t;if(e.has(n))return e.get(n);if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(n instanceof Map){let s=new Map;e.set(n,s);for(let[o,i]of n)s.set(Tt(o,e),Tt(i,e));return s}if(n instanceof Set){let s=new Set;e.set(n,s);for(let o of n)s.add(Tt(o,e));return s}if(Array.isArray(n)){let s=[];e.set(n,s);for(let o=0;o<n.length;o++)s[o]=Tt(n[o],e);return s}let r={};e.set(n,r);for(let s of Object.keys(n))r[s]=Tt(n[s],e);return r}function ml(t){return t==null?[]:typeof t=="string"?[{type:"text",content:t}]:Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{type:"text",content:e};if(typeof e=="object"&&e!==null){let n=e;if(n.type==="toolCall"||n.type==="tool_call"||n.type==="function_call")return{type:"tool_call",id:n.id||n.toolCallId||null,name:n.name||n.toolName||"",arguments:n.arguments||n.input||n.params||null};if(n.type==="toolResult"||n.type==="tool_result"||n.type==="tool_call_response"){let r=n.response??n.result??n.content??"";return{type:"tool_call_response",id:n.id||n.toolCallId||null,response:typeof r=="string"?r:JSON.stringify(r)}}return n.type==="text"?{type:"text",content:String(n.content??n.text??"")}:n.type==="thinking"||n.type==="reasoning"?{type:"reasoning",content:String(n.content??n.thinking??"")}:n.type?n:{type:"text",content:JSON.stringify(e)}}return{type:"text",content:String(e)}}):[{type:"text",content:JSON.stringify(t)}]}function gl(t){return Ie(JSON.stringify([{type:"text",content:t}]))}var nf={toolResult:"tool",tool_result:"tool",function:"tool"};function So(t,e){let n=[];for(let r of t){let s=nf[r.role]||r.role;n.push({role:s,parts:ml(r.content)})}return e&&n.push({role:"user",parts:[{type:"text",content:e}]}),Ie(JSON.stringify(n))}function St(t,e="stop"){return Ie(JSON.stringify(t.map(n=>({role:"assistant",parts:[{type:"text",content:n}],finish_reason:e}))))}function hl(t,e=[],n="stop"){let r=ml(t);return r.length>0?Ie(JSON.stringify([{role:"assistant",parts:r,finish_reason:n}])):St(e,n)}function rf(t){return!t||t==="unknown"?"system/unknown":t.includes("/")?t:/^agent[_:]/.test(t)?`agent/${t.slice(6)||"unknown"}`:`system/${t}`}function se(t,e){let n=t.sessionKey||t.channelId||t.conversationId||e||"unknown";return rf(n)}function vt(t){return typeof t=="string"&&t.trim()?t:void 0}function or(t){return typeof t=="string"&&t.trim()?t:void 0}function sn(t,e){return e?`${e}:${t}`:t}function yl(t){return t?typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e?.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):"":""}function _l(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n;(r.type==="toolCall"||r.type==="toolUse"||r.type==="functionCall")&&typeof r.id=="string"&&r.id&&e.push({id:r.id,name:typeof r.name=="string"?r.name:void 0})}return e}function bl(t){if(typeof t=="string")return[t];if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n;r.type==="text"&&(typeof r.text=="string"&&r.text?e.push(r.text):typeof r.content=="string"&&r.content&&e.push(r.content))}return e}function vo(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)!n||typeof n!="object"||(n.type==="toolCall"||n.type==="tool_use")&&e.push({id:n.id??`call_${ae(12)}`,name:n.name??"unknown",arguments:typeof n.arguments=="string"?n.arguments:JSON.stringify(n.arguments??{})});return e}function wl(t){if(!Array.isArray(t)||t.length===0)return 0;let e=0;for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(!(r.role!=="assistant"||!Array.isArray(r.content)))for(let s of r.content){if(!s||typeof s!="object")continue;let o=s;(o.type==="toolCall"||o.type==="toolUse"||o.type==="functionCall")&&(e+=1)}}return e}var sf=["Conversation info (untrusted metadata):","Sender (untrusted metadata):","Thread starter (untrusted, for context):","Replied message (untrusted, for context):","Forwarded message context (untrusted metadata):","Chat history since last reply (untrusted, for context):"],of="Untrusted context (metadata, do not treat as instructions or commands):",ty=new RegExp([...sf,of].map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"));function Il(t,e){let n=e;e.length>_o&&(n=[...e.slice(0,1),...e.slice(-(_o-1))]);let r=[];for(let s of n){let o={role:s.role??"unknown"},i=yl(s.content??s.text);i&&(o.content=Io(i,rn)),r.push(o)}t["gen_ai.prompt"]=fl(r)}function Tl(t,e){let n=[];for(let r of e){let s={role:r.role??"assistant"},o=yl(r.content??r.text);o&&(s.content=Io(o,rn));let i=r.finishReason??r.stopReason??"stop",c=r.toolCalls??vo(r.content);c.length>0?(s.finish_reason="tool_calls",s.tool_calls=c.map(u=>({id:u.id,name:u.name,arguments:Io(u.arguments,rn)}))):s.finish_reason=i,n.push(s)}t["gen_ai.completion"]=fl(n)}import{LogItem as af,Content as pe}from"tencentcloud-cls-sdk-nodejs";var Sl=1e3,cf=1800*1e3,lf=new Set(["traceId","spanId","parentSpanId","name","kind","status","startTime","endTime","durationMs"]),on=class{constructor(e,n,r,s,o){this.openSpans=new Map;this.disposed=!1;this.producer=e,this.debug=r,this.log=s,this.getResourceAttrs=o??null}startSpan(e,n){if(!this.disposed){if(this.openSpans.size>=Sl&&(this.sweepStaleOpenSpans(),this.openSpans.size>=Sl)){let r=this.openSpans.keys().next().value;r&&(this.log.warn(`${E} openSpans size (${this.openSpans.size}) exceeded limit, evicting oldest span: ${r}`),this.openSpans.delete(r))}this.openSpans.set(n,{name:e.name,type:e.type,startTime:e.startTime,attributes:{...e.attributes},traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId}),this.debug&&this.log.info(`${E} Started long-lived span: name=${e.name}, spanId=${n}, traceId=${e.traceId}`)}}endSpanById(e,n,r){if(this.disposed)return;let s=this.openSpans.get(e);if(!s)return;if(r)for(let[i,c]of Object.entries(r))c!=null&&(s.attributes[i]=c);let o=n??Date.now();this.sendRecord({...s.attributes,traceId:s.traceId,spanId:s.spanId,parentSpanId:s.parentSpanId||"",name:s.name,kind:s.attributes["gen_ai.span.kind"]??this.mapSpanKind(s.type),status:"OK",startTime:new Date(s.startTime).toISOString(),endTime:new Date(o).toISOString(),durationMs:String(o-s.startTime)}),this.openSpans.delete(e),this.debug&&this.log.info(`${E} Ended long-lived span: spanId=${e}, duration=${o-s.startTime}ms`)}patchOpenSpanAttributes(e,n){if(this.disposed)return;let r=this.openSpans.get(e);if(r)for(let[s,o]of Object.entries(n))o!=null&&(r.attributes[s]=o)}export(e){if(this.disposed)return;let n=e.startTime||Date.now(),r=e.endTime||Date.now(),s=e.attributes.error===!0||!!e.attributes["error.type"];this.sendRecord({...e.attributes,traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId||"",name:e.name,kind:e.attributes["gen_ai.span.kind"]??this.mapSpanKind(e.type),status:s?"ERROR":"OK",startTime:new Date(n).toISOString(),endTime:new Date(r).toISOString(),durationMs:String(r-n)})}async flush(){if(!this.disposed)try{typeof this.producer.flush=="function"?await this.producer.flush():typeof this.producer.batchSend=="function"&&await this.producer.batchSend()}catch{}}get isDisposed(){return this.disposed}async dispose(){this.disposed=!0;let e=Date.now();for(let[,n]of this.openSpans)try{let r=e;this.sendRecordCore({...n.attributes,"openclaw.force_closed":!0,"openclaw.force_closed.reason":"dispose",traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId||"",name:n.name,kind:n.attributes["gen_ai.span.kind"]??this.mapSpanKind(n.type),status:"UNSET",startTime:new Date(n.startTime).toISOString(),endTime:new Date(r).toISOString(),durationMs:String(r-n.startTime)})}catch{}try{typeof this.producer.flush=="function"?await this.producer.flush():typeof this.producer.batchSend=="function"&&await this.producer.batchSend()}catch{}this.openSpans.clear()}sweepStaleOpenSpans(){let e=Date.now(),n=[];for(let[r,s]of this.openSpans)e-s.startTime>cf&&n.push(r);for(let r of n){let s=this.openSpans.get(r);if(s){try{this.sendRecord({...s.attributes,"openclaw.force_closed":!0,"openclaw.force_closed.reason":"stale_sweep",traceId:s.traceId,spanId:s.spanId,parentSpanId:s.parentSpanId||"",name:s.name,kind:s.attributes["gen_ai.span.kind"]??this.mapSpanKind(s.type),status:"UNSET",startTime:new Date(s.startTime).toISOString(),endTime:new Date(e).toISOString(),durationMs:String(e-s.startTime)})}catch{}this.debug&&this.log.info(`${E} Evicted stale open span (force-sent): spanId=${r}, name=${s.name}, age=${e-s.startTime}ms`)}this.openSpans.delete(r)}}updateProducer(e,n){let r=this.producer;this.producer=e;let s=5e3,o=async()=>{try{typeof r.flush=="function"?await r.flush():typeof r.batchSend=="function"&&await r.batchSend(),typeof r.close=="function"?await r.close():typeof r.shutdown=="function"?await r.shutdown():typeof r.destroy=="function"&&await r.destroy()}catch{}},i,c=new Promise(u=>{i=setTimeout(u,s)});Promise.race([o(),c]).finally(()=>{i!==void 0&&clearTimeout(i)}).catch(()=>{})}sendRecord(e){this.disposed||this.sendRecordCore(e)}sendRecordCore(e){try{let n=this.getResourceAttrs?.()??{},r=e.traceId||"",s=e.spanId||"",o=e.parentSpanId||"",i=e.name||"",c=e.kind||"INTERNAL",u=e.status||"OK",f=e.startTime,h=e.endTime,_=e.durationMs,T=f?new Date(f).getTime():Date.now(),M=h?new Date(h).getTime():Date.now(),R=M-T,k=R<0?0:R;R<0&&this.log?.warn(`${E} [sendRecord] negative duration detected, clamped to 0. spanId=${s}, name=${i}, startMs=${T}, endMs=${M}`);let y=1000000n,$=(BigInt(T)*y).toString(),P=(BigInt(M)*y).toString(),L=(BigInt(k)*y).toString(),x={};for(let[V,Y]of Object.entries(e))lf.has(V)||Y!=null&&(x[V]=Y);_!=null&&(x.durationMs=String(_));for(let[V,Y]of Object.entries(n))Y!=null&&(x[V]=String(Y));let I=this.mapSpanKindToString(c),O=u==="OK"?"OK":u==="ERROR"?"ERROR":"UNSET",j=JSON.stringify(x),S=new af;S.setTime(Math.floor(T/1e3)),S.pushBack(new pe("traceID",r)),S.pushBack(new pe("spanID",s)),S.pushBack(new pe("parentSpanID",o)),S.pushBack(new pe("kind",I)),S.pushBack(new pe("name",i)),S.pushBack(new pe("links","[]")),S.pushBack(new pe("logs","[]")),S.pushBack(new pe("traceState","")),S.pushBack(new pe("start",$)),S.pushBack(new pe("end",P)),S.pushBack(new pe("duration",L)),S.pushBack(new pe("attribute",j)),S.pushBack(new pe("statusCode",O)),S.pushBack(new pe("statusMessage",""));let q=this.producer.send(S);q&&typeof q.catch=="function"&&q.catch(V=>{this.log.warn(`${E} CLS \u5F02\u6B65\u53D1\u9001\u5931\u8D25: ${V}`)})}catch(n){this.log.warn(`${E} CLS \u53D1\u9001\u5931\u8D25: ${n}`)}}mapSpanKind(e){switch(e){case"entry":case"gateway":return"ENTRY";case"agent":return"AGENT";case"step":return"STEP";case"model":return"LLM";case"tool":return"TOOL";case"session":return"SESSION";case"message":return"TASK";default:return"INTERNAL"}}mapSpanKindToString(e){switch(e){case"ENTRY":return"server";case"LLM":return"client";case"TOOL":return"client";default:return"internal"}}};import{readFile as uf}from"node:fs/promises";async function vl(t){try{let e=await uf(t,"utf8"),i=JSON.parse(e).plugins?.entries?.[al]?.config,c=i?.trace,u=c?.enabled!==!1,f=typeof c?.traceTopicId=="string"?c.traceTopicId.trim():"",h=i?.cls,_=typeof h?.endpoint=="string"?h.endpoint.trim():"",T=typeof h?.token=="string"?h.token.trim():"",M=typeof h?.credentialMode=="string"&&h.credentialMode.trim()==="cvmRole"?"cvmRole":"static",R=typeof h?.roleName=="string"?h.roleName.trim():"",k="",y="";try{k=typeof h?.secretId=="string"?ie(h.secretId.trim()):""}catch(L){console.warn(`[diagnostics-metrics-cls/trace] readTraceHotConfigFromDisk: secretId decrypt failed: ${String(L)}`)}try{y=typeof h?.secretKey=="string"?ie(h.secretKey.trim()):""}catch(L){console.warn(`[diagnostics-metrics-cls/trace] readTraceHotConfigFromDisk: secretKey decrypt failed: ${String(L)}`)}let $=c?.debug===!0,P=Array.isArray(c?.enabledHooks)?c.enabledHooks:void 0;return{enabled:u,traceTopicId:f,endpoint:_,secretId:k,secretKey:y,token:T,credentialMode:M,roleName:R,debug:$,enabledHooks:P}}catch(e){return e?.code==="ENOENT"||console.warn(`[diagnostics-metrics-cls/trace] readTraceHotConfigFromDisk failed: ${String(e)}`),null}}function Eo(t,e){if(!t)return{enabled:!1,traceTopicId:"",endpoint:"",secretId:"",secretKey:"",serviceName:"openclaw-agent"};let n=t.enabled!==!1,r=typeof t.traceTopicId=="string"?t.traceTopicId.trim():"",s=typeof e?.endpoint=="string"?e.endpoint.trim():"",o="",i="";try{o=typeof e?.secretId=="string"?ie(e.secretId.trim()):""}catch(_){console.warn(`[diagnostics-metrics-cls/trace] resolveTraceConfig: secretId decrypt failed: ${String(_)}`)}try{i=typeof e?.secretKey=="string"?ie(e.secretKey.trim()):""}catch(_){console.warn(`[diagnostics-metrics-cls/trace] resolveTraceConfig: secretKey decrypt failed: ${String(_)}`)}let c=typeof e?.token=="string"?e.token.trim():void 0,u=typeof e?.credentialMode=="string"&&e.credentialMode.trim()==="cvmRole"?"cvmRole":"static",f=typeof e?.roleName=="string"?e.roleName.trim():void 0;return{enabled:n&&(u==="cvmRole"?!!(r&&s&&f):!!(r&&s&&o&&i)),traceTopicId:r,endpoint:s,secretId:o,secretKey:i,token:c,credentialMode:u,roleName:f,serviceName:typeof t.serviceName=="string"?t.serviceName:"openclaw-agent",debug:t.debug===!0,enabledHooks:Array.isArray(t.enabledHooks)?t.enabledHooks:void 0}}function Rl(t){let e=t.traceTopicId??"",n=t.endpoint??"",r=t.secretId??"",s=t.secretKey??"",o=t.token,i=t.credentialMode??"static",c=t.roleName??"",u=t.sharedCredentialManager??null,f=t.debug??!1,h=t.enabled===!0,_=t.enabledHooks,T=t.serviceName||df(process.cwd())||"openclaw-agent",M=`${T}@${El()}:${process.pid}`,R={"service.name":T,"service.instance.id":M,"host.name":El(),"telemetry.sdk.language":"nodejs"};function k(){let a=Oe(),d={...R};return a.cvmInstanceId&&(d.cvm_instance_id=a.cvmInstanceId),a.cvmInstanceName&&(d.cvm_instance_name=a.cvmInstanceName),a.cvmInstanceIntraIp&&(d.cvm_instance_intra_ip=a.cvmInstanceIntraIp),d}let y=null,$=null,P=null;function L(a){return{topic_id:e,endpoint:n,credential:{secretId:a.secretId,secretKey:a.secretKey,token:a.token},onSendLogsError:d=>{d?.status!==200?C?.warn(`${E} CLS \u53D1\u9001\u5931\u8D25: ${JSON.stringify(d)}`):f&&C?.debug(`${E} CLS \u53D1\u9001\u6210\u529F: requestId=${d?.requestId}`)}}}let x=new Map,I=new Map,O=new Map,j=new Map,S=new Map,q=new Map,V=new Map,Y,ce,Se,ve="unknown",nt=null,C=null,rt=!1,Ee=new Set,ye=new Map,ln=2e3;function lr(){let a=Date.now(),d=new Set,g=[];for(let[m,b]of x)a-b.createdAt>bo&&(g.push(m),d.add(b));for(let m of g)x.delete(m);for(let m of d)I.delete(m.runId);if(d.size>0){let m=[];for(let[N,v]of O){for(let U of d)v.delete(U);v.size===0&&m.push(N)}for(let N of m)O.delete(N);let b=[];for(let[N,v]of j)d.has(v)&&b.push(N);for(let N of b)j.delete(N);ce&&d.has(ce)&&(ce=void 0,Y=void 0,Se=void 0)}let p=[];for(let[m,b]of S)(a-b.createdAt>bo||d.has(b.traceContext))&&p.push(m);for(let m of p)S.delete(m);let l=[];for(let[m,b]of V)a-b.createdAt>ll&&l.push(m);for(let m of l)V.delete(m);y&&y.sweepStaleOpenSpans()}function z(a){return _?_.includes(a):!0}function st(a){return a.startsWith(cl)}function ur(a,d){let g=[];for(let[p,l]of S)l.runId===a&&g.push({oldKey:p,pending:l});for(let{oldKey:p,pending:l}of g){S.delete(p),l.runId=d;let m=sn(l.toolCallId,d);S.has(m)&&f&&C?.warn(`${E} movePendingToolCallsRunBinding: key collision detected, overwriting existing entry: ${m}`),S.set(m,l)}}function un(a,d,g){let p=vt(d);if(!p||a.runId===p)return;let l=I.get(p);if(l&&l!==a)return;let m=a.runId;if(!st(m))return;I.get(m)===a&&I.delete(m),a.runId=p,a.turnId=p,I.set(p,a),ur(m,p);let b={"openclaw.run.id":p,"openclaw.turn.id":p};y?.patchOpenSpanAttributes(a.rootSpanId,b),a.agentSpanId&&y?.patchOpenSpanAttributes(a.agentSpanId,b),a.stepSpanId&&y?.patchOpenSpanAttributes(a.stepSpanId,b),f&&C?.info(`${E} Rebound temporary runId: hook=${g}, oldRunId=${m}, realRunId=${p}`)}function dn(a,d){if(rt)return Promise.resolve();if(q.size>=ul)return C?.warn(`${E} trace task queue size (${q.size}) exceeded limit, dropping task for trace ${a}`),Promise.resolve();let g=q.get(a)||Promise.resolve(),p=()=>{let b,N=new Promise((v,U)=>{b=setTimeout(()=>U(new Error(`trace task timeout after ${wo}ms`)),wo)});return Promise.race([d(),N]).finally(()=>{b!==void 0&&clearTimeout(b)})},l=g.catch(()=>{}).then(p),m;return m=l.finally(()=>{q.get(a)===m&&q.delete(a)}),q.set(a,m),m}async function pn(a){if(!a)return;let d=q.get(a);if(d)try{await d}catch(g){C?.warn(`${E} drainTraceTasks failed for traceId=${a}: ${String(g)}`)}}function fn(a){if(!a)return;let d=`${a}:`,g=[];for(let[p,l]of S)(p.startsWith(d)||l.runId===a)&&g.push(p);for(let p of g)S.delete(p)}function dr(a){let d=vt(a.runId),g=or(a.toolCallId);if(g){let m=[sn(g,d),sn(g,void 0)];for(let b of m){let N=S.get(b);if(N)return S.delete(b),N}}let p,l;for(let[m,b]of S)b.toolName===a.toolName&&(d&&b.runId!==d||!d&&b.runId||(!l||b.toolStartTime>l.toolStartTime)&&(l=b,p=m));return l&&p&&S.delete(p),l}function pr(a,d){let g=O.get(a);g||(g=new Set,O.set(a,g)),g.add(d)}function fr(a,d){let g=O.get(a);g&&(g.delete(d),g.size===0&&O.delete(a))}function Ct(a,d){x.set(a,d),pr(a,d)}function mn(a,d){x.get(a)===d&&x.delete(a),fr(a,d)}async function gn(a=!0){rt=!0,nt&&(clearInterval(nt),nt=null),$&&(clearInterval($),$=null),P&&(P(),P=null);for(let g of Ee)clearTimeout(g);Ee.clear();for(let g of ye.values())clearTimeout(g);ye.clear();let d=Array.from(q.values());d.length>0&&await Promise.allSettled(d),q.clear(),S.clear(),V.clear(),x.clear(),I.clear(),O.clear(),j.clear(),ce=void 0,Y=void 0,Se=void 0,a&&y&&(await y.dispose(),y=null)}function Ke(){S.clear(),V.clear(),x.clear(),I.clear(),O.clear(),j.clear(),ce=void 0,Y=void 0,Se=void 0;for(let a of Ee)clearTimeout(a);Ee.clear();for(let a of ye.values())clearTimeout(a);ye.clear()}function hn(a){let d=x.get(a);d&&Ge(d)}function Ge(a){I.get(a.runId)===a&&I.delete(a.runId);let d=[];for(let[l,m]of x)m===a&&d.push(l);for(let l of d)x.delete(l);let g=[];for(let[l,m]of O)m.has(a)&&(m.delete(a),m.size===0&&g.push(l));for(let l of g)O.delete(l);let p=[];for(let[l,m]of j)m===a&&p.push(l);for(let l of p)j.delete(l);V.delete(a.traceId),ce===a&&(ce=void 0,Y=void 0,Se=void 0)}function Ve(a,d,g){let l={traceId:ae(32),rootSpanId:ae(16),runId:a,turnId:a,channelId:d,originalChannelId:g||d,createdAt:Date.now(),llmPendingToolCallIds:new Set,llmPendingToolResultsForNextInput:[],llmPendingToolCallCountFallback:0,llmSegmentCount:0,stepRoundCounter:0,stepAwaitingToolResults:!1};return Ct(d,l),I.set(a,l),l}function ze(a,d){let g=O.get(a);if(!g||g.size===0)return d;let p=Array.from(g).filter(l=>l.agentSpanId&&!l.isClosing);return p.length===0?d||Array.from(g)[0]:(p.sort((l,m)=>(m.agentStartTime||m.createdAt)-(l.agentStartTime||l.createdAt)),p[0])}function ko(a){let d=I.get(a);return d?.originalChannelId||d?.channelId}function Q(a,d,g){let p=a,l=a.startsWith("agent/")?a:void 0,m=l&&j.get(l)||x.get(a),b=vt(d),N=b||m?.runId||`__temp_run_${ae(12)}`,v=()=>a.startsWith("agent/")&&!!ce&&!!Se&&Date.now()-(Se||0)<sl,U=()=>{if(!ce)return;let K=ce;if(!(b&&K.runId!==b&&!st(K.runId)))return p=Y||p,Ct(a,K),I.set(N,K),f&&C?.info(`${E} LINKING agent to user context: hook=${g}, agentChannel=${a}, userChannel=${p}, traceId=${K.traceId}`),K};if(a.startsWith("agent/")&&N){let K=ko(N);K&&(p=K,m=x.get(K)||m)}if(m||(m=I.get(N)),g==="agent_end"&&!b&&(m=ze(p,m)),!m&&v()&&(m=U()),g==="message_received"&&!a.startsWith("agent/")&&m&&(m.agentSpanId||m.hasSeenLlmInput||m.isClosing)&&(m=void 0,b||(N=`__temp_run_${ae(12)}`)),m&&b&&m.runId!==b&&!st(m.runId)&&(m=void 0,N=b),m&&b&&st(m.runId)){let K=I.get(b);K&&K!==m&&(m=K,Ct(p,m))}!m&&v()&&(m=U());let F=!1;return m||(m=Ve(N,p,a!==p?a:void 0),F=!0,f&&C?.info(`${E} NEW TraceContext: hook=${g}, channelId=${p}, runId=${N}, traceId=${m.traceId}`)),l&&m&&!m.isClosing&&j.set(l,m),m&&d&&un(m,d,g),{ctx:m,channelId:p,isNew:F}}function _e(a,d,g,p,l,m,b={},N){return{name:g,type:p,startTime:l,endTime:m,attributes:{...b,"openclaw.version":ve,"openclaw.session.id":a.sessionId||d,"gen_ai.session.id":a.sessionId||d,"openclaw.run.id":a.runId,"openclaw.turn.id":a.turnId},traceId:a.traceId,spanId:ae(16),parentSpanId:N||a.rootSpanId}}function De(a){return a.agentSpanId||a.rootSpanId}function yn(a){return a.stepSpanId||a.agentSpanId||a.rootSpanId}async function _n(a,d,g){if(!y)return;let p=g.endTime||Date.now(),l=a.llmPendingStartTime||p,m=p<l?l:p,b=a.llmProvider||"unknown",N=a.llmModel||"unknown",v=g.stopReason||"stop",U=g.usage?.input??0,F=g.usage?.output??0,K=g.usage?.cacheRead??0,ue=g.usage?.cacheWrite??0,Je=g.usage?.total??U+F+K+ue,oe={"gen_ai.span.kind":"LLM","gen_ai.operation.name":"chat","gen_ai.provider.name":b,"gen_ai.system":b,"gen_ai.request.model":N,"gen_ai.response.model":N,"gen_ai.usage.input_tokens":U,"gen_ai.usage.output_tokens":F,"gen_ai.usage.total_tokens":Je,"gen_ai.usage.cache_read.input_tokens":K,"gen_ai.usage.cache_creation.input_tokens":ue,"llm.request.type":"chat"};a.llmPendingSystemInstructions&&(oe["gen_ai.system_instructions"]=a.llmPendingSystemInstructions);let Z=a.llmPendingInputMessages||a.llmLastInputMessages;Z&&(oe["gen_ai.input.messages"]=Z),(g.outputContent!==void 0||g.outputTexts.length>0)&&(oe["gen_ai.output.messages"]=hl(g.outputContent,g.outputTexts,v)),oe["gen_ai.response.finish_reasons"]=JSON.stringify([v]);try{if(Z){let H=JSON.parse(Z);if(Array.isArray(H)){let Pe=H.map(me=>({role:me.role,content:Array.isArray(me.parts)?me.parts.filter(We=>We.type==="text").map(We=>We.content).join(""):""}));Il(oe,Pe)}}if(g.outputTexts.length>0){let H=[{role:"assistant",content:g.outputTexts.join(""),stopReason:v,toolCalls:g.outputContent?vo(Array.isArray(g.outputContent)?g.outputContent:void 0):void 0}];H[0].toolCalls?.length===0&&delete H[0].toolCalls,Tl(oe,H)}}catch(H){f&&C?.warn(`${E} Failed to set indexed prompt/completion attrs: ${String(H)}`)}let te=_e(a,d,`chat ${N}`,"model",l,m,oe,yn(a));a.llmPendingSpanId&&(te.spanId=a.llmPendingSpanId);try{y.export(te),C?.debug(`${E} [span] Exported LLM span: ${b}/${N}, traceId=${a.traceId}, spanId=${te.spanId}, duration=${m-l}ms`),f&&C?.info(`${E} Exported segmented LLM span: ${b}/${N}, duration=${m-l}ms, reason=${v}`)}finally{a.llmPendingStartTime=void 0,a.llmPendingSpanId=void 0,a.llmPendingSystemInstructions=void 0,a.llmPendingInputMessages=void 0,a.llmSegmentCount+=1}}async function Be(a,d,g){let p=typeof g.timestamp=="number"&&Number.isFinite(g.timestamp)?g.timestamp:Date.now(),l=_l(g.content),m=bl(g.content),b=typeof g.stopReason=="string"?g.stopReason:l.length>0?"toolUse":"stop";a.llmPendingStartTime||(a.llmPendingStartTime=p),a.llmPendingSpanId||(a.llmPendingSpanId=ae(16)),await _n(a,d,{endTime:p,outputTexts:m,outputContent:g.content,stopReason:b,usage:g.usage}),m.length>0&&(a.lastOutput=m.join(`
|
|
14
|
-
`)),a.llmPendingToolCallIds.clear(),a.llmPendingToolResultsForNextInput=[],a.llmLastAssistantContent=g.content;for(let N of l)a.llmPendingToolCallIds.add(N.id);a.llmPendingToolCallCountFallback=a.llmPendingToolCallIds.size>0?0:l.length,a.stepAwaitingToolResults=l.length>0,l.length===0&&D(a,p,b,d),f&&C?.info(`${E} Processed assistant message: runId=${a.runId}, toolCalls=${l.length}, stopReason=${b}`)}function je(a,d,g={}){if(a.rootSpanStartTime||!y)return;let p=Date.now();a.rootSpanStartTime=p;let l={"gen_ai.span.kind":"ENTRY","gen_ai.operation.name":"enter","gen_ai.user.id":g.userId||"unknown","openclaw.session.id":a.sessionId||d,"gen_ai.session.id":a.sessionId||d,"openclaw.run.id":a.runId,"openclaw.turn.id":a.turnId,"openclaw.message.role":g.role||"unknown","openclaw.message.from":g.from||"unknown","openclaw.version":ve};a.userInput&&(l["gen_ai.input.messages"]=Ie(JSON.stringify([{role:"user",parts:[{type:"text",content:String(a.userInput)}]}]))),y.startSpan({name:"enter_openclaw_system",type:"entry",startTime:p,attributes:l,traceId:a.traceId,spanId:a.rootSpanId},a.rootSpanId),C?.debug(`${E} [span] Started entry span: traceId=${a.traceId}, spanId=${a.rootSpanId}`)}function ot(a,d,g){if(a.agentSpanId||!y)return;let p=Date.now();a.agentStartTime=p,a.agentSpanId=ae(16),y.startSpan({name:`invoke_agent ${g}`,type:"agent",startTime:p,attributes:{"gen_ai.span.kind":"AGENT","gen_ai.operation.name":"invoke_agent","gen_ai.provider.name":"openclaw","gen_ai.agent.id":g,"gen_ai.agent.name":g,"openclaw.session.id":a.sessionId||d,"gen_ai.session.id":a.sessionId||d,"openclaw.run.id":a.runId,"openclaw.turn.id":a.turnId,"openclaw.version":ve},traceId:a.traceId,spanId:a.agentSpanId,parentSpanId:a.rootSpanId},a.agentSpanId),C?.debug(`${E} [span] Started agent span: ${g}, spanId=${a.agentSpanId}, traceId=${a.traceId}`)}function w(a,d,g){if(a.stepSpanId||!y)return;let p=a.stepRoundCounter+1,l=ae(16);y.startSpan({name:"react step",type:"step",startTime:g,attributes:{"gen_ai.span.kind":"STEP","gen_ai.operation.name":"react","gen_ai.react.round":p,"openclaw.session.id":a.sessionId||d,"gen_ai.session.id":a.sessionId||d,"openclaw.run.id":a.runId,"openclaw.turn.id":a.turnId,"openclaw.version":ve},traceId:a.traceId,spanId:l,parentSpanId:De(a)},l),a.stepSpanId=l,a.stepStartTime=g,a.stepRoundCounter=p,a.stepCurrentRound=p,a.stepAwaitingToolResults=!1,f&&C?.info(`${E} Started step span: round=${p}, spanId=${l}`)}function D(a,d,g,p){if(!a.stepSpanId||!y)return;let l=a.stepSpanId,m=a.stepCurrentRound||a.stepRoundCounter||1;y.endSpanById(l,d,{"gen_ai.react.round":m,"gen_ai.react.finish_reason":g||"stop","openclaw.session.id":a.sessionId||p,"gen_ai.session.id":a.sessionId||p,"openclaw.run.id":a.runId,"openclaw.turn.id":a.turnId}),a.stepSpanId=void 0,a.stepStartTime=void 0,a.stepCurrentRound=void 0,a.stepAwaitingToolResults=!1,f&&C?.info(`${E} Ended step span: round=${m}, reason=${g}, spanId=${l}`)}function J(a){a.acpFallbackPending=!1;let d=ye.get(a.traceId);d&&(clearTimeout(d),ye.delete(a.traceId))}function it(a,d){if(!a.acpFallbackPending||!y)return;let g=ye.get(a.traceId);g&&clearTimeout(g);let p=y,l=setTimeout(async()=>{if(ye.delete(a.traceId),Ee.delete(l),!!a.acpFallbackPending){a.acpFallbackPending=!1;try{if(C?.debug(`${E} [acp-fallback] Closing Entry Span for ACP mode: traceId=${a.traceId}`),a.rootSpanStartTime&&p&&!p.isDisposed){let m=Date.now(),b={"request.duration_ms":m-a.rootSpanStartTime,"openclaw.acp_mode":!0};a.sessionId&&(b["openclaw.session.id"]=a.sessionId,b["gen_ai.session.id"]=a.sessionId),a.userInput&&(b["gen_ai.input.messages"]=Ie(JSON.stringify([{role:"user",parts:[{type:"text",content:String(a.userInput)}]}]))),a.lastOutput&&(b["gen_ai.output.messages"]=St([typeof a.lastOutput=="string"?a.lastOutput:JSON.stringify(a.lastOutput)])),p.endSpanById(a.rootSpanId,m,b),C?.debug(`${E} [acp-fallback] Ended entry span: spanId=${a.rootSpanId}, traceId=${a.traceId}, duration=${m-a.rootSpanStartTime}ms`)}mn(d,a),Ge(a),p&&!p.isDisposed&&(await p.flush(),C?.debug(`${E} [acp-fallback] Flushed after ACP fallback close, traceId=${a.traceId}`))}catch(m){C?.warn(`${E} [acp-fallback] Error closing Entry Span: ${String(m)}`)}}},ln);ye.set(a.traceId,l),Ee.add(l)}let Nt={id:"diagnostics-metrics-cls-trace",async start(a){if(C=a.logger,ve=a.runtime?.version||"unknown",rt=!1,h&&e&&n&&(i==="cvmRole"?!!c:!!(r&&s))){let l;if(u){let m=u.getCredentialSnapshot();l={secretId:m.secretId,secretKey:m.secretKey,token:m.token},r=m.secretId,s=m.secretKey,o=m.token}else i==="static"?l={secretId:r,secretKey:s,token:o}:(C.warn(`${E} cvmRole \u6A21\u5F0F\u4F46\u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u4E0D\u53EF\u7528\uFF0Ctrace \u6570\u636E\u6682\u4E0D\u53D1\u9001`),l={secretId:"",secretKey:""});if(l.secretId&&l.secretKey){let m=new ir(L(l));y=new on(m,e,f,C,k),C.debug(`${E} CLS Producer \u5DF2\u521D\u59CB\u5316\uFF0Cendpoint=${n} traceTopicId=${e} credentialMode=${i}`),u&&!P&&(P=u.subscribe(b=>{if(!y||y.isDisposed||!(b.secretId!==r||b.secretKey!==s||(b.token||"")!==(o||"")))return;r=b.secretId,s=b.secretKey,o=b.token;let v=new ir(L(b));y.updateProducer(v,e),f&&C?.info(`${E} \u5171\u4EAB\u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}))}else C.warn(`${E} \u51ED\u8BC1\u83B7\u53D6\u5931\u8D25\uFF08credentialMode=${i}\uFF09\uFF0Ctrace \u6570\u636E\u6682\u4E0D\u53D1\u9001\uFF0C\u7B49\u5F85\u70ED\u66F4\u65B0\u6062\u590D`)}else C.warn(`${E} CLS \u914D\u7F6E\u4E0D\u5B8C\u6574\u6216 trace \u672A\u542F\u7528\uFF08traceEnabled=${h}\uFF0CcredentialMode=${i}\uFF09\uFF0Ctrace \u6570\u636E\u6682\u4E0D\u53D1\u9001\uFF0C\u7B49\u5F85\u70ED\u66F4\u65B0\u6062\u590D`);nt=setInterval(lr,ol);let g=pf(a.stateDir,"openclaw.json"),p=!1;$=setInterval(()=>{(async()=>{if(!p){p=!0;try{let l=await vl(g);if(!l)return;let m=l.enabled,b=l.traceTopicId,N=l.endpoint,v=l.secretId,U=l.secretKey,F=l.token,K=l.debug;K!==f&&(f=K,y&&(y.debug=f),C.debug(`${E} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Ctrace.debug=${f}`));let ue=l.enabledHooks;JSON.stringify(ue)!==JSON.stringify(_)&&(_=ue,C.debug(`${E} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CenabledHooks=${_?_.join(","):"\u5168\u90E8\u542F\u7528"}`));let oe=m!==h;if(oe)if(h=m,h)C.debug(`${E} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Ctrace.enabled=true\uFF0C\u6B63\u5728\u6062\u590D Trace \u94FE\u8DEF\u8FFD\u8E2A`);else{y&&(await y.dispose(),y=null),Ke(),C.debug(`${E} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Ctrace.enabled=false\uFF0C\u5DF2\u7981\u7528 Trace \u94FE\u8DEF\u8FFD\u8E2A`);return}if(!h)return;let Z=l.credentialMode,te=l.roleName,H=b!==e,Pe=N!==n,me=!u&&(v!==r||U!==s),We=!u&&(F||"")!==(o||""),mr=Z!==i,gr=te!==c;if(!(oe||H||Pe||me||We||mr||gr))return;if(H&&(e=b),Pe&&(n=N),mr&&(i=Z),gr&&(c=te),me&&(r=v,s=U),We&&(o=F||void 0),i==="cvmRole"?!e||!n||!c:!e||!n||!r||!s){y&&(await y.dispose(),y=null),C.warn(`${E} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CCLS \u914D\u7F6E\u4E0D\u5B8C\u6574\uFF08credentialMode=${i}\uFF09\uFF0Ctrace \u6570\u636E\u5C06\u4E0D\u4F1A\u53D1\u9001`);return}let Ot;if(u){let at=u.getCredentialSnapshot();Ot={secretId:at.secretId,secretKey:at.secretKey,token:at.token},r=at.secretId,s=at.secretKey,o=at.token}else if(i==="static")Ot={secretId:r,secretKey:s,token:o};else{C.warn(`${E} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CcvmRole \u6A21\u5F0F\u4F46\u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u4E0D\u53EF\u7528`);return}if(!Ot.secretId||!Ot.secretKey){y&&(await y.dispose(),y=null),C.warn(`${E} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0C\u51ED\u8BC1\u83B7\u53D6\u5931\u8D25\uFF0Ctrace \u6570\u636E\u5C06\u4E0D\u4F1A\u53D1\u9001`);return}let Mo=new ir(L(Ot));y?y.updateProducer(Mo,e):y=new on(Mo,e,f,C,k),rt=!1;let Ue=[];oe&&Ue.push("enabled=true"),H&&Ue.push(`traceTopicId=${e}`),Pe&&Ue.push(`endpoint=${n}`),mr&&Ue.push(`credentialMode=${i}`),gr&&Ue.push(`roleName=${c}`),me&&Ue.push("\u51ED\u8BC1\u5DF2\u66F4\u65B0"),We&&Ue.push("token\u5DF2\u66F4\u65B0"),C.debug(`${E} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0C${Ue.join("\uFF0C")}`)}catch(l){C?.warn(`${E} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\u8F6E\u8BE2\u5931\u8D25: ${String(l)}`)}finally{p=!1}}})()},il)},async stop(){await gn()}};function kt(a){C=a.logger,ve=a.runtime?.version||ve,a.on("gateway_stop",async()=>{await gn()}),a.on("gateway_start",async d=>{try{if(!z("gateway_start")||!y)return;let g=Date.now(),p=ae(32),l=ae(16),m={name:"gateway_start",type:"gateway",startTime:g,endTime:g,attributes:{"openclaw.version":ve,"gen_ai.span.kind":"ENTRY","gateway.port":d.port},traceId:p,spanId:l,parentSpanId:""};y.export(m)}catch(g){C?.warn(`${E} [hook] gateway_start ERROR: ${String(g)}`)}}),a.on("session_start",async(d,g)=>{try{if(!z("session_start")||!y)return;let p=se(g,d.sessionId),{ctx:l,channelId:m}=Q(p,d?.runId,"session_start");d.sessionId&&(l.sessionId=d.sessionId);let b=Date.now(),N=_e(l,m,"session_start","session",b,b,{"gen_ai.span.kind":"SESSION","event.type":"session_start"});d.sessionId&&(N.attributes["openclaw.session.id"]=d.sessionId,N.attributes["gen_ai.session.id"]=d.sessionId),y.export(N)}catch(p){C?.warn(`${E} [hook] session_start ERROR: ${String(p)}`)}}),a.on("session_end",async(d,g)=>{try{if(!z("session_end")||!y)return;let p=se(g,d.sessionId),{ctx:l,channelId:m}=Q(p,d?.runId,"session_end"),b=Date.now(),N=_e(l,m,"session_end","session",b,b,{"gen_ai.span.kind":"SESSION","session.duration_ms":d.durationMs||0,"session.message_count":d.messageCount||0,"session.total_tokens":l.lastLlmUsage?.total||0});l.lastOutput&&(N.attributes["gen_ai.output.messages"]=St([typeof l.lastOutput=="string"?l.lastOutput:JSON.stringify(l.lastOutput)])),d.sessionId&&(N.attributes["openclaw.session.id"]=d.sessionId,N.attributes["gen_ai.session.id"]=d.sessionId),y.export(N),await pn(l.traceId),hn(m)}catch(p){C?.warn(`${E} [hook] session_end ERROR: ${String(p)}`)}}),a.on("message_received",async(d,g)=>{try{if(C?.debug(`${E} [hook] message_received fired, sender=${y?"OK":"null"}, enabled=${z("message_received")}`),!z("message_received")||!y)return;let p=se(g,d.from||d.metadata?.senderId),{ctx:l,channelId:m}=Q(p,d?.runId,"message_received");!p.startsWith("agent/")&&(Y=m,ce=l,Se=Date.now(),l.userInput=d.content,je(l,m,{userId:d.from||d.metadata?.senderId,role:"user",from:d.from}),l.acpFallbackPending=!0)}catch(p){C?.warn(`${E} [hook] message_received ERROR: ${String(p)}`),console.error(`${E} [hook] message_received ERROR:`,p)}}),a.on("message_sending",async(d,g)=>{try{if(!z("message_sending"))return;let p=se(g,d.to),{ctx:l}=Q(p,d?.runId,"message_sending");l.lastOutput=d.content}catch(p){C?.warn(`${E} [hook] message_sending ERROR: ${String(p)}`)}},{priority:-100}),a.on("message_sent",async(d,g)=>{try{if(!z("message_sent"))return;if(d.content&&d.success){let p=se(g,d.to),{ctx:l,channelId:m}=Q(p,d?.runId,"message_sent");l.lastOutput=d.content,l.acpFallbackPending&&it(l,m)}}catch(p){C?.warn(`${E} [hook] message_sent ERROR: ${String(p)}`)}},{priority:-100}),a.on("llm_input",async(d,g)=>{try{if(C?.debug(`${E} [hook] llm_input fired, sender=${y?"OK":"null"}, enabled=${z("llm_input")}`),!z("llm_input")||!y)return;let p=se(g),{ctx:l,channelId:m}=Q(p,d.runId,"llm_input");J(l),d.sessionId&&(l.sessionId=d.sessionId),!l.userInput&&d.prompt&&(l.userInput=d.prompt),je(l,m,{userId:g.trigger||"system",role:g.trigger||"system",from:g.agentId||"openclaw"}),ot(l,m,g.agentId||"openclaw"),l.llmProvider=d.provider,l.llmModel=d.model,l.hasSeenLlmInput=!0,l.isClosing=!1,p.startsWith("agent/")&&j.set(p,l),l.llmPendingStartTime=Date.now(),l.llmPendingSpanId=ae(16),w(l,m,l.llmPendingStartTime),l.llmPendingToolCallIds.clear(),l.llmPendingToolCallCountFallback=0,d.systemPrompt&&(l.llmPendingSystemInstructions=gl(d.systemPrompt));let b=d.historyMessages?.length?d.historyMessages.map(v=>To(v)):[];l.llmPendingInputMessages=So(b,d.prompt),l.llmLastInputMessages=l.llmPendingInputMessages;let N=V.get(l.traceId);if(N){V.delete(l.traceId);try{dn(l.traceId,async()=>{await Be(l,m,N.message)}).catch(v=>{C?.warn(`${E} replay pending assistant failed: ${String(v)}`)})}catch(v){C?.warn(`${E} replay pending assistant enqueue failed: ${String(v)}`)}}f&&C?.info(`${E} LLM input started: ${d.provider}/${d.model}, runId=${d.runId}`)}catch(p){C?.error(`${E} [hook] llm_input UNCAUGHT ERROR: ${String(p)}, stack=${p?.stack}`)}},{priority:-100}),a.on("llm_output",async(d,g)=>{try{if(!z("llm_output")||!y)return;let p=se(g),{ctx:l,channelId:m}=Q(p,d.runId,"llm_output");if(d.sessionId&&(l.sessionId=d.sessionId),d.assistantTexts?.length&&(l.lastOutput=d.assistantTexts.join(`
|
|
15
|
-
`)),d.usage&&(l.lastLlmUsage={input:d.usage.input,output:d.usage.output,cacheRead:d.usage.cacheRead,cacheWrite:d.usage.cacheWrite,total:d.usage.total}),l.llmSegmentCount===0&&l.llmPendingStartTime){let b=Date.now(),N=d.lastAssistant,v=typeof N?.stopReason=="string"?N.stopReason:void 0;await _n(l,m,{endTime:b,outputTexts:d.assistantTexts||[],stopReason:v,usage:d.usage}),D(l,b,v||"stop",m)}}catch(p){C?.warn(`${E} [hook] llm_output ERROR: ${String(p)}`)}},{priority:-100}),a.on("before_message_write",(d,g)=>{try{if(C?.debug(`${E} [hook] before_message_write fired, sender=${y?"OK":"null"}, enabled=${z("before_message_write")}, role=${d?.message?.role}`),!z("before_message_write")||!y)return;let p=d.message;if(!p||p.role!=="assistant")return;let l=se(g),m=l.startsWith("agent/")?j.get(l):void 0;if(l.startsWith("agent/")&&!m)return;let{ctx:b,channelId:N}=m?{ctx:m,channelId:m.channelId}:Q(l,void 0,"before_message_write");if(!b.hasSeenLlmInput){V.set(b.traceId,{message:p,createdAt:Date.now()});return}try{dn(b.traceId,async()=>{await Be(b,N,p)}).catch(v=>{C?.warn(`${E} before_message_write segmented export failed: ${String(v)}`)})}catch(v){C?.warn(`${E} before_message_write enqueue failed: ${String(v)}`)}}catch(p){C?.warn(`${E} [hook] before_message_write uncaught error: ${String(p)}, stack=${p?.stack}`)}},{priority:-100}),a.on("before_tool_call",async(d,g)=>{try{if(!z("before_tool_call")||!y)return;let p=se(g),l=p.startsWith("agent/")?j.get(p):void 0;if(p.startsWith("agent/")&&!l)return;let{ctx:m,channelId:b}=l?{ctx:l,channelId:l.channelId}:Q(p,vt(d.runId),"before_tool_call");if(l&&d.runId&&un(m,d.runId,"before_tool_call"),!m.hasSeenLlmInput)return;let N=vt(d.runId)||m.runId,v=or(d.toolCallId)||`call_${ae(12)}`;if(S.size>=dl){C?.warn(`${E} pendingToolCalls size (${S.size}) exceeded limit, dropping tool call ${v}`);return}S.set(sn(v,N),{runId:N,toolName:d.toolName,toolCallId:v,toolSpanId:ae(16),toolStartTime:Date.now(),toolInput:d.params,traceContext:m,channelId:b,createdAt:Date.now()}),f&&C?.info(`${E} Tool call started: ${d.toolName}, toolCallId=${v}`)}catch(p){C?.warn(`${E} [hook] before_tool_call ERROR: ${String(p)}`)}},{priority:-100}),a.on("after_tool_call",async d=>{try{if(!z("after_tool_call")||!y)return;let g=dr(d);if(!g)return;let{toolName:p,toolCallId:l,toolSpanId:m,toolStartTime:b,toolInput:N,traceContext:v,channelId:U}=g,F=Date.now(),K={"gen_ai.span.kind":"TOOL","gen_ai.operation.name":"execute_tool","gen_ai.tool.name":p,"gen_ai.tool.call.id":l,"gen_ai.tool.type":"function","tool.duration_ms":d.durationMs||F-b};N!==void 0&&(K["gen_ai.tool.call.arguments"]=Ie(typeof N=="string"?N:JSON.stringify(N))),d.error?K["error.type"]=d.error:d.result!==void 0&&(K["gen_ai.tool.call.result"]=Ie(typeof d.result=="string"?d.result:JSON.stringify(d.result)));let ue=_e(v,U,`execute_tool ${p}`,"tool",b,F,K,yn(v));ue.spanId=m,y.export(ue);let Je=d.error?[{type:"toolResult",toolCallId:l,toolName:p,isError:!0,content:d.error}]:[{type:"toolResult",toolCallId:l,toolName:p,content:d.result}];if(v.llmPendingToolResultsForNextInput.push({role:"toolResult",content:Je}),v.llmPendingToolCallIds.size>0||v.llmPendingToolCallCountFallback>0){if(v.llmPendingToolCallIds.size>0){if(v.llmPendingToolCallIds.has(l))v.llmPendingToolCallIds.delete(l);else if(!or(d.toolCallId)){let te=v.llmPendingToolCallIds.values().next().value;te&&v.llmPendingToolCallIds.delete(te)}}else v.llmPendingToolCallCountFallback>0&&(v.llmPendingToolCallCountFallback-=1);if(v.llmPendingToolCallIds.size===0&&v.llmPendingToolCallCountFallback===0){let te=[];v.llmLastAssistantContent!==void 0&&te.push({role:"assistant",content:v.llmLastAssistantContent}),v.llmPendingToolResultsForNextInput.length>0&&te.push(...v.llmPendingToolResultsForNextInput),D(v,F,"toolUse",U),v.llmPendingStartTime=F,v.llmPendingSpanId=ae(16),w(v,U,F),v.llmPendingSystemInstructions=void 0,v.llmPendingInputMessages=te.length>0?So(te):void 0,v.llmLastInputMessages=v.llmPendingInputMessages,v.llmPendingToolResultsForNextInput=[]}}f&&C?.info(`${E} Exported tool span: ${p}, duration=${F-b}ms`)}catch(g){C?.warn(`${E} [hook] after_tool_call ERROR: ${String(g)}`)}},{priority:-100}),a.on("before_compaction",async(d,g)=>{try{if(!z("before_compaction")||!y)return;let p=se(g),{ctx:l}=Q(p,d?.runId,"before_compaction");l._compactionStartTime=Date.now()}catch(p){C?.warn(`${E} [hook] before_compaction ERROR: ${String(p)}`)}},{priority:-100}),a.on("after_compaction",async(d,g)=>{try{if(!z("after_compaction")||!y)return;let p=se(g),{ctx:l,channelId:m}=Q(p,d?.runId,"after_compaction"),b=l._compactionStartTime||Date.now(),N=Date.now(),v=_e(l,m,"openclaw.compaction","tool",b,N,{"gen_ai.span.kind":"TOOL","gen_ai.operation.name":"compaction","openclaw.compaction.messages.after":d?.messageCount??-1,"openclaw.compaction.tokens.after":d?.tokenCount??-1,"openclaw.compaction.compacted_count":d?.compactedCount??0},De(l));y.export(v),l._compactionStartTime=void 0}catch(p){C?.warn(`${E} [hook] after_compaction ERROR: ${String(p)}`)}},{priority:-100}),a.on("subagent_spawned",async(d,g)=>{try{if(!z("subagent_spawned")||!y)return;let p=se(g),{ctx:l}=Q(p,d?.runId,"subagent_spawned"),m=d?.sessionKey??d?.childSessionKey??"unknown-child";l._subagentStartTimes||(l._subagentStartTimes=new Map),l._subagentStartTimes.set(m,Date.now())}catch(p){C?.warn(`${E} [hook] subagent_spawned ERROR: ${String(p)}`)}},{priority:-100}),a.on("subagent_ended",async(d,g)=>{try{if(!z("subagent_ended")||!y)return;let p=se(g),{ctx:l,channelId:m}=Q(p,d?.runId,"subagent_ended"),b=d?.sessionKey??d?.childSessionKey??"unknown-child",N=l._subagentStartTimes?.get(b)||Date.now(),v=Date.now(),U=_e(l,m,`openclaw.subagent.${b}`,"agent",N,v,{"gen_ai.span.kind":"AGENT","gen_ai.operation.name":"invoke_subagent","openclaw.subagent.session_key":b},De(l));y.export(U),l._subagentStartTimes?.delete(b)}catch(p){C?.warn(`${E} [hook] subagent_ended ERROR: ${String(p)}`)}},{priority:-100}),a.on("before_agent_start",async(d,g)=>{try{if(!z("before_agent_start")||!y)return;let p=se(g),l=g.agentId||"openclaw",{ctx:m,channelId:b}=Q(p,d?.runId,"before_agent_start");J(m),je(m,b,{userId:g.trigger||"system",role:g.trigger||"system",from:l}),ot(m,b,l)}catch(p){C?.warn(`${E} [hook] before_agent_start ERROR: ${String(p)}`)}},{priority:-100}),a.on("agent_end",async(d,g)=>{try{if(C?.debug(`${E} [hook] agent_end fired, sender=${y?"OK":"null"}, enabled=${z("agent_end")}`),!z("agent_end")||!y)return;let p=se(g),{ctx:l,channelId:m}=Q(p,d?.runId,"agent_end");J(l),await pn(l.traceId),l.isClosing=!0;let b=Date.now();l.stepSpanId&&D(l,b,l.stepAwaitingToolResults?"agent_end":"stop",m);let N=l.agentSpanId,v=b,U;if(N){let K=Array.isArray(d.messages)?d.messages.length:0,ue=wl(d.messages);U={"agent.duration_ms":d.durationMs||0,"agent.message_count":K,"agent.tool_call_count":ue,"gen_ai.usage.input_tokens":l.lastLlmUsage?.input||0,"gen_ai.usage.output_tokens":l.lastLlmUsage?.output||0,"gen_ai.usage.total_tokens":l.lastLlmUsage?.total||0},l.sessionId&&(U["openclaw.session.id"]=l.sessionId||m,U["gen_ai.session.id"]=l.sessionId||m),l.userInput&&(U["gen_ai.input.messages"]=Ie(JSON.stringify([{role:"user",parts:[{type:"text",content:String(l.userInput)}]}]))),l.agentSpanId=void 0,l.agentStartTime=void 0}let F=l;if(F.rootSpanStartTime||N){let K=F.rootSpanId,ue=F.rootSpanStartTime,Je=F.userInput,oe=l.sessionId||F.sessionId;mn(m,F);let Z=y,te=setTimeout(async()=>{Ee.delete(te);try{let H=l.lastOutput||F.lastOutput;if(N&&U&&Z&&!Z.isDisposed&&(H&&(U["gen_ai.output.messages"]=St([typeof H=="string"?H:JSON.stringify(H)])),Z.endSpanById(N,v,U),C?.debug(`${E} [span] Ended agent span: spanId=${N}, traceId=${F.traceId}, duration=${d.durationMs}ms`)),ue&&Z&&!Z.isDisposed){let Pe=Date.now(),me={"request.duration_ms":Pe-ue};oe&&(me["openclaw.session.id"]=oe,me["gen_ai.session.id"]=oe),Je&&(me["gen_ai.input.messages"]=Ie(JSON.stringify([{role:"user",parts:[{type:"text",content:String(Je)}]}]))),H&&(me["gen_ai.output.messages"]=St([typeof H=="string"?H:JSON.stringify(H)])),Z.endSpanById(K,Pe,me),C?.debug(`${E} [span] Ended entry span: spanId=${K}, traceId=${F.traceId}, duration=${Pe-ue}ms`)}fn(l.runId),Ge(F),Z&&!Z.isDisposed&&(await Z.flush(),C?.debug(`${E} [span] Flushed after agent_end, traceId=${F.traceId}`))}catch(H){C?.warn(`${E} agent_end delayed cleanup failed: ${String(H)}`)}},100);Ee.add(te)}else fn(l.runId),Ge(F),y&&await y.flush()}catch(p){C?.error(`${E} [hook] agent_end UNCAUGHT ERROR: ${String(p)}`,p instanceof Error?p.stack:void 0)}},{priority:-100}),a.on("before_reset",async(d,g)=>{try{if(!z("before_reset")||!y)return;let p=se(g),{ctx:l}=Q(p,d?.runId,"before_reset");y?.patchOpenSpanAttributes(l.rootSpanId,{"openclaw.reset":!0,"openclaw.reset.reason":d?.reason??"user_request"})}catch(p){C?.warn(`${E} [hook] before_reset ERROR: ${String(p)}`)}},{priority:-100}),C?.debug(`${E} Registered trace hook handlers (v2 \u2014 \u5B8C\u6574\u94FE\u8DEF\u8FFD\u8E2A).`)}function Mt(a){a!==u&&(P&&(P(),P=null),u=a,u&&y&&!y.isDisposed&&(P=u.subscribe(xt)))}function xt(a){if(!y||y.isDisposed||!(a.secretId!==r||a.secretKey!==s||(a.token||"")!==(o||"")))return;r=a.secretId,s=a.secretKey,o=a.token;let g=new ir(L(a));y.updateProducer(g,e),C?.debug(`${E} \u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u66F4\u65B0\u540E\uFF0CProducer \u5DF2\u91CD\u5EFA\uFF08\u65B0\u51ED\u8BC1\uFF09`)}return{service:Nt,registerHooks:kt,updateSharedCredentialManager:Mt}}import{Producer as an,LogItem as ff,Content as mf}from"tencentcloud-cls-sdk-nodejs";var ar={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},fe="[diagnostics-metrics-cls/log]";function Ro(t,e){if(!t||!(t.enableLogReport===!0))return null;let r=typeof t.logTopicId=="string"?t.logTopicId.trim():"";if(!r)return null;let s=typeof e?.endpoint=="string"?e.endpoint.trim():"";if(!s)return null;let o="",i="";try{o=typeof e?.secretId=="string"?ie(e.secretId.trim()):""}catch{}try{i=typeof e?.secretKey=="string"?ie(e.secretKey.trim()):""}catch{}let c=typeof e?.token=="string"?e.token.trim():void 0,u=typeof e?.credentialMode=="string"&&e.credentialMode.trim()==="cvmRole"?"cvmRole":"static",f=typeof e?.roleName=="string"?e.roleName.trim():void 0;if(!(u==="cvmRole"?!!(s&&f):!!(s&&o&&i)))return null;let _=typeof t.source=="string"&&t.source.trim()?t.source.trim():"openclaw",T=t.enableGatewayLog!==!1,M=t.enableSessionLog!==!1,R=typeof t.minLevel=="string"&&ar[t.minLevel]!==void 0?t.minLevel:"info",k=typeof t.sendTimeThreshold=="number"&&t.sendTimeThreshold>=1?t.sendTimeThreshold:2,y=typeof t.sendCountThreshold=="number"&&t.sendCountThreshold>=1?Math.floor(t.sendCountThreshold):1e3;return{endpoint:s,secretId:o,secretKey:i,token:c,credentialMode:u,roleName:f,logTopicId:r,source:_,enableGatewayLog:T,enableSessionLog:M,minLevel:R,sendTimeThreshold:k,sendCountThreshold:y}}function gf(t){let e=t._meta,n=(e?.logLevelName??"INFO").toLowerCase(),r=e?.date instanceof Date?e.date.getTime():Date.now(),s=e?.name,o=Object.entries(t).filter(([f])=>/^\d+$/.test(f)).sort((f,h)=>Number(f[0])-Number(h[0])).map(([,f])=>f),i,c={};if(typeof o[0]=="string"&&o[0].trim().startsWith("{"))try{let f=JSON.parse(o[0]);if(f&&typeof f=="object"&&!Array.isArray(f)){typeof f.subsystem=="string"&&(i=f.subsystem);for(let[h,_]of Object.entries(f))h!=="subsystem"&&(typeof _=="string"||typeof _=="number"||typeof _=="boolean")&&(c[h]=String(_));o.shift()}}catch{}let u="";for(let f=o.length-1;f>=0;f--)if(typeof o[f]=="string"){u=String(o[f]),o.splice(f,1);break}if(!u&&o.length===1){try{u=JSON.stringify(o[0])}catch{u=String(o[0])}o.length=0}if(u||(u="(empty)"),o.length>0)try{c.args=JSON.stringify(o)}catch{c.args=String(o)}return{level:n,message:u,timestamp:r,subsystem:i,logger:s,extra:c}}function hf(t){let e=typeof t.role=="string"?t.role:"unknown",n;try{n=JSON.stringify(t)}catch{n=String(t)}let r,s,o,i;if(e==="toolResult")typeof t.toolCallId=="string"&&(r=t.toolCallId),typeof t.toolName=="string"&&(s=t.toolName);else if(e==="assistant"){typeof t.stopReason=="string"&&(o=t.stopReason);let u=(Array.isArray(t.content)?t.content:[]).filter(f=>f!==null&&typeof f=="object"&&f.type==="tool_use").length;u>0&&(i=u)}return{role:e,content:n,toolCallId:r,toolName:s,stopReason:o,toolCallCount:i}}function Cl(t,e,n){let r={...t},s=e,o=null,i=null,c=null,u=null,f=!1,h=ar[r.minLevel??"info"]??2;function _($,P,L){return{topic_id:r.logTopicId,endpoint:r.endpoint,credential:{secretId:$,secretKey:P,...L?{token:L}:{}},time:r.sendTimeThreshold??2,count:r.sendCountThreshold??1e3,onSendLogsError:x=>{if(x!==null&&typeof x=="object"&&x.status===200)return;let I;if(x instanceof Error)I=x.message;else if(typeof x=="object"&&x!==null)try{I=JSON.stringify(x)}catch{I=Object.prototype.toString.call(x)}else I=String(x);u?.warn(`${fe} \u65E5\u5FD7\u4E0A\u4F20\u5931\u8D25 - ${I}`)}}}function T($,P){if(o)try{let L=$;if(n){let I=n();(I.cvmInstanceId||I.cvmInstanceName||I.cvmInstanceIntraIp)&&(L={...$},I.cvmInstanceId&&(L.cvm_instance_id=I.cvmInstanceId),I.cvmInstanceName&&(L.cvm_instance_name=I.cvmInstanceName),I.cvmInstanceIntraIp&&(L.cvm_instance_intra_ip=I.cvmInstanceIntraIp))}let x=new ff;x.setTime(P);for(let[I,O]of Object.entries(L))x.pushBack(new mf(I,O));o.send(x).catch(I=>{let O;if(I instanceof Error)O=I.message;else try{O=JSON.stringify(I)}catch{O=Object.prototype.toString.call(I)}u?.warn(`${fe} send \u5931\u8D25: ${O}`)})}catch{}}let M={id:"diagnostics-metrics-cls-log",async start($){if(u=$.logger,n)try{await rr($.logger,$.stateDir),f=!0}catch(I){u?.warn(`${fe} \u5B9E\u4F8B\u5143\u6570\u636E\u521D\u59CB\u5316\u5931\u8D25\uFF0CCVM \u5143\u5B57\u6BB5\u5C06\u7F3A\u5931: ${String(I)}`)}let P=r.secretId,L=r.secretKey,x=r.token;if(s){let I=s.getCredentialSnapshot();P=I.secretId,L=I.secretKey,x=I.token,c=s.subscribe(O=>{if(o)try{o=new an(_(O.secretId,O.secretKey,O.token)),u?.debug(`${fe} \u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}catch(j){u?.warn(`${fe} \u51ED\u8BC1\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String(j)}`)}})}try{o=new an(_(P,L,x))}catch(I){u?.error(`${fe} \u521B\u5EFA Producer \u5931\u8D25: ${String(I)}`),f&&(tn(),f=!1);return}if(u?.info(`${fe} \u542F\u52A8\uFF0Cendpoint=${r.endpoint}\uFF0ClogTopicId=${r.logTopicId}\uFF0CenableGatewayLog=${r.enableGatewayLog}\uFF0CenableSessionLog=${r.enableSessionLog}\uFF0CminLevel=${r.minLevel}`),r.enableGatewayLog){let I="openclaw/plugin-sdk/diagnostics-otel",O;try{O=(await import(I)).registerLogTransport}catch{}O?i=O(j=>{if(o)try{let S=gf(j);if((ar[S.level]??0)<h)return;let V={log_type:"gateway",level:S.level,message:S.message,source:r.source??"openclaw"};S.subsystem&&(V.subsystem=S.subsystem),S.logger&&(V.logger=S.logger);for(let[Y,ce]of Object.entries(S.extra))V[Y]=ce;T(V,Math.floor(S.timestamp/1e3))}catch{}}):u?.warn(`${fe} registerLogTransport \u5728\u5F53\u524D openclaw \u7248\u672C\uFF08>=2026.4.27\uFF09\u4E2D\u5DF2\u79FB\u9664\uFF0Cgateway \u65E5\u5FD7\u4E0A\u62A5\u5DF2\u8DF3\u8FC7`)}},async stop(){i?.(),i=null,c?.(),c=null,o=null,f&&(tn(),f=!1),u=null}};function R($){let P=$.logTopicId!==r.logTopicId,L=$.endpoint!==r.endpoint;if(r={...$},h=ar[r.minLevel??"info"]??2,(P||L)&&o)try{let x=r.secretId,I=r.secretKey,O=r.token;if(s){let j=s.getCredentialSnapshot();x=j.secretId,I=j.secretKey,O=j.token}o=new an(_(x,I,O)),u?.info(`${fe} \u914D\u7F6E\u70ED\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA\uFF0ClogTopicId=${r.logTopicId}\uFF0Cendpoint=${r.endpoint}`)}catch(x){u?.warn(`${fe} \u914D\u7F6E\u70ED\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String(x)}`)}}function k($){if($!==s&&(c?.(),c=null,s=$,o&&s)){let P=s.getCredentialSnapshot();try{o=new an(_(P.secretId,P.secretKey,P.token)),u?.debug(`${fe} \u51ED\u8BC1\u7BA1\u7406\u5668\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}catch(L){u?.warn(`${fe} \u51ED\u8BC1\u7BA1\u7406\u5668\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String(L)}`)}c=s.subscribe(L=>{if(o)try{o=new an(_(L.secretId,L.secretKey,L.token)),u?.debug(`${fe} \u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}catch(x){u?.warn(`${fe} \u51ED\u8BC1\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String(x)}`)}})}}function y($){r.enableSessionLog&&$.on("before_message_write",(P,L)=>{if(o)try{let x=P?.message;if(!x)return;let I=L?.sessionKey??P?.sessionKey??"",O=L?.agentId??P?.agentId??"",j=Math.floor(Date.now()/1e3),S=hf(x),q={log_type:"session",role:S.role,content:S.content,source:r.source??"openclaw"};S.toolCallId&&(q.tool_call_id=S.toolCallId),S.toolName&&(q.tool_name=S.toolName),S.stopReason&&(q.stop_reason=S.stopReason),S.toolCallCount!==void 0&&(q.tool_calls=String(S.toolCallCount)),I&&(q.session_key=I),O&&(q.agent_id=O),T(q,j)}catch{}})}return{service:M,registerHooks:y,updateConfig:R,updateSharedCredentialManager:k}}import yf from"node:http";import _f from"node:https";import{URL as bf}from"node:url";var Ol="http://metadata.tencentyun.com/latest/meta-data/",wf=Ol+"cam/security-credentials/",If=Ol+"cam/service-role-security-credentials/",Nl="custom-role-",Tf=5e3,kl=3600*1e3,Ml=8192,xl=3;function Pl(t,e=0){if(e>xl)return Promise.reject(new Error(`Too many redirects (>${xl}) for ${t}`));let n;try{n=new bf(t)}catch{return Promise.reject(new Error(`Invalid URL: ${t}`))}let r=n.protocol==="https:"?_f:yf;return new Promise((s,o)=>{let i=r.get(t,{timeout:Tf},c=>{let u=c.statusCode??0;if(u>=300&&u<400&&c.headers.location){c.resume(),Pl(c.headers.location,e+1).then(s,o);return}if(u!==200){c.resume(),o(new Error(`HTTP ${u} for ${t}`));return}let f=[],h=0,_=!1;c.on("data",T=>{if(!_){if(h+=T.length,h>Ml){_=!0,c.destroy(),o(new Error(`Response body too large (>${Ml} bytes) for ${t}`));return}f.push(T)}}),c.on("end",()=>{_||s(Buffer.concat(f).toString("utf-8").trim())}),c.on("error",T=>{_||o(T)})});i.on("timeout",()=>{i.destroy(),o(new Error(`Request timeout for ${t}`))}),i.on("error",o)})}var Co=class t{constructor(e){this.credentialTask=null;this.lastResolvedExpiredTime=null;this.roleName=e}static{this.MAX_EXPIRED_RETRY=3}getRoleUrl(){return this.roleName.indexOf(Nl)===0?wf+this.roleName.slice(Nl.length):If+this.roleName}async fetchRoleCredential(){let e=await Pl(this.getRoleUrl()),n;try{n=JSON.parse(e)}catch{throw new Error(`Failed to parse credential response for role [${this.roleName}]: ${e.slice(0,200)}`)}if(n.Code!=="Success")throw new Error(`Get credential from metadata server by role name [${this.roleName}] failed, Code: ${n.Code}`);if(!n.TmpSecretId||!n.TmpSecretKey)throw new Error(`Credential response for role [${this.roleName}] missing TmpSecretId or TmpSecretKey`);return n}async getCredential(){return this.getCredentialWithRetry(0)}async getCredentialWithRetry(e){this.credentialTask||(this.credentialTask=this.fetchRoleCredential());let n;try{n=await this.credentialTask}catch(r){throw this.credentialTask=null,r}if(n.ExpiredTime*1e3-kl<=Date.now()){if(e>=t.MAX_EXPIRED_RETRY)throw this.credentialTask=null,new Error(`Credential for role [${this.roleName}] is still expired after ${t.MAX_EXPIRED_RETRY} retries (ExpiredTime=${n.ExpiredTime}, now=${Math.floor(Date.now()/1e3)})`);return this.credentialTask=null,this.getCredentialWithRetry(e+1)}return this.lastResolvedExpiredTime=n.ExpiredTime,{secretId:n.TmpSecretId,secretKey:n.TmpSecretKey,token:n.Token,expiredTime:n.ExpiredTime}}invalidate(){this.credentialTask=null,this.lastResolvedExpiredTime=null}isExpiringSoon(){return this.lastResolvedExpiredTime===null?!0:this.lastResolvedExpiredTime*1e3-kl<=Date.now()}},Et=new Map;function Sf(t){let e=Et.get(t);return e||(e=new Co(t),Et.set(t,e)),e}async function Al(t){if(!t)throw new Error("roleName is required for CVM role credential provider");return Sf(t).getCredential()}function cr(t){let e=Et.get(t);return e?e.isExpiringSoon():!0}function $l(t){if(t)Et.get(t)?.invalidate();else for(let e of Et.values())e.invalidate()}function Ll(){Et.clear()}var vf=300*1e3,No=class t{constructor(e){this.listeners=[];this.refreshTimer=null;this.started=!1;this.stopped=!1;this.log=null;this.refreshingPromise=null;this.credentialMode=e.credentialMode,this.roleName=e.roleName,this.secretId=e.secretId,this.secretKey=e.secretKey,this.token=e.token,this.refreshIntervalMs=e.refreshIntervalMs??vf}static{this.LOG_PREFIX="[diagnostics-metrics-cls/shared-credential]"}setLogger(e){this.log=e}getCredentialMode(){return this.credentialMode}getRoleName(){return this.roleName}getCredentialSnapshot(){return{secretId:this.secretId,secretKey:this.secretKey,token:this.token}}subscribe(e){return this.listeners.push(e),()=>{let n=this.listeners.indexOf(e);n>=0&&this.listeners.splice(n,1)}}async start(){this.started||(this.started=!0,this.stopped=!1,this.credentialMode==="cvmRole"&&(await this.refreshCredentialInternal(),this.refreshTimer=setInterval(()=>{cr(this.roleName)&&this.refreshCredentialInternal()},this.refreshIntervalMs),typeof this.refreshTimer.unref=="function"&&this.refreshTimer.unref(),this.log?.debug(`${t.LOG_PREFIX} cvmRole \u51ED\u8BC1\u5B9A\u65F6\u5237\u65B0\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${this.refreshIntervalMs}ms`)))}stop(){this.stopped=!0,this.started=!1,this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.listeners=[],Ll()}async forceRefresh(){return this.credentialMode==="cvmRole"?this.refreshingPromise?(this.log?.warn(`${t.LOG_PREFIX} \u6536\u5230\u5F3A\u5236\u5237\u65B0\u8BF7\u6C42\uFF0C\u5DF2\u6709\u5237\u65B0\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u7B49\u5F85\u5B8C\u6210`),await this.refreshingPromise,!0):cr(this.roleName)?(this.log?.warn(`${t.LOG_PREFIX} \u6536\u5230\u5F3A\u5236\u5237\u65B0\u8BF7\u6C42\uFF0C\u4E34\u65F6\u5BC6\u94A5\u5DF2\u8FC7\u671F\uFF0C\u6B63\u5728\u5237\u65B0 cvmRole \u4E34\u65F6\u5BC6\u94A5`),$l(this.roleName),await this.refreshCredentialInternal(),!0):(this.log?.warn(`${t.LOG_PREFIX} \u6536\u5230\u5F3A\u5236\u5237\u65B0\u8BF7\u6C42\uFF0C\u4F46\u4E34\u65F6\u5BC6\u94A5\u5C1A\u672A\u8FC7\u671F\uFF0C\u8DF3\u8FC7\u5237\u65B0\uFF08401 \u53EF\u80FD\u7531\u6743\u9650\u914D\u7F6E\u7B49\u539F\u56E0\u5BFC\u81F4\uFF09`),!1):(this.log?.warn(`${t.LOG_PREFIX} \u6536\u5230\u5F3A\u5236\u5237\u65B0\u8BF7\u6C42\uFF0C\u5F53\u524D\u4E3A static \u51ED\u8BC1\u6A21\u5F0F\uFF0C\u65E0\u6CD5\u81EA\u52A8\u5237\u65B0`),!1)}updateStaticCredential(e,n,r){(e!==this.secretId||n!==this.secretKey||(r||"")!==(this.token||""))&&(this.secretId=e,this.secretKey=n,this.token=r,this.notifyListeners(),this.log?.debug(`${t.LOG_PREFIX} \u9759\u6001\u51ED\u8BC1\u5DF2\u66F4\u65B0`))}async updateMode(e,n,r,s,o){let i=e!==this.credentialMode,c=n!==this.roleName;this.credentialMode=e,this.roleName=n,e==="static"?(this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),r!==void 0&&s!==void 0&&(this.secretId=r,this.secretKey=s,this.token=o),this.notifyListeners()):e==="cvmRole"&&(this.started&&(i||c)&&await this.refreshCredentialInternal(),!this.refreshTimer&&this.started&&(this.refreshTimer=setInterval(()=>{cr(this.roleName)&&this.refreshCredentialInternal()},this.refreshIntervalMs),typeof this.refreshTimer.unref=="function"&&this.refreshTimer.unref()))}async refreshCredentialInternal(){if(!this.stopped){if(this.refreshingPromise){await this.refreshingPromise;return}this.refreshingPromise=this.doRefresh();try{await this.refreshingPromise}finally{this.refreshingPromise=null}}}async doRefresh(){try{let e=await Al(this.roleName);if(this.stopped)return;let n=e.secretId!==this.secretId||e.secretKey!==this.secretKey||(e.token||"")!==(this.token||"");this.secretId=e.secretId,this.secretKey=e.secretKey,this.token=e.token,n&&(this.notifyListeners(),this.log?.debug(`${t.LOG_PREFIX} cvmRole \u4E34\u65F6\u5BC6\u94A5\u5DF2\u5237\u65B0`))}catch(e){this.log?.warn(`${t.LOG_PREFIX} cvmRole \u4E34\u65F6\u5BC6\u94A5\u5237\u65B0\u5931\u8D25: ${String(e)}`)}}notifyListeners(){let e=this.getCredentialSnapshot();for(let n of this.listeners)try{n(e)}catch(r){this.log?.warn(`${t.LOG_PREFIX} \u51ED\u8BC1\u53D8\u66F4\u901A\u77E5\u56DE\u8C03\u5F02\u5E38: ${String(r)}`)}}};function Dl(t){if(!t)return null;let e=typeof t.credentialMode=="string"&&t.credentialMode.trim()==="cvmRole"?"cvmRole":"static",n=typeof t.roleName=="string"?t.roleName.trim():"",r=typeof t.secretId=="string"?t.secretId.trim():"",s=typeof t.secretKey=="string"?t.secretKey.trim():"",o=typeof t.token=="string"?t.token.trim():void 0,i=typeof t.credentialRefreshIntervalMs=="number"&&t.credentialRefreshIntervalMs>=6e4?t.credentialRefreshIntervalMs:void 0;return new No({credentialMode:e,roleName:n,secretId:r,secretKey:s,token:o,refreshIntervalMs:i})}var cn=null,Te=null,Rt=null,Bl="";function Ef(t){if(!t)return"";let e=["credentialMode","roleName","secretId","secretKey","token","credentialRefreshIntervalMs"],n=[];for(let r of e){let s=t[r];n.push(`${r}=${typeof s=="string"||typeof s=="number"?String(s):""}`)}return n.join("|")}var Rf={id:"clawpro-diagnostics-metrics-cls",name:"Diagnostics Metrics",description:"CLS\u8BCA\u65AD\u6307\u6807\u5BFC\u51FA\u63D2\u4EF6\uFF1APrometheus \u6307\u6807\uFF08pull/remote-write\uFF09+ \u5168\u94FE\u8DEF Trace",configSchema:{type:"object",properties:{prometheus:{type:"object",description:"Prometheus \u6307\u6807\u5BFC\u51FA\u914D\u7F6E",properties:{enabled:{type:"boolean",default:!0,description:"\u662F\u5426\u542F\u7528 Prometheus \u6307\u6807\u5BFC\u51FA"},metric_prefix:{type:"string",default:"openclaw",description:"\u6307\u6807\u540D\u79F0\u524D\u7F00"},pull:{type:"boolean",default:!0,description:"\u662F\u5426\u542F\u7528 /metrics HTTP pull \u7AEF\u70B9"},default_metrics:{type:"boolean",default:!0,description:"\u662F\u5426\u91C7\u96C6 Node.js \u9ED8\u8BA4\u6307\u6807"},push_interval_ms:{type:"number",default:3e4,description:"Remote Write \u63A8\u9001\u95F4\u9694\uFF08\u6BEB\u79D2\uFF09"}}},cls:{type:"object",description:"\u817E\u8BAF\u4E91 CLS \u51ED\u8BC1\u4E0E\u63A5\u5165\u914D\u7F6E",properties:{endpoint:{type:"string",description:"CLS \u63A5\u5165\u70B9"},secretId:{type:"string",description:"\u817E\u8BAF\u4E91 SecretId"},secretKey:{type:"string",description:"\u817E\u8BAF\u4E91 SecretKey"},metricTopicId:{type:"string",description:"\u6307\u6807\u65E5\u5FD7\u4E3B\u9898 ID"},credentialMode:{type:"string",enum:["static","cvmRole"],description:"\u51ED\u8BC1\u6A21\u5F0F"},roleName:{type:"string",description:"CVM \u89D2\u8272\u540D\u79F0"},enableReport:{type:"boolean",default:!0,description:"\u662F\u5426\u542F\u7528\u6307\u6807\u63A8\u9001"}}},log:{type:"object",description:"CLS \u65E5\u5FD7\u4E0A\u62A5\u914D\u7F6E\uFF0C\u5C06 gateway \u8FD0\u884C\u65E5\u5FD7\u3001\u4F1A\u8BDD\u65E5\u5FD7\uFF08session JSONL\uFF09\u5B9E\u65F6\u4E0A\u62A5\u5230 CLS",properties:{enableLogReport:{type:"boolean",default:!1,description:"\u662F\u5426\u542F\u7528\u65E5\u5FD7\u4E0A\u62A5\uFF0C\u9ED8\u8BA4 false"},logTopicId:{type:"string",description:"\u65E5\u5FD7\u4E0A\u62A5\u4F7F\u7528\u7684 CLS \u65E5\u5FD7\u4E3B\u9898 ID"},source:{type:"string",description:"\u65E5\u5FD7\u6765\u6E90\u6807\u8BC6\uFF0C\u9ED8\u8BA4 openclaw"},enableGatewayLog:{type:"boolean",default:!0,description:"\u662F\u5426\u542F\u7528 gateway \u8FD0\u884C\u65E5\u5FD7\u4E0A\u62A5\uFF0C\u9ED8\u8BA4 true"},enableSessionLog:{type:"boolean",default:!0,description:"\u662F\u5426\u542F\u7528\u4F1A\u8BDD\u65E5\u5FD7\u4E0A\u62A5\uFF08session JSONL\uFF09\uFF0C\u9ED8\u8BA4 true"},minLevel:{type:"string",description:"\u6700\u4F4E\u4E0A\u62A5\u65E5\u5FD7\u7EA7\u522B\uFF08\u4EC5\u5BF9 gateway \u8FD0\u884C\u65E5\u5FD7\u751F\u6548\uFF09\uFF0C\u9ED8\u8BA4 info"},sendTimeThreshold:{type:"number",default:2,description:"CLS SDK \u5F02\u6B65\u53D1\u9001\u65F6\u95F4\u9608\u503C\uFF08\u79D2\uFF09\uFF0C\u9ED8\u8BA4 2"},sendCountThreshold:{type:"number",default:1e3,description:"CLS SDK \u5F02\u6B65\u53D1\u9001\u6761\u6570\u9608\u503C\uFF0C\u9ED8\u8BA4 1000"}}},trace:{type:"object",description:"CLS \u5168\u94FE\u8DEF Trace \u8FFD\u8E2A\u914D\u7F6E",properties:{enabled:{type:"boolean",default:!1,description:"\u662F\u5426\u542F\u7528 Trace \u94FE\u8DEF\u8FFD\u8E2A"},traceTopicId:{type:"string",description:"Trace \u65E5\u5FD7\u4E3B\u9898 ID"},serviceName:{type:"string",default:"openclaw-agent",description:"\u670D\u52A1\u540D\u79F0"},debug:{type:"boolean",default:!1,description:"\u662F\u5426\u5F00\u542F\u8C03\u8BD5\u65E5\u5FD7"},batchSize:{type:"number",default:10,description:"Span \u7F13\u51B2\u533A\u5927\u5C0F"},flushIntervalMs:{type:"number",default:5e3,description:"Span \u7F13\u51B2\u533A\u6700\u5927\u7B49\u5F85\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09"},enabledHooks:{type:"array",items:{type:"string"},description:"\u542F\u7528\u7684 hook \u5217\u8868\uFF0C\u4E0D\u8BBE\u7F6E\u5219\u5168\u90E8\u542F\u7528"}}}}},register(t){if(t.registrationMode==="cli-metadata")return;let e=t.pluginConfig?.prometheus,n=t.pluginConfig?.cls,r=t.pluginConfig?.trace,s=t.pluginConfig?.log,o;if(n){if(o={...n},typeof n.secretId=="string")try{o.secretId=ie(n.secretId)}catch{}if(typeof n.secretKey=="string")try{o.secretKey=ie(n.secretKey)}catch{}}let i=Ef(o),c;if(Rt&&Bl===i)c=Rt;else if(Rt&&o){let T=o.credentialMode==="cvmRole"?"cvmRole":"static",M=typeof o.roleName=="string"?o.roleName:"",R=typeof o.secretId=="string"?o.secretId:"",k=typeof o.secretKey=="string"?o.secretKey:"",y=typeof o.token=="string"?o.token:void 0;Rt.updateMode(T,M,R,k,y),c=Rt}else c=Dl(o),Rt=c;Bl=i;let u={...e,...n},h=rl(u,c,(T,M)=>{if(!Te||!T||!M)return;let R={...s??{},enableLogReport:T,logTopicId:M},k=Ro(R,n);k&&Te.updateConfig(k)});if(c&&t.registerService({id:"diagnostics-metrics-cls-shared-credential",async start(T){c.setLogger(T.logger),await c.start()},async stop(T){T.logger?.debug?.("[diagnostics-metrics-cls] shared-credential service stopping"),c.stop()}}),t.registerService(h),t.registerHttpRoute({path:"/metrics",auth:"plugin",match:"exact",replaceExisting:!0,handler:async(T,M)=>{let R=h.getExports();if(!R?.registry)return M.writeHead(503,{"Content-Type":"text/plain"}),M.end(`Prometheus metrics not initialized
|
|
16
|
-
`),!0;try{let k=await R.registry.metrics();M.writeHead(200,{"Content-Type":R.registry.contentType}),M.end(k)}catch{M.writeHead(500,{"Content-Type":"text/plain"}),M.end(`Failed to collect metrics
|
|
17
|
-
`)}return!0}}),!cn){let T=Eo(r,n);T.sharedCredentialManager=c,cn=Rl(T)}if(cn.updateSharedCredentialManager(c),cn.registerHooks(t),t.registerService(cn.service),s?.enableLogReport===!0){let T=Ro(s,n);T&&(Te?Te.updateConfig(T):Te=Cl(T,c,Oe),Te.updateSharedCredentialManager(c),Te.registerHooks(t),t.registerService(Te.service))}else Te&&(Te.service.stop(),Te=null)}},Fy=Rf;export{Fy as default};
|
|
1
|
+
import{Registry as Dr,Counter as pe,Histogram as Je,Gauge as bt,collectDefaultMetrics as Br}from"prom-client";import tt from"node:fs";import dn from"node:fs/promises";import yr from"node:http";import Ir from"node:https";import un from"snappyjs";function cn(t){let e=[],n=t>>>0;for(;n>127;)e.push(n&127|128),n>>>=7;return e.push(n&127),e}function ar(t){let e=[],n=BigInt.asUintN(64,t);for(;n>0x7fn;)e.push(Number(n&0x7fn)|128),n>>=7n;return e.push(Number(n&0x7fn)),e}function cr(t){return ar(BigInt(Math.trunc(t)))}var lr=new TextEncoder;function an(t){return lr.encode(t)}function dr(t){let e=new ArrayBuffer(8);return new Float64Array(e)[0]=t,new Uint8Array(e)}function xt(t,e){return cn(t<<3|e)}var ur=0,pr=1,fr=2;function et(t,e){let n=xt(t,fr),r=cn(e.length),o=new Uint8Array(n.length+r.length+e.length);return o.set(n,0),o.set(r,n.length),o.set(e,n.length+r.length),o}function _t(t){let e=0;for(let o of t)e+=o.length;let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.length;return n}function gr(t){let e=[];if(t.name.length>0){let n=an(t.name);e.push(et(1,n))}if(t.value.length>0){let n=an(t.value);e.push(et(2,n))}return _t(e)}function mr(t){let e=[];{let n=xt(1,pr),r=dr(t.value),o=new Uint8Array(n.length+8);o.set(n,0),o.set(r,n.length),e.push(o)}{let n=xt(2,ur),r=cr(t.timestampMs),o=new Uint8Array(n.length+r.length);o.set(n,0),o.set(r,n.length),e.push(o)}return _t(e)}function hr(t){let e=[];for(let n of t.labels)e.push(et(1,gr(n)));for(let n of t.samples)e.push(et(2,mr(n)));return _t(e)}function ln(t){let e=[];for(let n of t.timeseries)e.push(et(1,hr(n)));return _t(e)}var wr=64*1024;function _r(t){return t.map(e=>({source_labels:e.source_labels??["__name__"],regex:new RegExp(e.regex??"(.*)"),action:e.action??"keep"}))}function Tr(t,e){for(let n of e){let r=n.source_labels.map(c=>t.find(l=>l.name===c)?.value??"").join(";"),o=n.regex.test(r);if(n.action==="keep"&&!o||n.action==="drop"&&o)return null}return t}var Le=class{constructor(e,n,r){this.buffer=[];this.flushTimer=null;this.stopped=!1;this.flushing=!1;this.consecutiveFailures=0;this.circuitOpen=!1;this.lastCircuitWarnMs=0;this.config=e,this.logger=n,this.onUnauthorized=r;let o=e.queue_config??{};this.capacity=o.capacity??2500,this.maxSamplesPerSend=o.max_samples_per_send??500,this.batchDeadlineMs=o.batch_send_deadline_ms??5e3,this.maxRetries=o.max_retries??3,this.minBackoffMs=o.min_backoff_ms??30,this.maxBackoffMs=o.max_backoff_ms??5e3,this.timeoutMs=e.remote_timeout_ms??3e4,this.maxConsecutiveFailures=o.max_consecutive_failures??3,this.compiledRelabelConfigs=_r(e.write_relabel_configs??[]);let c=e.tls_config;if(c?.ca_file)try{this.cachedTlsCa=tt.readFileSync(c.ca_file)}catch(l){n.warn(`diagnostics-prometheus: \u8BFB\u53D6 TLS ca_file \u5931\u8D25: ${l instanceof Error?l.message:String(l)}`)}if(c?.cert_file)try{this.cachedTlsCert=tt.readFileSync(c.cert_file)}catch(l){n.warn(`diagnostics-prometheus: \u8BFB\u53D6 TLS cert_file \u5931\u8D25: ${l instanceof Error?l.message:String(l)}`)}if(c?.key_file)try{this.cachedTlsKey=tt.readFileSync(c.key_file)}catch(l){n.warn(`diagnostics-prometheus: \u8BFB\u53D6 TLS key_file \u5931\u8D25: ${l instanceof Error?l.message:String(l)}`)}}enqueue(e){if(this.stopped)return;if(this.circuitOpen){let r=Date.now();r-this.lastCircuitWarnMs>=6e5&&(this.lastCircuitWarnMs=r,this.logger.warn(`diagnostics-prometheus: \u7194\u65AD\u5668\u5DF2\u6253\u5F00\uFF08\u8FDE\u7EED ${this.consecutiveFailures} \u6279\u6B21\u53D1\u9001\u5931\u8D25\uFF09\uFF0C\u6570\u636E\u4E0A\u62A5\u5DF2\u6682\u505C\u3002\u8BF7\u68C0\u67E5\u91C7\u96C6\u5668\u914D\u7F6E\uFF08endpoint/\u8BA4\u8BC1\u4FE1\u606F\u7B49\uFF09\uFF0C\u914D\u7F6E\u4FEE\u6B63\u540E\u5C06\u81EA\u52A8\u6062\u590D\uFF08\u70ED\u52A0\u8F7D\u751F\u6548\u5373\u53EF\uFF09\u3002`));return}this.refreshFileCredentials();let n=this.applyRelabelFilters(e);if(n.length!==0){if(this.buffer.push(...n),this.buffer.length>this.capacity&&this.buffer.splice(0,this.buffer.length-this.capacity),this.buffer.length>=this.maxSamplesPerSend){this.flush();return}this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},this.batchDeadlineMs),typeof this.flushTimer.unref=="function"&&this.flushTimer.unref())}}async flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),!this.flushing){this.flushing=!0;try{for(;this.buffer.length>0;){let e=this.buffer.splice(0,this.maxSamplesPerSend);await this.sendBatch(e)}}finally{this.flushing=!1}}}updateConfig(e){this.config={...this.config,...e},(e.basic_auth||e.bearer_token_file)&&(this.cachedPasswordFileContent=void 0,this.cachedBearerTokenFileContent=void 0),(this.circuitOpen||this.consecutiveFailures>0)&&(this.consecutiveFailures=0,this.circuitOpen=!1,this.logger.debug("diagnostics-prometheus: \u914D\u7F6E\u5DF2\u66F4\u65B0\uFF0C\u7194\u65AD\u5668\u5DF2\u91CD\u7F6E\uFF0C\u6570\u636E\u4E0A\u62A5\u6062\u590D\u3002"))}async stop(){this.stopped=!0,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),await this.flush().catch(()=>{})}async refreshFileCredentials(){if(this.config.basic_auth?.password_file&&this.cachedPasswordFileContent===void 0)try{this.cachedPasswordFileContent=(await dn.readFile(this.config.basic_auth.password_file,"utf-8")).trim()}catch(e){this.logger.warn(`diagnostics-prometheus: \u5F02\u6B65\u8BFB\u53D6 password_file \u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}if(this.config.bearer_token_file&&this.cachedBearerTokenFileContent===void 0)try{this.cachedBearerTokenFileContent=(await dn.readFile(this.config.bearer_token_file,"utf-8")).trim()}catch(e){this.logger.warn(`diagnostics-prometheus: \u5F02\u6B65\u8BFB\u53D6 bearer_token_file \u5931\u8D25: ${e instanceof Error?e.message:String(e)}`)}}applyRelabelFilters(e){return this.compiledRelabelConfigs.length===0?e:e.filter(n=>Tr(n.labels,this.compiledRelabelConfigs)!==null)}async sendBatch(e){if(e.length===0)return;let n=ln({timeseries:e}),r=un.compress??un.default?.compress;if(!r){this.logger.error(`diagnostics-prometheus: snappyjs compress \u51FD\u6570\u672A\u627E\u5230\uFF0C\u65E0\u6CD5\u538B\u7F29\u6570\u636E\uFF0Cdropping ${e.length} samples\u3002\u8BF7\u68C0\u67E5 snappyjs \u5305\u7248\u672C\u548C\u6A21\u5757\u52A0\u8F7D\u65B9\u5F0F`);return}let o=r(Buffer.from(n));for(let c=0;c<=this.maxRetries;c++)try{let{statusCode:l,body:u}=await this.httpPost(o);if(l>=200&&l<300){this.consecutiveFailures=0;return}if(l===401){if(this.onUnauthorized){this.logger.warn(`diagnostics-prometheus: remote write 401 Unauthorized, \u6B63\u5728\u68C0\u67E5\u51ED\u8BC1\u72B6\u6001 (attempt ${c+1}/${this.maxRetries}). Response: ${u}`);let g;try{g=await this.onUnauthorized()}catch(m){this.logger.error(`diagnostics-prometheus: \u51ED\u8BC1\u5237\u65B0\u5931\u8D25: ${Ft(m)}, dropping ${e.length} samples. Response: ${u}`),this.recordBatchFailure();return}if(!g){this.logger.error(`diagnostics-prometheus: remote write 401 Unauthorized, \u4E34\u65F6\u5BC6\u94A5\u672A\u8FC7\u671F\uFF0C\u8DF3\u8FC7\u91CD\u8BD5, dropping ${e.length} samples. Response: ${u}`),this.recordBatchFailure();return}if(c<this.maxRetries)continue;this.logger.error(`diagnostics-prometheus: remote write 401 after ${this.maxRetries} retries, dropping ${e.length} samples. Response: ${u}`),this.recordBatchFailure();return}this.logger.error(`diagnostics-prometheus: remote write 401 Unauthorized, dropping ${e.length} samples. Response: ${u}`),this.recordBatchFailure();return}if(l===400||l===415){this.logger.error(`diagnostics-prometheus: remote write rejected with ${l}, dropping ${e.length} samples. Response: ${u}`),this.recordBatchFailure();return}if(l===429||l>=500&&l<600){if(c<this.maxRetries){let g=this.calculateBackoff(c);this.logger.warn(`diagnostics-prometheus: remote write ${l}, retrying in ${g}ms (attempt ${c+1}/${this.maxRetries}). Response: ${u}`),await this.sleep(g);continue}this.logger.error(`diagnostics-prometheus: remote write failed after ${this.maxRetries} retries, dropping ${e.length} samples. Response: ${u}`),this.recordBatchFailure();return}this.logger.warn(`diagnostics-prometheus: remote write unexpected status ${l}. Response: ${u}`);return}catch(l){if(c<this.maxRetries){let u=this.calculateBackoff(c);this.logger.warn(`diagnostics-prometheus: remote write error: ${Ft(l)}, retrying in ${u}ms`),await this.sleep(u);continue}this.logger.error(`diagnostics-prometheus: remote write failed: ${Ft(l)}, dropping ${e.length} samples`),this.recordBatchFailure();return}}recordBatchFailure(){++this.consecutiveFailures,!this.circuitOpen&&this.consecutiveFailures>=this.maxConsecutiveFailures&&(this.circuitOpen=!0,this.lastCircuitWarnMs=0,this.logger.error(`diagnostics-prometheus: \u8FDE\u7EED ${this.consecutiveFailures} \u6279\u6B21\u53D1\u9001\u5931\u8D25\uFF0C\u7194\u65AD\u5668\u5DF2\u6253\u5F00\uFF0C\u6570\u636E\u4E0A\u62A5\u5DF2\u6682\u505C\u3002\u8BF7\u68C0\u67E5\u91C7\u96C6\u5668\u914D\u7F6E\uFF08endpoint/\u8BA4\u8BC1\u4FE1\u606F\u7B49\uFF09\uFF0C\u914D\u7F6E\u4FEE\u6B63\u540E\u70ED\u52A0\u8F7D\u5C06\u81EA\u52A8\u91CD\u7F6E\u7194\u65AD\u5668\u5E76\u6062\u590D\u4E0A\u62A5\u3002`))}httpPost(e){return new Promise((n,r)=>{let o=new URL(this.config.url),c=o.protocol==="https:",l=c?Ir:yr,u={"Content-Type":"application/x-protobuf","Content-Encoding":"snappy","X-Prometheus-Remote-Write-Version":"0.1.0","User-Agent":"openclaw-diagnostics-prometheus/1.0",...this.config.headers??{}};if(this.config.basic_auth){let _=this.config.basic_auth.username??"",S=this.config.basic_auth.password??"";if(!S&&this.config.basic_auth.password_file&&(S=this.cachedPasswordFileContent??"",!S)){this.logger.warn("diagnostics-prometheus: password_file \u7F13\u5B58\u4E3A\u7A7A\uFF0C\u5C1D\u8BD5\u540C\u6B65\u8BFB\u53D6\u4F5C\u4E3A\u56DE\u9000");try{S=tt.readFileSync(this.config.basic_auth.password_file,"utf-8").trim()}catch(C){this.logger.warn(`diagnostics-prometheus: \u8BFB\u53D6 password_file \u5931\u8D25: ${C instanceof Error?C.message:String(C)}`)}}u.Authorization=`Basic ${Buffer.from(`${_}:${S}`).toString("base64")}`}else if(this.config.bearer_token)u.Authorization=`Bearer ${this.config.bearer_token}`;else if(this.config.bearer_token_file){let _=this.cachedBearerTokenFileContent??"";if(_)u.Authorization=`Bearer ${_}`;else{this.logger.warn("diagnostics-prometheus: bearer_token_file \u7F13\u5B58\u4E3A\u7A7A\uFF0C\u5C1D\u8BD5\u540C\u6B65\u8BFB\u53D6\u4F5C\u4E3A\u56DE\u9000");try{u.Authorization=`Bearer ${tt.readFileSync(this.config.bearer_token_file,"utf-8").trim()}`}catch(S){this.logger.warn(`diagnostics-prometheus: \u8BFB\u53D6 bearer_token_file \u5931\u8D25: ${S instanceof Error?S.message:String(S)}`)}}}let g={method:"POST",hostname:o.hostname,port:o.port||(c?443:80),path:o.pathname+o.search,headers:u,timeout:this.timeoutMs};if(c&&this.config.tls_config){let _=this.config.tls_config;this.cachedTlsCa&&(g.ca=this.cachedTlsCa),this.cachedTlsCert&&(g.cert=this.cachedTlsCert),this.cachedTlsKey&&(g.key=this.cachedTlsKey),_.server_name&&(g.servername=_.server_name),_.insecure_skip_verify&&(g.rejectUnauthorized=!1)}let m=l.request(g,_=>{let S=[],C=0,E=!1;_.on("data",N=>{if(!E){if(C+=N.length,C>wr){E=!0,_.destroy();let P=Buffer.concat(S).toString("utf-8");n({statusCode:_.statusCode??0,body:P+"...(truncated)"});return}S.push(N)}}),_.on("end",()=>{if(E)return;let N=Buffer.concat(S).toString("utf-8");n({statusCode:_.statusCode??0,body:N})}),_.on("error",()=>{E||n({statusCode:_.statusCode??0,body:""})})});m.on("error",r),m.on("timeout",()=>{m.destroy(new Error("remote write request timed out"))}),m.write(Buffer.isBuffer(e)?e:Buffer.from(e)),m.end()})}calculateBackoff(e){let n=this.minBackoffMs*Math.pow(2,e),r=Math.min(n,this.maxBackoffMs),o=r*.25*(Math.random()*2-1);return Math.round(r+o)}sleep(e){return new Promise(n=>setTimeout(n,e))}};function Ft(t){return t instanceof Error?t.stack??t.message:typeof t=="string"?t:String(t)}import br from"node:http";import Sr from"node:https";import{URL as Rr}from"node:url";import Bt from"node:os";import re from"node:fs/promises";import hn from"node:path";var kr="http://metadata.tencentyun.com/latest/meta-data",vr=2e3,Cr=30*1e3,Kt=3,pn=1024,fn=3,nt="clawpro-diagnostics-metrics-cls",yn=Object.freeze({cvmInstanceId:"",cvmInstanceName:"",cvmInstanceIntraIp:"",hostName:""}),ge=yn,rt=!1,it=!1,Re=null,st=0,ot=0;function Dt(t,e=0){let n=e===0?`${kr}/${t}`:t;if(e>fn)return Promise.reject(new Error(`Too many redirects (>${fn}) for ${n}`));let r;try{r=new Rr(n)}catch{return Promise.reject(new Error(`Invalid URL: ${n}`))}let o=r.protocol==="https:"?Sr:br;return new Promise((c,l)=>{let u=o.get(n,{timeout:vr},g=>{let m=g.statusCode??0;if(m>=300&&m<400&&g.headers.location){g.resume(),Dt(g.headers.location,e+1).then(c,l);return}if(m!==200){g.resume(),l(new Error(`HTTP ${m} for ${n}`));return}$r(g,n,c,l)});u.on("timeout",()=>{u.destroy(),l(new Error(`Request timeout for ${n}`))}),u.on("error",l)})}function $r(t,e,n,r){let o=[],c=0,l=!1;t.on("data",u=>{if(!l){if(c+=u.length,c>pn){l=!0,t.destroy(),r(new Error(`Response body too large (>${pn} bytes) for ${e}`));return}o.push(u)}}),t.on("end",()=>{l||n(Buffer.concat(o).toString("utf-8").trim())}),t.on("error",u=>{l||r(u)})}async function Er(t){let e={instanceId:"",instanceName:"",localIpv4:""};try{let n=hn.join(t,"openclaw.json"),r=await re.readFile(n,"utf8"),m=JSON.parse(r).plugins?.entries?.[nt]?.config?.instance_metadata;if(!m)return e;let _=S=>typeof S=="string"&&S.trim()?S.trim():"";return{instanceId:_(m.instance_id),instanceName:_(m.instance_name),localIpv4:_(m.local_ipv4)}}catch{return e}}var gn=50,Mr=5e3;async function Nr(t,e){let n=Date.now()+e;for(;Date.now()<n;){let r=null;try{return r=await re.open(t,re.constants.O_CREAT|re.constants.O_EXCL|re.constants.O_WRONLY),await r.writeFile(String(process.pid),"utf8"),await r.close(),r=null,!0}catch(o){if(r!==null){try{await r.close()}catch{}try{await re.unlink(t)}catch{}r=null,await new Promise(u=>setTimeout(u,gn*10));continue}if(o.code!=="EEXIST")return!1;if(await Pr(t)){try{await re.unlink(t)}catch{}continue}await new Promise(u=>setTimeout(u,gn))}}return!1}async function Pr(t){try{let e=await re.readFile(t,"utf8"),n=parseInt(e.trim(),10);if(isNaN(n)||n<=0)return!0;try{return process.kill(n,0),!1}catch(r){return r.code==="ESRCH"}}catch{return!1}}async function Ar(t){try{await re.unlink(t)}catch{}}async function Ut(t,e,n){let r={};if(e.instanceId&&(r.instance_id=e.instanceId),e.instanceName&&(r.instance_name=e.instanceName),Object.keys(r).length===0)return;let o=hn.join(t,"openclaw.json"),c=o+".lock",l=o+".tmp";if(!await Nr(c,Mr)){n?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6 openclaw.json \u6587\u4EF6\u9501\u8D85\u65F6\uFF0C\u8DF3\u8FC7\u672C\u6B21\u5199\u5165");return}try{let g={};try{let P=await re.readFile(o,"utf8");g=JSON.parse(P)}catch{}(!g.plugins||typeof g.plugins!="object")&&(g.plugins={});let m=g.plugins;(!m.entries||typeof m.entries!="object")&&(m.entries={});let _=m.entries;(!_[nt]||typeof _[nt]!="object")&&(_[nt]={});let S=_[nt];(!S.config||typeof S.config!="object")&&(S.config={});let C=S.config,E=C.instance_metadata;C.instance_metadata={...E??{},...r};let N=JSON.stringify(g,null,2)+`
|
|
2
|
+
`;await re.writeFile(l,N,"utf8");try{await re.rename(l,o)}catch(P){if(P.code==="EXDEV"){await re.copyFile(l,o);try{await re.unlink(l)}catch{}}else throw P}n?.debug(`diagnostics-metrics/instance-metadata: \u5B9E\u4F8B\u5143\u6570\u636E\u5DF2\u6301\u4E45\u5316\u5199\u5165 openclaw.json (${Object.keys(r).join(", ")})`)}catch(g){try{await re.unlink(l)}catch{}n?.warn(`diagnostics-metrics/instance-metadata: \u5199\u5165\u5B9E\u4F8B\u5143\u6570\u636E\u5230 openclaw.json \u5931\u8D25: ${String(g)}`)}finally{await Ar(c)}}function In(){let t;try{t=Bt.networkInterfaces()}catch{return""}let e=[];for(let[r,o]of Object.entries(t))if(o)for(let c of o)c.family!=="IPv4"||c.internal||c.address.startsWith("169.254.")||e.push({iface:r,address:c.address});if(e.length===0)return"";let n=r=>r.startsWith("eth")?0:r.startsWith("en")?1:2;return e.sort((r,o)=>{let c=n(r.iface),l=n(o.iface);return c!==l?c-l:r.iface<o.iface?-1:r.iface>o.iface?1:0}),e[0].address}async function jt(t){let e=ge,n=!e.cvmInstanceId,r=!e.cvmInstanceName,[o,c]=await Promise.all([n?mn(Dt("instance-id")):Promise.resolve({status:"skipped"}),r?mn(Dt("instance-name")):Promise.resolve({status:"skipped"})]),l=e.hostName;try{l=Bt.hostname()}catch{t?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6 hostname \u5931\u8D25")}let u=In(),g={},m={...e,hostName:l||e.hostName};o.status==="fulfilled"&&o.value?(m.cvmInstanceId=o.value,g.instanceId=o.value):o.status==="rejected"?t?.warn(`diagnostics-metrics/instance-metadata: \u83B7\u53D6 instance-id \u5931\u8D25: ${String(o.reason)}`):o.status==="fulfilled"&&t?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6 instance-id \u5931\u8D25: empty response"),c.status==="fulfilled"&&c.value?(m.cvmInstanceName=c.value,g.instanceName=c.value):c.status==="rejected"?t?.warn(`diagnostics-metrics/instance-metadata: \u83B7\u53D6 instance-name \u5931\u8D25: ${String(c.reason)}`):c.status==="fulfilled"&&t?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6 instance-name \u5931\u8D25: empty response"),u?m.cvmInstanceIntraIp=u:t?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6\u672C\u5730\u975E\u73AF\u56DE IPv4 \u5730\u5740\u5931\u8D25: \u672A\u627E\u5230\u53EF\u7528\u7F51\u7EDC\u63A5\u53E3"),ge=Object.freeze(m);let _=!!m.cvmInstanceId&&!!m.cvmInstanceName;return t?.debug(`diagnostics-metrics/instance-metadata: \u5F53\u524D\u5B9E\u4F8B\u4FE1\u606F cvm_instance_id=${ge.cvmInstanceId}, cvm_instance_name=${ge.cvmInstanceName}, cvm_instance_intra_ip=${ge.cvmInstanceIntraIp}, host_name=${ge.hostName}`),{allSuccess:_,fetched:g}}function mn(t){return t.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))}function _e(){return ge}function wn(t,e,n){if(!rt){e?.warn("diagnostics-metrics/instance-metadata: updateInstanceMetadata \u8C03\u7528\u65F6\u6A21\u5757\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u672C\u6B21\u70ED\u66F4\u65B0\u5DF2\u8DF3\u8FC7");return}let r=ge,o=t.instanceId!==void 0?t.instanceId:r.cvmInstanceId,c=t.instanceName!==void 0?t.instanceName:r.cvmInstanceName,l=t.localIpv4!==void 0?t.localIpv4:r.cvmInstanceIntraIp;if(o===r.cvmInstanceId&&c===r.cvmInstanceName&&l===r.cvmInstanceIntraIp)return;ge=Object.freeze({cvmInstanceId:o,cvmInstanceName:c,cvmInstanceIntraIp:l,hostName:r.hostName}),(!o||!c)&&(e?.debug("diagnostics-metrics/instance-metadata: \u70ED\u66F4\u65B0\u6E05\u7A7A\u4E86\u90E8\u5206\u5B57\u6BB5\uFF0C\u91CD\u65B0\u89E6\u53D1 metadata \u63A5\u53E3\u83B7\u53D6"),st=0,Re&&(clearTimeout(Re),Re=null),jt(e).then(({allSuccess:g,fetched:m})=>{it||(n&&(m.instanceId||m.instanceName)&&Ut(n,m,e),g||Jt(e,n))}))}async function Tt(t,e){if(ot++,!rt){it=!1,rt=!0;try{let n="";try{n=Bt.hostname()}catch{}let r=e?await Er(e):{instanceId:"",instanceName:"",localIpv4:""},o=r.localIpv4||In();o||t?.warn("diagnostics-metrics/instance-metadata: \u83B7\u53D6\u672C\u5730\u975E\u73AF\u56DE IPv4 \u5730\u5740\u5931\u8D25: \u672A\u627E\u5230\u53EF\u7528\u7F51\u7EDC\u63A5\u53E3");let c={cvmInstanceId:r.instanceId,cvmInstanceName:r.instanceName,cvmInstanceIntraIp:o,hostName:n};if(ge=Object.freeze(c),c.cvmInstanceId&&c.cvmInstanceName){t?.debug(`diagnostics-metrics/instance-metadata: \u5F53\u524D\u5B9E\u4F8B\u4FE1\u606F cvm_instance_id=${c.cvmInstanceId}, cvm_instance_name=${c.cvmInstanceName}, cvm_instance_intra_ip=${c.cvmInstanceIntraIp}, host_name=${c.hostName}`);return}let{allSuccess:l,fetched:u}=await jt(t);if(e&&(u.instanceId||u.instanceName)&&await Ut(e,u,t),!l){t?.warn("diagnostics-metrics/instance-metadata: \u9996\u6B21\u83B7\u53D6\u5B58\u5728\u672A\u5C31\u7EEA\u5B57\u6BB5\uFF0C\u53EF\u80FD\u4E0D\u5728\u817E\u8BAF\u4E91\u73AF\u5883\uFF0C\u5C06\u5728 30 \u79D2\u540E\u91CD\u8BD5"),Jt(t,e);return}}catch(n){throw rt=!1,ot--,n}}}function Jt(t,e){if(st>=Kt){t?.warn(`diagnostics-metrics/instance-metadata: \u5DF2\u91CD\u8BD5 ${Kt} \u6B21\u4ECD\u672A\u6210\u529F\uFF0C\u505C\u6B62\u91CD\u8BD5`);return}Re=setTimeout(async()=>{if(it)return;st++,t?.debug(`diagnostics-metrics/instance-metadata: \u7B2C ${st}/${Kt} \u6B21\u91CD\u8BD5\u83B7\u53D6\u5143\u6570\u636E`);let{allSuccess:n,fetched:r}=await jt(t);if(!it&&(e&&(r.instanceId||r.instanceName)&&await Ut(e,r,t),!n)){Jt(t,e);return}},Cr),typeof Re.unref=="function"&&Re.unref()}function at(){ot!==0&&(ot--,!(ot>0)&&(it=!0,Re&&(clearTimeout(Re),Re=null),st=0,rt=!1,ge=yn))}import{createCipheriv as Lr,createDecipheriv as Or,createHash as xr,randomBytes as Fr}from"node:crypto";var ct="ENC:",Kr="openclaw-diag-metrics-cls",_n="aes-256-cbc";function Tn(){return xr("sha256").update(Kr).digest()}function Wt(t){if(!t||t.startsWith(ct))return t;let e=Tn(),n=Fr(16),r=Lr(_n,e,n),o=Buffer.concat([r.update(t,"utf8"),r.final()]),c=Buffer.concat([n,o]).toString("base64");return`${ct}${c}`}function ee(t){if(!t||!t.startsWith(ct))return t;try{let e=t.slice(ct.length),n=Buffer.from(e,"base64");if(n.length<17)return console.error(`[crypto-utils] \u89E3\u5BC6\u5931\u8D25: \u5BC6\u6587\u6570\u636E\u4E0D\u5B8C\u6574 (\u957F\u5EA6=${n.length}), \u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u52A0\u5BC6\u5B57\u6BB5\u662F\u5426\u88AB\u7BE1\u6539\u6216\u622A\u65AD`),"";let r=n.subarray(0,16),o=n.subarray(16),c=Tn(),l=Or(_n,c,r);return Buffer.concat([l.update(o),l.final()]).toString("utf8")}catch(e){let n=e instanceof Error?e.message:String(e);return console.error(`[crypto-utils] \u89E3\u5BC6\u5931\u8D25: ${n}, \u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684\u52A0\u5BC6\u5B57\u6BB5\u662F\u5426\u6B63\u786E`),""}}function qt(t){return typeof t=="string"&&t.startsWith(ct)}var je="clawpro-diagnostics-metrics-cls";import ke from"node:path";import Xt from"node:fs/promises";import{createRequire as Ur}from"node:module";import{pathToFileURL as jr}from"node:url";var Jr=300*1e3;function Sn(t){return t?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t):!0}function Wr(t){let e=typeof t?.metricTopicId=="string"?t.metricTopicId.trim():"",n=typeof t?.endpoint=="string"?t.endpoint.trim():"",r=typeof t?.credentialMode=="string"&&t.credentialMode.trim()==="cvmRole"?"cvmRole":"static",o=typeof t?.roleName=="string"&&t.roleName.trim()?t.roleName.trim():"",c=typeof t?.secretId=="string"?ee(t.secretId.trim()):"",l=typeof t?.secretKey=="string"?ee(t.secretKey.trim()):"",u=typeof t?.token=="string"?t.token.trim():void 0;if(e&&!Sn(e)&&(e=""),r==="static"&&(!c||!l)||r==="cvmRole"&&!o)return null;let g=typeof t?.credentialRefreshIntervalMs=="number"&&t.credentialRefreshIntervalMs>=6e4?t.credentialRefreshIntervalMs:Jr,m=t?.enableReport!==!1;return{metricTopicId:e,credentialMode:r,roleName:o,secretId:c,secretKey:l,token:u,endpoint:n,credentialRefreshIntervalMs:g,enableReport:m}}var qr=1e4;async function Xr(t){try{let e=await Xt.readFile(t,"utf8"),l=JSON.parse(e).plugins?.entries?.[je]?.config,u=l?.cls,g=typeof u?.metricTopicId=="string"?u.metricTopicId.trim():"",m=typeof u?.endpoint=="string"?u.endpoint.trim():"",_=u?.enableReport!==!1,S=typeof u?.secretId=="string"?ee(u.secretId.trim()):"",C=typeof u?.secretKey=="string"?ee(u.secretKey.trim()):"",E=g;g&&!Sn(g)&&(E=void 0);let N=l?.instance_metadata,P=L=>typeof L!="string"?null:L.trim(),w=N?P(N.instance_id):null,K=N?P(N.instance_name):null,x=N?P(N.local_ipv4):null,F=w??"",$=K??"",I=x??"",M=l?.log,A=M?.enableLogReport===!0,R=typeof M?.logTopicId=="string"?M.logTopicId.trim():"";return{metricTopicId:E,endpoint:m,enableReport:_,secretId:S,secretKey:C,instanceId:F,instanceName:$,localIpv4:I,enableLogReport:A,logTopicId:R}}catch{return null}}function bn(t,e){return!t||!e?"":`https://${t}/prometheus/${e}/api/v1/write`}function Rn(t){return t instanceof Error?t.stack??t.message:typeof t=="string"?t:String(t)}async function Gr(t){let e=ke.join(t.stateDir,"openclaw.json"),n;try{n=await Xt.readFile(e,"utf8")}catch{return}let r;try{r=JSON.parse(n)}catch{return}let o=!1,c=r.diagnostics;c?.enabled!==!0&&(r.diagnostics={...c??{},enabled:!0},o=!0,t.logger.debug?.("diagnostics-metrics/prometheus: \u5DF2\u81EA\u52A8\u5199\u5165 diagnostics.enabled=true \u5230 openclaw.json\uFF0C\u91CD\u542F\u540E\u751F\u6548"));let _=r.plugins?.entries?.[je]?.config?.cls;if(_){let S=_.secretId,C=_.secretKey;typeof S=="string"&&S.trim()&&!qt(S.trim())&&(_.secretId=Wt(S.trim()),o=!0,t.logger.debug?.("diagnostics-metrics/prometheus: \u5DF2\u5C06 secretId \u52A0\u5BC6\u540E\u5199\u5165\u914D\u7F6E\u6587\u4EF6")),typeof C=="string"&&C.trim()&&!qt(C.trim())&&(_.secretKey=Wt(C.trim()),o=!0,t.logger.debug?.("diagnostics-metrics/prometheus: \u5DF2\u5C06 secretKey \u52A0\u5BC6\u540E\u5199\u5165\u914D\u7F6E\u6587\u4EF6"))}o&&await Xt.writeFile(e,JSON.stringify(r,null,2)+`
|
|
3
|
+
`,"utf8")}function kn(t,e,n){let r=Wr(t),o=null,c=null,l=[],u=null,g=null,m=null,_=null,S="",C="",E=!0,N="",P="",w="",K="",x="",F=!1,$="";return{id:"clawpro-diagnostics-metrics-cls",getExports(){return g},async start(I){let M={debug:I.logger.debug??(()=>{}),info:I.logger.info.bind(I.logger),warn:I.logger.warn.bind(I.logger),error:I.logger.error.bind(I.logger)},A=t;if(A?.enabled===!1)return;let R=A?.metric_prefix??"openclaw",L={...A?.external_labels??{}};await Tt(M,I.stateDir).catch(y=>{let O=y instanceof Error?y.message:String(y);I.logger.warn(`diagnostics-metrics/prometheus: \u5B9E\u4F8B\u5143\u6570\u636E\u5B9A\u65F6\u5237\u65B0\u542F\u52A8\u5931\u8D25 (${O})\uFF0C\u5C06\u4F7F\u7528 unknown \u4F5C\u4E3A\u9ED8\u8BA4\u503C`)}),await Gr(I).catch(()=>{I.logger.warn('diagnostics-metrics/prometheus: \u65E0\u6CD5\u81EA\u52A8\u5199\u5165 diagnostics.enabled\uFF0C\u8BF7\u624B\u52A8\u5728 openclaw.json \u4E2D\u6DFB\u52A0 { "diagnostics": { "enabled": true } }')}),o=new Dr,A?.default_metrics!==!1&&Br({register:o,prefix:`${R}_node_`});let D=new pe({name:`${R}_tokens_total`,help:"Total tokens consumed",labelNames:["openclaw_type","openclaw_provider","openclaw_model","openclaw_channel"],registers:[o]}),W=new pe({name:`${R}_cost_usd_total`,help:"Estimated model cost in USD",labelNames:["openclaw_provider","openclaw_model","openclaw_channel"],registers:[o]}),Y=new Je({name:`${R}_run_duration_ms`,help:"Agent run duration in milliseconds",labelNames:["openclaw_provider","openclaw_model","openclaw_channel"],buckets:[100,250,500,1e3,2500,5e3,1e4,3e4,6e4],registers:[o]}),ce=new Je({name:`${R}_context_tokens`,help:"Context window token count",labelNames:["openclaw_provider","openclaw_model","openclaw_channel","openclaw_type"],buckets:[1e3,4e3,8e3,16e3,32e3,64e3,128e3,2e5],registers:[o]}),ye=new pe({name:`${R}_webhook_received_total`,help:"Webhook requests received",labelNames:["openclaw_channel","openclaw_update_type"],registers:[o]}),xe=new pe({name:`${R}_webhook_error_total`,help:"Webhook processing errors",labelNames:["openclaw_channel","openclaw_update_type"],registers:[o]}),k=new Je({name:`${R}_webhook_duration_ms`,help:"Webhook processing duration in milliseconds",labelNames:["openclaw_channel","openclaw_update_type"],buckets:[10,50,100,250,500,1e3,2500,5e3],registers:[o]}),Fe=new pe({name:`${R}_message_queued_total`,help:"Messages queued for processing",labelNames:["openclaw_channel","openclaw_source"],registers:[o]}),Ie=new pe({name:`${R}_message_processed_total`,help:"Messages processed by outcome",labelNames:["openclaw_channel","openclaw_outcome"],registers:[o]}),fe=new Je({name:`${R}_message_duration_ms`,help:"Message processing duration in milliseconds",labelNames:["openclaw_channel","openclaw_outcome"],buckets:[100,500,1e3,2500,5e3,1e4,3e4,6e4],registers:[o]}),gt=new bt({name:`${R}_queue_depth`,help:"Current queue depth per lane",labelNames:["openclaw_lane"],registers:[o]}),$t=new Je({name:`${R}_queue_wait_ms`,help:"Queue wait time before execution in milliseconds",labelNames:["openclaw_lane"],buckets:[10,50,100,500,1e3,5e3,1e4],registers:[o]}),q=new pe({name:`${R}_queue_lane_enqueue_total`,help:"Queue lane enqueue events",labelNames:["openclaw_lane"],registers:[o]}),Ke=new pe({name:`${R}_queue_lane_dequeue_total`,help:"Queue lane dequeue events",labelNames:["openclaw_lane"],registers:[o]}),Et=new pe({name:`${R}_session_state_total`,help:"Session state transitions",labelNames:["openclaw_state","openclaw_reason"],registers:[o]}),mt=new pe({name:`${R}_session_stuck_total`,help:"Sessions detected as stuck",labelNames:["openclaw_state"],registers:[o]}),ht=new Je({name:`${R}_session_stuck_age_ms`,help:"Age of stuck sessions in milliseconds",labelNames:["openclaw_state"],buckets:[1e3,5e3,1e4,3e4,6e4,12e4,3e5],registers:[o]}),yt=new pe({name:`${R}_run_attempt_total`,help:"Agent run attempts",labelNames:["openclaw_attempt"],registers:[o]}),It=new bt({name:`${R}_active_sessions`,help:"Number of currently active sessions",registers:[o]}),Mt=new bt({name:`${R}_waiting_sessions`,help:"Number of sessions in waiting state",registers:[o]}),Nt=new bt({name:`${R}_queued_messages`,help:"Total messages currently queued",registers:[o]}),Pt=new pe({name:`${R}_tool_loop_total`,help:"Tool loop detections",labelNames:["openclaw_tool","openclaw_detector","openclaw_level","openclaw_action"],registers:[o]}),Ve=y=>{try{switch(y.type){case"model.usage":{let O={openclaw_provider:y.provider??"unknown",openclaw_model:y.model??"unknown",openclaw_channel:y.channel??"unknown"},J=y.usage;if(!J)break;J.input&&D.inc({...O,openclaw_type:"input"},J.input),J.output&&D.inc({...O,openclaw_type:"output"},J.output),J.cacheRead&&D.inc({...O,openclaw_type:"cache_read"},J.cacheRead),J.cacheWrite&&D.inc({...O,openclaw_type:"cache_write"},J.cacheWrite),J.promptTokens&&D.inc({...O,openclaw_type:"prompt"},J.promptTokens),J.total&&D.inc({...O,openclaw_type:"total"},J.total),y.costUsd&&W.inc({openclaw_provider:O.openclaw_provider,openclaw_model:O.openclaw_model,openclaw_channel:O.openclaw_channel},y.costUsd),y.durationMs&&Y.observe({openclaw_provider:O.openclaw_provider,openclaw_model:O.openclaw_model,openclaw_channel:O.openclaw_channel},y.durationMs),y.context?.limit&&ce.observe({openclaw_provider:O.openclaw_provider,openclaw_model:O.openclaw_model,openclaw_channel:O.openclaw_channel,openclaw_type:"limit"},y.context.limit),y.context?.used&&ce.observe({openclaw_provider:O.openclaw_provider,openclaw_model:O.openclaw_model,openclaw_channel:O.openclaw_channel,openclaw_type:"used"},y.context.used);break}case"webhook.received":{ye.inc({openclaw_channel:y.channel??"unknown",openclaw_update_type:y.updateType??"unknown"});break}case"webhook.processed":{typeof y.durationMs=="number"&&k.observe({openclaw_channel:y.channel??"unknown",openclaw_update_type:y.updateType??"unknown"},y.durationMs);break}case"webhook.error":{xe.inc({openclaw_channel:y.channel??"unknown",openclaw_update_type:y.updateType??"unknown"});break}case"message.queued":{Fe.inc({openclaw_channel:y.channel??"unknown",openclaw_source:y.source??"unknown"});break}case"message.processed":{Ie.inc({openclaw_channel:y.channel??"unknown",openclaw_outcome:y.outcome??"unknown"}),typeof y.durationMs=="number"&&fe.observe({openclaw_channel:y.channel??"unknown",openclaw_outcome:y.outcome??"unknown"},y.durationMs);break}case"queue.lane.enqueue":{q.inc({openclaw_lane:y.lane}),gt.set({openclaw_lane:y.lane},y.queueSize??0);break}case"queue.lane.dequeue":{Ke.inc({openclaw_lane:y.lane}),gt.set({openclaw_lane:y.lane},y.queueSize??0),typeof y.waitMs=="number"&&$t.observe({openclaw_lane:y.lane},y.waitMs);break}case"session.state":{Et.inc({openclaw_state:y.state,openclaw_reason:y.reason??""});break}case"session.stuck":{mt.inc({openclaw_state:y.state}),typeof y.ageMs=="number"&&ht.observe({openclaw_state:y.state},y.ageMs);break}case"run.attempt":{yt.inc({openclaw_attempt:String(y.attempt)});break}case"diagnostic.heartbeat":{It.set(y.active??0),Mt.set(y.waiting??0),Nt.set(y.queued??0);break}case"tool.loop":{Pt.inc({openclaw_tool:y.toolName,openclaw_detector:y.detector,openclaw_level:y.level,openclaw_action:y.action});break}}}catch(O){I.logger.error(`diagnostics-metrics/prometheus: event handler failed (${y.type}): ${Rn(O)}`)}},Te;try{let y=async(ne,Q)=>{let se=[ke.join(ne,Q+".js"),ke.join(ne,Q)];for(let $e of se)try{return await import(jr($e).href)}catch{}},O=async ne=>{let Q=await y(ne,"plugin-sdk/diagnostics-otel");if(Q?.onDiagnosticEvent)return Q.onDiagnosticEvent;let se=await y(ne,"plugin-sdk/diagnostic-runtime");if(se?.onDiagnosticEvent)return se.onDiagnosticEvent},J=ke.dirname(new URL(import.meta.url).pathname),{existsSync:de,readFileSync:be}=await import("node:fs"),ue=J;for(let ne=0;ne<8&&!Te;++ne){let Q=ke.dirname(ue);if(Q===ue)break;ue=Q;let se=ke.join(ue,"plugin-sdk"),$e=ke.join(ue,"package.json");try{if(!de(se)||!de($e)||JSON.parse(be($e,"utf-8")).name!=="openclaw")continue;Te=await O(ue)}catch{}}if(!Te)try{let Q=Ur(import.meta.url).resolve("openclaw/package.json"),se=ke.dirname(Q);Te=await O(se)}catch{}}catch(y){I.logger.warn(`diagnostics-metrics/prometheus: \u65E0\u6CD5\u89E3\u6790 openclaw \u5305\u8DEF\u5F84\uFF0ConDiagnosticEvent \u4E0D\u53EF\u7528: ${y instanceof Error?y.message:String(y)}`)}Te?c=Te(Ve):I.logger.warn("diagnostics-metrics/prometheus: onDiagnosticEvent \u5728\u5F53\u524D openclaw \u7248\u672C\u4E2D\u4E0D\u53EF\u7528\uFF0C\u6307\u6807\u91C7\u96C6\u5DF2\u8DF3\u8FC7");let Ye=r?.metricTopicId??"",wt=r?.endpoint??"";S=Ye,C=wt,E=r?.enableReport??!0,N=r?.secretId??"",P=r?.secretKey??"",w=_e().cvmInstanceId,K=_e().cvmInstanceName,x=_e().cvmInstanceIntraIp;let Me=A?.remote_write??[],we=r?.credentialMode??"static",sn=r?.roleName||"",At=ke.join(I.stateDir,"openclaw.json"),De=async()=>e?(I.logger.warn("diagnostics-metrics/prometheus: \u6536\u5230 401\uFF0C\u901A\u8FC7\u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u68C0\u67E5\u5E76\u5237\u65B0\u4E34\u65F6\u5BC6\u94A5"),await e.forceRefresh()):we==="cvmRole"?(I.logger.warn("diagnostics-metrics/prometheus: \u6536\u5230 401\uFF0C\u4F46\u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u4E0D\u53EF\u7528"),!1):(I.logger.warn("diagnostics-metrics/prometheus: \u6536\u5230 401\uFF0C\u5F53\u524D\u4E3A static \u51ED\u8BC1\u6A21\u5F0F\uFF0C\u8BF7\u68C0\u67E5 secretId/secretKey \u662F\u5426\u6B63\u786E"),!1),G=bn(C,S),ve=Me.some(y=>!y.url),Qe=Me.some(y=>y.url);if(G&&ve&&!Qe){let y=Me.find(O=>!O.url);y&&(l=[new Le({...y,url:G},M,De)])}else G&&Me.length===0?l=[new Le({url:G},M,De)]:l=Me.filter(y=>y.url).map(y=>new Le(y,M,De));let Ce=A?.push_interval_ms??3e4;if(l.length>0&&E?(u=setInterval(()=>{St(o,l,L,M)},Ce),typeof u.unref=="function"&&u.unref(),I.logger.debug?.(`diagnostics-metrics/prometheus: remote write enabled for ${l.length} target(s), push interval ${Ce}ms`)):l.length>0&&!E&&I.logger.debug?.("diagnostics-metrics/prometheus: remote write clients created but pushTimer not started (enableReport=false)"),we==="static"&&r&&l.length>0&&!e){let y=r.secretKey;r.token!==void 0&&r.token!==""&&(y=y+"#"+r.token);let O={username:r.secretId,password:y};for(let J of l)J.updateConfig({basic_auth:O});I.logger.debug?.("diagnostics-metrics/prometheus: static \u51ED\u8BC1\u6A21\u5F0F\uFF08\u65E0\u5171\u4EAB\u7BA1\u7406\u5668\uFF09\uFF0C\u5DF2\u8BBE\u7F6E basic_auth")}let Ne=y=>{let O=y.secretKey;y.token!==void 0&&y.token!==""&&(O=O+"#"+y.token);let J={username:y.secretId,password:O};for(let de of l)de.updateConfig({basic_auth:J});l.length>0&&!u&&E&&(u=setInterval(()=>{St(o,l,L,M)},Ce),typeof u.unref=="function"&&u.unref(),I.logger.debug?.("diagnostics-metrics/prometheus: \u51ED\u8BC1\u66F4\u65B0\u6210\u529F\uFF0C\u5DF2\u6062\u590D remote write \u63A8\u9001"))};if(e&&l.length>0){let y=e.getCredentialSnapshot();y.secretId&&y.secretKey&&Ne(y),_=e.subscribe(O=>{Ne(O),I.logger.debug?.("diagnostics-metrics/prometheus: \u5171\u4EAB\u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0C\u5DF2\u540C\u6B65\u5230 RemoteWriteClient")}),I.logger.debug?.("diagnostics-metrics/prometheus: \u5DF2\u8BA2\u9605\u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u7684\u51ED\u8BC1\u53D8\u66F4\u4E8B\u4EF6")}let Be=!1;m=setInterval(()=>{(async()=>{if(!Be){Be=!0;try{let y=await Xr(At);if(!y)return;let O=y.metricTopicId??Ye,J=y.endpoint??wt,de=y.enableReport,be=y.secretId,ue=y.secretKey,ne=y.instanceId,Q=y.instanceName,se=y.localIpv4,$e=O!==S,s=J!==C,a=_e();!w&&a.cvmInstanceId&&(w=a.cvmInstanceId),!K&&a.cvmInstanceName&&(K=a.cvmInstanceName),!x&&a.cvmInstanceIntraIp&&(x=a.cvmInstanceIntraIp);let f=ne!==w||Q!==K||se!==x,d=de!==E,i=we==="static"&&be&&ue&&(be!==N||ue!==P);if(f&&(w=ne,K=Q,x=se,wn({instanceId:ne,instanceName:Q,localIpv4:se},M,I.stateDir),I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Cinstance_metadata \u5DF2\u66F4\u65B0 (instance_id=${w}, instance_name=${K}, local_ipv4=${x})`)),i){if(N=be,P=ue,e&&we==="static")e.updateStaticCredential(N,P);else if(l.length>0){let h=P;r?.token!==void 0&&r.token!==""&&(h=h+"#"+r.token);let T={username:N,password:h};for(let v of l)v.updateConfig({basic_auth:T})}I.logger.debug?.("diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Cstatic \u6A21\u5F0F\u5BC6\u94A5\u5DF2\u66F4\u65B0")}if(d&&(E=de,E?(l.length>0&&!u&&(u=setInterval(()=>{St(o,l,L,M)},Ce),typeof u.unref=="function"&&u.unref()),I.logger.debug?.("diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CenableReport=true\uFF0C\u5DF2\u6062\u590D remote write \u63A8\u9001")):(u&&(clearInterval(u),u=null),I.logger.debug?.("diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CenableReport=false\uFF0C\u5DF2\u6682\u505C remote write \u63A8\u9001"))),n){let h=y.enableLogReport,T=y.logTopicId;(h!==F||T!==$)&&(F=h,$=T,n(h,T),I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Clog \u914D\u7F6E\u5DF2\u53D8\u66F4\uFF08enableLogReport=${h}\uFF0ClogTopicId=${T||"(\u7A7A)"}\uFF09`))}if(!$e&&!s)return;S=O,C=J;let p=bn(C,S);if(!p){if(l.length>0){I.logger.debug?.("diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Cendpoint \u6216 metricTopicId \u4E3A\u7A7A\uFF0Cremote write \u5DF2\u6682\u505C");for(let h of l)h.stop().catch(()=>{});l=[],u&&(clearInterval(u),u=null)}return}if(l.length>0){for(let h of l)h.updateConfig({url:p});I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0C\u5DF2\u66F4\u65B0 RemoteWriteClient url=${p}`)}else{let h=new Le({url:p},M,De);if(l=[h],e){let T=e.getCredentialSnapshot();T.secretId&&T.secretKey&&Ne(T)}else we==="static"&&N&&P&&h.updateConfig({basic_auth:{username:N,password:P}});e&&!_&&(_=e.subscribe(T=>{Ne(T),I.logger.debug?.("diagnostics-metrics/prometheus: \u5171\u4EAB\u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0C\u5DF2\u540C\u6B65\u5230 RemoteWriteClient")})),E&&!u&&(u=setInterval(()=>{St(o,l,L,M)},Ce),typeof u.unref=="function"&&u.unref()),I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0C\u52A8\u6001\u521B\u5EFA RemoteWriteClient url=${p}`)}}finally{Be=!1}}})()},qr),m&&typeof m.unref=="function"&&m.unref(),g=A?.pull!==!1?{registry:o}:null,I.logger.debug?.(`diagnostics-metrics/prometheus: started (pull=${A?.pull!==!1}, remote_write=${l.length} targets, metricTopicId=${S||"(\u5F85\u914D\u7F6E\u6587\u4EF6\u6CE8\u5165)"}, endpoint=${C||"(\u5F85\u914D\u7F6E\u6587\u4EF6\u6CE8\u5165)"})`)},async stop(){c?.(),c=null,m&&(clearInterval(m),m=null),_&&(_(),_=null),u&&(clearInterval(u),u=null);for(let I of l)await I.stop().catch(()=>{});l=[],at(),o&&(o.clear(),o=null),g=null,S="",C="",E=!0,N="",P="",w="",K="",x=""}}}async function St(t,e,n,r){if(e.length!==0)try{let o=_e(),c={...n};c.cvm_instance_id||(c.cvm_instance_id=o.cvmInstanceId),c.cvm_instance_name||(c.cvm_instance_name=o.cvmInstanceName),c.cvm_instance_intra_ip||(c.cvm_instance_intra_ip=o.cvmInstanceIntraIp),c.host_name||(c.host_name=o.hostName);let l=await t.getMetricsAsJSON(),u=Date.now(),g=[];for(let m of l){let _=m.values;for(let S of _){let E=[{name:"__name__",value:S.metricName??m.name}];for(let[N,P]of Object.entries(c))E.push({name:N,value:P});if(S.labels)for(let[N,P]of Object.entries(S.labels))E.push({name:N,value:String(P)});E.sort((N,P)=>N.name.localeCompare(P.name)),g.push({labels:E,samples:[{value:S.value??0,timestampMs:u}]})}}if(g.length===0)return;for(let m of e)m.enqueue(g)}catch(o){r.error(`diagnostics-metrics/prometheus: failed to collect metrics for push: ${Rn(o)}`)}}import{Producer as kt}from"tencentcloud-cls-sdk-nodejs";import{hostname as Gn}from"node:os";import{basename as is,join as as}from"node:path";var b="[diagnostics-metrics-cls/trace]",Oe=32e5,lt=4096,Gt=20,vn=3e3,Ht=1200*1e3,Cn=600*1e3,$n=1e4,En=je,Mn="__temp_run_",Nn=15e3,Pn=1e4,zt=300*1e3,An=5e3;import{randomBytes as Hr}from"crypto";function te(t=16){let e=Math.ceil(t/2);return Hr(e).toString("hex").slice(0,t)}function me(t){return t.length>Oe?t.substring(0,Oe):t}function On(t){let e=JSON.stringify(t);if(e.length<=Oe)return e;let n=Yt(t),r=zr(n.length),o=64;for(let l=0;l<20;l++){let u=JSON.stringify(n);if(u.length<=Oe)return u;let g=!1;for(let m of r){let _=n[m];if(_&&Vr(_,o)){g=!0;break}}if(!g)break}let c=Yr(n);return JSON.stringify(c)}function zr(t){let e=[];if(t<=0)return e;let n=Math.floor(t/2);e.push(n);for(let r=1;r<=t;r++){let o=n-r,c=n+r;c<t&&e.push(c),o>=0&&e.push(o)}return e}function Vr(t,e){let n=null,r=(u,g)=>{typeof u=="string"&&(u.length<=e||(!n||u.length>n.value.length)&&(n={set:g,value:u}))};if(r(t.content,u=>{t.content=u}),Array.isArray(t.tool_calls))for(let u of t.tool_calls)!u||typeof u!="object"||r(u.arguments,g=>{u.arguments=g});if(!n)return!1;let o=n,c=o.value,l=Math.max(e,Math.floor(c.length/2));return l>=c.length?!1:(o.set(c.slice(0,l)+`... [truncated, total ${c.length} chars]`),!0)}function Yr(t){if(t.length<=2)return t.map(l=>Ln(l,2048));let e=t[0],n=Math.min(5,t.length-1),r=null;for(;n>=1;){let l=t.slice(t.length-n),u=t.length-1-n,g=t.slice(1,t.length-n).reduce((C,E)=>C+JSON.stringify(E).length,0),m={role:"system",content:`[...omitted ${u} messages, total ${g} chars]`},_=[e,m,...l];if(JSON.stringify(_).length<=Oe)return _;r=_,n--}let o=r??[e,t[t.length-1]],c=Math.max(1024,Math.floor((Oe-256)/Math.max(1,o.length)));return o.map(l=>Ln(l,c))}function Ln(t,e){let n={...t};return typeof n.content=="string"&&n.content.length>e&&(n.content=n.content.slice(0,e)+`... [truncated, total ${n.content.length} chars]`),Array.isArray(n.tool_calls)&&(n.tool_calls=n.tool_calls.map(r=>{if(!r||typeof r!="object")return r;let o={...r};return typeof o.arguments=="string"&&o.arguments.length>e&&(o.arguments=o.arguments.slice(0,e)+`... [truncated, total ${o.arguments.length} chars]`),o})),n}function Vt(t,e=lt){return t?t.length<=e?t:t.slice(0,e)+`... [truncated, total ${t.length} chars]`:""}function Yt(t){return typeof globalThis.structuredClone=="function"?globalThis.structuredClone(t):We(t)}function We(t,e=new WeakMap){if(t===null||typeof t!="object")return t;let n=t;if(e.has(n))return e.get(n);if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(n instanceof Map){let o=new Map;e.set(n,o);for(let[c,l]of n)o.set(We(c,e),We(l,e));return o}if(n instanceof Set){let o=new Set;e.set(n,o);for(let c of n)o.add(We(c,e));return o}if(Array.isArray(n)){let o=[];e.set(n,o);for(let c=0;c<n.length;c++)o[c]=We(n[c],e);return o}let r={};e.set(n,r);for(let o of Object.keys(n))r[o]=We(n[o],e);return r}function xn(t){return t==null?[]:typeof t=="string"?[{type:"text",content:t}]:Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{type:"text",content:e};if(typeof e=="object"&&e!==null){let n=e;if(n.type==="toolCall"||n.type==="tool_call"||n.type==="function_call")return{type:"tool_call",id:n.id||n.toolCallId||null,name:n.name||n.toolName||"",arguments:n.arguments||n.input||n.params||null};if(n.type==="toolResult"||n.type==="tool_result"||n.type==="tool_call_response"){let r=n.response??n.result??n.content??"";return{type:"tool_call_response",id:n.id||n.toolCallId||null,response:typeof r=="string"?r:JSON.stringify(r)}}return n.type==="text"?{type:"text",content:String(n.content??n.text??"")}:n.type==="thinking"||n.type==="reasoning"?{type:"reasoning",content:String(n.content??n.thinking??"")}:n.type?n:{type:"text",content:JSON.stringify(e)}}return{type:"text",content:String(e)}}):[{type:"text",content:JSON.stringify(t)}]}function Fn(t){return me(JSON.stringify([{type:"text",content:t}]))}var Qr={toolResult:"tool",tool_result:"tool",function:"tool"};function Qt(t,e){let n=[];for(let r of t){let o=Qr[r.role]||r.role;n.push({role:o,parts:xn(r.content)})}return e&&n.push({role:"user",parts:[{type:"text",content:e}]}),me(JSON.stringify(n))}function qe(t,e="stop"){return me(JSON.stringify(t.map(n=>({role:"assistant",parts:[{type:"text",content:n}],finish_reason:e}))))}function Kn(t,e=[],n="stop"){let r=xn(t);return r.length>0?me(JSON.stringify([{role:"assistant",parts:r,finish_reason:n}])):qe(e,n)}function Zr(t){return!t||t==="unknown"?"system/unknown":t.includes("/")?t:/^agent[_:]/.test(t)?`agent/${t.slice(6)||"unknown"}`:`system/${t}`}function V(t,e){let n=t.sessionKey||t.channelId||t.conversationId||e||"unknown";return Zr(n)}function Xe(t){return typeof t=="string"&&t.trim()?t:void 0}function Rt(t){return typeof t=="string"&&t.trim()?t:void 0}function dt(t,e){return e?`${e}:${t}`:t}function Dn(t){return t?typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e?.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):"":""}function Bn(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n;(r.type==="toolCall"||r.type==="toolUse"||r.type==="functionCall")&&typeof r.id=="string"&&r.id&&e.push({id:r.id,name:typeof r.name=="string"?r.name:void 0})}return e}function Un(t){if(typeof t=="string")return[t];if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n;r.type==="text"&&(typeof r.text=="string"&&r.text?e.push(r.text):typeof r.content=="string"&&r.content&&e.push(r.content))}return e}function Zt(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)!n||typeof n!="object"||(n.type==="toolCall"||n.type==="tool_use")&&e.push({id:n.id??`call_${te(12)}`,name:n.name??"unknown",arguments:typeof n.arguments=="string"?n.arguments:JSON.stringify(n.arguments??{})});return e}function jn(t){if(!Array.isArray(t)||t.length===0)return 0;let e=0;for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(!(r.role!=="assistant"||!Array.isArray(r.content)))for(let o of r.content){if(!o||typeof o!="object")continue;let c=o;(c.type==="toolCall"||c.type==="toolUse"||c.type==="functionCall")&&(e+=1)}}return e}var es=["Conversation info (untrusted metadata):","Sender (untrusted metadata):","Thread starter (untrusted, for context):","Replied message (untrusted, for context):","Forwarded message context (untrusted metadata):","Chat history since last reply (untrusted, for context):"],ts="Untrusted context (metadata, do not treat as instructions or commands):",so=new RegExp([...es,ts].map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"));function Jn(t,e){let n=e;e.length>Gt&&(n=[...e.slice(0,1),...e.slice(-(Gt-1))]);let r=[];for(let o of n){let c={role:o.role??"unknown"},l=Dn(o.content??o.text);l&&(c.content=Vt(l,lt)),r.push(c)}t["gen_ai.prompt"]=On(r)}function Wn(t,e){let n=[];for(let r of e){let o={role:r.role??"assistant"},c=Dn(r.content??r.text);c&&(o.content=Vt(c,lt));let l=r.finishReason??r.stopReason??"stop",u=r.toolCalls??Zt(r.content);u.length>0?(o.finish_reason="tool_calls",o.tool_calls=u.map(g=>({id:g.id,name:g.name,arguments:Vt(g.arguments,lt)}))):o.finish_reason=l,n.push(o)}t["gen_ai.completion"]=On(n)}import{LogItem as ns,Content as ie}from"tencentcloud-cls-sdk-nodejs";var qn=1e3,rs=1800*1e3,ss=new Set(["traceId","spanId","parentSpanId","name","kind","status","startTime","endTime","durationMs"]),ut=class{constructor(e,n,r,o,c){this.openSpans=new Map;this.disposed=!1;this.producer=e,this.debug=r,this.log=o,this.getResourceAttrs=c??null}startSpan(e,n){if(!this.disposed){if(this.openSpans.size>=qn&&(this.sweepStaleOpenSpans(),this.openSpans.size>=qn)){let r=this.openSpans.keys().next().value;r&&(this.log.warn(`${b} openSpans size (${this.openSpans.size}) exceeded limit, evicting oldest span: ${r}`),this.openSpans.delete(r))}this.openSpans.set(n,{name:e.name,type:e.type,startTime:e.startTime,attributes:{...e.attributes},traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId}),this.debug&&this.log.info(`${b} Started long-lived span: name=${e.name}, spanId=${n}, traceId=${e.traceId}`)}}endSpanById(e,n,r){if(this.disposed)return;let o=this.openSpans.get(e);if(!o)return;if(r)for(let[l,u]of Object.entries(r))u!=null&&(o.attributes[l]=u);let c=n??Date.now();this.sendRecord({...o.attributes,traceId:o.traceId,spanId:o.spanId,parentSpanId:o.parentSpanId||"",name:o.name,kind:o.attributes["gen_ai.span.kind"]??this.mapSpanKind(o.type),status:"OK",startTime:new Date(o.startTime).toISOString(),endTime:new Date(c).toISOString(),durationMs:String(c-o.startTime)}),this.openSpans.delete(e),this.debug&&this.log.info(`${b} Ended long-lived span: spanId=${e}, duration=${c-o.startTime}ms`)}patchOpenSpanAttributes(e,n){if(this.disposed)return;let r=this.openSpans.get(e);if(r)for(let[o,c]of Object.entries(n))c!=null&&(r.attributes[o]=c)}export(e){if(this.disposed)return;let n=e.startTime||Date.now(),r=e.endTime||Date.now(),o=e.attributes.error===!0||!!e.attributes["error.type"];this.sendRecord({...e.attributes,traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId||"",name:e.name,kind:e.attributes["gen_ai.span.kind"]??this.mapSpanKind(e.type),status:o?"ERROR":"OK",startTime:new Date(n).toISOString(),endTime:new Date(r).toISOString(),durationMs:String(r-n)})}async flush(){if(!this.disposed)try{typeof this.producer.flush=="function"?await this.producer.flush():typeof this.producer.batchSend=="function"&&await this.producer.batchSend()}catch{}}get isDisposed(){return this.disposed}async dispose(){this.disposed=!0;let e=Date.now();for(let[,n]of this.openSpans)try{let r=e;this.sendRecordCore({...n.attributes,"openclaw.force_closed":!0,"openclaw.force_closed.reason":"dispose",traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId||"",name:n.name,kind:n.attributes["gen_ai.span.kind"]??this.mapSpanKind(n.type),status:"UNSET",startTime:new Date(n.startTime).toISOString(),endTime:new Date(r).toISOString(),durationMs:String(r-n.startTime)})}catch{}try{typeof this.producer.flush=="function"?await this.producer.flush():typeof this.producer.batchSend=="function"&&await this.producer.batchSend()}catch{}this.openSpans.clear()}sweepStaleOpenSpans(){let e=Date.now(),n=[];for(let[r,o]of this.openSpans)e-o.startTime>rs&&n.push(r);for(let r of n){let o=this.openSpans.get(r);if(o){try{this.sendRecord({...o.attributes,"openclaw.force_closed":!0,"openclaw.force_closed.reason":"stale_sweep",traceId:o.traceId,spanId:o.spanId,parentSpanId:o.parentSpanId||"",name:o.name,kind:o.attributes["gen_ai.span.kind"]??this.mapSpanKind(o.type),status:"UNSET",startTime:new Date(o.startTime).toISOString(),endTime:new Date(e).toISOString(),durationMs:String(e-o.startTime)})}catch{}this.debug&&this.log.info(`${b} Evicted stale open span (force-sent): spanId=${r}, name=${o.name}, age=${e-o.startTime}ms`)}this.openSpans.delete(r)}}updateProducer(e,n){let r=this.producer;this.producer=e;let o=5e3,c=async()=>{try{typeof r.flush=="function"?await r.flush():typeof r.batchSend=="function"&&await r.batchSend(),typeof r.close=="function"?await r.close():typeof r.shutdown=="function"?await r.shutdown():typeof r.destroy=="function"&&await r.destroy()}catch{}},l,u=new Promise(g=>{l=setTimeout(g,o)});Promise.race([c(),u]).finally(()=>{l!==void 0&&clearTimeout(l)}).catch(()=>{})}sendRecord(e){this.disposed||this.sendRecordCore(e)}sendRecordCore(e){try{let n=this.getResourceAttrs?.()??{},r=e.traceId||"",o=e.spanId||"",c=e.parentSpanId||"",l=e.name||"",u=e.kind||"INTERNAL",g=e.status||"OK",m=e.startTime,_=e.endTime,S=e.durationMs,C=m?new Date(m).getTime():Date.now(),E=_?new Date(_).getTime():Date.now(),N=E-C,P=N<0?0:N;N<0&&this.log?.warn(`${b} [sendRecord] negative duration detected, clamped to 0. spanId=${o}, name=${l}, startMs=${C}, endMs=${E}`);let w=1000000n,K=(BigInt(C)*w).toString(),x=(BigInt(E)*w).toString(),F=(BigInt(P)*w).toString(),$={};for(let[D,W]of Object.entries(e))ss.has(D)||W!=null&&($[D]=W);S!=null&&($.durationMs=String(S));for(let[D,W]of Object.entries(n))W!=null&&($[D]=String(W));let I=this.mapSpanKindToString(u),M=g==="OK"?"OK":g==="ERROR"?"ERROR":"UNSET",A=JSON.stringify($),R=new ns;R.setTime(Math.floor(C/1e3)),R.pushBack(new ie("traceID",r)),R.pushBack(new ie("spanID",o)),R.pushBack(new ie("parentSpanID",c)),R.pushBack(new ie("kind",I)),R.pushBack(new ie("name",l)),R.pushBack(new ie("links","[]")),R.pushBack(new ie("logs","[]")),R.pushBack(new ie("traceState","")),R.pushBack(new ie("start",K)),R.pushBack(new ie("end",x)),R.pushBack(new ie("duration",F)),R.pushBack(new ie("attribute",A)),R.pushBack(new ie("statusCode",M)),R.pushBack(new ie("statusMessage",""));let L=this.producer.send(R);L&&typeof L.catch=="function"&&L.catch(D=>{this.log.warn(`${b} CLS \u5F02\u6B65\u53D1\u9001\u5931\u8D25: ${D}`)})}catch(n){this.log.warn(`${b} CLS \u53D1\u9001\u5931\u8D25: ${n}`)}}mapSpanKind(e){switch(e){case"entry":case"gateway":return"ENTRY";case"agent":return"AGENT";case"step":return"STEP";case"model":return"LLM";case"tool":return"TOOL";case"session":return"SESSION";case"message":return"TASK";default:return"INTERNAL"}}mapSpanKindToString(e){switch(e){case"ENTRY":return"server";case"LLM":return"client";case"TOOL":return"client";default:return"internal"}}};import{readFile as os}from"node:fs/promises";async function Xn(t){try{let e=await os(t,"utf8"),l=JSON.parse(e).plugins?.entries?.[En]?.config,u=l?.trace,g=u?.enabled!==!1,m=typeof u?.traceTopicId=="string"?u.traceTopicId.trim():"",_=l?.cls,S=typeof _?.endpoint=="string"?_.endpoint.trim():"",C=typeof _?.token=="string"?_.token.trim():"",E=typeof _?.credentialMode=="string"&&_.credentialMode.trim()==="cvmRole"?"cvmRole":"static",N=typeof _?.roleName=="string"?_.roleName.trim():"",P="",w="";try{P=typeof _?.secretId=="string"?ee(_.secretId.trim()):""}catch(F){console.warn(`[diagnostics-metrics-cls/trace] readTraceHotConfigFromDisk: secretId decrypt failed: ${String(F)}`)}try{w=typeof _?.secretKey=="string"?ee(_.secretKey.trim()):""}catch(F){console.warn(`[diagnostics-metrics-cls/trace] readTraceHotConfigFromDisk: secretKey decrypt failed: ${String(F)}`)}let K=u?.debug===!0,x=Array.isArray(u?.enabledHooks)?u.enabledHooks:void 0;return{enabled:g,traceTopicId:m,endpoint:S,secretId:P,secretKey:w,token:C,credentialMode:E,roleName:N,debug:K,enabledHooks:x}}catch(e){return e?.code==="ENOENT"||console.warn(`[diagnostics-metrics-cls/trace] readTraceHotConfigFromDisk failed: ${String(e)}`),null}}function en(t,e){if(!t)return{enabled:!1,traceTopicId:"",endpoint:"",secretId:"",secretKey:"",serviceName:"openclaw-agent"};let n=t.enabled!==!1,r=typeof t.traceTopicId=="string"?t.traceTopicId.trim():"",o=typeof e?.endpoint=="string"?e.endpoint.trim():"",c="",l="";try{c=typeof e?.secretId=="string"?ee(e.secretId.trim()):""}catch(S){console.warn(`[diagnostics-metrics-cls/trace] resolveTraceConfig: secretId decrypt failed: ${String(S)}`)}try{l=typeof e?.secretKey=="string"?ee(e.secretKey.trim()):""}catch(S){console.warn(`[diagnostics-metrics-cls/trace] resolveTraceConfig: secretKey decrypt failed: ${String(S)}`)}let u=typeof e?.token=="string"?e.token.trim():void 0,g=typeof e?.credentialMode=="string"&&e.credentialMode.trim()==="cvmRole"?"cvmRole":"static",m=typeof e?.roleName=="string"?e.roleName.trim():void 0;return{enabled:n&&(g==="cvmRole"?!!(r&&o&&m):!!(r&&o&&c&&l)),traceTopicId:r,endpoint:o,secretId:c,secretKey:l,token:u,credentialMode:g,roleName:m,serviceName:typeof t.serviceName=="string"?t.serviceName:"openclaw-agent",debug:t.debug===!0,enabledHooks:Array.isArray(t.enabledHooks)?t.enabledHooks:void 0}}function Hn(t){let e=t.traceTopicId??"",n=t.endpoint??"",r=t.secretId??"",o=t.secretKey??"",c=t.token,l=t.credentialMode??"static",u=t.roleName??"",g=t.sharedCredentialManager??null,m=t.debug??!1,_=t.enabled===!0,S=t.enabledHooks,C=t.serviceName||is(process.cwd())||"openclaw-agent",E=`${C}@${Gn()}:${process.pid}`,N={"service.name":C,"service.instance.id":E,"host.name":Gn(),"telemetry.sdk.language":"nodejs"};function P(){let s=_e(),a={...N};return s.cvmInstanceId&&(a.cvm_instance_id=s.cvmInstanceId),s.cvmInstanceName&&(a.cvm_instance_name=s.cvmInstanceName),s.cvmInstanceIntraIp&&(a.cvm_instance_intra_ip=s.cvmInstanceIntraIp),a}let w=null,K=null,x=null;function F(s){return{topic_id:e,endpoint:n,credential:{secretId:s.secretId,secretKey:s.secretKey,token:s.token},onSendLogsError:a=>{a?.status!==200?k?.warn(`${b} CLS \u53D1\u9001\u5931\u8D25: ${JSON.stringify(a)}`):m&&k?.debug(`${b} CLS \u53D1\u9001\u6210\u529F: requestId=${a?.requestId}`)}}}let $=new Map,I=new Map,M=new Map,A=new Map,R=new Map,L=new Map,D=new Map,W,Y,ce,ye="unknown",xe=null,k=null,Fe=!1,Ie=new Set,fe=new Map,gt=2e3;function $t(){let s=Date.now(),a=new Set,f=[];for(let[p,h]of $)s-h.createdAt>Ht&&(f.push(p),a.add(h));for(let p of f)$.delete(p);for(let p of a)I.delete(p.runId);if(a.size>0){let p=[];for(let[T,v]of M){for(let j of a)v.delete(j);v.size===0&&p.push(T)}for(let T of p)M.delete(T);let h=[];for(let[T,v]of A)a.has(v)&&h.push(T);for(let T of h)A.delete(T);Y&&a.has(Y)&&(Y=void 0,W=void 0,ce=void 0)}let d=[];for(let[p,h]of R)(s-h.createdAt>Ht||a.has(h.traceContext))&&d.push(p);for(let p of d)R.delete(p);let i=[];for(let[p,h]of D)s-h.createdAt>Nn&&i.push(p);for(let p of i)D.delete(p);w&&w.sweepStaleOpenSpans()}function q(s){return S?S.includes(s):!0}function Ke(s){return s.startsWith(Mn)}function Et(s,a){let f=[];for(let[d,i]of R)i.runId===s&&f.push({oldKey:d,pending:i});for(let{oldKey:d,pending:i}of f){R.delete(d),i.runId=a;let p=dt(i.toolCallId,a);R.has(p)&&m&&k?.warn(`${b} movePendingToolCallsRunBinding: key collision detected, overwriting existing entry: ${p}`),R.set(p,i)}}function mt(s,a,f){let d=Xe(a);if(!d||s.runId===d)return;let i=I.get(d);if(i&&i!==s)return;let p=s.runId;if(!Ke(p))return;I.get(p)===s&&I.delete(p),s.runId=d,s.turnId=d,I.set(d,s),Et(p,d);let h={"openclaw.run.id":d,"openclaw.turn.id":d};w?.patchOpenSpanAttributes(s.rootSpanId,h),s.agentSpanId&&w?.patchOpenSpanAttributes(s.agentSpanId,h),s.stepSpanId&&w?.patchOpenSpanAttributes(s.stepSpanId,h),m&&k?.info(`${b} Rebound temporary runId: hook=${f}, oldRunId=${p}, realRunId=${d}`)}function ht(s,a){if(Fe)return Promise.resolve();if(L.size>=Pn)return k?.warn(`${b} trace task queue size (${L.size}) exceeded limit, dropping task for trace ${s}`),Promise.resolve();let f=L.get(s)||Promise.resolve(),d=()=>{let h,T=new Promise((v,j)=>{h=setTimeout(()=>j(new Error(`trace task timeout after ${zt}ms`)),zt)});return Promise.race([a(),T]).finally(()=>{h!==void 0&&clearTimeout(h)})},i=f.catch(()=>{}).then(d),p;return p=i.finally(()=>{L.get(s)===p&&L.delete(s)}),L.set(s,p),p}async function yt(s){if(!s)return;let a=L.get(s);if(a)try{await a}catch(f){k?.warn(`${b} drainTraceTasks failed for traceId=${s}: ${String(f)}`)}}function It(s){if(!s)return;let a=`${s}:`,f=[];for(let[d,i]of R)(d.startsWith(a)||i.runId===s)&&f.push(d);for(let d of f)R.delete(d)}function Mt(s){let a=Xe(s.runId),f=Rt(s.toolCallId);if(f){let p=[dt(f,a),dt(f,void 0)];for(let h of p){let T=R.get(h);if(T)return R.delete(h),T}}let d,i;for(let[p,h]of R)h.toolName===s.toolName&&(a&&h.runId!==a||!a&&h.runId||(!i||h.toolStartTime>i.toolStartTime)&&(i=h,d=p));return i&&d&&R.delete(d),i}function Nt(s,a){let f=M.get(s);f||(f=new Set,M.set(s,f)),f.add(a)}function Pt(s,a){let f=M.get(s);f&&(f.delete(a),f.size===0&&M.delete(s))}function Ve(s,a){$.set(s,a),Nt(s,a)}function Te(s,a){$.get(s)===a&&$.delete(s),Pt(s,a)}async function Ye(s=!0){Fe=!0,xe&&(clearInterval(xe),xe=null),K&&(clearInterval(K),K=null),x&&(x(),x=null);for(let f of Ie)clearTimeout(f);Ie.clear();for(let f of fe.values())clearTimeout(f);fe.clear();let a=Array.from(L.values());a.length>0&&await Promise.allSettled(a),L.clear(),R.clear(),D.clear(),$.clear(),I.clear(),M.clear(),A.clear(),Y=void 0,W=void 0,ce=void 0,s&&w&&(await w.dispose(),w=null)}function wt(){R.clear(),D.clear(),$.clear(),I.clear(),M.clear(),A.clear(),Y=void 0,W=void 0,ce=void 0;for(let s of Ie)clearTimeout(s);Ie.clear();for(let s of fe.values())clearTimeout(s);fe.clear()}function Me(s){let a=$.get(s);a&&we(a)}function we(s){I.get(s.runId)===s&&I.delete(s.runId);let a=[];for(let[i,p]of $)p===s&&a.push(i);for(let i of a)$.delete(i);let f=[];for(let[i,p]of M)p.has(s)&&(p.delete(s),p.size===0&&f.push(i));for(let i of f)M.delete(i);let d=[];for(let[i,p]of A)p===s&&d.push(i);for(let i of d)A.delete(i);D.delete(s.traceId),Y===s&&(Y=void 0,W=void 0,ce=void 0)}function sn(s,a,f){let i={traceId:te(32),rootSpanId:te(16),runId:s,turnId:s,channelId:a,originalChannelId:f||a,createdAt:Date.now(),llmPendingToolCallIds:new Set,llmPendingToolResultsForNextInput:[],llmPendingToolCallCountFallback:0,llmSegmentCount:0,stepRoundCounter:0,stepAwaitingToolResults:!1};return Ve(a,i),I.set(s,i),i}function At(s,a){let f=M.get(s);if(!f||f.size===0)return a;let d=Array.from(f).filter(i=>i.agentSpanId&&!i.isClosing);return d.length===0?a||Array.from(f)[0]:(d.sort((i,p)=>(p.agentStartTime||p.createdAt)-(i.agentStartTime||i.createdAt)),d[0])}function De(s){let a=I.get(s);return a?.originalChannelId||a?.channelId}function G(s,a,f){let d=s,i=s.startsWith("agent/")?s:void 0,p=i&&A.get(i)||$.get(s),h=Xe(a),T=h||p?.runId||`__temp_run_${te(12)}`,v=()=>s.startsWith("agent/")&&!!Y&&!!ce&&Date.now()-(ce||0)<vn,j=()=>{if(!Y)return;let B=Y;if(!(h&&B.runId!==h&&!Ke(B.runId)))return d=W||d,Ve(s,B),I.set(T,B),m&&k?.info(`${b} LINKING agent to user context: hook=${f}, agentChannel=${s}, userChannel=${d}, traceId=${B.traceId}`),B};if(s.startsWith("agent/")&&T){let B=De(T);B&&(d=B,p=$.get(B)||p)}if(p||(p=I.get(T)),f==="agent_end"&&!h&&(p=At(d,p)),!p&&v()&&(p=j()),f==="message_received"&&!s.startsWith("agent/")&&p&&(p.agentSpanId||p.hasSeenLlmInput||p.isClosing)&&(p=void 0,h||(T=`__temp_run_${te(12)}`)),p&&h&&p.runId!==h&&!Ke(p.runId)&&(p=void 0,T=h),p&&h&&Ke(p.runId)){let B=I.get(h);B&&B!==p&&(p=B,Ve(d,p))}!p&&v()&&(p=j());let U=!1;return p||(p=sn(T,d,s!==d?s:void 0),U=!0,m&&k?.info(`${b} NEW TraceContext: hook=${f}, channelId=${d}, runId=${T}, traceId=${p.traceId}`)),i&&p&&!p.isClosing&&A.set(i,p),p&&a&&mt(p,a,f),{ctx:p,channelId:d,isNew:U}}function ve(s,a,f,d,i,p,h={},T){return{name:f,type:d,startTime:i,endTime:p,attributes:{...h,"openclaw.version":ye,"openclaw.session.id":s.sessionId||a,"gen_ai.session.id":s.sessionId||a,"openclaw.run.id":s.runId,"openclaw.turn.id":s.turnId},traceId:s.traceId,spanId:te(16),parentSpanId:T||s.rootSpanId}}function Qe(s){return s.agentSpanId||s.rootSpanId}function Ce(s){return s.stepSpanId||s.agentSpanId||s.rootSpanId}async function Ne(s,a,f){if(!w)return;let d=f.endTime||Date.now(),i=s.llmPendingStartTime||d,p=d<i?i:d,h=s.llmProvider||"unknown",T=s.llmModel||"unknown",v=f.stopReason||"stop",j=f.usage?.input??0,U=f.usage?.output??0,B=f.usage?.cacheRead??0,oe=f.usage?.cacheWrite??0,Pe=f.usage?.total??j+U+B+oe,Z={"gen_ai.span.kind":"LLM","gen_ai.operation.name":"chat","gen_ai.provider.name":h,"gen_ai.system":h,"gen_ai.request.model":T,"gen_ai.response.model":T,"gen_ai.usage.input_tokens":j,"gen_ai.usage.output_tokens":U,"gen_ai.usage.total_tokens":Pe,"gen_ai.usage.cache_read.input_tokens":B,"gen_ai.usage.cache_creation.input_tokens":oe,"llm.request.type":"chat"};s.llmPendingSystemInstructions&&(Z["gen_ai.system_instructions"]=s.llmPendingSystemInstructions);let H=s.llmPendingInputMessages||s.llmLastInputMessages;H&&(Z["gen_ai.input.messages"]=H),(f.outputContent!==void 0||f.outputTexts.length>0)&&(Z["gen_ai.output.messages"]=Kn(f.outputContent,f.outputTexts,v)),Z["gen_ai.response.finish_reasons"]=JSON.stringify([v]);try{if(H){let X=JSON.parse(H);if(Array.isArray(X)){let Se=X.map(le=>({role:le.role,content:Array.isArray(le.parts)?le.parts.filter(Ae=>Ae.type==="text").map(Ae=>Ae.content).join(""):""}));Jn(Z,Se)}}if(f.outputTexts.length>0){let X=[{role:"assistant",content:f.outputTexts.join(""),stopReason:v,toolCalls:f.outputContent?Zt(Array.isArray(f.outputContent)?f.outputContent:void 0):void 0}];X[0].toolCalls?.length===0&&delete X[0].toolCalls,Wn(Z,X)}}catch(X){m&&k?.warn(`${b} Failed to set indexed prompt/completion attrs: ${String(X)}`)}let z=ve(s,a,`chat ${T}`,"model",i,p,Z,Ce(s));s.llmPendingSpanId&&(z.spanId=s.llmPendingSpanId);try{w.export(z),k?.debug(`${b} [span] Exported LLM span: ${h}/${T}, traceId=${s.traceId}, spanId=${z.spanId}, duration=${p-i}ms`),m&&k?.info(`${b} Exported segmented LLM span: ${h}/${T}, duration=${p-i}ms, reason=${v}`)}finally{s.llmPendingStartTime=void 0,s.llmPendingSpanId=void 0,s.llmPendingSystemInstructions=void 0,s.llmPendingInputMessages=void 0,s.llmSegmentCount+=1}}async function Be(s,a,f){let d=typeof f.timestamp=="number"&&Number.isFinite(f.timestamp)?f.timestamp:Date.now(),i=Bn(f.content),p=Un(f.content),h=typeof f.stopReason=="string"?f.stopReason:i.length>0?"toolUse":"stop";s.llmPendingStartTime||(s.llmPendingStartTime=d),s.llmPendingSpanId||(s.llmPendingSpanId=te(16)),await Ne(s,a,{endTime:d,outputTexts:p,outputContent:f.content,stopReason:h,usage:f.usage}),p.length>0&&(s.lastOutput=p.join(`
|
|
4
|
+
`)),s.llmPendingToolCallIds.clear(),s.llmPendingToolResultsForNextInput=[],s.llmLastAssistantContent=f.content;for(let T of i)s.llmPendingToolCallIds.add(T.id);s.llmPendingToolCallCountFallback=s.llmPendingToolCallIds.size>0?0:i.length,s.stepAwaitingToolResults=i.length>0,i.length===0&&de(s,d,h,a),m&&k?.info(`${b} Processed assistant message: runId=${s.runId}, toolCalls=${i.length}, stopReason=${h}`)}function y(s,a,f={}){if(s.rootSpanStartTime||!w)return;let d=Date.now();s.rootSpanStartTime=d;let i={"gen_ai.span.kind":"ENTRY","gen_ai.operation.name":"enter","gen_ai.user.id":f.userId||"unknown","openclaw.session.id":s.sessionId||a,"gen_ai.session.id":s.sessionId||a,"openclaw.run.id":s.runId,"openclaw.turn.id":s.turnId,"openclaw.message.role":f.role||"unknown","openclaw.message.from":f.from||"unknown","openclaw.version":ye};s.userInput&&(i["gen_ai.input.messages"]=me(JSON.stringify([{role:"user",parts:[{type:"text",content:String(s.userInput)}]}]))),w.startSpan({name:"enter_openclaw_system",type:"entry",startTime:d,attributes:i,traceId:s.traceId,spanId:s.rootSpanId},s.rootSpanId),k?.debug(`${b} [span] Started entry span: traceId=${s.traceId}, spanId=${s.rootSpanId}`)}function O(s,a,f){if(s.agentSpanId||!w)return;let d=Date.now();s.agentStartTime=d,s.agentSpanId=te(16),w.startSpan({name:`invoke_agent ${f}`,type:"agent",startTime:d,attributes:{"gen_ai.span.kind":"AGENT","gen_ai.operation.name":"invoke_agent","gen_ai.provider.name":"openclaw","gen_ai.agent.id":f,"gen_ai.agent.name":f,"openclaw.session.id":s.sessionId||a,"gen_ai.session.id":s.sessionId||a,"openclaw.run.id":s.runId,"openclaw.turn.id":s.turnId,"openclaw.version":ye},traceId:s.traceId,spanId:s.agentSpanId,parentSpanId:s.rootSpanId},s.agentSpanId),k?.debug(`${b} [span] Started agent span: ${f}, spanId=${s.agentSpanId}, traceId=${s.traceId}`)}function J(s,a,f){if(s.stepSpanId||!w)return;let d=s.stepRoundCounter+1,i=te(16);w.startSpan({name:"react step",type:"step",startTime:f,attributes:{"gen_ai.span.kind":"STEP","gen_ai.operation.name":"react","gen_ai.react.round":d,"openclaw.session.id":s.sessionId||a,"gen_ai.session.id":s.sessionId||a,"openclaw.run.id":s.runId,"openclaw.turn.id":s.turnId,"openclaw.version":ye},traceId:s.traceId,spanId:i,parentSpanId:Qe(s)},i),s.stepSpanId=i,s.stepStartTime=f,s.stepRoundCounter=d,s.stepCurrentRound=d,s.stepAwaitingToolResults=!1,m&&k?.info(`${b} Started step span: round=${d}, spanId=${i}`)}function de(s,a,f,d){if(!s.stepSpanId||!w)return;let i=s.stepSpanId,p=s.stepCurrentRound||s.stepRoundCounter||1;w.endSpanById(i,a,{"gen_ai.react.round":p,"gen_ai.react.finish_reason":f||"stop","openclaw.session.id":s.sessionId||d,"gen_ai.session.id":s.sessionId||d,"openclaw.run.id":s.runId,"openclaw.turn.id":s.turnId}),s.stepSpanId=void 0,s.stepStartTime=void 0,s.stepCurrentRound=void 0,s.stepAwaitingToolResults=!1,m&&k?.info(`${b} Ended step span: round=${p}, reason=${f}, spanId=${i}`)}function be(s){s.acpFallbackPending=!1;let a=fe.get(s.traceId);a&&(clearTimeout(a),fe.delete(s.traceId))}function ue(s,a){if(!s.acpFallbackPending||!w)return;let f=fe.get(s.traceId);f&&clearTimeout(f);let d=w,i=setTimeout(async()=>{if(fe.delete(s.traceId),Ie.delete(i),!!s.acpFallbackPending){s.acpFallbackPending=!1;try{if(k?.debug(`${b} [acp-fallback] Closing Entry Span for ACP mode: traceId=${s.traceId}`),s.rootSpanStartTime&&d&&!d.isDisposed){let p=Date.now(),h={"request.duration_ms":p-s.rootSpanStartTime,"openclaw.acp_mode":!0};s.sessionId&&(h["openclaw.session.id"]=s.sessionId,h["gen_ai.session.id"]=s.sessionId),s.userInput&&(h["gen_ai.input.messages"]=me(JSON.stringify([{role:"user",parts:[{type:"text",content:String(s.userInput)}]}]))),s.lastOutput&&(h["gen_ai.output.messages"]=qe([typeof s.lastOutput=="string"?s.lastOutput:JSON.stringify(s.lastOutput)])),d.endSpanById(s.rootSpanId,p,h),k?.debug(`${b} [acp-fallback] Ended entry span: spanId=${s.rootSpanId}, traceId=${s.traceId}, duration=${p-s.rootSpanStartTime}ms`)}Te(a,s),we(s),d&&!d.isDisposed&&(await d.flush(),k?.debug(`${b} [acp-fallback] Flushed after ACP fallback close, traceId=${s.traceId}`))}catch(p){k?.warn(`${b} [acp-fallback] Error closing Entry Span: ${String(p)}`)}}},gt);fe.set(s.traceId,i),Ie.add(i)}let ne={id:"diagnostics-metrics-cls-trace",async start(s){if(k=s.logger,ye=s.runtime?.version||"unknown",Fe=!1,_&&e&&n&&(l==="cvmRole"?!!u:!!(r&&o))){let i;if(g){let p=g.getCredentialSnapshot();i={secretId:p.secretId,secretKey:p.secretKey,token:p.token},r=p.secretId,o=p.secretKey,c=p.token}else l==="static"?i={secretId:r,secretKey:o,token:c}:(k.warn(`${b} cvmRole \u6A21\u5F0F\u4F46\u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u4E0D\u53EF\u7528\uFF0Ctrace \u6570\u636E\u6682\u4E0D\u53D1\u9001`),i={secretId:"",secretKey:""});if(i.secretId&&i.secretKey){let p=new kt(F(i));w=new ut(p,e,m,k,P),k.debug(`${b} CLS Producer \u5DF2\u521D\u59CB\u5316\uFF0Cendpoint=${n} traceTopicId=${e} credentialMode=${l}`),g&&!x&&(x=g.subscribe(h=>{if(!w||w.isDisposed||!(h.secretId!==r||h.secretKey!==o||(h.token||"")!==(c||"")))return;r=h.secretId,o=h.secretKey,c=h.token;let v=new kt(F(h));w.updateProducer(v,e),m&&k?.info(`${b} \u5171\u4EAB\u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}))}else k.warn(`${b} \u51ED\u8BC1\u83B7\u53D6\u5931\u8D25\uFF08credentialMode=${l}\uFF09\uFF0Ctrace \u6570\u636E\u6682\u4E0D\u53D1\u9001\uFF0C\u7B49\u5F85\u70ED\u66F4\u65B0\u6062\u590D`)}else k.warn(`${b} CLS \u914D\u7F6E\u4E0D\u5B8C\u6574\u6216 trace \u672A\u542F\u7528\uFF08traceEnabled=${_}\uFF0CcredentialMode=${l}\uFF09\uFF0Ctrace \u6570\u636E\u6682\u4E0D\u53D1\u9001\uFF0C\u7B49\u5F85\u70ED\u66F4\u65B0\u6062\u590D`);xe=setInterval($t,Cn);let f=as(s.stateDir,"openclaw.json"),d=!1;K=setInterval(()=>{(async()=>{if(!d){d=!0;try{let i=await Xn(f);if(!i)return;let p=i.enabled,h=i.traceTopicId,T=i.endpoint,v=i.secretId,j=i.secretKey,U=i.token,B=i.debug;B!==m&&(m=B,w&&(w.debug=m),k.debug(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Ctrace.debug=${m}`));let oe=i.enabledHooks;JSON.stringify(oe)!==JSON.stringify(S)&&(S=oe,k.debug(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CenabledHooks=${S?S.join(","):"\u5168\u90E8\u542F\u7528"}`));let Z=p!==_;if(Z)if(_=p,_)k.debug(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Ctrace.enabled=true\uFF0C\u6B63\u5728\u6062\u590D Trace \u94FE\u8DEF\u8FFD\u8E2A`);else{w&&(await w.dispose(),w=null),wt(),k.debug(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Ctrace.enabled=false\uFF0C\u5DF2\u7981\u7528 Trace \u94FE\u8DEF\u8FFD\u8E2A`);return}if(!_)return;let H=i.credentialMode,z=i.roleName,X=h!==e,Se=T!==n,le=!g&&(v!==r||j!==o),Ae=!g&&(U||"")!==(c||""),Lt=H!==l,Ot=z!==u;if(!(Z||X||Se||le||Ae||Lt||Ot))return;if(X&&(e=h),Se&&(n=T),Lt&&(l=H),Ot&&(u=z),le&&(r=v,o=j),Ae&&(c=U||void 0),l==="cvmRole"?!e||!n||!u:!e||!n||!r||!o){w&&(await w.dispose(),w=null),k.warn(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CCLS \u914D\u7F6E\u4E0D\u5B8C\u6574\uFF08credentialMode=${l}\uFF09\uFF0Ctrace \u6570\u636E\u5C06\u4E0D\u4F1A\u53D1\u9001`);return}let Ze;if(g){let Ue=g.getCredentialSnapshot();Ze={secretId:Ue.secretId,secretKey:Ue.secretKey,token:Ue.token},r=Ue.secretId,o=Ue.secretKey,c=Ue.token}else if(l==="static")Ze={secretId:r,secretKey:o,token:c};else{k.warn(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CcvmRole \u6A21\u5F0F\u4F46\u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u4E0D\u53EF\u7528`);return}if(!Ze.secretId||!Ze.secretKey){w&&(await w.dispose(),w=null),k.warn(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0C\u51ED\u8BC1\u83B7\u53D6\u5931\u8D25\uFF0Ctrace \u6570\u636E\u5C06\u4E0D\u4F1A\u53D1\u9001`);return}let on=new kt(F(Ze));w?w.updateProducer(on,e):w=new ut(on,e,m,k,P),Fe=!1;let Ee=[];Z&&Ee.push("enabled=true"),X&&Ee.push(`traceTopicId=${e}`),Se&&Ee.push(`endpoint=${n}`),Lt&&Ee.push(`credentialMode=${l}`),Ot&&Ee.push(`roleName=${u}`),le&&Ee.push("\u51ED\u8BC1\u5DF2\u66F4\u65B0"),Ae&&Ee.push("token\u5DF2\u66F4\u65B0"),k.debug(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0C${Ee.join("\uFF0C")}`)}catch(i){k?.warn(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\u8F6E\u8BE2\u5931\u8D25: ${String(i)}`)}finally{d=!1}}})()},$n)},async stop(){await Ye()}};function Q(s){k=s.logger,ye=s.runtime?.version||ye,s.on("gateway_stop",async()=>{await Ye()}),s.on("gateway_start",async a=>{try{if(!q("gateway_start")||!w)return;let f=Date.now(),d=te(32),i=te(16),p={name:"gateway_start",type:"gateway",startTime:f,endTime:f,attributes:{"openclaw.version":ye,"gen_ai.span.kind":"ENTRY","gateway.port":a.port},traceId:d,spanId:i,parentSpanId:""};w.export(p)}catch(f){k?.warn(`${b} [hook] gateway_start ERROR: ${String(f)}`)}}),s.on("session_start",async(a,f)=>{try{if(!q("session_start")||!w)return;let d=V(f,a.sessionId),{ctx:i,channelId:p}=G(d,a?.runId,"session_start");a.sessionId&&(i.sessionId=a.sessionId);let h=Date.now(),T=ve(i,p,"session_start","session",h,h,{"gen_ai.span.kind":"SESSION","event.type":"session_start"});a.sessionId&&(T.attributes["openclaw.session.id"]=a.sessionId,T.attributes["gen_ai.session.id"]=a.sessionId),w.export(T)}catch(d){k?.warn(`${b} [hook] session_start ERROR: ${String(d)}`)}}),s.on("session_end",async(a,f)=>{try{if(!q("session_end")||!w)return;let d=V(f,a.sessionId),{ctx:i,channelId:p}=G(d,a?.runId,"session_end"),h=Date.now(),T=ve(i,p,"session_end","session",h,h,{"gen_ai.span.kind":"SESSION","session.duration_ms":a.durationMs||0,"session.message_count":a.messageCount||0,"session.total_tokens":i.lastLlmUsage?.total||0});i.lastOutput&&(T.attributes["gen_ai.output.messages"]=qe([typeof i.lastOutput=="string"?i.lastOutput:JSON.stringify(i.lastOutput)])),a.sessionId&&(T.attributes["openclaw.session.id"]=a.sessionId,T.attributes["gen_ai.session.id"]=a.sessionId),w.export(T),await yt(i.traceId),Me(p)}catch(d){k?.warn(`${b} [hook] session_end ERROR: ${String(d)}`)}}),s.on("message_received",async(a,f)=>{try{if(k?.debug(`${b} [hook] message_received fired, sender=${w?"OK":"null"}, enabled=${q("message_received")}`),!q("message_received")||!w)return;let d=V(f,a.from||a.metadata?.senderId),{ctx:i,channelId:p}=G(d,a?.runId,"message_received");!d.startsWith("agent/")&&(W=p,Y=i,ce=Date.now(),i.userInput=a.content,y(i,p,{userId:a.from||a.metadata?.senderId,role:"user",from:a.from}),i.acpFallbackPending=!0)}catch(d){k?.warn(`${b} [hook] message_received ERROR: ${String(d)}`),console.error(`${b} [hook] message_received ERROR:`,d)}}),s.on("message_sending",async(a,f)=>{try{if(!q("message_sending"))return;let d=V(f,a.to),{ctx:i}=G(d,a?.runId,"message_sending");i.lastOutput=a.content}catch(d){k?.warn(`${b} [hook] message_sending ERROR: ${String(d)}`)}},{priority:-100}),s.on("message_sent",async(a,f)=>{try{if(!q("message_sent"))return;if(a.content&&a.success){let d=V(f,a.to),{ctx:i,channelId:p}=G(d,a?.runId,"message_sent");i.lastOutput=a.content,i.acpFallbackPending&&ue(i,p)}}catch(d){k?.warn(`${b} [hook] message_sent ERROR: ${String(d)}`)}},{priority:-100}),s.on("llm_input",async(a,f)=>{try{if(k?.debug(`${b} [hook] llm_input fired, sender=${w?"OK":"null"}, enabled=${q("llm_input")}`),!q("llm_input")||!w)return;let d=V(f),{ctx:i,channelId:p}=G(d,a.runId,"llm_input");be(i),a.sessionId&&(i.sessionId=a.sessionId),!i.userInput&&a.prompt&&(i.userInput=a.prompt),y(i,p,{userId:f.trigger||"system",role:f.trigger||"system",from:f.agentId||"openclaw"}),O(i,p,f.agentId||"openclaw"),i.llmProvider=a.provider,i.llmModel=a.model,i.hasSeenLlmInput=!0,i.isClosing=!1,d.startsWith("agent/")&&A.set(d,i),i.llmPendingStartTime=Date.now(),i.llmPendingSpanId=te(16),J(i,p,i.llmPendingStartTime),i.llmPendingToolCallIds.clear(),i.llmPendingToolCallCountFallback=0,a.systemPrompt&&(i.llmPendingSystemInstructions=Fn(a.systemPrompt));let h=a.historyMessages?.length?a.historyMessages.map(v=>Yt(v)):[];i.llmPendingInputMessages=Qt(h,a.prompt),i.llmLastInputMessages=i.llmPendingInputMessages;let T=D.get(i.traceId);if(T){D.delete(i.traceId);try{ht(i.traceId,async()=>{await Be(i,p,T.message)}).catch(v=>{k?.warn(`${b} replay pending assistant failed: ${String(v)}`)})}catch(v){k?.warn(`${b} replay pending assistant enqueue failed: ${String(v)}`)}}m&&k?.info(`${b} LLM input started: ${a.provider}/${a.model}, runId=${a.runId}`)}catch(d){k?.error(`${b} [hook] llm_input UNCAUGHT ERROR: ${String(d)}, stack=${d?.stack}`)}},{priority:-100}),s.on("llm_output",async(a,f)=>{try{if(!q("llm_output")||!w)return;let d=V(f),{ctx:i,channelId:p}=G(d,a.runId,"llm_output");if(a.sessionId&&(i.sessionId=a.sessionId),a.assistantTexts?.length&&(i.lastOutput=a.assistantTexts.join(`
|
|
5
|
+
`)),a.usage&&(i.lastLlmUsage={input:a.usage.input,output:a.usage.output,cacheRead:a.usage.cacheRead,cacheWrite:a.usage.cacheWrite,total:a.usage.total}),i.llmSegmentCount===0&&i.llmPendingStartTime){let h=Date.now(),T=a.lastAssistant,v=typeof T?.stopReason=="string"?T.stopReason:void 0;await Ne(i,p,{endTime:h,outputTexts:a.assistantTexts||[],stopReason:v,usage:a.usage}),de(i,h,v||"stop",p)}}catch(d){k?.warn(`${b} [hook] llm_output ERROR: ${String(d)}`)}},{priority:-100}),s.on("before_message_write",(a,f)=>{try{if(k?.debug(`${b} [hook] before_message_write fired, sender=${w?"OK":"null"}, enabled=${q("before_message_write")}, role=${a?.message?.role}`),!q("before_message_write")||!w)return;let d=a.message;if(!d||d.role!=="assistant")return;let i=V(f),p=i.startsWith("agent/")?A.get(i):void 0;if(i.startsWith("agent/")&&!p)return;let{ctx:h,channelId:T}=p?{ctx:p,channelId:p.channelId}:G(i,void 0,"before_message_write");if(!h.hasSeenLlmInput){D.set(h.traceId,{message:d,createdAt:Date.now()});return}try{ht(h.traceId,async()=>{await Be(h,T,d)}).catch(v=>{k?.warn(`${b} before_message_write segmented export failed: ${String(v)}`)})}catch(v){k?.warn(`${b} before_message_write enqueue failed: ${String(v)}`)}}catch(d){k?.warn(`${b} [hook] before_message_write uncaught error: ${String(d)}, stack=${d?.stack}`)}},{priority:-100}),s.on("before_tool_call",async(a,f)=>{try{if(!q("before_tool_call")||!w)return;let d=V(f),i=d.startsWith("agent/")?A.get(d):void 0;if(d.startsWith("agent/")&&!i)return;let{ctx:p,channelId:h}=i?{ctx:i,channelId:i.channelId}:G(d,Xe(a.runId),"before_tool_call");if(i&&a.runId&&mt(p,a.runId,"before_tool_call"),!p.hasSeenLlmInput)return;let T=Xe(a.runId)||p.runId,v=Rt(a.toolCallId)||`call_${te(12)}`;if(R.size>=An){k?.warn(`${b} pendingToolCalls size (${R.size}) exceeded limit, dropping tool call ${v}`);return}R.set(dt(v,T),{runId:T,toolName:a.toolName,toolCallId:v,toolSpanId:te(16),toolStartTime:Date.now(),toolInput:a.params,traceContext:p,channelId:h,createdAt:Date.now()}),m&&k?.info(`${b} Tool call started: ${a.toolName}, toolCallId=${v}`)}catch(d){k?.warn(`${b} [hook] before_tool_call ERROR: ${String(d)}`)}},{priority:-100}),s.on("after_tool_call",async a=>{try{if(!q("after_tool_call")||!w)return;let f=Mt(a);if(!f)return;let{toolName:d,toolCallId:i,toolSpanId:p,toolStartTime:h,toolInput:T,traceContext:v,channelId:j}=f,U=Date.now(),B={"gen_ai.span.kind":"TOOL","gen_ai.operation.name":"execute_tool","gen_ai.tool.name":d,"gen_ai.tool.call.id":i,"gen_ai.tool.type":"function","tool.duration_ms":a.durationMs||U-h};T!==void 0&&(B["gen_ai.tool.call.arguments"]=me(typeof T=="string"?T:JSON.stringify(T))),a.error?B["error.type"]=a.error:a.result!==void 0&&(B["gen_ai.tool.call.result"]=me(typeof a.result=="string"?a.result:JSON.stringify(a.result)));let oe=ve(v,j,`execute_tool ${d}`,"tool",h,U,B,Ce(v));oe.spanId=p,w.export(oe);let Pe=a.error?[{type:"toolResult",toolCallId:i,toolName:d,isError:!0,content:a.error}]:[{type:"toolResult",toolCallId:i,toolName:d,content:a.result}];if(v.llmPendingToolResultsForNextInput.push({role:"toolResult",content:Pe}),v.llmPendingToolCallIds.size>0||v.llmPendingToolCallCountFallback>0){if(v.llmPendingToolCallIds.size>0){if(v.llmPendingToolCallIds.has(i))v.llmPendingToolCallIds.delete(i);else if(!Rt(a.toolCallId)){let z=v.llmPendingToolCallIds.values().next().value;z&&v.llmPendingToolCallIds.delete(z)}}else v.llmPendingToolCallCountFallback>0&&(v.llmPendingToolCallCountFallback-=1);if(v.llmPendingToolCallIds.size===0&&v.llmPendingToolCallCountFallback===0){let z=[];v.llmLastAssistantContent!==void 0&&z.push({role:"assistant",content:v.llmLastAssistantContent}),v.llmPendingToolResultsForNextInput.length>0&&z.push(...v.llmPendingToolResultsForNextInput),de(v,U,"toolUse",j),v.llmPendingStartTime=U,v.llmPendingSpanId=te(16),J(v,j,U),v.llmPendingSystemInstructions=void 0,v.llmPendingInputMessages=z.length>0?Qt(z):void 0,v.llmLastInputMessages=v.llmPendingInputMessages,v.llmPendingToolResultsForNextInput=[]}}m&&k?.info(`${b} Exported tool span: ${d}, duration=${U-h}ms`)}catch(f){k?.warn(`${b} [hook] after_tool_call ERROR: ${String(f)}`)}},{priority:-100}),s.on("before_compaction",async(a,f)=>{try{if(!q("before_compaction")||!w)return;let d=V(f),{ctx:i}=G(d,a?.runId,"before_compaction");i._compactionStartTime=Date.now()}catch(d){k?.warn(`${b} [hook] before_compaction ERROR: ${String(d)}`)}},{priority:-100}),s.on("after_compaction",async(a,f)=>{try{if(!q("after_compaction")||!w)return;let d=V(f),{ctx:i,channelId:p}=G(d,a?.runId,"after_compaction"),h=i._compactionStartTime||Date.now(),T=Date.now(),v=ve(i,p,"openclaw.compaction","tool",h,T,{"gen_ai.span.kind":"TOOL","gen_ai.operation.name":"compaction","openclaw.compaction.messages.after":a?.messageCount??-1,"openclaw.compaction.tokens.after":a?.tokenCount??-1,"openclaw.compaction.compacted_count":a?.compactedCount??0},Qe(i));w.export(v),i._compactionStartTime=void 0}catch(d){k?.warn(`${b} [hook] after_compaction ERROR: ${String(d)}`)}},{priority:-100}),s.on("subagent_spawned",async(a,f)=>{try{if(!q("subagent_spawned")||!w)return;let d=V(f),{ctx:i}=G(d,a?.runId,"subagent_spawned"),p=a?.sessionKey??a?.childSessionKey??"unknown-child";i._subagentStartTimes||(i._subagentStartTimes=new Map),i._subagentStartTimes.set(p,Date.now())}catch(d){k?.warn(`${b} [hook] subagent_spawned ERROR: ${String(d)}`)}},{priority:-100}),s.on("subagent_ended",async(a,f)=>{try{if(!q("subagent_ended")||!w)return;let d=V(f),{ctx:i,channelId:p}=G(d,a?.runId,"subagent_ended"),h=a?.sessionKey??a?.childSessionKey??"unknown-child",T=i._subagentStartTimes?.get(h)||Date.now(),v=Date.now(),j=ve(i,p,`openclaw.subagent.${h}`,"agent",T,v,{"gen_ai.span.kind":"AGENT","gen_ai.operation.name":"invoke_subagent","openclaw.subagent.session_key":h},Qe(i));w.export(j),i._subagentStartTimes?.delete(h)}catch(d){k?.warn(`${b} [hook] subagent_ended ERROR: ${String(d)}`)}},{priority:-100}),s.on("before_agent_start",async(a,f)=>{try{if(!q("before_agent_start")||!w)return;let d=V(f),i=f.agentId||"openclaw",{ctx:p,channelId:h}=G(d,a?.runId,"before_agent_start");be(p),y(p,h,{userId:f.trigger||"system",role:f.trigger||"system",from:i}),O(p,h,i)}catch(d){k?.warn(`${b} [hook] before_agent_start ERROR: ${String(d)}`)}},{priority:-100}),s.on("agent_end",async(a,f)=>{try{if(k?.debug(`${b} [hook] agent_end fired, sender=${w?"OK":"null"}, enabled=${q("agent_end")}`),!q("agent_end")||!w)return;let d=V(f),{ctx:i,channelId:p}=G(d,a?.runId,"agent_end");be(i),await yt(i.traceId),i.isClosing=!0;let h=Date.now();i.stepSpanId&&de(i,h,i.stepAwaitingToolResults?"agent_end":"stop",p);let T=i.agentSpanId,v=h,j;if(T){let B=Array.isArray(a.messages)?a.messages.length:0,oe=jn(a.messages);j={"agent.duration_ms":a.durationMs||0,"agent.message_count":B,"agent.tool_call_count":oe,"gen_ai.usage.input_tokens":i.lastLlmUsage?.input||0,"gen_ai.usage.output_tokens":i.lastLlmUsage?.output||0,"gen_ai.usage.total_tokens":i.lastLlmUsage?.total||0},i.sessionId&&(j["openclaw.session.id"]=i.sessionId||p,j["gen_ai.session.id"]=i.sessionId||p),i.userInput&&(j["gen_ai.input.messages"]=me(JSON.stringify([{role:"user",parts:[{type:"text",content:String(i.userInput)}]}]))),i.agentSpanId=void 0,i.agentStartTime=void 0}let U=i;if(U.rootSpanStartTime||T){let B=U.rootSpanId,oe=U.rootSpanStartTime,Pe=U.userInput,Z=i.sessionId||U.sessionId;Te(p,U);let H=w,z=setTimeout(async()=>{Ie.delete(z);try{let X=i.lastOutput||U.lastOutput;if(T&&j&&H&&!H.isDisposed&&(X&&(j["gen_ai.output.messages"]=qe([typeof X=="string"?X:JSON.stringify(X)])),H.endSpanById(T,v,j),k?.debug(`${b} [span] Ended agent span: spanId=${T}, traceId=${U.traceId}, duration=${a.durationMs}ms`)),oe&&H&&!H.isDisposed){let Se=Date.now(),le={"request.duration_ms":Se-oe};Z&&(le["openclaw.session.id"]=Z,le["gen_ai.session.id"]=Z),Pe&&(le["gen_ai.input.messages"]=me(JSON.stringify([{role:"user",parts:[{type:"text",content:String(Pe)}]}]))),X&&(le["gen_ai.output.messages"]=qe([typeof X=="string"?X:JSON.stringify(X)])),H.endSpanById(B,Se,le),k?.debug(`${b} [span] Ended entry span: spanId=${B}, traceId=${U.traceId}, duration=${Se-oe}ms`)}It(i.runId),we(U),H&&!H.isDisposed&&(await H.flush(),k?.debug(`${b} [span] Flushed after agent_end, traceId=${U.traceId}`))}catch(X){k?.warn(`${b} agent_end delayed cleanup failed: ${String(X)}`)}},100);Ie.add(z)}else It(i.runId),we(U),w&&await w.flush()}catch(d){k?.error(`${b} [hook] agent_end UNCAUGHT ERROR: ${String(d)}`,d instanceof Error?d.stack:void 0)}},{priority:-100}),s.on("before_reset",async(a,f)=>{try{if(!q("before_reset")||!w)return;let d=V(f),{ctx:i}=G(d,a?.runId,"before_reset");w?.patchOpenSpanAttributes(i.rootSpanId,{"openclaw.reset":!0,"openclaw.reset.reason":a?.reason??"user_request"})}catch(d){k?.warn(`${b} [hook] before_reset ERROR: ${String(d)}`)}},{priority:-100}),k?.debug(`${b} Registered trace hook handlers (v2 \u2014 \u5B8C\u6574\u94FE\u8DEF\u8FFD\u8E2A).`)}function se(s){s!==g&&(x&&(x(),x=null),g=s,g&&w&&!w.isDisposed&&(x=g.subscribe($e)))}function $e(s){if(!w||w.isDisposed||!(s.secretId!==r||s.secretKey!==o||(s.token||"")!==(c||"")))return;r=s.secretId,o=s.secretKey,c=s.token;let f=new kt(F(s));w.updateProducer(f,e),k?.debug(`${b} \u5171\u4EAB\u51ED\u8BC1\u7BA1\u7406\u5668\u66F4\u65B0\u540E\uFF0CProducer \u5DF2\u91CD\u5EFA\uFF08\u65B0\u51ED\u8BC1\uFF09`)}return{service:ne,registerHooks:Q,updateSharedCredentialManager:se}}import{Producer as pt,LogItem as cs,Content as ls}from"tencentcloud-cls-sdk-nodejs";import{createRequire as ds}from"node:module";import{pathToFileURL as us}from"node:url";import Ge from"node:path";var vt={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},ae="[diagnostics-metrics-cls/log]";function tn(t,e){if(!t||!(t.enableLogReport===!0))return null;let r=typeof t.logTopicId=="string"?t.logTopicId.trim():"";if(!r)return null;let o=typeof e?.endpoint=="string"?e.endpoint.trim():"";if(!o)return null;let c="",l="";try{c=typeof e?.secretId=="string"?ee(e.secretId.trim()):""}catch{}try{l=typeof e?.secretKey=="string"?ee(e.secretKey.trim()):""}catch{}let u=typeof e?.token=="string"?e.token.trim():void 0,g=typeof e?.credentialMode=="string"&&e.credentialMode.trim()==="cvmRole"?"cvmRole":"static",m=typeof e?.roleName=="string"?e.roleName.trim():void 0;if(!(g==="cvmRole"?!!(o&&m):!!(o&&c&&l)))return null;let S=typeof t.source=="string"&&t.source.trim()?t.source.trim():"openclaw",C=t.enableGatewayLog!==!1,E=t.enableSessionLog!==!1,N=typeof t.minLevel=="string"&&vt[t.minLevel]!==void 0?t.minLevel:"info",P=typeof t.sendTimeThreshold=="number"&&t.sendTimeThreshold>=1?t.sendTimeThreshold:2,w=typeof t.sendCountThreshold=="number"&&t.sendCountThreshold>=1?Math.floor(t.sendCountThreshold):1e3;return{endpoint:o,secretId:c,secretKey:l,token:u,credentialMode:g,roleName:m,logTopicId:r,source:S,enableGatewayLog:C,enableSessionLog:E,minLevel:N,sendTimeThreshold:P,sendCountThreshold:w}}function ps(t){let e=t._meta,n=(e?.logLevelName??"INFO").toLowerCase(),r=e?.date instanceof Date?e.date.getTime():Date.now(),o=e?.name,c=Object.entries(t).filter(([m])=>/^\d+$/.test(m)).sort((m,_)=>Number(m[0])-Number(_[0])).map(([,m])=>m),l,u={};if(typeof c[0]=="string"&&c[0].trim().startsWith("{"))try{let m=JSON.parse(c[0]);if(m&&typeof m=="object"&&!Array.isArray(m)){typeof m.subsystem=="string"&&(l=m.subsystem);for(let[_,S]of Object.entries(m))_!=="subsystem"&&(typeof S=="string"||typeof S=="number"||typeof S=="boolean")&&(u[_]=String(S));c.shift()}}catch{}let g="";for(let m=c.length-1;m>=0;m--)if(typeof c[m]=="string"){g=String(c[m]),c.splice(m,1);break}if(!g&&c.length===1){try{g=JSON.stringify(c[0])}catch{g=String(c[0])}c.length=0}if(g||(g="(empty)"),c.length>0)try{u.args=JSON.stringify(c)}catch{u.args=String(c)}return{level:n,message:g,timestamp:r,subsystem:l,logger:o,extra:u}}function fs(t){let e=typeof t.role=="string"?t.role:"unknown",n;try{n=JSON.stringify(t)}catch{n=String(t)}let r,o,c,l;if(e==="toolResult")typeof t.toolCallId=="string"&&(r=t.toolCallId),typeof t.toolName=="string"&&(o=t.toolName);else if(e==="assistant"){typeof t.stopReason=="string"&&(c=t.stopReason);let g=(Array.isArray(t.content)?t.content:[]).filter(m=>m!==null&&typeof m=="object"&&m.type==="tool_use").length;g>0&&(l=g)}return{role:e,content:n,toolCallId:r,toolName:o,stopReason:c,toolCallCount:l}}function zn(t,e,n){let r={...t},o=e,c=null,l=null,u=null,g=null,m=!1,_=vt[r.minLevel??"info"]??2;function S(K,x,F){return{topic_id:r.logTopicId,endpoint:r.endpoint,credential:{secretId:K,secretKey:x,...F?{token:F}:{}},time:r.sendTimeThreshold??2,count:r.sendCountThreshold??1e3,onSendLogsError:$=>{if($!==null&&typeof $=="object"&&$.status===200)return;let I;if($ instanceof Error)I=$.message;else if(typeof $=="object"&&$!==null)try{I=JSON.stringify($)}catch{I=Object.prototype.toString.call($)}else I=String($);g?.warn(`${ae} \u65E5\u5FD7\u4E0A\u4F20\u5931\u8D25 - ${I}`)}}}function C(K,x){if(c)try{let F=K;if(n){let I=n();(I.cvmInstanceId||I.cvmInstanceName||I.cvmInstanceIntraIp)&&(F={...K},I.cvmInstanceId&&(F.cvm_instance_id=I.cvmInstanceId),I.cvmInstanceName&&(F.cvm_instance_name=I.cvmInstanceName),I.cvmInstanceIntraIp&&(F.cvm_instance_intra_ip=I.cvmInstanceIntraIp))}let $=new cs;$.setTime(x);for(let[I,M]of Object.entries(F))$.pushBack(new ls(I,M));c.send($).catch(I=>{let M;if(I instanceof Error)M=I.message;else try{M=JSON.stringify(I)}catch{M=Object.prototype.toString.call(I)}g?.warn(`${ae} send \u5931\u8D25: ${M}`)})}catch{}}let E={id:"diagnostics-metrics-cls-log",async start(K){if(g=K.logger,n)try{await Tt(K.logger,K.stateDir),m=!0}catch(I){g?.warn(`${ae} \u5B9E\u4F8B\u5143\u6570\u636E\u521D\u59CB\u5316\u5931\u8D25\uFF0CCVM \u5143\u5B57\u6BB5\u5C06\u7F3A\u5931: ${String(I)}`)}let x=r.secretId,F=r.secretKey,$=r.token;if(o){let I=o.getCredentialSnapshot();x=I.secretId,F=I.secretKey,$=I.token,u=o.subscribe(M=>{if(c)try{c=new pt(S(M.secretId,M.secretKey,M.token)),g?.debug(`${ae} \u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}catch(A){g?.warn(`${ae} \u51ED\u8BC1\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String(A)}`)}})}try{c=new pt(S(x,F,$))}catch(I){g?.error(`${ae} \u521B\u5EFA Producer \u5931\u8D25: ${String(I)}`),m&&(at(),m=!1);return}if(g?.info(`${ae} \u542F\u52A8\uFF0Cendpoint=${r.endpoint}\uFF0ClogTopicId=${r.logTopicId}\uFF0CenableGatewayLog=${r.enableGatewayLog}\uFF0CenableSessionLog=${r.enableSessionLog}\uFF0CminLevel=${r.minLevel}`),r.enableGatewayLog){let I;try{let M=async L=>{let D=[Ge.join(L,"plugin-sdk","diagnostics-otel.js"),Ge.join(L,"plugin-sdk","diagnostics-otel")];for(let W of D)try{let ce=(await import(us(W).href)).registerLogTransport;if(ce)return ce}catch{}},R=Ge.dirname(new URL(import.meta.url).pathname);for(let L=0;L<8&&!I;++L){let D=Ge.dirname(R);if(D===R)break;R=D;let W=Ge.join(R,"plugin-sdk");try{let{existsSync:Y}=await import("node:fs");Y(W)&&(I=await M(R))}catch{}}if(!I)try{let D=ds(import.meta.url).resolve("openclaw/package.json"),W=Ge.dirname(D);I=await M(W)}catch{}}catch{}I?l=I(M=>{if(c)try{let A=ps(M);if((vt[A.level]??0)<_)return;let L={log_type:"gateway",level:A.level,message:A.message,source:r.source??"openclaw"};A.subsystem&&(L.subsystem=A.subsystem),A.logger&&(L.logger=A.logger);for(let[D,W]of Object.entries(A.extra))L[D]=W;C(L,Math.floor(A.timestamp/1e3))}catch{}}):g?.warn(`${ae} registerLogTransport \u5728\u5F53\u524D openclaw \u7248\u672C\uFF08>=2026.4.27\uFF09\u4E2D\u5DF2\u79FB\u9664\uFF0Cgateway \u65E5\u5FD7\u4E0A\u62A5\u5DF2\u8DF3\u8FC7`)}},async stop(){l?.(),l=null,u?.(),u=null,c=null,m&&(at(),m=!1),g=null}};function N(K){let x=K.logTopicId!==r.logTopicId,F=K.endpoint!==r.endpoint;if(r={...K},_=vt[r.minLevel??"info"]??2,(x||F)&&c)try{let $=r.secretId,I=r.secretKey,M=r.token;if(o){let A=o.getCredentialSnapshot();$=A.secretId,I=A.secretKey,M=A.token}c=new pt(S($,I,M)),g?.info(`${ae} \u914D\u7F6E\u70ED\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA\uFF0ClogTopicId=${r.logTopicId}\uFF0Cendpoint=${r.endpoint}`)}catch($){g?.warn(`${ae} \u914D\u7F6E\u70ED\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String($)}`)}}function P(K){if(K!==o&&(u?.(),u=null,o=K,c&&o)){let x=o.getCredentialSnapshot();try{c=new pt(S(x.secretId,x.secretKey,x.token)),g?.debug(`${ae} \u51ED\u8BC1\u7BA1\u7406\u5668\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}catch(F){g?.warn(`${ae} \u51ED\u8BC1\u7BA1\u7406\u5668\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String(F)}`)}u=o.subscribe(F=>{if(c)try{c=new pt(S(F.secretId,F.secretKey,F.token)),g?.debug(`${ae} \u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}catch($){g?.warn(`${ae} \u51ED\u8BC1\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String($)}`)}})}}function w(K){r.enableSessionLog&&K.on("before_message_write",(x,F)=>{if(c)try{let $=x?.message;if(!$)return;let I=F?.sessionKey??x?.sessionKey??"",M=F?.agentId??x?.agentId??"",A=Math.floor(Date.now()/1e3),R=fs($),L={log_type:"session",role:R.role,content:R.content,source:r.source??"openclaw"};R.toolCallId&&(L.tool_call_id=R.toolCallId),R.toolName&&(L.tool_name=R.toolName),R.stopReason&&(L.stop_reason=R.stopReason),R.toolCallCount!==void 0&&(L.tool_calls=String(R.toolCallCount)),I&&(L.session_key=I),M&&(L.agent_id=M),C(L,A)}catch{}})}return{service:E,registerHooks:w,updateConfig:N,updateSharedCredentialManager:P}}import gs from"node:http";import ms from"node:https";import{URL as hs}from"node:url";var er="http://metadata.tencentyun.com/latest/meta-data/",ys=er+"cam/security-credentials/",Is=er+"cam/service-role-security-credentials/",Vn="custom-role-",ws=5e3,Yn=3600*1e3,Qn=8192,Zn=3;function tr(t,e=0){if(e>Zn)return Promise.reject(new Error(`Too many redirects (>${Zn}) for ${t}`));let n;try{n=new hs(t)}catch{return Promise.reject(new Error(`Invalid URL: ${t}`))}let r=n.protocol==="https:"?ms:gs;return new Promise((o,c)=>{let l=r.get(t,{timeout:ws},u=>{let g=u.statusCode??0;if(g>=300&&g<400&&u.headers.location){u.resume(),tr(u.headers.location,e+1).then(o,c);return}if(g!==200){u.resume(),c(new Error(`HTTP ${g} for ${t}`));return}let m=[],_=0,S=!1;u.on("data",C=>{if(!S){if(_+=C.length,_>Qn){S=!0,u.destroy(),c(new Error(`Response body too large (>${Qn} bytes) for ${t}`));return}m.push(C)}}),u.on("end",()=>{S||o(Buffer.concat(m).toString("utf-8").trim())}),u.on("error",C=>{S||c(C)})});l.on("timeout",()=>{l.destroy(),c(new Error(`Request timeout for ${t}`))}),l.on("error",c)})}var nn=class t{constructor(e){this.credentialTask=null;this.lastResolvedExpiredTime=null;this.roleName=e}static{this.MAX_EXPIRED_RETRY=3}getRoleUrl(){return this.roleName.indexOf(Vn)===0?ys+this.roleName.slice(Vn.length):Is+this.roleName}async fetchRoleCredential(){let e=await tr(this.getRoleUrl()),n;try{n=JSON.parse(e)}catch{throw new Error(`Failed to parse credential response for role [${this.roleName}]: ${e.slice(0,200)}`)}if(n.Code!=="Success")throw new Error(`Get credential from metadata server by role name [${this.roleName}] failed, Code: ${n.Code}`);if(!n.TmpSecretId||!n.TmpSecretKey)throw new Error(`Credential response for role [${this.roleName}] missing TmpSecretId or TmpSecretKey`);return n}async getCredential(){return this.getCredentialWithRetry(0)}async getCredentialWithRetry(e){this.credentialTask||(this.credentialTask=this.fetchRoleCredential());let n;try{n=await this.credentialTask}catch(r){throw this.credentialTask=null,r}if(n.ExpiredTime*1e3-Yn<=Date.now()){if(e>=t.MAX_EXPIRED_RETRY)throw this.credentialTask=null,new Error(`Credential for role [${this.roleName}] is still expired after ${t.MAX_EXPIRED_RETRY} retries (ExpiredTime=${n.ExpiredTime}, now=${Math.floor(Date.now()/1e3)})`);return this.credentialTask=null,this.getCredentialWithRetry(e+1)}return this.lastResolvedExpiredTime=n.ExpiredTime,{secretId:n.TmpSecretId,secretKey:n.TmpSecretKey,token:n.Token,expiredTime:n.ExpiredTime}}invalidate(){this.credentialTask=null,this.lastResolvedExpiredTime=null}isExpiringSoon(){return this.lastResolvedExpiredTime===null?!0:this.lastResolvedExpiredTime*1e3-Yn<=Date.now()}},He=new Map;function _s(t){let e=He.get(t);return e||(e=new nn(t),He.set(t,e)),e}async function nr(t){if(!t)throw new Error("roleName is required for CVM role credential provider");return _s(t).getCredential()}function Ct(t){let e=He.get(t);return e?e.isExpiringSoon():!0}function rr(t){if(t)He.get(t)?.invalidate();else for(let e of He.values())e.invalidate()}function sr(){He.clear()}var Ts=300*1e3,rn=class t{constructor(e){this.listeners=[];this.refreshTimer=null;this.started=!1;this.stopped=!1;this.log=null;this.refreshingPromise=null;this.credentialMode=e.credentialMode,this.roleName=e.roleName,this.secretId=e.secretId,this.secretKey=e.secretKey,this.token=e.token,this.refreshIntervalMs=e.refreshIntervalMs??Ts}static{this.LOG_PREFIX="[diagnostics-metrics-cls/shared-credential]"}setLogger(e){this.log=e}getCredentialMode(){return this.credentialMode}getRoleName(){return this.roleName}getCredentialSnapshot(){return{secretId:this.secretId,secretKey:this.secretKey,token:this.token}}subscribe(e){return this.listeners.push(e),()=>{let n=this.listeners.indexOf(e);n>=0&&this.listeners.splice(n,1)}}async start(){this.started||(this.started=!0,this.stopped=!1,this.credentialMode==="cvmRole"&&(await this.refreshCredentialInternal(),this.refreshTimer=setInterval(()=>{Ct(this.roleName)&&this.refreshCredentialInternal()},this.refreshIntervalMs),typeof this.refreshTimer.unref=="function"&&this.refreshTimer.unref(),this.log?.debug(`${t.LOG_PREFIX} cvmRole \u51ED\u8BC1\u5B9A\u65F6\u5237\u65B0\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${this.refreshIntervalMs}ms`)))}stop(){this.stopped=!0,this.started=!1,this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),this.listeners=[],sr()}async forceRefresh(){return this.credentialMode==="cvmRole"?this.refreshingPromise?(this.log?.warn(`${t.LOG_PREFIX} \u6536\u5230\u5F3A\u5236\u5237\u65B0\u8BF7\u6C42\uFF0C\u5DF2\u6709\u5237\u65B0\u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u7B49\u5F85\u5B8C\u6210`),await this.refreshingPromise,!0):Ct(this.roleName)?(this.log?.warn(`${t.LOG_PREFIX} \u6536\u5230\u5F3A\u5236\u5237\u65B0\u8BF7\u6C42\uFF0C\u4E34\u65F6\u5BC6\u94A5\u5DF2\u8FC7\u671F\uFF0C\u6B63\u5728\u5237\u65B0 cvmRole \u4E34\u65F6\u5BC6\u94A5`),rr(this.roleName),await this.refreshCredentialInternal(),!0):(this.log?.warn(`${t.LOG_PREFIX} \u6536\u5230\u5F3A\u5236\u5237\u65B0\u8BF7\u6C42\uFF0C\u4F46\u4E34\u65F6\u5BC6\u94A5\u5C1A\u672A\u8FC7\u671F\uFF0C\u8DF3\u8FC7\u5237\u65B0\uFF08401 \u53EF\u80FD\u7531\u6743\u9650\u914D\u7F6E\u7B49\u539F\u56E0\u5BFC\u81F4\uFF09`),!1):(this.log?.warn(`${t.LOG_PREFIX} \u6536\u5230\u5F3A\u5236\u5237\u65B0\u8BF7\u6C42\uFF0C\u5F53\u524D\u4E3A static \u51ED\u8BC1\u6A21\u5F0F\uFF0C\u65E0\u6CD5\u81EA\u52A8\u5237\u65B0`),!1)}updateStaticCredential(e,n,r){(e!==this.secretId||n!==this.secretKey||(r||"")!==(this.token||""))&&(this.secretId=e,this.secretKey=n,this.token=r,this.notifyListeners(),this.log?.debug(`${t.LOG_PREFIX} \u9759\u6001\u51ED\u8BC1\u5DF2\u66F4\u65B0`))}async updateMode(e,n,r,o,c){let l=e!==this.credentialMode,u=n!==this.roleName;this.credentialMode=e,this.roleName=n,e==="static"?(this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null),r!==void 0&&o!==void 0&&(this.secretId=r,this.secretKey=o,this.token=c),this.notifyListeners()):e==="cvmRole"&&(this.started&&(l||u)&&await this.refreshCredentialInternal(),!this.refreshTimer&&this.started&&(this.refreshTimer=setInterval(()=>{Ct(this.roleName)&&this.refreshCredentialInternal()},this.refreshIntervalMs),typeof this.refreshTimer.unref=="function"&&this.refreshTimer.unref()))}async refreshCredentialInternal(){if(!this.stopped){if(this.refreshingPromise){await this.refreshingPromise;return}this.refreshingPromise=this.doRefresh();try{await this.refreshingPromise}finally{this.refreshingPromise=null}}}async doRefresh(){try{let e=await nr(this.roleName);if(this.stopped)return;let n=e.secretId!==this.secretId||e.secretKey!==this.secretKey||(e.token||"")!==(this.token||"");this.secretId=e.secretId,this.secretKey=e.secretKey,this.token=e.token,n&&(this.notifyListeners(),this.log?.debug(`${t.LOG_PREFIX} cvmRole \u4E34\u65F6\u5BC6\u94A5\u5DF2\u5237\u65B0`))}catch(e){this.log?.warn(`${t.LOG_PREFIX} cvmRole \u4E34\u65F6\u5BC6\u94A5\u5237\u65B0\u5931\u8D25: ${String(e)}`)}}notifyListeners(){let e=this.getCredentialSnapshot();for(let n of this.listeners)try{n(e)}catch(r){this.log?.warn(`${t.LOG_PREFIX} \u51ED\u8BC1\u53D8\u66F4\u901A\u77E5\u56DE\u8C03\u5F02\u5E38: ${String(r)}`)}}};function or(t){if(!t)return null;let e=typeof t.credentialMode=="string"&&t.credentialMode.trim()==="cvmRole"?"cvmRole":"static",n=typeof t.roleName=="string"?t.roleName.trim():"",r=typeof t.secretId=="string"?t.secretId.trim():"",o=typeof t.secretKey=="string"?t.secretKey.trim():"",c=typeof t.token=="string"?t.token.trim():void 0,l=typeof t.credentialRefreshIntervalMs=="number"&&t.credentialRefreshIntervalMs>=6e4?t.credentialRefreshIntervalMs:void 0;return new rn({credentialMode:e,roleName:n,secretId:r,secretKey:o,token:c,refreshIntervalMs:l})}var ft=null,he=null,ze=null,ir="";function bs(t){if(!t)return"";let e=["credentialMode","roleName","secretId","secretKey","token","credentialRefreshIntervalMs"],n=[];for(let r of e){let o=t[r];n.push(`${r}=${typeof o=="string"||typeof o=="number"?String(o):""}`)}return n.join("|")}var Ss={id:"clawpro-diagnostics-metrics-cls",name:"Diagnostics Metrics",description:"CLS\u8BCA\u65AD\u6307\u6807\u5BFC\u51FA\u63D2\u4EF6\uFF1APrometheus \u6307\u6807\uFF08pull/remote-write\uFF09+ \u5168\u94FE\u8DEF Trace",configSchema:{type:"object",properties:{prometheus:{type:"object",description:"Prometheus \u6307\u6807\u5BFC\u51FA\u914D\u7F6E",properties:{enabled:{type:"boolean",default:!0,description:"\u662F\u5426\u542F\u7528 Prometheus \u6307\u6807\u5BFC\u51FA"},metric_prefix:{type:"string",default:"openclaw",description:"\u6307\u6807\u540D\u79F0\u524D\u7F00"},pull:{type:"boolean",default:!0,description:"\u662F\u5426\u542F\u7528 /metrics HTTP pull \u7AEF\u70B9"},default_metrics:{type:"boolean",default:!0,description:"\u662F\u5426\u91C7\u96C6 Node.js \u9ED8\u8BA4\u6307\u6807"},push_interval_ms:{type:"number",default:3e4,description:"Remote Write \u63A8\u9001\u95F4\u9694\uFF08\u6BEB\u79D2\uFF09"}}},cls:{type:"object",description:"\u817E\u8BAF\u4E91 CLS \u51ED\u8BC1\u4E0E\u63A5\u5165\u914D\u7F6E",properties:{endpoint:{type:"string",description:"CLS \u63A5\u5165\u70B9"},secretId:{type:"string",description:"\u817E\u8BAF\u4E91 SecretId"},secretKey:{type:"string",description:"\u817E\u8BAF\u4E91 SecretKey"},metricTopicId:{type:"string",description:"\u6307\u6807\u65E5\u5FD7\u4E3B\u9898 ID"},credentialMode:{type:"string",enum:["static","cvmRole"],description:"\u51ED\u8BC1\u6A21\u5F0F"},roleName:{type:"string",description:"CVM \u89D2\u8272\u540D\u79F0"},enableReport:{type:"boolean",default:!0,description:"\u662F\u5426\u542F\u7528\u6307\u6807\u63A8\u9001"}}},log:{type:"object",description:"CLS \u65E5\u5FD7\u4E0A\u62A5\u914D\u7F6E\uFF0C\u5C06 gateway \u8FD0\u884C\u65E5\u5FD7\u3001\u4F1A\u8BDD\u65E5\u5FD7\uFF08session JSONL\uFF09\u5B9E\u65F6\u4E0A\u62A5\u5230 CLS",properties:{enableLogReport:{type:"boolean",default:!1,description:"\u662F\u5426\u542F\u7528\u65E5\u5FD7\u4E0A\u62A5\uFF0C\u9ED8\u8BA4 false"},logTopicId:{type:"string",description:"\u65E5\u5FD7\u4E0A\u62A5\u4F7F\u7528\u7684 CLS \u65E5\u5FD7\u4E3B\u9898 ID"},source:{type:"string",description:"\u65E5\u5FD7\u6765\u6E90\u6807\u8BC6\uFF0C\u9ED8\u8BA4 openclaw"},enableGatewayLog:{type:"boolean",default:!0,description:"\u662F\u5426\u542F\u7528 gateway \u8FD0\u884C\u65E5\u5FD7\u4E0A\u62A5\uFF0C\u9ED8\u8BA4 true"},enableSessionLog:{type:"boolean",default:!0,description:"\u662F\u5426\u542F\u7528\u4F1A\u8BDD\u65E5\u5FD7\u4E0A\u62A5\uFF08session JSONL\uFF09\uFF0C\u9ED8\u8BA4 true"},minLevel:{type:"string",description:"\u6700\u4F4E\u4E0A\u62A5\u65E5\u5FD7\u7EA7\u522B\uFF08\u4EC5\u5BF9 gateway \u8FD0\u884C\u65E5\u5FD7\u751F\u6548\uFF09\uFF0C\u9ED8\u8BA4 info"},sendTimeThreshold:{type:"number",default:2,description:"CLS SDK \u5F02\u6B65\u53D1\u9001\u65F6\u95F4\u9608\u503C\uFF08\u79D2\uFF09\uFF0C\u9ED8\u8BA4 2"},sendCountThreshold:{type:"number",default:1e3,description:"CLS SDK \u5F02\u6B65\u53D1\u9001\u6761\u6570\u9608\u503C\uFF0C\u9ED8\u8BA4 1000"}}},trace:{type:"object",description:"CLS \u5168\u94FE\u8DEF Trace \u8FFD\u8E2A\u914D\u7F6E",properties:{enabled:{type:"boolean",default:!1,description:"\u662F\u5426\u542F\u7528 Trace \u94FE\u8DEF\u8FFD\u8E2A"},traceTopicId:{type:"string",description:"Trace \u65E5\u5FD7\u4E3B\u9898 ID"},serviceName:{type:"string",default:"openclaw-agent",description:"\u670D\u52A1\u540D\u79F0"},debug:{type:"boolean",default:!1,description:"\u662F\u5426\u5F00\u542F\u8C03\u8BD5\u65E5\u5FD7"},batchSize:{type:"number",default:10,description:"Span \u7F13\u51B2\u533A\u5927\u5C0F"},flushIntervalMs:{type:"number",default:5e3,description:"Span \u7F13\u51B2\u533A\u6700\u5927\u7B49\u5F85\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09"},enabledHooks:{type:"array",items:{type:"string"},description:"\u542F\u7528\u7684 hook \u5217\u8868\uFF0C\u4E0D\u8BBE\u7F6E\u5219\u5168\u90E8\u542F\u7528"}}}}},register(t){if(t.registrationMode==="cli-metadata")return;let e=t.pluginConfig?.prometheus,n=t.pluginConfig?.cls,r=t.pluginConfig?.trace,o=t.pluginConfig?.log,c;if(n){if(c={...n},typeof n.secretId=="string")try{c.secretId=ee(n.secretId)}catch{}if(typeof n.secretKey=="string")try{c.secretKey=ee(n.secretKey)}catch{}}let l=bs(c),u;if(ze&&ir===l)u=ze;else if(ze&&c){let C=c.credentialMode==="cvmRole"?"cvmRole":"static",E=typeof c.roleName=="string"?c.roleName:"",N=typeof c.secretId=="string"?c.secretId:"",P=typeof c.secretKey=="string"?c.secretKey:"",w=typeof c.token=="string"?c.token:void 0;ze.updateMode(C,E,N,P,w),u=ze}else u=or(c),ze=u;ir=l;let g={...e,...n},_=kn(g,u,(C,E)=>{if(!he||!C||!E)return;let N={...o??{},enableLogReport:C,logTopicId:E},P=tn(N,n);P&&he.updateConfig(P)});if(u&&t.registerService({id:"diagnostics-metrics-cls-shared-credential",async start(C){u.setLogger(C.logger),await u.start()},async stop(C){C.logger?.debug?.("[diagnostics-metrics-cls] shared-credential service stopping"),u.stop()}}),t.registerService(_),t.registerHttpRoute({path:"/metrics",auth:"plugin",match:"exact",replaceExisting:!0,handler:async(C,E)=>{let N=_.getExports();if(!N?.registry)return E.writeHead(503,{"Content-Type":"text/plain"}),E.end(`Prometheus metrics not initialized
|
|
6
|
+
`),!0;try{let P=await N.registry.metrics();E.writeHead(200,{"Content-Type":N.registry.contentType}),E.end(P)}catch{E.writeHead(500,{"Content-Type":"text/plain"}),E.end(`Failed to collect metrics
|
|
7
|
+
`)}return!0}}),!ft){let C=en(r,n);C.sharedCredentialManager=u,ft=Hn(C)}if(ft.updateSharedCredentialManager(u),ft.registerHooks(t),t.registerService(ft.service),o?.enableLogReport===!0){let C=tn(o,n);C&&(he?he.updateConfig(C):he=zn(C,u,_e),he.updateSharedCredentialManager(u),he.registerHooks(t),t.registerService(he.service))}else he&&(he.service.stop(),he=null)}},zo=Ss;export{zo as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clawpro-diagnostics-metrics-cls",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.6",
|
|
4
4
|
"description": "CLS OpenClaw diagnostics exporter: Prometheus metrics (pull/remote-write) + full-link Trace",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -60,12 +60,13 @@
|
|
|
60
60
|
"node": ">=18"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"tencentcloud-cls-sdk-nodejs": "1.0.3"
|
|
63
|
+
"tencentcloud-cls-sdk-nodejs": "1.0.3",
|
|
64
|
+
"prom-client": "^15.1.3",
|
|
65
|
+
"snappyjs": "^0.7.0"
|
|
64
66
|
},
|
|
65
67
|
"devDependencies": {
|
|
68
|
+
"@types/node": "^25.6.0",
|
|
66
69
|
"typescript": "^5.9.3",
|
|
67
|
-
"esbuild": "^0.25.0"
|
|
68
|
-
"prom-client": "^15.1.3",
|
|
69
|
-
"snappyjs": "^0.7.0"
|
|
70
|
+
"esbuild": "^0.25.0"
|
|
70
71
|
}
|
|
71
72
|
}
|