clawpro-diagnostics-metrics-cls 3.0.6 → 3.0.7
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 +6 -6
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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
|
|
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
|
|
1
|
+
import{Registry as Dr,Counter as ge,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:p}=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: ${p}`);let g;try{g=await this.onUnauthorized()}catch(h){this.logger.error(`diagnostics-prometheus: \u51ED\u8BC1\u5237\u65B0\u5931\u8D25: ${Ft(h)}, dropping ${e.length} samples. Response: ${p}`),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: ${p}`),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: ${p}`),this.recordBatchFailure();return}this.logger.error(`diagnostics-prometheus: remote write 401 Unauthorized, dropping ${e.length} samples. Response: ${p}`),this.recordBatchFailure();return}if(l===400||l===415){this.logger.error(`diagnostics-prometheus: remote write rejected with ${l}, dropping ${e.length} samples. Response: ${p}`),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: ${p}`),await this.sleep(g);continue}this.logger.error(`diagnostics-prometheus: remote write failed after ${this.maxRetries} retries, dropping ${e.length} samples. Response: ${p}`),this.recordBatchFailure();return}this.logger.warn(`diagnostics-prometheus: remote write unexpected status ${l}. Response: ${p}`);return}catch(l){if(c<this.maxRetries){let p=this.calculateBackoff(c);this.logger.warn(`diagnostics-prometheus: remote write error: ${Ft(l)}, retrying in ${p}ms`),await this.sleep(p);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,p={"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)}`)}}p.Authorization=`Basic ${Buffer.from(`${_}:${S}`).toString("base64")}`}else if(this.config.bearer_token)p.Authorization=`Bearer ${this.config.bearer_token}`;else if(this.config.bearer_token_file){let _=this.cachedBearerTokenFileContent??"";if(_)p.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{p.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:p,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 h=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:""})})});h.on("error",r),h.on("timeout",()=>{h.destroy(new Error("remote write request timed out"))}),h.write(Buffer.isBuffer(e)?e:Buffer.from(e)),h.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 ie 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:""}),ye=yn,rt=!1,it=!1,ve=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 p=o.get(n,{timeout:vr},g=>{let h=g.statusCode??0;if(h>=300&&h<400&&g.headers.location){g.resume(),Dt(g.headers.location,e+1).then(c,l);return}if(h!==200){g.resume(),l(new Error(`HTTP ${h} for ${n}`));return}$r(g,n,c,l)});p.on("timeout",()=>{p.destroy(),l(new Error(`Request timeout for ${n}`))}),p.on("error",l)})}function $r(t,e,n,r){let o=[],c=0,l=!1;t.on("data",p=>{if(!l){if(c+=p.length,c>pn){l=!0,t.destroy(),r(new Error(`Response body too large (>${pn} bytes) for ${e}`));return}o.push(p)}}),t.on("end",()=>{l||n(Buffer.concat(o).toString("utf-8").trim())}),t.on("error",p=>{l||r(p)})}async function Er(t){let e={instanceId:"",instanceName:"",localIpv4:""};try{let n=hn.join(t,"openclaw.json"),r=await ie.readFile(n,"utf8"),h=JSON.parse(r).plugins?.entries?.[nt]?.config?.instance_metadata;if(!h)return e;let _=S=>typeof S=="string"&&S.trim()?S.trim():"";return{instanceId:_(h.instance_id),instanceName:_(h.instance_name),localIpv4:_(h.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 ie.open(t,ie.constants.O_CREAT|ie.constants.O_EXCL|ie.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 ie.unlink(t)}catch{}r=null,await new Promise(p=>setTimeout(p,gn*10));continue}if(o.code!=="EEXIST")return!1;if(await Pr(t)){try{await ie.unlink(t)}catch{}continue}await new Promise(p=>setTimeout(p,gn))}}return!1}async function Pr(t){try{let e=await ie.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 ie.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 ie.readFile(o,"utf8");g=JSON.parse(P)}catch{}(!g.plugins||typeof g.plugins!="object")&&(g.plugins={});let h=g.plugins;(!h.entries||typeof h.entries!="object")&&(h.entries={});let _=h.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 ie.writeFile(l,N,"utf8");try{await ie.rename(l,o)}catch(P){if(P.code==="EXDEV"){await ie.copyFile(l,o);try{await ie.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 ie.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=ye,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 p=In(),g={},h={...e,hostName:l||e.hostName};o.status==="fulfilled"&&o.value?(h.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?(h.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"),p?h.cvmInstanceIntraIp=p: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"),ye=Object.freeze(h);let _=!!h.cvmInstanceId&&!!h.cvmInstanceName;return t?.debug(`diagnostics-metrics/instance-metadata: \u5F53\u524D\u5B9E\u4F8B\u4FE1\u606F cvm_instance_id=${ye.cvmInstanceId}, cvm_instance_name=${ye.cvmInstanceName}, cvm_instance_intra_ip=${ye.cvmInstanceIntraIp}, host_name=${ye.hostName}`),{allSuccess:_,fetched:g}}function mn(t){return t.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))}function Re(){return ye}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=ye,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;ye=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,ve&&(clearTimeout(ve),ve=null),jt(e).then(({allSuccess:g,fetched:h})=>{it||(n&&(h.instanceId||h.instanceName)&&Ut(n,h,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(ye=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:p}=await jt(t);if(e&&(p.instanceId||p.instanceName)&&await Ut(e,p,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}ve=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 ve.unref=="function"&&ve.unref()}function at(){ot!==0&&(ot--,!(ot>0)&&(it=!0,ve&&(clearTimeout(ve),ve=null),st=0,rt=!1,ye=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 se(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 Y 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"?se(t.secretId.trim()):"",l=typeof t?.secretKey=="string"?se(t.secretKey.trim()):"",p=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,h=t?.enableReport!==!1;return{metricTopicId:e,credentialMode:r,roleName:o,secretId:c,secretKey:l,token:p,endpoint:n,credentialRefreshIntervalMs:g,enableReport:h}}var qr=1e4;async function Xr(t){try{let e=await Xt.readFile(t,"utf8"),l=JSON.parse(e).plugins?.entries?.[je]?.config,p=l?.cls,g=typeof p?.metricTopicId=="string"?p.metricTopicId.trim():"",h=typeof p?.endpoint=="string"?p.endpoint.trim():"",_=p?.enableReport!==!1,S=typeof p?.secretId=="string"?se(p.secretId.trim()):"",C=typeof p?.secretKey=="string"?se(p.secretKey.trim()):"",E=g;g&&!Sn(g)&&(E=void 0);let N=l?.instance_metadata,P=O=>typeof O!="string"?null:O.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:h,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=Y.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=[],p=null,g=null,h=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",O={...A?.external_labels??{}};await Tt(M,I.stateDir).catch(y=>{let L=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 (${L})\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 ge({name:`${R}_tokens_total`,help:"Total tokens consumed",labelNames:["openclaw_type","openclaw_provider","openclaw_model","openclaw_channel"],registers:[o]}),q=new ge({name:`${R}_cost_usd_total`,help:"Estimated model cost in USD",labelNames:["openclaw_provider","openclaw_model","openclaw_channel"],registers:[o]}),ee=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]}),de=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]}),_e=new ge({name:`${R}_webhook_received_total`,help:"Webhook requests received",labelNames:["openclaw_channel","openclaw_update_type"],registers:[o]}),xe=new ge({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 ge({name:`${R}_message_queued_total`,help:"Messages queued for processing",labelNames:["openclaw_channel","openclaw_source"],registers:[o]}),Te=new ge({name:`${R}_message_processed_total`,help:"Messages processed by outcome",labelNames:["openclaw_channel","openclaw_outcome"],registers:[o]}),me=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]}),X=new ge({name:`${R}_queue_lane_enqueue_total`,help:"Queue lane enqueue events",labelNames:["openclaw_lane"],registers:[o]}),Ke=new ge({name:`${R}_queue_lane_dequeue_total`,help:"Queue lane dequeue events",labelNames:["openclaw_lane"],registers:[o]}),Et=new ge({name:`${R}_session_state_total`,help:"Session state transitions",labelNames:["openclaw_state","openclaw_reason"],registers:[o]}),mt=new ge({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 ge({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 ge({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 L={openclaw_provider:y.provider??"unknown",openclaw_model:y.model??"unknown",openclaw_channel:y.channel??"unknown"},W=y.usage;if(!W)break;W.input&&D.inc({...L,openclaw_type:"input"},W.input),W.output&&D.inc({...L,openclaw_type:"output"},W.output),W.cacheRead&&D.inc({...L,openclaw_type:"cache_read"},W.cacheRead),W.cacheWrite&&D.inc({...L,openclaw_type:"cache_write"},W.cacheWrite),W.promptTokens&&D.inc({...L,openclaw_type:"prompt"},W.promptTokens),W.total&&D.inc({...L,openclaw_type:"total"},W.total),y.costUsd&&q.inc({openclaw_provider:L.openclaw_provider,openclaw_model:L.openclaw_model,openclaw_channel:L.openclaw_channel},y.costUsd),y.durationMs&&ee.observe({openclaw_provider:L.openclaw_provider,openclaw_model:L.openclaw_model,openclaw_channel:L.openclaw_channel},y.durationMs),y.context?.limit&&de.observe({openclaw_provider:L.openclaw_provider,openclaw_model:L.openclaw_model,openclaw_channel:L.openclaw_channel,openclaw_type:"limit"},y.context.limit),y.context?.used&&de.observe({openclaw_provider:L.openclaw_provider,openclaw_model:L.openclaw_model,openclaw_channel:L.openclaw_channel,openclaw_type:"used"},y.context.used);break}case"webhook.received":{_e.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":{Te.inc({openclaw_channel:y.channel??"unknown",openclaw_outcome:y.outcome??"unknown"}),typeof y.durationMs=="number"&&me.observe({openclaw_channel:y.channel??"unknown",openclaw_outcome:y.outcome??"unknown"},y.durationMs);break}case"queue.lane.enqueue":{X.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(L){I.logger.error(`diagnostics-metrics/prometheus: event handler failed (${y.type}): ${Rn(L)}`)}},fe;try{let y=async(H,U)=>{let ne=[Y.join(H,U+".js"),Y.join(H,U)];for(let he of ne)try{return await import(jr(he).href)}catch{}},L=async H=>{let U=[[H,"plugin-sdk/diagnostics-otel"],[H,"plugin-sdk/diagnostic-runtime"],[H,"plugin-sdk/runtime"],[H,"dist/plugin-sdk/diagnostics-otel"],[H,"dist/plugin-sdk/diagnostic-runtime"],[H,"dist/plugin-sdk/runtime"]];for(let[ne,he]of U){let s=await y(ne,he);if(s?.onDiagnosticEvent)return s.onDiagnosticEvent}},W=Y.dirname(new URL(import.meta.url).pathname),{existsSync:te,readFileSync:Se}=await import("node:fs"),ue=W;for(let H=0;H<8&&!fe;++H){let U=Y.dirname(ue);if(U===ue)break;ue=U;let ne=Y.join(ue,"plugin-sdk"),he=Y.join(ue,"dist","plugin-sdk"),s=Y.join(ue,"package.json");try{if(!te(s)||!te(ne)&&!te(he)||JSON.parse(Se(s,"utf-8")).name!=="openclaw")continue;fe=await L(ue)}catch{}}if(!fe)try{let U=Ur(import.meta.url).resolve("openclaw/package.json"),ne=Y.dirname(U);fe=await L(ne)}catch{}if(!fe)try{let H=process.argv[1];if(H){let U=Y.dirname(Y.resolve(H));for(let ne=0;ne<8&&!fe;++ne){let he=Y.join(U,"plugin-sdk"),s=Y.join(U,"dist","plugin-sdk"),a=Y.join(U,"package.json");try{let d=te(a),i=te(he)||te(s);if(!d||!i){let m=Y.dirname(U);if(m===U)break;U=m;continue}if(JSON.parse(Se(a,"utf-8")).name!=="openclaw"){let m=Y.dirname(U);if(m===U)break;U=m;continue}fe=await L(U)}catch{}let f=Y.dirname(U);if(f===U)break;U=f}}}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)}`)}fe?c=fe(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=Re().cvmInstanceId,K=Re().cvmInstanceName,x=Re().cvmInstanceIntraIp;let Me=A?.remote_write??[],be=r?.credentialMode??"static",sn=r?.roleName||"",At=Y.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()):be==="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),z=bn(C,S),Ce=Me.some(y=>!y.url),Qe=Me.some(y=>y.url);if(z&&Ce&&!Qe){let y=Me.find(L=>!L.url);y&&(l=[new Le({...y,url:z},M,De)])}else z&&Me.length===0?l=[new Le({url:z},M,De)]:l=Me.filter(y=>y.url).map(y=>new Le(y,M,De));let $e=A?.push_interval_ms??3e4;if(l.length>0&&E?(p=setInterval(()=>{St(o,l,O,M)},$e),typeof p.unref=="function"&&p.unref(),I.logger.debug?.(`diagnostics-metrics/prometheus: remote write enabled for ${l.length} target(s), push interval ${$e}ms`)):l.length>0&&!E&&I.logger.debug?.("diagnostics-metrics/prometheus: remote write clients created but pushTimer not started (enableReport=false)"),be==="static"&&r&&l.length>0&&!e){let y=r.secretKey;r.token!==void 0&&r.token!==""&&(y=y+"#"+r.token);let L={username:r.secretId,password:y};for(let W of l)W.updateConfig({basic_auth:L});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 L=y.secretKey;y.token!==void 0&&y.token!==""&&(L=L+"#"+y.token);let W={username:y.secretId,password:L};for(let te of l)te.updateConfig({basic_auth:W});l.length>0&&!p&&E&&(p=setInterval(()=>{St(o,l,O,M)},$e),typeof p.unref=="function"&&p.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(L=>{Ne(L),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;h=setInterval(()=>{(async()=>{if(!Be){Be=!0;try{let y=await Xr(At);if(!y)return;let L=y.metricTopicId??Ye,W=y.endpoint??wt,te=y.enableReport,Se=y.secretId,ue=y.secretKey,H=y.instanceId,U=y.instanceName,ne=y.localIpv4,he=L!==S,s=W!==C,a=Re();!w&&a.cvmInstanceId&&(w=a.cvmInstanceId),!K&&a.cvmInstanceName&&(K=a.cvmInstanceName),!x&&a.cvmInstanceIntraIp&&(x=a.cvmInstanceIntraIp);let f=H!==w||U!==K||ne!==x,d=te!==E,i=be==="static"&&Se&&ue&&(Se!==N||ue!==P);if(f&&(w=H,K=U,x=ne,wn({instanceId:H,instanceName:U,localIpv4:ne},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=Se,P=ue,e&&be==="static")e.updateStaticCredential(N,P);else if(l.length>0){let m=P;r?.token!==void 0&&r.token!==""&&(m=m+"#"+r.token);let T={username:N,password:m};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=te,E?(l.length>0&&!p&&(p=setInterval(()=>{St(o,l,O,M)},$e),typeof p.unref=="function"&&p.unref()),I.logger.debug?.("diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CenableReport=true\uFF0C\u5DF2\u6062\u590D remote write \u63A8\u9001")):(p&&(clearInterval(p),p=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 m=y.enableLogReport,T=y.logTopicId;(m!==F||T!==$)&&(F=m,$=T,n(m,T),I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Clog \u914D\u7F6E\u5DF2\u53D8\u66F4\uFF08enableLogReport=${m}\uFF0ClogTopicId=${T||"(\u7A7A)"}\uFF09`))}if(!he&&!s)return;S=L,C=W;let u=bn(C,S);if(!u){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 m of l)m.stop().catch(()=>{});l=[],p&&(clearInterval(p),p=null)}return}if(l.length>0){for(let m of l)m.updateConfig({url:u});I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0C\u5DF2\u66F4\u65B0 RemoteWriteClient url=${u}`)}else{let m=new Le({url:u},M,De);if(l=[m],e){let T=e.getCredentialSnapshot();T.secretId&&T.secretKey&&Ne(T)}else be==="static"&&N&&P&&m.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&&!p&&(p=setInterval(()=>{St(o,l,O,M)},$e),typeof p.unref=="function"&&p.unref()),I.logger.debug?.(`diagnostics-metrics/prometheus: \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0C\u52A8\u6001\u521B\u5EFA RemoteWriteClient url=${u}`)}}finally{Be=!1}}})()},qr),h&&typeof h.unref=="function"&&h.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,h&&(clearInterval(h),h=null),_&&(_(),_=null),p&&(clearInterval(p),p=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=Re(),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(),p=Date.now(),g=[];for(let h of l){let _=h.values;for(let S of _){let E=[{name:"__name__",value:S.metricName??h.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:p}]})}}if(g.length===0)return;for(let h of e)h.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 oe(t=16){let e=Math.ceil(t/2);return Hr(e).toString("hex").slice(0,t)}function Ie(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 p=JSON.stringify(n);if(p.length<=Oe)return p;let g=!1;for(let h of r){let _=n[h];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=(p,g)=>{typeof p=="string"&&(p.length<=e||(!n||p.length>n.value.length)&&(n={set:g,value:p}))};if(r(t.content,p=>{t.content=p}),Array.isArray(t.tool_calls))for(let p of t.tool_calls)!p||typeof p!="object"||r(p.arguments,g=>{p.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),p=t.length-1-n,g=t.slice(1,t.length-n).reduce((C,E)=>C+JSON.stringify(E).length,0),h={role:"system",content:`[...omitted ${p} messages, total ${g} chars]`},_=[e,h,...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 Ie(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}]}),Ie(JSON.stringify(n))}function qe(t,e="stop"){return Ie(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?Ie(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 Z(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_${oe(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",p=r.toolCalls??Zt(r.content);p.length>0?(o.finish_reason="tool_calls",o.tool_calls=p.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 ce}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,p]of Object.entries(r))p!=null&&(o.attributes[l]=p);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,p=new Promise(g=>{l=setTimeout(g,o)});Promise.race([c(),p]).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||"",p=e.kind||"INTERNAL",g=e.status||"OK",h=e.startTime,_=e.endTime,S=e.durationMs,C=h?new Date(h).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,q]of Object.entries(e))ss.has(D)||q!=null&&($[D]=q);S!=null&&($.durationMs=String(S));for(let[D,q]of Object.entries(n))q!=null&&($[D]=String(q));let I=this.mapSpanKindToString(p),M=g==="OK"?"OK":g==="ERROR"?"ERROR":"UNSET",A=JSON.stringify($),R=new ns;R.setTime(Math.floor(C/1e3)),R.pushBack(new ce("traceID",r)),R.pushBack(new ce("spanID",o)),R.pushBack(new ce("parentSpanID",c)),R.pushBack(new ce("kind",I)),R.pushBack(new ce("name",l)),R.pushBack(new ce("links","[]")),R.pushBack(new ce("logs","[]")),R.pushBack(new ce("traceState","")),R.pushBack(new ce("start",K)),R.pushBack(new ce("end",x)),R.pushBack(new ce("duration",F)),R.pushBack(new ce("attribute",A)),R.pushBack(new ce("statusCode",M)),R.pushBack(new ce("statusMessage",""));let O=this.producer.send(R);O&&typeof O.catch=="function"&&O.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,p=l?.trace,g=p?.enabled!==!1,h=typeof p?.traceTopicId=="string"?p.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"?se(_.secretId.trim()):""}catch(F){console.warn(`[diagnostics-metrics-cls/trace] readTraceHotConfigFromDisk: secretId decrypt failed: ${String(F)}`)}try{w=typeof _?.secretKey=="string"?se(_.secretKey.trim()):""}catch(F){console.warn(`[diagnostics-metrics-cls/trace] readTraceHotConfigFromDisk: secretKey decrypt failed: ${String(F)}`)}let K=p?.debug===!0,x=Array.isArray(p?.enabledHooks)?p.enabledHooks:void 0;return{enabled:g,traceTopicId:h,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"?se(e.secretId.trim()):""}catch(S){console.warn(`[diagnostics-metrics-cls/trace] resolveTraceConfig: secretId decrypt failed: ${String(S)}`)}try{l=typeof e?.secretKey=="string"?se(e.secretKey.trim()):""}catch(S){console.warn(`[diagnostics-metrics-cls/trace] resolveTraceConfig: secretKey decrypt failed: ${String(S)}`)}let p=typeof e?.token=="string"?e.token.trim():void 0,g=typeof e?.credentialMode=="string"&&e.credentialMode.trim()==="cvmRole"?"cvmRole":"static",h=typeof e?.roleName=="string"?e.roleName.trim():void 0;return{enabled:n&&(g==="cvmRole"?!!(r&&o&&h):!!(r&&o&&c&&l)),traceTopicId:r,endpoint:o,secretId:c,secretKey:l,token:p,credentialMode:g,roleName:h,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",p=t.roleName??"",g=t.sharedCredentialManager??null,h=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=Re(),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)}`):h&&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,O=new Map,D=new Map,q,ee,de,_e="unknown",xe=null,k=null,Fe=!1,Te=new Set,me=new Map,gt=2e3;function $t(){let s=Date.now(),a=new Set,f=[];for(let[u,m]of $)s-m.createdAt>Ht&&(f.push(u),a.add(m));for(let u of f)$.delete(u);for(let u of a)I.delete(u.runId);if(a.size>0){let u=[];for(let[T,v]of M){for(let J of a)v.delete(J);v.size===0&&u.push(T)}for(let T of u)M.delete(T);let m=[];for(let[T,v]of A)a.has(v)&&m.push(T);for(let T of m)A.delete(T);ee&&a.has(ee)&&(ee=void 0,q=void 0,de=void 0)}let d=[];for(let[u,m]of R)(s-m.createdAt>Ht||a.has(m.traceContext))&&d.push(u);for(let u of d)R.delete(u);let i=[];for(let[u,m]of D)s-m.createdAt>Nn&&i.push(u);for(let u of i)D.delete(u);w&&w.sweepStaleOpenSpans()}function X(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 u=dt(i.toolCallId,a);R.has(u)&&h&&k?.warn(`${b} movePendingToolCallsRunBinding: key collision detected, overwriting existing entry: ${u}`),R.set(u,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 u=s.runId;if(!Ke(u))return;I.get(u)===s&&I.delete(u),s.runId=d,s.turnId=d,I.set(d,s),Et(u,d);let m={"openclaw.run.id":d,"openclaw.turn.id":d};w?.patchOpenSpanAttributes(s.rootSpanId,m),s.agentSpanId&&w?.patchOpenSpanAttributes(s.agentSpanId,m),s.stepSpanId&&w?.patchOpenSpanAttributes(s.stepSpanId,m),h&&k?.info(`${b} Rebound temporary runId: hook=${f}, oldRunId=${u}, realRunId=${d}`)}function ht(s,a){if(Fe)return Promise.resolve();if(O.size>=Pn)return k?.warn(`${b} trace task queue size (${O.size}) exceeded limit, dropping task for trace ${s}`),Promise.resolve();let f=O.get(s)||Promise.resolve(),d=()=>{let m,T=new Promise((v,J)=>{m=setTimeout(()=>J(new Error(`trace task timeout after ${zt}ms`)),zt)});return Promise.race([a(),T]).finally(()=>{m!==void 0&&clearTimeout(m)})},i=f.catch(()=>{}).then(d),u;return u=i.finally(()=>{O.get(s)===u&&O.delete(s)}),O.set(s,u),u}async function yt(s){if(!s)return;let a=O.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 u=[dt(f,a),dt(f,void 0)];for(let m of u){let T=R.get(m);if(T)return R.delete(m),T}}let d,i;for(let[u,m]of R)m.toolName===s.toolName&&(a&&m.runId!==a||!a&&m.runId||(!i||m.toolStartTime>i.toolStartTime)&&(i=m,d=u));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 fe(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 Te)clearTimeout(f);Te.clear();for(let f of me.values())clearTimeout(f);me.clear();let a=Array.from(O.values());a.length>0&&await Promise.allSettled(a),O.clear(),R.clear(),D.clear(),$.clear(),I.clear(),M.clear(),A.clear(),ee=void 0,q=void 0,de=void 0,s&&w&&(await w.dispose(),w=null)}function wt(){R.clear(),D.clear(),$.clear(),I.clear(),M.clear(),A.clear(),ee=void 0,q=void 0,de=void 0;for(let s of Te)clearTimeout(s);Te.clear();for(let s of me.values())clearTimeout(s);me.clear()}function Me(s){let a=$.get(s);a&&be(a)}function be(s){I.get(s.runId)===s&&I.delete(s.runId);let a=[];for(let[i,u]of $)u===s&&a.push(i);for(let i of a)$.delete(i);let f=[];for(let[i,u]of M)u.has(s)&&(u.delete(s),u.size===0&&f.push(i));for(let i of f)M.delete(i);let d=[];for(let[i,u]of A)u===s&&d.push(i);for(let i of d)A.delete(i);D.delete(s.traceId),ee===s&&(ee=void 0,q=void 0,de=void 0)}function sn(s,a,f){let i={traceId:oe(32),rootSpanId:oe(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,u)=>(u.agentStartTime||u.createdAt)-(i.agentStartTime||i.createdAt)),d[0])}function De(s){let a=I.get(s);return a?.originalChannelId||a?.channelId}function z(s,a,f){let d=s,i=s.startsWith("agent/")?s:void 0,u=i&&A.get(i)||$.get(s),m=Xe(a),T=m||u?.runId||`__temp_run_${oe(12)}`,v=()=>s.startsWith("agent/")&&!!ee&&!!de&&Date.now()-(de||0)<vn,J=()=>{if(!ee)return;let B=ee;if(!(m&&B.runId!==m&&!Ke(B.runId)))return d=q||d,Ve(s,B),I.set(T,B),h&&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,u=$.get(B)||u)}if(u||(u=I.get(T)),f==="agent_end"&&!m&&(u=At(d,u)),!u&&v()&&(u=J()),f==="message_received"&&!s.startsWith("agent/")&&u&&(u.agentSpanId||u.hasSeenLlmInput||u.isClosing)&&(u=void 0,m||(T=`__temp_run_${oe(12)}`)),u&&m&&u.runId!==m&&!Ke(u.runId)&&(u=void 0,T=m),u&&m&&Ke(u.runId)){let B=I.get(m);B&&B!==u&&(u=B,Ve(d,u))}!u&&v()&&(u=J());let j=!1;return u||(u=sn(T,d,s!==d?s:void 0),j=!0,h&&k?.info(`${b} NEW TraceContext: hook=${f}, channelId=${d}, runId=${T}, traceId=${u.traceId}`)),i&&u&&!u.isClosing&&A.set(i,u),u&&a&&mt(u,a,f),{ctx:u,channelId:d,isNew:j}}function Ce(s,a,f,d,i,u,m={},T){return{name:f,type:d,startTime:i,endTime:u,attributes:{...m,"openclaw.version":_e,"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:oe(16),parentSpanId:T||s.rootSpanId}}function Qe(s){return s.agentSpanId||s.rootSpanId}function $e(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,u=d<i?i:d,m=s.llmProvider||"unknown",T=s.llmModel||"unknown",v=f.stopReason||"stop",J=f.usage?.input??0,j=f.usage?.output??0,B=f.usage?.cacheRead??0,ae=f.usage?.cacheWrite??0,Pe=f.usage?.total??J+j+B+ae,re={"gen_ai.span.kind":"LLM","gen_ai.operation.name":"chat","gen_ai.provider.name":m,"gen_ai.system":m,"gen_ai.request.model":T,"gen_ai.response.model":T,"gen_ai.usage.input_tokens":J,"gen_ai.usage.output_tokens":j,"gen_ai.usage.total_tokens":Pe,"gen_ai.usage.cache_read.input_tokens":B,"gen_ai.usage.cache_creation.input_tokens":ae,"llm.request.type":"chat"};s.llmPendingSystemInstructions&&(re["gen_ai.system_instructions"]=s.llmPendingSystemInstructions);let V=s.llmPendingInputMessages||s.llmLastInputMessages;V&&(re["gen_ai.input.messages"]=V),(f.outputContent!==void 0||f.outputTexts.length>0)&&(re["gen_ai.output.messages"]=Kn(f.outputContent,f.outputTexts,v)),re["gen_ai.response.finish_reasons"]=JSON.stringify([v]);try{if(V){let G=JSON.parse(V);if(Array.isArray(G)){let ke=G.map(pe=>({role:pe.role,content:Array.isArray(pe.parts)?pe.parts.filter(Ae=>Ae.type==="text").map(Ae=>Ae.content).join(""):""}));Jn(re,ke)}}if(f.outputTexts.length>0){let G=[{role:"assistant",content:f.outputTexts.join(""),stopReason:v,toolCalls:f.outputContent?Zt(Array.isArray(f.outputContent)?f.outputContent:void 0):void 0}];G[0].toolCalls?.length===0&&delete G[0].toolCalls,Wn(re,G)}}catch(G){h&&k?.warn(`${b} Failed to set indexed prompt/completion attrs: ${String(G)}`)}let Q=Ce(s,a,`chat ${T}`,"model",i,u,re,$e(s));s.llmPendingSpanId&&(Q.spanId=s.llmPendingSpanId);try{w.export(Q),k?.debug(`${b} [span] Exported LLM span: ${m}/${T}, traceId=${s.traceId}, spanId=${Q.spanId}, duration=${u-i}ms`),h&&k?.info(`${b} Exported segmented LLM span: ${m}/${T}, duration=${u-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),u=Un(f.content),m=typeof f.stopReason=="string"?f.stopReason:i.length>0?"toolUse":"stop";s.llmPendingStartTime||(s.llmPendingStartTime=d),s.llmPendingSpanId||(s.llmPendingSpanId=oe(16)),await Ne(s,a,{endTime:d,outputTexts:u,outputContent:f.content,stopReason:m,usage:f.usage}),u.length>0&&(s.lastOutput=u.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&&te(s,d,m,a),h&&k?.info(`${b} Processed assistant message: runId=${s.runId}, toolCalls=${i.length}, stopReason=${m}`)}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":_e};s.userInput&&(i["gen_ai.input.messages"]=Ie(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 L(s,a,f){if(s.agentSpanId||!w)return;let d=Date.now();s.agentStartTime=d,s.agentSpanId=oe(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":_e},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 W(s,a,f){if(s.stepSpanId||!w)return;let d=s.stepRoundCounter+1,i=oe(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":_e},traceId:s.traceId,spanId:i,parentSpanId:Qe(s)},i),s.stepSpanId=i,s.stepStartTime=f,s.stepRoundCounter=d,s.stepCurrentRound=d,s.stepAwaitingToolResults=!1,h&&k?.info(`${b} Started step span: round=${d}, spanId=${i}`)}function te(s,a,f,d){if(!s.stepSpanId||!w)return;let i=s.stepSpanId,u=s.stepCurrentRound||s.stepRoundCounter||1;w.endSpanById(i,a,{"gen_ai.react.round":u,"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,h&&k?.info(`${b} Ended step span: round=${u}, reason=${f}, spanId=${i}`)}function Se(s){s.acpFallbackPending=!1;let a=me.get(s.traceId);a&&(clearTimeout(a),me.delete(s.traceId))}function ue(s,a){if(!s.acpFallbackPending||!w)return;let f=me.get(s.traceId);f&&clearTimeout(f);let d=w,i=setTimeout(async()=>{if(me.delete(s.traceId),Te.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 u=Date.now(),m={"request.duration_ms":u-s.rootSpanStartTime,"openclaw.acp_mode":!0};s.sessionId&&(m["openclaw.session.id"]=s.sessionId,m["gen_ai.session.id"]=s.sessionId),s.userInput&&(m["gen_ai.input.messages"]=Ie(JSON.stringify([{role:"user",parts:[{type:"text",content:String(s.userInput)}]}]))),s.lastOutput&&(m["gen_ai.output.messages"]=qe([typeof s.lastOutput=="string"?s.lastOutput:JSON.stringify(s.lastOutput)])),d.endSpanById(s.rootSpanId,u,m),k?.debug(`${b} [acp-fallback] Ended entry span: spanId=${s.rootSpanId}, traceId=${s.traceId}, duration=${u-s.rootSpanStartTime}ms`)}fe(a,s),be(s),d&&!d.isDisposed&&(await d.flush(),k?.debug(`${b} [acp-fallback] Flushed after ACP fallback close, traceId=${s.traceId}`))}catch(u){k?.warn(`${b} [acp-fallback] Error closing Entry Span: ${String(u)}`)}}},gt);me.set(s.traceId,i),Te.add(i)}let H={id:"diagnostics-metrics-cls-trace",async start(s){if(k=s.logger,_e=s.runtime?.version||"unknown",Fe=!1,_&&e&&n&&(l==="cvmRole"?!!p:!!(r&&o))){let i;if(g){let u=g.getCredentialSnapshot();i={secretId:u.secretId,secretKey:u.secretKey,token:u.token},r=u.secretId,o=u.secretKey,c=u.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 u=new kt(F(i));w=new ut(u,e,h,k,P),k.debug(`${b} CLS Producer \u5DF2\u521D\u59CB\u5316\uFF0Cendpoint=${n} traceTopicId=${e} credentialMode=${l}`),g&&!x&&(x=g.subscribe(m=>{if(!w||w.isDisposed||!(m.secretId!==r||m.secretKey!==o||(m.token||"")!==(c||"")))return;r=m.secretId,o=m.secretKey,c=m.token;let v=new kt(F(m));w.updateProducer(v,e),h&&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 u=i.enabled,m=i.traceTopicId,T=i.endpoint,v=i.secretId,J=i.secretKey,j=i.token,B=i.debug;B!==h&&(h=B,w&&(w.debug=h),k.debug(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0Ctrace.debug=${h}`));let ae=i.enabledHooks;JSON.stringify(ae)!==JSON.stringify(S)&&(S=ae,k.debug(`${b} \u914D\u7F6E\u6587\u4EF6\u70ED\u66F4\u65B0\uFF0CenabledHooks=${S?S.join(","):"\u5168\u90E8\u542F\u7528"}`));let re=u!==_;if(re)if(_=u,_)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 V=i.credentialMode,Q=i.roleName,G=m!==e,ke=T!==n,pe=!g&&(v!==r||J!==o),Ae=!g&&(j||"")!==(c||""),Lt=V!==l,Ot=Q!==p;if(!(re||G||ke||pe||Ae||Lt||Ot))return;if(G&&(e=m),ke&&(n=T),Lt&&(l=V),Ot&&(p=Q),pe&&(r=v,o=J),Ae&&(c=j||void 0),l==="cvmRole"?!e||!n||!p:!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,h,k,P),Fe=!1;let Ee=[];re&&Ee.push("enabled=true"),G&&Ee.push(`traceTopicId=${e}`),ke&&Ee.push(`endpoint=${n}`),Lt&&Ee.push(`credentialMode=${l}`),Ot&&Ee.push(`roleName=${p}`),pe&&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 U(s){k=s.logger,_e=s.runtime?.version||_e,s.on("gateway_stop",async()=>{await Ye()}),s.on("gateway_start",async a=>{try{if(!X("gateway_start")||!w)return;let f=Date.now(),d=oe(32),i=oe(16),u={name:"gateway_start",type:"gateway",startTime:f,endTime:f,attributes:{"openclaw.version":_e,"gen_ai.span.kind":"ENTRY","gateway.port":a.port},traceId:d,spanId:i,parentSpanId:""};w.export(u)}catch(f){k?.warn(`${b} [hook] gateway_start ERROR: ${String(f)}`)}}),s.on("session_start",async(a,f)=>{try{if(!X("session_start")||!w)return;let d=Z(f,a.sessionId),{ctx:i,channelId:u}=z(d,a?.runId,"session_start");a.sessionId&&(i.sessionId=a.sessionId);let m=Date.now(),T=Ce(i,u,"session_start","session",m,m,{"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(!X("session_end")||!w)return;let d=Z(f,a.sessionId),{ctx:i,channelId:u}=z(d,a?.runId,"session_end"),m=Date.now(),T=Ce(i,u,"session_end","session",m,m,{"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(u)}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=${X("message_received")}`),!X("message_received")||!w)return;let d=Z(f,a.from||a.metadata?.senderId),{ctx:i,channelId:u}=z(d,a?.runId,"message_received");!d.startsWith("agent/")&&(q=u,ee=i,de=Date.now(),i.userInput=a.content,y(i,u,{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(!X("message_sending"))return;let d=Z(f,a.to),{ctx:i}=z(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(!X("message_sent"))return;if(a.content&&a.success){let d=Z(f,a.to),{ctx:i,channelId:u}=z(d,a?.runId,"message_sent");i.lastOutput=a.content,i.acpFallbackPending&&ue(i,u)}}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=${X("llm_input")}`),!X("llm_input")||!w)return;let d=Z(f),{ctx:i,channelId:u}=z(d,a.runId,"llm_input");Se(i),a.sessionId&&(i.sessionId=a.sessionId),!i.userInput&&a.prompt&&(i.userInput=a.prompt),y(i,u,{userId:f.trigger||"system",role:f.trigger||"system",from:f.agentId||"openclaw"}),L(i,u,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=oe(16),W(i,u,i.llmPendingStartTime),i.llmPendingToolCallIds.clear(),i.llmPendingToolCallCountFallback=0,a.systemPrompt&&(i.llmPendingSystemInstructions=Fn(a.systemPrompt));let m=a.historyMessages?.length?a.historyMessages.map(v=>Yt(v)):[];i.llmPendingInputMessages=Qt(m,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,u,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)}`)}}h&&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(!X("llm_output")||!w)return;let d=Z(f),{ctx:i,channelId:u}=z(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 m=Date.now(),T=a.lastAssistant,v=typeof T?.stopReason=="string"?T.stopReason:void 0;await Ne(i,u,{endTime:m,outputTexts:a.assistantTexts||[],stopReason:v,usage:a.usage}),te(i,m,v||"stop",u)}}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=${X("before_message_write")}, role=${a?.message?.role}`),!X("before_message_write")||!w)return;let d=a.message;if(!d||d.role!=="assistant")return;let i=Z(f),u=i.startsWith("agent/")?A.get(i):void 0;if(i.startsWith("agent/")&&!u)return;let{ctx:m,channelId:T}=u?{ctx:u,channelId:u.channelId}:z(i,void 0,"before_message_write");if(!m.hasSeenLlmInput){D.set(m.traceId,{message:d,createdAt:Date.now()});return}try{ht(m.traceId,async()=>{await Be(m,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(!X("before_tool_call")||!w)return;let d=Z(f),i=d.startsWith("agent/")?A.get(d):void 0;if(d.startsWith("agent/")&&!i)return;let{ctx:u,channelId:m}=i?{ctx:i,channelId:i.channelId}:z(d,Xe(a.runId),"before_tool_call");if(i&&a.runId&&mt(u,a.runId,"before_tool_call"),!u.hasSeenLlmInput)return;let T=Xe(a.runId)||u.runId,v=Rt(a.toolCallId)||`call_${oe(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:oe(16),toolStartTime:Date.now(),toolInput:a.params,traceContext:u,channelId:m,createdAt:Date.now()}),h&&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(!X("after_tool_call")||!w)return;let f=Mt(a);if(!f)return;let{toolName:d,toolCallId:i,toolSpanId:u,toolStartTime:m,toolInput:T,traceContext:v,channelId:J}=f,j=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||j-m};T!==void 0&&(B["gen_ai.tool.call.arguments"]=Ie(typeof T=="string"?T:JSON.stringify(T))),a.error?B["error.type"]=a.error:a.result!==void 0&&(B["gen_ai.tool.call.result"]=Ie(typeof a.result=="string"?a.result:JSON.stringify(a.result)));let ae=Ce(v,J,`execute_tool ${d}`,"tool",m,j,B,$e(v));ae.spanId=u,w.export(ae);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 Q=v.llmPendingToolCallIds.values().next().value;Q&&v.llmPendingToolCallIds.delete(Q)}}else v.llmPendingToolCallCountFallback>0&&(v.llmPendingToolCallCountFallback-=1);if(v.llmPendingToolCallIds.size===0&&v.llmPendingToolCallCountFallback===0){let Q=[];v.llmLastAssistantContent!==void 0&&Q.push({role:"assistant",content:v.llmLastAssistantContent}),v.llmPendingToolResultsForNextInput.length>0&&Q.push(...v.llmPendingToolResultsForNextInput),te(v,j,"toolUse",J),v.llmPendingStartTime=j,v.llmPendingSpanId=oe(16),W(v,J,j),v.llmPendingSystemInstructions=void 0,v.llmPendingInputMessages=Q.length>0?Qt(Q):void 0,v.llmLastInputMessages=v.llmPendingInputMessages,v.llmPendingToolResultsForNextInput=[]}}h&&k?.info(`${b} Exported tool span: ${d}, duration=${j-m}ms`)}catch(f){k?.warn(`${b} [hook] after_tool_call ERROR: ${String(f)}`)}},{priority:-100}),s.on("before_compaction",async(a,f)=>{try{if(!X("before_compaction")||!w)return;let d=Z(f),{ctx:i}=z(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(!X("after_compaction")||!w)return;let d=Z(f),{ctx:i,channelId:u}=z(d,a?.runId,"after_compaction"),m=i._compactionStartTime||Date.now(),T=Date.now(),v=Ce(i,u,"openclaw.compaction","tool",m,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(!X("subagent_spawned")||!w)return;let d=Z(f),{ctx:i}=z(d,a?.runId,"subagent_spawned"),u=a?.sessionKey??a?.childSessionKey??"unknown-child";i._subagentStartTimes||(i._subagentStartTimes=new Map),i._subagentStartTimes.set(u,Date.now())}catch(d){k?.warn(`${b} [hook] subagent_spawned ERROR: ${String(d)}`)}},{priority:-100}),s.on("subagent_ended",async(a,f)=>{try{if(!X("subagent_ended")||!w)return;let d=Z(f),{ctx:i,channelId:u}=z(d,a?.runId,"subagent_ended"),m=a?.sessionKey??a?.childSessionKey??"unknown-child",T=i._subagentStartTimes?.get(m)||Date.now(),v=Date.now(),J=Ce(i,u,`openclaw.subagent.${m}`,"agent",T,v,{"gen_ai.span.kind":"AGENT","gen_ai.operation.name":"invoke_subagent","openclaw.subagent.session_key":m},Qe(i));w.export(J),i._subagentStartTimes?.delete(m)}catch(d){k?.warn(`${b} [hook] subagent_ended ERROR: ${String(d)}`)}},{priority:-100}),s.on("before_agent_start",async(a,f)=>{try{if(!X("before_agent_start")||!w)return;let d=Z(f),i=f.agentId||"openclaw",{ctx:u,channelId:m}=z(d,a?.runId,"before_agent_start");Se(u),y(u,m,{userId:f.trigger||"system",role:f.trigger||"system",from:i}),L(u,m,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=${X("agent_end")}`),!X("agent_end")||!w)return;let d=Z(f),{ctx:i,channelId:u}=z(d,a?.runId,"agent_end");Se(i),await yt(i.traceId),i.isClosing=!0;let m=Date.now();i.stepSpanId&&te(i,m,i.stepAwaitingToolResults?"agent_end":"stop",u);let T=i.agentSpanId,v=m,J;if(T){let B=Array.isArray(a.messages)?a.messages.length:0,ae=jn(a.messages);J={"agent.duration_ms":a.durationMs||0,"agent.message_count":B,"agent.tool_call_count":ae,"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||u,J["gen_ai.session.id"]=i.sessionId||u),i.userInput&&(J["gen_ai.input.messages"]=Ie(JSON.stringify([{role:"user",parts:[{type:"text",content:String(i.userInput)}]}]))),i.agentSpanId=void 0,i.agentStartTime=void 0}let j=i;if(j.rootSpanStartTime||T){let B=j.rootSpanId,ae=j.rootSpanStartTime,Pe=j.userInput,re=i.sessionId||j.sessionId;fe(u,j);let V=w,Q=setTimeout(async()=>{Te.delete(Q);try{let G=i.lastOutput||j.lastOutput;if(T&&J&&V&&!V.isDisposed&&(G&&(J["gen_ai.output.messages"]=qe([typeof G=="string"?G:JSON.stringify(G)])),V.endSpanById(T,v,J),k?.debug(`${b} [span] Ended agent span: spanId=${T}, traceId=${j.traceId}, duration=${a.durationMs}ms`)),ae&&V&&!V.isDisposed){let ke=Date.now(),pe={"request.duration_ms":ke-ae};re&&(pe["openclaw.session.id"]=re,pe["gen_ai.session.id"]=re),Pe&&(pe["gen_ai.input.messages"]=Ie(JSON.stringify([{role:"user",parts:[{type:"text",content:String(Pe)}]}]))),G&&(pe["gen_ai.output.messages"]=qe([typeof G=="string"?G:JSON.stringify(G)])),V.endSpanById(B,ke,pe),k?.debug(`${b} [span] Ended entry span: spanId=${B}, traceId=${j.traceId}, duration=${ke-ae}ms`)}It(i.runId),be(j),V&&!V.isDisposed&&(await V.flush(),k?.debug(`${b} [span] Flushed after agent_end, traceId=${j.traceId}`))}catch(G){k?.warn(`${b} agent_end delayed cleanup failed: ${String(G)}`)}},100);Te.add(Q)}else It(i.runId),be(j),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(!X("before_reset")||!w)return;let d=Z(f),{ctx:i}=z(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 ne(s){s!==g&&(x&&(x(),x=null),g=s,g&&w&&!w.isDisposed&&(x=g.subscribe(he)))}function he(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:H,registerHooks:U,updateSharedCredentialManager:ne}}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},le="[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"?se(e.secretId.trim()):""}catch{}try{l=typeof e?.secretKey=="string"?se(e.secretKey.trim()):""}catch{}let p=typeof e?.token=="string"?e.token.trim():void 0,g=typeof e?.credentialMode=="string"&&e.credentialMode.trim()==="cvmRole"?"cvmRole":"static",h=typeof e?.roleName=="string"?e.roleName.trim():void 0;if(!(g==="cvmRole"?!!(o&&h):!!(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:p,credentialMode:g,roleName:h,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(([h])=>/^\d+$/.test(h)).sort((h,_)=>Number(h[0])-Number(_[0])).map(([,h])=>h),l,p={};if(typeof c[0]=="string"&&c[0].trim().startsWith("{"))try{let h=JSON.parse(c[0]);if(h&&typeof h=="object"&&!Array.isArray(h)){typeof h.subsystem=="string"&&(l=h.subsystem);for(let[_,S]of Object.entries(h))_!=="subsystem"&&(typeof S=="string"||typeof S=="number"||typeof S=="boolean")&&(p[_]=String(S));c.shift()}}catch{}let g="";for(let h=c.length-1;h>=0;h--)if(typeof c[h]=="string"){g=String(c[h]),c.splice(h,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{p.args=JSON.stringify(c)}catch{p.args=String(c)}return{level:n,message:g,timestamp:r,subsystem:l,logger:o,extra:p}}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(h=>h!==null&&typeof h=="object"&&h.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,p=null,g=null,h=!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(`${le} \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(`${le} 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),h=!0}catch(I){g?.warn(`${le} \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,p=o.subscribe(M=>{if(c)try{c=new pt(S(M.secretId,M.secretKey,M.token)),g?.debug(`${le} \u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}catch(A){g?.warn(`${le} \u51ED\u8BC1\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String(A)}`)}})}try{c=new pt(S(x,F,$))}catch(I){g?.error(`${le} \u521B\u5EFA Producer \u5931\u8D25: ${String(I)}`),h&&(at(),h=!1);return}if(g?.info(`${le} \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 O=>{let D=[Ge.join(O,"plugin-sdk","diagnostics-otel.js"),Ge.join(O,"plugin-sdk","diagnostics-otel")];for(let q of D)try{let de=(await import(us(q).href)).registerLogTransport;if(de)return de}catch{}},R=Ge.dirname(new URL(import.meta.url).pathname);for(let O=0;O<8&&!I;++O){let D=Ge.dirname(R);if(D===R)break;R=D;let q=Ge.join(R,"plugin-sdk");try{let{existsSync:ee}=await import("node:fs");ee(q)&&(I=await M(R))}catch{}}if(!I)try{let D=ds(import.meta.url).resolve("openclaw/package.json"),q=Ge.dirname(D);I=await M(q)}catch{}}catch{}I?l=I(M=>{if(c)try{let A=ps(M);if((vt[A.level]??0)<_)return;let O={log_type:"gateway",level:A.level,message:A.message,source:r.source??"openclaw"};A.subsystem&&(O.subsystem=A.subsystem),A.logger&&(O.logger=A.logger);for(let[D,q]of Object.entries(A.extra))O[D]=q;C(O,Math.floor(A.timestamp/1e3))}catch{}}):g?.warn(`${le} 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,p?.(),p=null,c=null,h&&(at(),h=!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(`${le} \u914D\u7F6E\u70ED\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA\uFF0ClogTopicId=${r.logTopicId}\uFF0Cendpoint=${r.endpoint}`)}catch($){g?.warn(`${le} \u914D\u7F6E\u70ED\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String($)}`)}}function P(K){if(K!==o&&(p?.(),p=null,o=K,c&&o)){let x=o.getCredentialSnapshot();try{c=new pt(S(x.secretId,x.secretKey,x.token)),g?.debug(`${le} \u51ED\u8BC1\u7BA1\u7406\u5668\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}catch(F){g?.warn(`${le} \u51ED\u8BC1\u7BA1\u7406\u5668\u66F4\u65B0\u540E\u91CD\u5EFA Producer \u5931\u8D25: ${String(F)}`)}p=o.subscribe(F=>{if(c)try{c=new pt(S(F.secretId,F.secretKey,F.token)),g?.debug(`${le} \u51ED\u8BC1\u5DF2\u66F4\u65B0\uFF0CProducer \u5DF2\u91CD\u5EFA`)}catch($){g?.warn(`${le} \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($),O={log_type:"session",role:R.role,content:R.content,source:r.source??"openclaw"};R.toolCallId&&(O.tool_call_id=R.toolCallId),R.toolName&&(O.tool_name=R.toolName),R.stopReason&&(O.stop_reason=R.stopReason),R.toolCallCount!==void 0&&(O.tool_calls=String(R.toolCallCount)),I&&(O.session_key=I),M&&(O.agent_id=M),C(O,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},p=>{let g=p.statusCode??0;if(g>=300&&g<400&&p.headers.location){p.resume(),tr(p.headers.location,e+1).then(o,c);return}if(g!==200){p.resume(),c(new Error(`HTTP ${g} for ${t}`));return}let h=[],_=0,S=!1;p.on("data",C=>{if(!S){if(_+=C.length,_>Qn){S=!0,p.destroy(),c(new Error(`Response body too large (>${Qn} bytes) for ${t}`));return}h.push(C)}}),p.on("end",()=>{S||o(Buffer.concat(h).toString("utf-8").trim())}),p.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,p=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||p)&&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,we=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=se(n.secretId)}catch{}if(typeof n.secretKey=="string")try{c.secretKey=se(n.secretKey)}catch{}}let l=bs(c),p;if(ze&&ir===l)p=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),p=ze}else p=or(c),ze=p;ir=l;let g={...e,...n},_=kn(g,p,(C,E)=>{if(!we||!C||!E)return;let N={...o??{},enableLogReport:C,logTopicId:E},P=tn(N,n);P&&we.updateConfig(P)});if(p&&t.registerService({id:"diagnostics-metrics-cls-shared-credential",async start(C){p.setLogger(C.logger),await p.start()},async stop(C){C.logger?.debug?.("[diagnostics-metrics-cls] shared-credential service stopping"),p.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
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=
|
|
7
|
+
`)}return!0}}),!ft){let C=en(r,n);C.sharedCredentialManager=p,ft=Hn(C)}if(ft.updateSharedCredentialManager(p),ft.registerHooks(t),t.registerService(ft.service),o?.enableLogReport===!0){let C=tn(o,n);C&&(we?we.updateConfig(C):we=zn(C,p,Re),we.updateSharedCredentialManager(p),we.registerHooks(t),t.registerService(we.service))}else we&&(we.service.stop(),we=null)}},zo=Ss;export{zo as default};
|
package/openclaw.plugin.json
CHANGED
package/package.json
CHANGED