@lark-tns/openclaw-guardian-plugin 2026.5.7 → 2026.6.13

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/README.md CHANGED
@@ -1,61 +1,3 @@
1
1
  # OpenClaw Guardian Plugin
2
2
 
3
- This plugin uses the new OpenClaw SDK entry style and reports trust-layer payloads for the active hook points below:
4
-
5
- - logs the payload to the official plugin logger
6
- - pulls runtime toggles from `http://localhost:8001/open-apis/security_plugin/v1/openclaw_plugin/config`
7
- - forwards detect requests to `http://localhost:8001/open-apis/security_plugin/v1/openclaw_plugin/detect`
8
-
9
- - `llm_input`
10
- - `llm_output`
11
- - `before_tool_call`
12
- - `after_tool_call`
13
-
14
- The runtime config polling is managed by `api.registerService(...)`. The service initializes remote config on startup, keeps an in-memory snapshot for hook handlers, and disposes the refresh timer on shutdown.
15
-
16
- ## Files
17
-
18
- - `openclaw.plugin.json`: native plugin manifest
19
- - `src/index.ts`: plugin entry registered with `definePluginEntry`, hook registration, and `api.registerService(...)` wiring
20
- - `src/runtime-config.ts`: remote config store plus polling service, typed against `OpenClawPluginApi` / `api.registerService(...)`
21
- - `src/hook-payloads.ts`: hook-specific payload builders required by the trust-layer API
22
- - `src/logger.ts`: safe payload formatter and logger helper
23
- - `src/http-client.ts`: request body builder and detect/config service client
24
- - `src/fetch-interceptor.ts`: optional `before_llm_fetch` / `after_llm_fetch` request-response interceptor, currently not enabled in `src/index.ts`
25
- - `src/tool-effects.ts`: effect parser and hook-specific deny/rewrite handling
26
-
27
- ## Install
28
-
29
- Link-install the plugin from this directory:
30
-
31
- ```bash
32
- openclaw plugins install -l .
33
- ```
34
-
35
- Then enable it in your OpenClaw config if needed:
36
-
37
- ```json5
38
- {
39
- plugins: {
40
- entries: {
41
- "openclaw-guardian-plugin": {
42
- enabled: true
43
- }
44
- }
45
- }
46
- }
47
- ```
48
-
49
- Restart the Gateway after config changes.
50
-
51
- ## Notes
52
-
53
- - The plugin logs via `api.logger.info(...)`.
54
- - The plugin registers a background service via `api.registerService(...)`; the service typing is derived from `OpenClawPluginApi`, GETs remote runtime config on startup, retries up to 3 times, defaults to all hooks disabled on first-start failure, and refreshes the config every 60 seconds.
55
- - The plugin POSTs `{ hook_name, payload }` to `http://localhost:8001/open-apis/security_plugin/v1/openclaw_plugin/detect`.
56
- - Hook handlers read the latest in-memory runtime-config snapshot instead of fetching `/config` inline on every hook invocation.
57
- - Hook payloads are sent as the trust-layer contract requires, such as tool/session fields for tool hooks and `domain` / `path` / `origin_req` or `origin_resp` for LLM fetch hooks.
58
- - `llm_input` and `llm_output` are report-only hooks; deny/rewrite responses are logged but not applied.
59
- - `after_tool_call` is also observe-only in runtime; detect decisions are logged but do not rewrite the actual hook return value.
60
- - Payloads are serialized defensively so circular references and `Error` objects do not break logging.
61
- - `before_llm_fetch` / `after_llm_fetch` support remains in `src/fetch-interceptor.ts`, but those hooks are not active until `installFetchInterceptor(api, configStore)` is enabled in `src/index.ts`.
3
+ OpenClaw 安全治理插件,用于拦截 LLM 请求与工具调用,检测 SKILL 安全性问题
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import{createRequire as e}from"node:module";import{definePluginEntry as t}from"openclaw/plugin-sdk/plugin-entry";import{basename as n,dirname as r,join as i,relative as a,resolve as o}from"node:path";import{homedir as s,hostname as c}from"node:os";import{lstat as l,mkdir as u,readFile as d,readdir as f,rename as p,stat as m,unlink as h,writeFile as g}from"node:fs/promises";import{createHash as _}from"node:crypto";import{existsSync as v}from"node:fs";var y=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),b=e(import.meta.url);const ee=2e4;function x(e){return`[openclaw-guardian-plugin] ${e}`}function S(){let e=new WeakSet;return(t,n)=>{if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(typeof n==`bigint`)return n.toString();if(typeof n==`object`&&n){if(e.has(n))return`[Circular]`;e.add(n)}return n}}function C(e){let t=JSON.stringify(e,S(),2)??`null`;return t.length<=ee?t:`${t.slice(0,ee)}\n...<truncated>`}function w(e,t){return t===`online`?`[payload omitted in online]`:C(e)}function T(e,t,n,r){e.logger.info(x(`[${t}] ${w(n,r)}`))}function te(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):JSON.stringify(e,S(),2)??`null`}function E(e){let t=e?.pluginConfig?.env;return t===`boe`||t===`dev`||t===`pre`?t:`online`}let D=null,O=null;function k(e,t){if(typeof e!=`string`||!e)throw Error(`missing or invalid ${t}`);return e}function A(...e){for(let t of e)if(typeof t==`string`&&t)return t;return null}function j(e){return!e||typeof e!=`object`||Array.isArray(e)?null:e}function M(e){let t=A(e?.pluginConfig?.appId),n=A(e?.pluginConfig?.appSecret),r=t&&n?{appId:t,appSecret:n}:null,i=j(j(j(e?.config)?.channels)?.feishu),a=A(i?.appId,i?.app_id),o=A(i?.appSecret,i?.app_secret),s=a&&o?{appId:a,appSecret:o}:null,c=E(e);return c===`online`||c===`pre`?s??r??null:r??s??null}function N(e){return!!M(e)}function P(e){let t=e?.pluginConfig?.x_tt_env;return typeof t==`string`&&t?t:E(e)===`boe`?`boe_tns_api`:null}function F(e){let t=E(e);return t===`online`?`https://open.feishu.cn`:t===`pre`?`https://open.feishu-pre.cn`:`https://open.feishu-boe.cn`}function ne(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;return{code:typeof t.code==`number`?t.code:NaN,msg:typeof t.msg==`string`?t.msg:``,tenant_access_token:typeof t.tenant_access_token==`string`?t.tenant_access_token:void 0,expire:typeof t.expire==`number`?t.expire:void 0}}async function I(e){let t=Date.now();return D&&D.expiresAtMs-t>18e5?D.token:O||(O=(async()=>{let t=M(e);if(!t)throw Error(`missing Feishu appId/appSecret from api.config.channels.feishu or pluginConfig`);let n=k(t.appId,`appId`),r=k(t.appSecret,`appSecret`),i=`${F(e)}/open-apis/auth/v3/tenant_access_token/internal`,a={"content-type":`application/json`},o=P(e);o&&(a[`x-tt-env`]=o),e.logger.debug?.(x(`[auth] requesting tenant_access_token`));let{signal:s,clear:c}=ie(U),l;try{l=await fetch(i,{method:`POST`,headers:a,body:JSON.stringify({app_id:n,app_secret:r}),signal:s})}catch(e){throw c(),e instanceof Error&&e.name===`AbortError`?new z(i,U):new B(i,e)}finally{c()}let u=await l.text();if(!l.ok)throw Error(`[auth] tenant_access_token request failed status=${l.status} body=${u||`<empty>`}`);let d=null;try{d=u?JSON.parse(u):null}catch{d=null}let f=ne(d);if(!f||!Number.isFinite(f.code))throw Error(`[auth] tenant_access_token response parse failed`);if(f.code!==0)throw Error(`[auth] tenant_access_token request failed code=${f.code}${f.msg?` msg=${f.msg}`:``}`);let p=k(f.tenant_access_token,`tenant_access_token`),m=typeof f.expire==`number`&&f.expire>0?f.expire:7200;return D={token:p,expiresAtMs:Date.now()+m*1e3},e.logger.debug?.(x(`[auth] tenant_access_token updated`)),p})().finally(()=>{O=null}),O)}async function L(e){if(E(e)===`dev`)return{};let t={},n=P(e);return n&&(t[`x-tt-env`]=n),t.authorization=`Bearer ${await I(e)}`,t}async function R(e,t={}){let n=await L(e),r=new Headers(t.headers??{});for(let[e,t]of Object.entries(n))r.set(e,t);return{...t,headers:r}}var z=class extends Error{code=`TIMEOUT`;constructor(e,t){super(`Request to ${e} timed out after ${t}ms`),this.name=`RequestTimeoutError`}},B=class extends Error{code=`NETWORK`;constructor(e,t){super(`Network error requesting ${e}: ${t instanceof Error?t.message:String(t)}`),this.name=`NetworkError`}},re=class extends Error{code=`SERVER`;statusCode;constructor(e,t,n){super(`Server error ${t} from ${e}${n?`: ${n}`:``}`),this.name=`ServerError`,this.statusCode=t}};function V(e){return e instanceof z?`TIMEOUT`:e instanceof B?`NETWORK`:e instanceof re?`SERVER`:e instanceof Error&&e.name===`AbortError`?`TIMEOUT`:`UNKNOWN`}const H=5e3,U=5e3;function ie(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e);return typeof n==`object`&&`unref`in n&&n.unref(),{signal:t.signal,clear:()=>clearTimeout(n)}}function ae(e,t){if(!e)return t;let n=new AbortController,r=()=>n.abort();return e.addEventListener(`abort`,r,{once:!0}),t.addEventListener(`abort`,r,{once:!0}),n.signal}const oe={dev:`http://localhost:8001`,online:`https://open.feishu.cn`,boe:`https://open.feishu-boe.cn`,pre:`https://open.feishu-pre.cn`};function W(e){return`${oe[E(e)]}/open-apis/security_plugin/v1/openclaw_plugin`}function se(e){return`${W(e)}/config`}function ce(e){return`${W(e)}/detect`}function le(e){return`${W(e)}/batch_check_skill_detection`}function ue(e){return`${W(e)}/skill_detect`}function de(e={}){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=te(r);return t}function fe(e,t,n=``){return{hook_name:e,payload:de(t),source:n}}function pe(e){if(!e)return null;try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function me(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.code==`number`&&Number.isFinite(t.code)&&typeof t.msg==`string`}async function he(e,t,n){let r=await n.text();if(e.logger.debug?.(x(`[${t}] response: ${r}`)),!n.ok)throw Error(`${t} request failed: status=${n.status} body=${r||`<empty>`}`);let i=pe(r);if(!me(i))throw Error(`${t} response parse failed: missing or invalid code/msg fields`);if(i.code!==0)throw Error(`${t} request failed: code=${i.code}${i.msg?` msg=${i.msg}`:``}`);return i.data??null}async function G(e,t,n,r,i=H){let a=await R(e,r),{signal:o,clear:s}=ie(i),c=ae(a.signal,o),l,u=Date.now();try{l=await fetch(n,{...a,signal:c});let r=Date.now()-u;e.logger.info(x(`[${t}] http_elapsed=${r}ms status=${l.status} url=${n}`))}catch(r){let a=Date.now()-u;throw e.logger.info(x(`[${t}] http_elapsed=${a}ms error=${r instanceof Error?r.message:String(r)} url=${n}`)),s(),r instanceof Error&&r.name===`AbortError`?new z(n,i):new B(n,r)}finally{s()}return he(e,t,l)}let ge=null;function _e(){return ge||=c(),ge}function ve(){return{hostname:_e()}}function ye(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e;return Object.prototype.hasOwnProperty.call(t,`hostname`)?e:{...t,...ve()}}async function K(e,t,n){let r=fe(t,ye(n),`miaoda`);return G(e,t,ce(e),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r)},H)}function q(...e){return e.find(e=>e!=null)}function J(e){return e==null?``:typeof e==`string`?e:String(e)}function be(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function Y(e){return Array.isArray(e)?e:[]}function xe(e){try{let t=new URL(e);return{domain:t.host,path:t.pathname||`/`}}catch{return{domain:``,path:``}}}function Se(e){let{domain:t,path:n}=xe(J(e?.url));return{request_id:J(e?.request_id),domain:t,path:n,origin_req:q(e?.jsonBody,e?.rawBody,``)}}function Ce(e){let{domain:t,path:n}=xe(J(e?.url));return{request_id:J(e?.request_id),domain:t,path:n,is_sse:e?.isSse?`true`:`false`,chunks:Y(e?.chunks),origin_resp:e?.isSse?``:J(q(e?.originResp,``))}}function we(e,t){return{agent_name:J(t?.agentId),session_id:J(t?.sessionId),session_key:J(t?.sessionKey),channel_id:J(t?.channelId),message_provider:J(t?.messageProvider),trigger:J(t?.trigger),model:J(e?.model),provider:J(e?.provider),run_id:J(e?.runId)}}function Te(e,t){return{...we(e,t),prompt:J(e?.prompt),system_prompt:J(e?.systemPrompt),history_messages:Y(e?.historyMessages)}}function Ee(e,t){return{...we(e,t),assistant_texts:Y(e?.assistantTexts),last_assistant:J(JSON.stringify(e?.lastAssistant))}}function De(e,t){return{agent_name:J(t?.agentId),session_id:J(t?.sessionId),session_key:J(t?.sessionKey),tool_call_id:J(e?.toolCallId),tool_name:J(e?.toolName),tool_args:q(e?.params,{}),run_id:J(e?.runId)}}function Oe(e,t){return De(e,t)}function ke(e,t){return{...De(e,t),tool_output:q(e?.result,``),tool_error:q(e?.error,``),tool_duration_ms:J(q(e?.durationMs,``))}}function X(e,t,n,r){let i=t,a=t,o=n;switch(e){case`before_tool_call`:return Oe(i,o);case`after_tool_call`:return ke(i,o);case`before_llm_fetch`:return Se(r);case`after_llm_fetch`:return Ce(r);case`llm_input`:return Te(a,o);case`llm_output`:return Ee(a,o);default:return be(r)}}function Ae(e){return i(e??i(s(),`.openclaw`,`workspace`),`.openclaw-guardian`,`skill-detect-state.json`)}const je=Ae();function Me(e){if(!e||typeof e!=`object`||!(`code`in e))return;let{code:t}=e;return typeof t==`string`?t:void 0}function Ne(e,t){return e.is_detected?typeof e.last_detect_ts==`number`?(t??Date.now())-e.last_detect_ts>864e5:!0:!1}function Pe(e){return!e.skill_hash}let Fe=Promise.resolve();function Ie(e){let t=Fe.then(e,e);return Fe=t.catch(()=>void 0),t}async function Le(e){try{await h(e)}catch{}}async function Re(e,t){return Ie(async()=>{let n=t??je;e.logger.info(x(`[skill-storage] loading state from: ${n}`));try{let t=await d(n,`utf-8`),r=JSON.parse(t);return!r||typeof r!=`object`||Array.isArray(r)?(e.logger.warn(x(`[skill-storage] corrupted state file (invalid format), deleting and starting fresh`)),await Le(n),{}):(e.logger.info(x(`[skill-storage] loaded ${Object.keys(r).length} skill(s) from state`)),r)}catch(t){return Me(t)===`ENOENT`?(e.logger.info(x(`[skill-storage] no existing state file, starting fresh`)),{}):t instanceof SyntaxError?(e.logger.warn(x(`[skill-storage] corrupted state file (invalid JSON), deleting and starting fresh`)),await Le(n),{}):(e.logger.warn(x(`[skill-storage] failed to load state: ${t instanceof Error?t.message:String(t)}`)),{})}})}async function ze(e,t,n){return Ie(async()=>{let i=n??je,a=`${i}.tmp`;e.logger.info(x(`[skill-storage] saving state (${Object.keys(t).length} skill(s)) to: ${i}`));try{await u(r(i),{recursive:!0}),await g(a,JSON.stringify(t,null,2),`utf-8`),await p(a,i),e.logger.info(x(`[skill-storage] state saved successfully`))}catch(t){e.logger.error(x(`[skill-storage] failed to save state: ${t instanceof Error?t.message:String(t)}`)),await Le(a)}})}function Be(e,t,n){let r={...e},i=n??Date.now();for(let e of t){let t=r[e.dirName];t&&t.skill_hash===e.skillHash?Ne(t,i)?r[e.dirName]={...t,skill_name:e.skillName,is_detected:!1}:r[e.dirName]={...t,skill_name:e.skillName}:r[e.dirName]={skill_name:e.skillName,skill_hash:e.skillHash,is_detected:!1,last_detect_ts:null}}let a=new Set(t.map(e=>e.dirName));for(let e of Object.keys(r))a.has(e)||delete r[e];return r}var Ve=y(((e,t)=>{function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}let r=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function i(e){if(Buffer.isBuffer(e))return e;if(typeof e==`number`)return Buffer.alloc(e);if(typeof e==`string`)return Buffer.from(e);throw Error(`input must be buffer, number, or string, received `+typeof e)}function a(e){let t=i(4);return t.writeInt32BE(e,0),t}function o(e,t){e=i(e),Buffer.isBuffer(t)&&(t=t.readUInt32BE(0));let n=~~t^-1;for(var a=0;a<e.length;a++)n=r[(n^e[a])&255]^n>>>8;return n^-1}function s(){return a(o.apply(null,arguments))}s.signed=function(){return o.apply(null,arguments)},s.unsigned=function(){return o.apply(null,arguments)>>>0},t.exports=n(s)})),He=y((e=>{var t=b(`fs`),n=b(`stream`).Transform,r=b(`stream`).PassThrough,i=b(`zlib`),a=b(`util`),o=b(`events`).EventEmitter,s=b(`events`).errorMonitor,c=Ve();e.ZipFile=l,a.inherits(l,o);function l(){this.outputStream=new r,this.entries=[],this.outputStreamCursor=0,this.ended=!1,this.allDone=!1,this.forceZip64Eocd=!1,this.errored=!1,this.on(s,function(){this.errored=!0})}l.prototype.addFile=function(e,n,r){var i=this;if(n=x(n,!1),r??={},!g(i)){var a=new C(n,!1,r);i.entries.push(a),t.stat(e,function(n,o){if(n)return i.emit(`error`,n);if(!o.isFile())return i.emit(`error`,Error(`not a file: `+e));a.uncompressedSize=o.size,r.mtime??a.setLastModDate(o.mtime),r.mode??a.setFileAttributesMode(o.mode),a.setFileDataPumpFunction(function(){var n=t.createReadStream(e);a.state=C.FILE_DATA_IN_PROGRESS,n.on(`error`,function(e){i.emit(`error`,e)}),f(i,a,n)}),m(i)})}},l.prototype.addReadStream=function(e,t,n){this.addReadStreamLazy(t,n,function(t){t(null,e)})},l.prototype.addReadStreamLazy=function(e,t,n){var r=this;if(typeof t==`function`&&(n=t,t=null),t??={},e=x(e,!1),!g(r)){var i=new C(e,!1,t);r.entries.push(i),i.setFileDataPumpFunction(function(){i.state=C.FILE_DATA_IN_PROGRESS,n(function(e,t){if(e)return r.emit(`error`,e);f(r,i,t)})}),m(r)}},l.prototype.addBuffer=function(e,t,n){var r=this;if(t=x(t,!1),e.length>1073741823)throw Error(`buffer too large: `+e.length+` > 1073741823`);if(n??={},n.size!=null)throw Error(`options.size not allowed`);if(g(r))return;var a=new C(t,!1,n);a.uncompressedSize=e.length,a.crc32=c.unsigned(e),a.crcAndFileSizeKnown=!0,r.entries.push(a),a.compressionLevel===0?o(e):i.deflateRaw(e,{level:a.compressionLevel},function(e,t){o(t)});function o(e){a.compressedSize=e.length,a.setFileDataPumpFunction(function(){d(r,e),d(r,a.getDataDescriptor()),a.state=C.FILE_DATA_DONE,setImmediate(function(){m(r)})}),m(r)}},l.prototype.addEmptyDirectory=function(e,t){var n=this;if(e=x(e,!0),t??={},t.size!=null)throw Error(`options.size not allowed`);if(t.compress!=null)throw Error(`options.compress not allowed`);if(t.compressionLevel!=null)throw Error(`options.compressionLevel not allowed`);if(!g(n)){var r=new C(e,!0,t);n.entries.push(r),r.setFileDataPumpFunction(function(){d(n,r.getDataDescriptor()),r.state=C.FILE_DATA_DONE,m(n)}),m(n)}};var u=H([80,75,5,6]);l.prototype.end=function(e,t){if(typeof e==`function`&&(t=e,e=null),e??={},!this.ended&&(this.ended=!0,!this.errored)){if(this.calculatedTotalSizeCallback=t,this.forceZip64Eocd=!!e.forceZip64Format,e.comment){if(typeof e.comment==`string`?this.comment=re(e.comment):this.comment=e.comment,this.comment.length>65535)throw Error(`comment is too large`);if(U(this.comment,u))throw Error(`comment contains end of central directory record signature`)}else this.comment=S;m(this)}};function d(e,t){e.outputStream.write(t),e.outputStreamCursor+=t.length}function f(e,t,n){var a=new R,o=new L,s=t.compressionLevel===0?new r:new i.DeflateRaw({level:t.compressionLevel}),c=new L;n.pipe(a).pipe(o).pipe(s).pipe(c).pipe(e.outputStream,{end:!1}),c.on(`end`,function(){if(t.crc32=a.crc32,t.uncompressedSize==null)t.uncompressedSize=o.byteCount;else if(t.uncompressedSize!==o.byteCount)return e.emit(`error`,Error(`file data stream has unexpected number of bytes`));t.compressedSize=c.byteCount,e.outputStreamCursor+=t.compressedSize,d(e,t.getDataDescriptor()),t.state=C.FILE_DATA_DONE,m(e)})}function p(e){if(e.compress!=null&&e.compressionLevel!=null&&!!e.compress!=!!e.compressionLevel)throw Error(`conflicting settings for compress and compressionLevel`);return e.compressionLevel==null?e.compress===!1?0:6:e.compressionLevel}function m(e){if(e.allDone||e.errored)return;if(e.ended&&e.calculatedTotalSizeCallback!=null){var t=h(e);t!=null&&(e.calculatedTotalSizeCallback(t),e.calculatedTotalSizeCallback=null)}var n=r();function r(){for(var t=0;t<e.entries.length;t++){var n=e.entries[t];if(n.state<C.FILE_DATA_DONE)return n}return null}if(n!=null){if(n.state<C.READY_TO_PUMP_FILE_DATA||n.state===C.FILE_DATA_IN_PROGRESS)return;n.relativeOffsetOfLocalHeader=e.outputStreamCursor,d(e,n.getLocalFileHeader()),n.doFileDataPump()}else e.ended&&(e.offsetOfStartOfCentralDirectory=e.outputStreamCursor,e.entries.forEach(function(t){d(e,t.getCentralDirectoryRecord())}),d(e,ee(e)),e.outputStream.end(),e.allDone=!0)}function h(e){for(var t=0,n=0,r=0;r<e.entries.length;r++){var i=e.entries[r];if(i.compressionLevel!==0)return-1;if(i.state>=C.READY_TO_PUMP_FILE_DATA){if(i.uncompressedSize==null)return-1}else if(i.uncompressedSize==null)return null;i.relativeOffsetOfLocalHeader=t;var a=i.useZip64Format();t+=w+i.utf8FileName.length,t+=i.uncompressedSize,i.crcAndFileSizeKnown||(a?t+=A:t+=k),n+=j+i.utf8FileName.length+i.fileComment.length,i.forceDosTimestamp||(n+=M),a&&(n+=N)}var o=0;return(e.forceZip64Eocd||e.entries.length>=65535||n>=65535||t>=4294967295)&&(o+=_+v),o+=y+e.comment.length,t+n+o}function g(e){if(e.ended)throw Error(`cannot add entries after calling end()`);return!!e.errored}var _=56,v=20,y=22;function ee(e,t){var n=!1,r=e.entries.length;(e.forceZip64Eocd||e.entries.length>=65535)&&(r=65535,n=!0);var i=e.outputStreamCursor-e.offsetOfStartOfCentralDirectory,a=i;(e.forceZip64Eocd||i>=4294967295)&&(a=4294967295,n=!0);var o=e.offsetOfStartOfCentralDirectory;if((e.forceZip64Eocd||e.offsetOfStartOfCentralDirectory>=4294967295)&&(o=4294967295,n=!0),t)return n?_+v+y:y;var s=V(y+e.comment.length);if(s.writeUInt32LE(101010256,0),s.writeUInt16LE(0,4),s.writeUInt16LE(0,6),s.writeUInt16LE(r,8),s.writeUInt16LE(r,10),s.writeUInt32LE(a,12),s.writeUInt32LE(o,16),s.writeUInt16LE(e.comment.length,20),e.comment.copy(s,22),!n)return s;var c=V(_);c.writeUInt32LE(101075792,0),I(c,_-12,4),c.writeUInt16LE(E,12),c.writeUInt16LE(te,14),c.writeUInt32LE(0,16),c.writeUInt32LE(0,20),I(c,e.entries.length,24),I(c,e.entries.length,32),I(c,i,40),I(c,e.offsetOfStartOfCentralDirectory,48);var l=V(v);return l.writeUInt32LE(117853008,0),l.writeUInt32LE(0,4),I(l,e.outputStreamCursor,8),l.writeUInt32LE(1,16),Buffer.concat([c,l,s])}function x(e,t){if(e===``)throw Error(`empty metadataPath`);if(e=e.replace(/\\/g,`/`),/^[a-zA-Z]:/.test(e)||/^\//.test(e))throw Error(`absolute path: `+e);if(e.split(`/`).indexOf(`..`)!==-1)throw Error(`invalid relative path: `+e);var n=/\/$/.test(e);if(t)n||(e+=`/`);else if(n)throw Error(`file path cannot end with '/': `+e);return e}var S=V(0);function C(e,t,n){if(this.utf8FileName=H(e),this.utf8FileName.length>65535)throw Error(`utf8 file name too long. `+utf8FileName.length+` > 65535`);if(this.isDirectory=t,this.state=C.WAITING_FOR_METADATA,this.setLastModDate(n.mtime==null?new Date:n.mtime),this.forceDosTimestamp=!!n.forceDosTimestamp,n.mode==null?this.setFileAttributesMode(t?16893:33204):this.setFileAttributesMode(n.mode),t?(this.crcAndFileSizeKnown=!0,this.crc32=0,this.uncompressedSize=0,this.compressedSize=0):(this.crcAndFileSizeKnown=!1,this.crc32=null,this.uncompressedSize=null,this.compressedSize=null,n.size!=null&&(this.uncompressedSize=n.size)),t?this.compressionLevel=0:this.compressionLevel=p(n),this.forceZip64Format=!!n.forceZip64Format,n.fileComment){if(typeof n.fileComment==`string`?this.fileComment=H(n.fileComment,`utf-8`):this.fileComment=n.fileComment,this.fileComment.length>65535)throw Error(`fileComment is too large`)}else this.fileComment=S}C.WAITING_FOR_METADATA=0,C.READY_TO_PUMP_FILE_DATA=1,C.FILE_DATA_IN_PROGRESS=2,C.FILE_DATA_DONE=3,C.prototype.setLastModDate=function(e){this.mtime=e;var t=ne(e);this.lastModFileTime=t.time,this.lastModFileDate=t.date},C.prototype.setFileAttributesMode=function(e){if((e&65535)!==e)throw Error(`invalid mode. expected: 0 <= `+e+` <= 65535`);this.externalFileAttributes=e<<16>>>0},C.prototype.setFileDataPumpFunction=function(e){this.doFileDataPump=e,this.state=C.READY_TO_PUMP_FILE_DATA},C.prototype.useZip64Format=function(){return this.forceZip64Format||this.uncompressedSize!=null&&this.uncompressedSize>4294967294||this.compressedSize!=null&&this.compressedSize>4294967294||this.relativeOffsetOfLocalHeader!=null&&this.relativeOffsetOfLocalHeader>4294967294};var w=30,T=20,te=45,E=831,D=2048,O=8;C.prototype.getLocalFileHeader=function(){var e=0,t=0,n=0;this.crcAndFileSizeKnown&&(e=this.crc32,t=this.compressedSize,n=this.uncompressedSize);var r=V(w),i=D;return this.crcAndFileSizeKnown||(i|=O),r.writeUInt32LE(67324752,0),r.writeUInt16LE(T,4),r.writeUInt16LE(i,6),r.writeUInt16LE(this.getCompressionMethod(),8),r.writeUInt16LE(this.lastModFileTime,10),r.writeUInt16LE(this.lastModFileDate,12),r.writeUInt32LE(e,14),r.writeUInt32LE(t,18),r.writeUInt32LE(n,22),r.writeUInt16LE(this.utf8FileName.length,26),r.writeUInt16LE(0,28),Buffer.concat([r,this.utf8FileName])};var k=16,A=24;C.prototype.getDataDescriptor=function(){if(this.crcAndFileSizeKnown)return S;if(this.useZip64Format()){var e=V(A);return e.writeUInt32LE(134695760,0),e.writeUInt32LE(this.crc32,4),I(e,this.compressedSize,8),I(e,this.uncompressedSize,16),e}else{var e=V(k);return e.writeUInt32LE(134695760,0),e.writeUInt32LE(this.crc32,4),e.writeUInt32LE(this.compressedSize,8),e.writeUInt32LE(this.uncompressedSize,12),e}};var j=46,M=9,N=28;C.prototype.getCentralDirectoryRecord=function(){var e=V(j),t=D;this.crcAndFileSizeKnown||(t|=O);var n=S;if(!this.forceDosTimestamp){n=V(M),n.writeUInt16LE(21589,0),n.writeUInt16LE(M-4,2),n.writeUInt8(3,4);var r=Math.floor(this.mtime.getTime()/1e3);r<-2147483648&&(r=-2147483648),r>2147483647&&(r=2147483647),n.writeUInt32LE(r,5)}var i=this.compressedSize,a=this.uncompressedSize,o=this.relativeOffsetOfLocalHeader,s=T,c=S;return this.useZip64Format()&&(i=4294967295,a=4294967295,o=4294967295,s=te,c=V(N),c.writeUInt16LE(1,0),c.writeUInt16LE(N-4,2),I(c,this.uncompressedSize,4),I(c,this.compressedSize,12),I(c,this.relativeOffsetOfLocalHeader,20)),e.writeUInt32LE(33639248,0),e.writeUInt16LE(E,4),e.writeUInt16LE(s,6),e.writeUInt16LE(t,8),e.writeUInt16LE(this.getCompressionMethod(),10),e.writeUInt16LE(this.lastModFileTime,12),e.writeUInt16LE(this.lastModFileDate,14),e.writeUInt32LE(this.crc32,16),e.writeUInt32LE(i,20),e.writeUInt32LE(a,24),e.writeUInt16LE(this.utf8FileName.length,28),e.writeUInt16LE(n.length+c.length,30),e.writeUInt16LE(this.fileComment.length,32),e.writeUInt16LE(0,34),e.writeUInt16LE(0,36),e.writeUInt32LE(this.externalFileAttributes,38),e.writeUInt32LE(o,42),Buffer.concat([e,this.utf8FileName,n,c,this.fileComment])},C.prototype.getCompressionMethod=function(){return this.compressionLevel===0?0:8};var P=new Date(1980,0,1),F=new Date(2107,11,31,23,59,58);function ne(e){e<P?e=P:e>F&&(e=F);var t=0;t|=e.getDate()&31,t|=(e.getMonth()+1&15)<<5,t|=(e.getFullYear()-1980&127)<<9;var n=0;return n|=Math.floor(e.getSeconds()/2),n|=(e.getMinutes()&63)<<5,n|=(e.getHours()&31)<<11,{date:t,time:n}}function I(e,t,n){var r=Math.floor(t/4294967296),i=t%4294967296;e.writeUInt32LE(i,n),e.writeUInt32LE(r,n+4)}a.inherits(L,n);function L(e){n.call(this,e),this.byteCount=0}L.prototype._transform=function(e,t,n){this.byteCount+=e.length,n(null,e)},a.inherits(R,n);function R(e){n.call(this,e),this.crc32=0}R.prototype._transform=function(e,t,n){this.crc32=c.unsigned(e,this.crc32),n(null,e)};var z=`\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`;if(z.length!==256)throw Error(`assertion failure`);var B=null;function re(e){if(/^[\x20-\x7e]*$/.test(e))return H(e,`utf-8`);if(B==null){B={};for(var t=0;t<z.length;t++)B[z[t]]=t}for(var n=V(e.length),t=0;t<e.length;t++){var r=B[e[t]];if(r==null)throw Error(`character not encodable in CP437: `+JSON.stringify(e[t]));n[t]=r}return n}function V(e){V=t;try{return V(e)}catch{return V=n,V(e)}function t(e){return Buffer.allocUnsafe(e)}function n(e){return new Buffer(e)}}function H(e,t){H=n;try{return H(e,t)}catch{return H=r,H(e,t)}function n(e,t){return Buffer.from(e,t)}function r(e,t){return new Buffer(e,t)}}function U(e,t){U=n;try{return U(e,t)}catch{return U=r,U(e,t)}function n(e,t){return e.includes(t)}function r(e,t){for(var n=0;n<=e.length-t.length;n++)for(var r=0;;r++){if(r===t.length)return!0;if(e[n+r]!==t[r])break}return!1}}}))();function Z(e){return`v1:${e}`}function Ue(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))t[n]=r===!0;return t}function We(e){return{skills:Object.values(e).map(e=>({skill_name:e.skill_name,skill_hash:Z(e.skill_hash)}))}}async function Ge(e,t){let n=le(e),r=We(t),i=await G(e,`batch_check_detection`,n,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r)},H);return i&&typeof i==`object`&&!Array.isArray(i)&&`result`in i?Ue(i.result):Ue(i)}const Ke=10*1024*1024;async function qe(e){let t=await f(e),n=[];for(let r of t){let t=i(e,r),a=await l(t);a.isSymbolicLink()||(a.isDirectory()?n.push(...await qe(t)):a.isFile()&&n.push(t))}return n}async function Je(e){let t=await m(e).catch(()=>null);if(!t||!t.isDirectory())throw Error(`zipDirectory: path does not exist or is not a directory: ${e}`);let n=await qe(e);return n.sort((t,n)=>{let r=a(e,t),i=a(e,n);return r<i?-1:+(r>i)}),new Promise((t,r)=>{let i=new He.ZipFile,o=[],s=0,c=!1,l=e=>{c||(c=!0,r(e))};i.outputStream.on(`data`,t=>{if(!c){if(s+=t.length,s>Ke){l(Error(`zipDirectory: zip exceeds ${Ke} bytes limit for ${e} (${s} bytes)`));return}o.push(t)}}),i.outputStream.on(`end`,()=>{c||(c=!0,t(Buffer.concat(o)))}),i.outputStream.on(`error`,l);for(let t of n)i.addFile(t,a(e,t));i.end()})}async function Ye(e,t,n){let r=ue(e),i=`skill_detect:${n.skill_name}`;e.logger.info(x(`[skill-detect] detect: sending skill=${n.skill_name} hash=${n.skill_hash.slice(0,12)}... dir=${t}`));let a=await Je(t);e.logger.info(x(`[skill-detect] zipped ${t} (${a.length} bytes)`));let o=new FormData,s=new Blob([new Uint8Array(a)],{type:`application/zip`});return o.append(`file`,s,n.skill_name),o.append(`skill`,JSON.stringify({skill_name:n.skill_name,skill_hash:Z(n.skill_hash)})),o.append(`payload`,JSON.stringify(ve())),await G(e,i,r,{method:`POST`,body:o},6e5),e.logger.info(x(`[skill-detect] skill ${n.skill_name} detected successfully`)),!0}function Xe(e){if(e.tool_name!==`read`)return null;let t=e.tool_args;return!t||typeof t!=`object`||Array.isArray(t)?null:Object.values(t).find(e=>typeof e==`string`&&e.endsWith(`SKILL.md`))??null}async function Ze(e,t,i){let a=n(r(t));try{let t;i&&(t=Ae(e.runtime.agent.resolveAgentWorkspaceDir(e.config,i)));let n=(await Re(e,t))[a];return!n||!n.skill_hash?null:{skill_name:n.skill_name,skill_hash:Z(n.skill_hash)}}catch{return null}}function Qe(...e){return e.find(e=>typeof e==`string`)??``}function $e(e){return typeof e==`string`?e.toUpperCase():`PERMIT`}function et(e){if(!(typeof e!=`string`||e.length===0))try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function tt(e){return{effect:$e(e?.effect),denyOutput:Qe(e?.deny_output),rewriteOutput:Qe(e?.rewrite_output)}}function nt(e){let t=$e(e.effect);if(t===`DENY`)return e.denyOutput?{action:`deny`,output:e.denyOutput,returnValue:{block:!0,blockReason:e.denyOutput||`Tool call blocked by detect service`}}:{action:`permit`,returnValue:void 0};if(t===`REWRITE`){if(!e.rewriteOutput)return{action:`permit`,returnValue:void 0};let t=et(e.rewriteOutput);return t?{action:`rewrite`,returnValue:{params:t}}:{action:`rewrite_invalid`,returnValue:void 0}}return{action:`permit`,returnValue:void 0}}async function rt(e,t,n,r,i){if(!await t.isHookEnabled(n)){e.logger.info(x(`[${n}] detect skipped: hook disabled by runtime config`));return}let a=Date.now(),o=X(n,r,i);T(e,n,o,E(e));try{let t=tt(await K(e,n,o));e.logger.info(x(`[${n}] detect effect observed: effect=${t.effect} (report-only hook)`))}catch(t){e.logger.error(x(`[${n}] detect request failed: ${t instanceof Error?t.message:String(t)}`))}finally{let t=Date.now()-a;e.logger.info(x(`[${n}] total_elapsed=${t}ms`))}}async function it(e,t,n,r){let i=Date.now();if(!await t.isHookEnabled(`before_tool_call`)){e.logger.info(x(`[before_tool_call] detect skipped: hook disabled by runtime config`));return}let a=X(`before_tool_call`,n,r),o=Xe(a),s=a;if(o){let t=await Ze(e,o,r.agentId);t&&(s={...s,...t},e.logger.info(x(`[before_tool_call] skill read detected: skill=${t.skill_name} hash=${t.skill_hash.slice(0,12)}...`)))}T(e,`before_tool_call`,s,E(e));let c;try{let t=nt(tt(await K(e,`before_tool_call`,s)));e.logger.info(x(`[before_tool_call] detect effect applied: ${JSON.stringify(t.returnValue)}`)),c=t.returnValue}catch(t){e.logger.error(x(`[before_tool_call] detect request failed: ${t instanceof Error?t.message:String(t)}`))}let l=Date.now()-i;return e.logger.info(x(`[before_tool_call] total_elapsed=${l}ms`)),c}function at(e,t){e.on(`llm_input`,async(n,r)=>{await rt(e,t,`llm_input`,n,r)}),e.on(`llm_output`,async(n,r)=>{await rt(e,t,`llm_output`,n,r)}),e.on(`after_tool_call`,async(n,r)=>{await rt(e,t,`after_tool_call`,n,r)}),e.on(`before_tool_call`,async(n,r)=>it(e,t,n,r))}function Q(e){return typeof e==`object`&&!!e}function ot(e,t){if(!Q(e))return null;let n=e[t];return Q(n)?n:null}function st(e){let t=ot(ot(e,`models`),`providers`);return t?Object.entries(t).map(([e,t])=>{if(!Q(t))return null;let n=t.baseUrl??t.baseURL;return typeof n==`string`&&n?{providerId:e,baseUrl:n}:null}).filter(e=>e!==null):[]}function ct(e,t){for(let n of t)if(e.startsWith(n.baseUrl))return n;return null}function lt(e){return typeof e==`string`?e:e instanceof URLSearchParams?e.toString():e instanceof Uint8Array?new TextDecoder().decode(e):ArrayBuffer.isView(e)?new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):e instanceof ArrayBuffer?new TextDecoder().decode(new Uint8Array(e)):null}function ut(e){let t=lt(e);if(!t)return null;try{let e=JSON.parse(t);return Q(e)?e:null}catch{return null}}function dt(e){return Q(e)?Array.isArray(e.messages)||typeof e.prompt==`string`||typeof e.input==`string`:!1}function ft(e){return typeof e==`string`&&e.includes(`/open-apis/security_plugin/v1/openclaw_plugin`)}function pt(e){return typeof e==`string`&&e.includes(`text/event-stream`)}function mt(e,t){let n=e.split(/\r?\n/).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim()).filter(e=>e.length>0&&e!==`[DONE]`),r=Math.max(1,Number(t)||1);if(r===1)return n;let i=[];for(let e=0;e<n.length;e+=r)i.push(n.slice(e,e+r).join(`
2
- `));return i}function ht(e,t){return t?`${String(e).split(/\r?\n/).map(e=>`data: ${e}`).join(`
3
- `)}\n\n`:e}function gt(e,t,n){let r=new Headers(e.headers);return r.delete(`content-length`),n?r.set(`content-type`,`text/event-stream; charset=utf-8`):r.get(`content-type`)||r.set(`content-type`,`text/plain; charset=utf-8`),new Response(ht(t,n),{status:e.status,statusText:e.statusText,headers:r})}async function _t(e,t,n){let r=await t.clone().text(),i=pt(t.headers.get(`content-type`)??``);return{url:e,isSse:i,chunks:i?mt(r,n):[],originResp:i?``:r}}function vt(...e){return e.find(e=>typeof e==`string`)??``}function yt(e){return typeof e==`string`?e.toUpperCase():`PERMIT`}function bt(e){return{effect:yt(e?.effect),denyOutput:vt(e?.deny_output),rewriteOutput:vt(e?.rewrite_output)}}function xt(e){let t=yt(e.effect);return t===`DENY`&&e.denyOutput?{action:`deny`,output:e.denyOutput,effect:t}:t===`REWRITE`&&e.rewriteOutput?{action:`rewrite`,output:e.rewriteOutput,effect:t}:{action:`permit`,output:``,effect:t}}function St(e){let t=yt(e.effect);return t===`DENY`&&e.denyOutput?{action:`deny`,output:e.denyOutput,effect:t}:t===`REWRITE`&&e.rewriteOutput?{action:`rewrite`,output:e.rewriteOutput,effect:t}:{action:`permit`,output:``,effect:t}}function Ct(e,t,n){e.logger.info(x(`[${t}] ${w(n,E(e))}`))}function wt(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function Tt(e){let t=String(e);function n(e){if(typeof e!=`string`)return JSON.stringify(e);try{let t=JSON.parse(e);return typeof t==`string`?t:JSON.stringify(t)}catch{return e}}try{let e=JSON.parse(t);if(Array.isArray(e))return e.map(e=>n(e))}catch{}return t.split(/\r?\n/)}function Et(e,t){let n=new Headers(e.headers);n.delete(`content-length`),n.set(`content-type`,`text/event-stream; charset=utf-8`);let r=`${Tt(t).map(e=>`data: ${e}\n\n`).join(``)}`;return new Response(r,{status:e.status,statusText:e.statusText,headers:n})}function Dt(e){return(e.headers.get(`content-type`)??``).includes(`text/event-stream`)}async function Ot(e,t,n,r,i,a){let o=r.body;if(!o)return r;let s=Math.max(1,Number(await i.getSseChunkSize())||1),c=o.getReader(),l=new TextDecoder,u=new TextEncoder,d=``,f=[],p=[];async function m(r){let i=X(`after_llm_fetch`,null,null,{request_id:n,url:t,isSse:!0,chunks:r,originResp:``});return Ct(e,`after_llm_fetch`,i),St(bt(await K(e,`after_llm_fetch`,i)))}function h(e){f.length!==0&&(e.enqueue(u.encode(f.join(``))),f=[])}let g=new ReadableStream({async start(t){try{for(;;){let{value:i,done:o}=await c.read();if(o)break;for(d+=l.decode(i,{stream:!0});;){let i=d.indexOf(`
1
+ import e,{createRequire as t}from"node:module";import{definePluginEntry as n}from"openclaw/plugin-sdk/plugin-entry";import{existsSync as r}from"node:fs";import{basename as i,dirname as a,join as o,relative as s,resolve as c}from"node:path";import{fileURLToPath as l}from"node:url";import{execFile as u,spawn as d}from"node:child_process";import{createHash as f,randomBytes as p}from"node:crypto";import{lstat as m,mkdir as h,readFile as g,readdir as _,rename as ee,stat as v,unlink as te,writeFile as y}from"node:fs/promises";import{promisify as b}from"node:util";import{homedir as x,hostname as ne}from"node:os";import S from"node:http";import{AsyncLocalStorage as C}from"node:async_hooks";import re from"node:https";import ie from"node:http2";import{PassThrough as ae,Readable as w}from"node:stream";import{Agent as oe,BalancedPool as se,Client as ce,Dispatcher as le,EnvHttpProxyAgent as ue,Pool as de,ProxyAgent as fe,RetryAgent as T,RoundRobinPool as pe,getGlobalDispatcher as me,setGlobalDispatcher as he}from"undici";import{channel as E}from"node:diagnostics_channel";var ge=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),D=t(import.meta.url);let O=null;function k(e){let t=e?.pluginConfig?.env;return t===`boe`||t===`dev`||t===`pre`?t:`online`}function A(e){return c(a(l(import.meta.url)),e)}function _e(){return A(`../vender/bin`)}function ve(){return process.platform===`darwin`?`macos`:process.platform===`linux`?`linux`:``}function ye(){return process.arch===`x64`?`amd64`:process.arch===`arm64`?`arm64`:``}function be(e){for(let t of e){let e=c(_e(),t);if(r(e))return e}return c(_e(),e[0])}function xe(){let e=ve();if(!e)return``;let t=ye();return t?be([`${e}/${t}/lark-enterprise-cli`,`${e}/lark-enterprise-cli`,`lark-enterprise-cli`]):``}function Se(){let e=ve();return e?be([`${e}/env.sh`,`env.sh`]):``}function Ce(){let e=xe();return!!e&&r(e)}function we(){let e=Se();return!!e&&r(e)}function Te(e){O={...e,updatedAt:Date.now()}}function j(){O=null}function Ee(){return O?{...O}:null}const De=`...<truncated>`;function M(e){return`[openclaw-guardian-plugin] ${e}`}function Oe(e,t=1e3){if(Buffer.byteLength(e,`utf8`)<=t)return e;let n=Buffer.byteLength(De,`utf8`),r=Math.max(0,t-n),i=Buffer.from(e,`utf8`).subarray(0,r).toString(`utf8`);for(;Buffer.byteLength(i,`utf8`)>r&&i.length>0;)i=i.slice(0,-1);return`${i}${De}`}function ke(){let e=new WeakSet;return(t,n)=>{if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(typeof n==`bigint`)return n.toString();if(typeof n==`string`)return Oe(n);if(typeof n==`object`&&n){if(e.has(n))return`[Circular]`;e.add(n)}return n}}function Ae(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):JSON.stringify(e,ke(),2)??`null`}function je(e){return o(e??o(x(),`.openclaw`,`workspace`),`.openclaw-guardian`,`skill-detect-state.json`)}const Me=je();function Ne(e){if(!e||typeof e!=`object`||!(`code`in e))return;let{code:t}=e;return typeof t==`string`?t:void 0}function Pe(e,t){return e.is_detected?typeof e.last_detect_ts==`number`?(t??Date.now())-e.last_detect_ts>864e5:!0:!1}function Fe(e){return!e.skill_hash}let Ie=Promise.resolve();function Le(e){let t=Ie.then(e,e);return Ie=t.catch(()=>void 0),t}async function Re(e){try{await te(e)}catch{}}async function ze(e,t){return Le(async()=>{let n=t??Me;e.logger.info(M(`[skill-storage] loading state from: ${n}`));try{let t=await g(n,`utf-8`),r=JSON.parse(t);return!r||typeof r!=`object`||Array.isArray(r)?(e.logger.warn(M(`[skill-storage] corrupted state file (invalid format), deleting and starting fresh`)),await Re(n),{}):(e.logger.info(M(`[skill-storage] loaded ${Object.keys(r).length} skill(s) from state`)),r)}catch(t){return Ne(t)===`ENOENT`?(e.logger.info(M(`[skill-storage] no existing state file, starting fresh`)),{}):t instanceof SyntaxError?(e.logger.warn(M(`[skill-storage] corrupted state file (invalid JSON), deleting and starting fresh`)),await Re(n),{}):(e.logger.warn(M(`[skill-storage] failed to load state: ${t instanceof Error?t.message:String(t)}`)),{})}})}async function Be(e,t,n){return Le(async()=>{let r=n??Me,i=`${r}.tmp`;e.logger.info(M(`[skill-storage] saving state (${Object.keys(t).length} skill(s)) to: ${r}`));try{await h(a(r),{recursive:!0}),await y(i,JSON.stringify(t,null,2),`utf-8`),await ee(i,r),e.logger.info(M(`[skill-storage] state saved successfully`))}catch(t){e.logger.error(M(`[skill-storage] failed to save state: ${t instanceof Error?t.message:String(t)}`)),await Re(i)}})}function Ve(e,t,n){let r={...e},i=n??Date.now();for(let e of t){let t=r[e.dirName];t&&t.skill_hash===e.skillHash?Pe(t,i)?r[e.dirName]={...t,skill_name:e.skillName,is_detected:!1}:r[e.dirName]={...t,skill_name:e.skillName}:r[e.dirName]={skill_name:e.skillName,skill_hash:e.skillHash,is_detected:!1,last_detect_ts:null}}let a=new Set(t.map(e=>e.dirName));for(let e of Object.keys(r))a.has(e)||delete r[e];return r}const He=new C;function Ue(e){return He.run(!0,e)}function N(){return He.getStore()===!0}function P(...e){return e.find(e=>e!=null)}function F(e){return e==null?``:typeof e==`string`?e:String(e)}function I(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function We(e){return Array.isArray(e)?e:[]}function L(...e){for(let t of e){if(!t||typeof t!=`object`||Array.isArray(t))continue;let e=t,n=F(e.sender_id??e.senderId??e.SenderId);if(n)return n}return``}function Ge(e){return!e||!Number.isFinite(e.proxyPort)||e.proxyPort<=0||typeof e.rootCa!=`string`||e.rootCa.length===0?null:{proxyPort:Math.floor(e.proxyPort),rootCa:e.rootCa}}function Ke(e){return Ue(()=>new Promise(t=>{let n=S.get({hostname:`127.0.0.1`,port:e,path:`/`,timeout:300},e=>{e.resume(),t(e.statusCode===200)});n.on(`timeout`,()=>{n.destroy(),t(!1)}),n.on(`error`,()=>{t(!1)})}))}async function qe(e,t,n={}){if(e.toolName!==`exec`||!e.params)return{modifiedEvent:e,injected:!1,proxyAlive:!1,mitmAuthEnabled:!1};let r={...e.params},i=r.command??``;if(typeof i!=`string`)return{modifiedEvent:e,injected:!1,proxyAlive:!1,mitmAuthEnabled:!1};let a=Ge(Ee()),o=Se(),s=we(),c=a?await Ke(a.proxyPort):!1,l=!!a&&s&&c,u=l?`. ${F(o)}; `:``,d=F(t),f=n.appendMitmAuth?`,mitm`:``;r.command=`${u}${i}`;let p=r.env&&typeof r.env==`object`&&!Array.isArray(r.env)?r.env:{},m=l?{CLI_CERT_PATH:F(a?.rootCa),CLI_PORT:a?String(a.proxyPort):``}:{};return r.env={...p,LARKSUITE_CLI_AGENT_TRACE:d,AGENT_TRACE:d,MITM_ENV:f,...m},{modifiedEvent:{...e,params:r},injected:!0,proxyAlive:c,mitmAuthEnabled:!!n.appendMitmAuth}}const Je=b(u),Ye=o(a(je()),`lark-enterprise-cli-version.json`);function Xe(e){return new Promise(t=>{setTimeout(t,e).unref()})}function Ze(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.version==`string`&&typeof t.binarySha256==`string`&&typeof t.recordedAt==`number`&&Number.isFinite(t.recordedAt)}function Qe(e,t){return!!e&&(e?.version!==t.version||e?.binarySha256!==t.binarySha256)}function $e(e){try{return process.kill(e,0),!0}catch{return!1}}async function et(e){let[t,n]=await Promise.all([tt(e),g(e)]);return{version:t,binarySha256:f(`sha256`).update(n).digest(`hex`),recordedAt:Date.now()}}async function tt(e){let t=a(e),n=[o(t,`VERSION`),o(a(t),`VERSION`),o(a(a(t)),`VERSION`)];for(let e of n)try{return(await g(e,`utf8`)).trim()}catch{}return``}async function nt(){try{let e=await g(Ye,`utf8`),t=JSON.parse(e);return Ze(t)?t:null}catch{return null}}async function rt(e){await h(a(Ye),{recursive:!0}),await y(Ye,`${JSON.stringify(e)}\n`,`utf8`)}function it(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.proxy_port==`number`&&Number.isFinite(t.proxy_port)&&t.proxy_port>0&&typeof t.root_ca==`string`&&t.root_ca.length>0&&typeof t.daemon_pid==`number`&&Number.isFinite(t.daemon_pid)&&t.daemon_pid>0}async function at(e){let{stdout:t}=await Je(e,[`config`,`print`],{encoding:`utf8`,maxBuffer:256*1024}),n=JSON.parse(t);return it(n)?n:null}async function ot(e){let t=await at(e);return!t||!await Ke(t.proxy_port)?null:(Te({daemonPid:t.daemon_pid,proxyPort:t.proxy_port,rootCa:t.root_ca}),{daemonPid:t.daemon_pid,proxyPort:t.proxy_port,rootCa:t.root_ca})}async function st(e){return ot(e)}async function ct(e){let t=await at(e).catch(()=>null);if(!t||!await Ke(t.proxy_port).catch(()=>!1)||!$e(t.daemon_pid))return!1;try{process.kill(t.daemon_pid,`SIGTERM`)}catch{return!1}for(let e=0;e<6;e+=1)if(await Xe(500),!$e(t.daemon_pid)||!await Ke(t.proxy_port).catch(()=>!1))return j(),!0;try{process.kill(t.daemon_pid,`SIGKILL`)}catch{}return j(),await Xe(500),!0}async function lt(e){let t=await et(e).catch(()=>null);return t?Qe(await nt(),t)?{currentVersion:t,stoppedForUpgrade:await ct(e)}:{currentVersion:t,stoppedForUpgrade:!1}:{currentVersion:null,stoppedForUpgrade:!1}}function ut(e){let t=d(e,[`start`],{detached:!0,stdio:`ignore`});return t.unref(),t.pid}async function dt(e,t={}){let n=t.checkCliUpgrade?await lt(e):{currentVersion:null,stoppedForUpgrade:!1},r=Ee();if(r?.proxyPort&&await Ke(r.proxyPort))return n.currentVersion&&await rt(n.currentVersion).catch(()=>{}),{status:`already_running`,daemonPid:r.daemonPid,proxyPort:r.proxyPort,rootCa:r.rootCa,restartedAfterUpgrade:n.stoppedForUpgrade};let i=await ot(e).catch(()=>null);if(i)return n.currentVersion&&await rt(n.currentVersion).catch(()=>{}),{status:`already_running`,restartedAfterUpgrade:n.stoppedForUpgrade,...i};j();let a=ut(e);await Xe(3e3);for(let t=0;t<3;t+=1){t>0&&await Xe(300);let r=await ot(e).catch(()=>null);if(r)return n.currentVersion&&await rt(n.currentVersion).catch(()=>{}),{status:`started`,spawnPid:a,restartedAfterUpgrade:n.stoppedForUpgrade,...r}}throw Error(`lark-enterprise-cli start issued but daemon_pid was not observed`)}let ft=null,pt=null;function mt(e,t){if(typeof e!=`string`||!e)throw Error(`missing or invalid ${t}`);return e}function ht(...e){for(let t of e)if(typeof t==`string`&&t)return t;return null}function gt(e){return!e||typeof e!=`object`||Array.isArray(e)?null:e}function _t(e){let t=ht(e?.pluginConfig?.appId),n=ht(e?.pluginConfig?.appSecret),r=t&&n?{appId:t,appSecret:n}:null,i=gt(gt(gt(e?.config)?.channels)?.feishu),a=ht(i?.appId,i?.app_id),o=ht(i?.appSecret,i?.app_secret),s=a&&o?{appId:a,appSecret:o}:null,c=k(e);return c===`online`||c===`pre`?s??r??null:r??s??null}function vt(e){return!!_t(e)}function yt(e){let t=e?.pluginConfig?.x_tt_env;return typeof t==`string`&&t?t:null}function bt(e){let t=k(e);if(t===`pre`)return{"x-tt-env":`ppe_tns_openclaw`,"x-use-ppe":`1`};let n=yt(e)??(t===`boe`?`boe_tns_api`:null);return n?{"x-tt-env":n}:{}}function xt(e){let t=k(e);return t===`online`?`https://open.feishu.cn`:t===`pre`?`https://open.feishu-pre.cn`:`https://open.feishu-boe.cn`}function St(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;return{code:typeof t.code==`number`?t.code:NaN,msg:typeof t.msg==`string`?t.msg:``,tenant_access_token:typeof t.tenant_access_token==`string`?t.tenant_access_token:void 0,expire:typeof t.expire==`number`?t.expire:void 0}}async function Ct(e){let t=Date.now();return ft&&ft.expiresAtMs-t>18e5?ft.token:pt||(pt=(async()=>{let t=_t(e);if(!t)throw Error(`missing Feishu appId/appSecret from api.config.channels.feishu or pluginConfig`);let n=mt(t.appId,`appId`),r=mt(t.appSecret,`appSecret`),i=`${xt(e)}/open-apis/auth/v3/tenant_access_token/internal`,a={"content-type":`application/json`,...bt(e)},{signal:o,clear:s}=jt(At),c;try{c=await Ue(()=>fetch(i,{method:`POST`,headers:a,body:JSON.stringify({app_id:n,app_secret:r}),signal:o}))}catch(e){throw s(),e instanceof Error&&e.name===`AbortError`?new Et(i,At):new Dt(i,e)}finally{s()}let l=await c.text();if(!c.ok)throw Error(`[auth] tenant_access_token request failed status=${c.status}`);let u=null;try{u=l?JSON.parse(l):null}catch{u=null}let d=St(u);if(!d||!Number.isFinite(d.code))throw Error(`[auth] tenant_access_token response parse failed`);if(d.code!==0)throw Error(`[auth] tenant_access_token request failed code=${d.code}${d.msg?` msg=${d.msg}`:``}`);let f=mt(d.tenant_access_token,`tenant_access_token`),p=typeof d.expire==`number`&&d.expire>0?d.expire:7200;return ft={token:f,expiresAtMs:Date.now()+p*1e3},e.logger.info(M(`[auth] tenant_access_token updated`)),f})().finally(()=>{pt=null}),pt)}async function wt(e){if(k(e)===`dev`)return{};let t=bt(e);return t.authorization=`Bearer ${await Ct(e)}`,t}async function Tt(e,t={}){let n=await wt(e),r=new Headers(t.headers??{});for(let[e,t]of Object.entries(n))r.set(e,t);return{...t,headers:r}}var Et=class extends Error{code=`TIMEOUT`;constructor(e,t){super(`Request to ${e} timed out after ${t}ms`),this.name=`RequestTimeoutError`}},Dt=class extends Error{code=`NETWORK`;constructor(e,t){super(`Network error requesting ${e}: ${t instanceof Error?t.message:String(t)}`),this.name=`NetworkError`}},Ot=class extends Error{code=`SERVER`;statusCode;constructor(e,t,n){super(`Server error ${t} from ${e}${n?`: ${n}`:``}`),this.name=`ServerError`,this.statusCode=t}};function kt(e){return e instanceof Et?`TIMEOUT`:e instanceof Dt?`NETWORK`:e instanceof Ot?`SERVER`:e instanceof Error&&e.name===`AbortError`?`TIMEOUT`:`UNKNOWN`}const R=5e3,At=5e3;function jt(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e);return typeof n==`object`&&`unref`in n&&n.unref(),{signal:t.signal,clear:()=>clearTimeout(n)}}function Mt(e,t){if(!e)return t;let n=new AbortController,r=()=>n.abort();return e.addEventListener(`abort`,r,{once:!0}),t.addEventListener(`abort`,r,{once:!0}),n.signal}const Nt={dev:`http://localhost:8001`,online:`https://open.feishu.cn`,boe:`https://open.feishu-boe.cn`,pre:`https://open.feishu-pre.cn`};function z(e){return`${Nt[k(e)]}/open-apis/security_plugin/v1/openclaw_plugin`}function Pt(e){return`${z(e)}/config`}function Ft(e){return`${z(e)}/detect`}function It(e){return`${z(e)}/batch_check_skill_detection`}function Lt(e){return`${z(e)}/skill_detect`}function Rt(e){return`${z(e)}/tracking_openclaw_plugin`}function zt(e={}){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Ae(r);return t}function Bt(e,t,n=``){return{hook_name:e,payload:zt(t),source:n}}function Vt(e){if(!e)return null;try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function Ht(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.code==`number`&&Number.isFinite(t.code)&&typeof t.msg==`string`}async function Ut(e,t){let n=await t.text();if(!t.ok)throw Error(`${e} request failed: status=${t.status}`);let r=Vt(n);if(!Ht(r))throw Error(`${e} response parse failed: missing or invalid code/msg fields`);if(r.code!==0)throw Error(`${e} request failed: code=${r.code}${r.msg?` msg=${r.msg}`:``}`);return r.data??null}async function B(e,t,n,r,i=R){let a=await Tt(e,r),{signal:o,clear:s}=jt(i),c=Mt(a.signal,o),l,u=Date.now();try{l=await Ue(()=>fetch(n,{...a,signal:c}));let r=Date.now()-u;e.logger.info(M(`[${t}] http_elapsed=${r}ms status=${l.status} url=${n}`))}catch(r){let a=Date.now()-u;throw e.logger.info(M(`[${t}] http_elapsed=${a}ms error=${r instanceof Error?r.message:String(r)} url=${n}`)),s(),r instanceof Error&&r.name===`AbortError`?new Et(n,i):new Dt(n,r)}finally{s()}return Ut(t,l)}let Wt=null;function Gt(){return Wt||=ne(),Wt}function Kt(){return{hostname:Gt(),ts:Date.now()}}function qt(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=Kt();return{...t,hostname:typeof t.hostname==`string`&&t.hostname.length>0?t.hostname:n.hostname,ts:n.ts}}const Jt=`llm_req_async_detect_result`;async function V(e,t,n,r=R){let i=Bt(t,qt(n),`miaoda`);return await B(e,t,Ft(e),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(i)},r)}async function Yt(e,t){let n={name:Jt,tag_kv:{request_id:t.requestId,source:`miaoda`,need_block:String(t.needBlock),out_token_cnt:String(Math.max(0,Math.floor(t.outTokenCnt))),detect_duration_ms:String(Math.max(0,Math.floor(t.detectDurationMs)))}};await B(e,Jt,Rt(e),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)},R)}function Xt(e){if(!e)return{logs:[],remainingCount:0};try{let t=I(JSON.parse(e)),n=(Array.isArray(t.logs)?t.logs:[]).map(e=>I(e)).filter(e=>Object.keys(e).length>0),r=t.remaining_count;return{logs:n,remainingCount:typeof r==`number`&&Number.isFinite(r)?r:0}}catch{return{logs:[],remainingCount:0}}}async function Zt(e){let t=Ee();if(!t?.proxyPort)return e.logger.info(M(`[gateway_start] network_access_log poll skipped: missing proxy runtime cache`)),{logs:[],remainingCount:0};try{let n=await Ue(()=>new Promise((e,n)=>{let r=re.request({hostname:`127.0.0.1`,port:t.proxyPort,path:`/_sec/api/v1/network-access-log?pg_size=100`,method:`GET`,rejectUnauthorized:!1},t=>{let n=[];t.on(`data`,e=>{if(typeof e==`string`){n.push(Buffer.from(e));return}n.push(Buffer.from(e))}),t.on(`end`,()=>{e({statusCode:t.statusCode??null,headers:t.headers,body:Buffer.concat(n).toString(`utf8`)})})});r.on(`error`,n),r.end()}));return n.statusCode===200?Xt(n.body):(e.logger.warn(M(`[gateway_start] network_access_log poll request failed status=${n.statusCode??`unknown`}`)),{logs:[],remainingCount:0})}catch(t){return e.logger.error(M(`[gateway_start] network_access_log poll failed error=${t instanceof Error?t.message:String(t)}`)),{logs:[],remainingCount:0}}}function Qt(){return 100}const $t=30*1e3;let H=null,en=!1,tn=null;async function nn(e,t){if(!await t.isNetworkAccessEnabled())return;let n=xe();if(!Ce()){e.logger.warn(M(`[gateway_start] network_access_log poll skipped: lark-enterprise-cli not found path=${n}`));return}try{let t=await dt(n);t.status===`started`&&e.logger.warn(M(`[gateway_start] network_access_log poll recovered lark-enterprise-cli spawn_pid=${t.spawnPid??`unknown`} daemon_pid=${t.daemonPid} proxy_port=${t.proxyPort}`))}catch(t){j(),e.logger.error(M(`[gateway_start] network_access_log poll failed to ensure lark-enterprise-cli running: ${t instanceof Error?t.message:String(t)}`));return}for(;;){if(!await t.isNetworkAccessEnabled())return;let{logs:n,remainingCount:r}=await Zt(e);if(n.length===0)return;for(let t of n){let{uuid:n,...r}=t;try{await V(e,`network_access`,r)}catch(t){e.logger.error(M(`[gateway_start] network_access detect failed host=${r.host??`<unknown>`} path=${r.path??`<unknown>`} error=${t instanceof Error?t.message:String(t)}`))}}if(r===0)return}}function rn(){H&&=(clearTimeout(H),null)}function an(e,t){if(!H){if(!t.isNetworkAccessEnabledSnapshot()){rn();return}H=setTimeout(async()=>{if(H=null,t.isNetworkAccessEnabledSnapshot()){if(en){e.logger.info(M(`[gateway_start] network_access_log poll skipped: previous poll still running`)),an(e,t);return}en=!0;try{await nn(e,t)}catch(t){e.logger.error(M(`[gateway_start] network_access_log poll loop failed: ${t instanceof Error?t.message:String(t)}`))}finally{en=!1,an(e,t)}}},$t),typeof H.unref==`function`&&H.unref()}}function on(e,t){if(!t.isNetworkAccessEnabledSnapshot()){rn();return}H||en||(e.logger.info(M(`[gateway_start] network_access_log polling started interval=${$t}ms pg_size=${Qt()}`)),an(e,t))}function sn(e,t){tn||=t.onConfigChange(()=>{if(!t.isNetworkAccessEnabledSnapshot()){rn();return}on(e,t)}),t.isNetworkAccessEnabled().then(n=>{if(!n){rn();return}on(e,t)}).catch(t=>{e.logger.error(M(`[gateway_start] network_access_log polling config check failed: ${t instanceof Error?t.message:String(t)}`))})}const cn=30*1e3;let U=null,ln=!1;function un(){U&&=(clearTimeout(U),null)}function dn(e,t){U||ln||(U=setTimeout(async()=>{U=null,ln=!0;let n=!0;try{let r=xe();if(!Ce()){e.logger.warn(M(`[gateway_start] lark-enterprise-cli runtime detect retry skipped: cli not found path=${r} next_retry_ms=${cn}`));return}let i=await st(r);if(!i){j(),e.logger.warn(M(`[gateway_start] lark-enterprise-cli runtime detect retry failed: config runtime not reachable next_retry_ms=${cn}`));return}n=!1,e.logger.info(M(`[gateway_start] lark-enterprise-cli runtime detected after retry daemon_pid=${i.daemonPid} proxy_port=${i.proxyPort} root_ca=${i.rootCa}`)),sn(e,t)}catch(t){j(),e.logger.warn(M(`[gateway_start] lark-enterprise-cli runtime detect retry failed: ${t instanceof Error?t.message:String(t)} next_retry_ms=${cn}`))}finally{ln=!1,n&&dn(e,t)}},cn),typeof U.unref==`function`&&U.unref())}async function fn(e,t,n,r){let i=xe();if(e.logger.info(M(`[gateway_start] gateway ready on port=${n.port} ctx=${JSON.stringify(r)}`)),e.logger.info(M(`[gateway_start] lark-enterprise-cli path=${i} exists=${String(Ce())}`)),!Ce()){e.logger.warn(M(`[gateway_start] lark-enterprise-cli not found, skip start path=${i}`));return}try{let n=await dt(i,{checkCliUpgrade:!0}),r=Ee();un(),n.status===`already_running`?e.logger.info(M(`[gateway_start] lark-enterprise-cli already running daemon_pid=${n.daemonPid} proxy_port=${n.proxyPort} root_ca=${n.rootCa} restarted_after_upgrade=${String(n.restartedAfterUpgrade===!0)}`)):e.logger.info(M(`[gateway_start] started detached lark-enterprise-cli spawn_pid=${n.spawnPid??`unknown`} daemon_pid=${n.daemonPid} proxy_port=${n.proxyPort} root_ca=${n.rootCa} restarted_after_upgrade=${String(n.restartedAfterUpgrade===!0)}`)),r&&e.logger.info(M(`[gateway_start] cached lark-enterprise-cli runtime daemon_pid=${r.daemonPid} proxy_port=${r.proxyPort} root_ca=${r.rootCa}`)),sn(e,t)}catch(n){j(),e.logger.error(M(`[gateway_start] failed to ensure lark-enterprise-cli running: ${n instanceof Error?n.message:String(n)}`)),dn(e,t)}}function pn(e,t){e.on(`gateway_start`,async(n,r)=>{await fn(e,t,n,r)})}function mn(e){try{let t=new URL(e);return{domain:t.host,path:t.pathname||`/`}}catch{return{domain:``,path:``}}}function hn(e){let{domain:t,path:n}=mn(F(e?.url)),r=L(e);return{request_id:F(e?.request_id),domain:t,path:n,llm_req_detect_type:F(e?.llmReqDetectType),...r?{sender_id:r}:{},origin_req:P(e?.jsonBody,e?.rawBody,``)}}function gn(e){let{domain:t,path:n}=mn(F(e?.url)),r=L(e);return{request_id:F(e?.request_id),domain:t,path:n,is_sse:e?.isSse?`true`:`false`,llm_detect_time_ms:F(e?.llm_detect_time_ms),...r?{sender_id:r}:{},chunks:We(e?.chunks),origin_resp:e?.isSse?``:F(P(e?.originResp,``))}}function _n(e){let t=L(e);return{request_id:F(e?.request_id),domain:F(e?.domain),path:F(e?.path),llm_detect_time_ms:F(e?.llm_detect_time_ms),...t?{sender_id:t}:{},api_type:`openai-completions`}}function vn(){return new Map}function yn(e,t=Date.now()){for(let[n,r]of e)r.expiresAt<=t&&e.delete(n)}function bn(e,t,n){t&&e.set(t,{value:n,expiresAt:Date.now()+72e5})}function xn(e,t){if(!t)return;let n=e.get(t);if(n){if(n.expiresAt<=Date.now()){e.delete(t);return}return n.value}}function Sn(e,t){return t?e.delete(t):!1}const Cn=vn();function W(e,t){return`${e}:${t}`}function wn(e,t,n){e&&t&&bn(Cn,W(e,t),n)}function Tn(e,t){return!e||!t?``:xn(Cn,W(e,t))??``}function En(e,t){return!e||!t?!1:Sn(Cn,W(e,t))}const Dn=vn();function On(e,t){e&&t&&bn(Dn,e,t)}function kn(e){return e?xn(Dn,e)??``:``}function An(e){return Sn(Dn,e)}const jn=vn();function Mn(e,t){e&&t&&bn(jn,e,t)}function Nn(e){return e?xn(jn,e)??``:``}function Pn(e){return Sn(jn,e)}function Fn(e){return e?e.match(/(om_[a-zA-Z0-9]+)/)?.[1]??``:``}const G=vn();function In(e,t,n){e&&t&&n&&bn(G,W(e,t),n)}function Ln(e,t){return!e||!t?``:xn(G,W(e,t))??``}function Rn(e,t){return!e||!t?!1:Sn(G,W(e,t))}function zn(e,t){if(!t)return 0;let n=0;for(let r of e.keys())r.startsWith(t)&&e.delete(r)&&(n+=1);return n}function Bn(e=Date.now()){yn(Cn,e),yn(Dn,e),yn(jn,e),yn(G,e)}function Vn(e,t){return{llmCallIdCount:+!!En(e,t),sessionRunSenderIdCount:+!!Rn(e,t)}}function Hn(e,t){let n=e?`${e}:`:``;return{llmCallIdCount:zn(Cn,n),sessionRunSenderIdCount:zn(G,n),subagentParentCallIdCount:+!!An(t)}}function Un(e){return{subagentParentCallIdCount:+!!An(e)}}function Wn(){return`llm_${Array.from(p(24),e=>`abcdefghijklmnopqrstuvwxyz0123456789`[e%36]).join(``)}`}function Gn(e,t,n={}){let r=F(e?.sessionId??t?.sessionId),i=F(t?.sessionKey),a=F(e?.runId??t?.runId),o=n.reuseExistingLlmCallId&&Tn(r,a)||Wn(),s=Ln(r,a)||L(e,t);return wn(r,a,o),{agent_name:F(t?.agentId),session_id:r,session_key:i,channel_id:F(t?.channelId),message_provider:F(t?.messageProvider),trigger:F(t?.trigger),model:F(e?.model),provider:F(e?.provider),run_id:a,llm_call_id:o,parent_tool_call_id:kn(i),...s?{sender_id:s}:{}}}function Kn(e,t){return{...Gn(e,t),prompt:F(e?.prompt),system_prompt:F(e?.systemPrompt),history_messages:We(e?.historyMessages)}}function qn(e,t){return{...Gn(e,t,{reuseExistingLlmCallId:!0}),assistant_texts:We(e?.assistantTexts),last_assistant:F(JSON.stringify(e?.lastAssistant))}}function Jn(e,t){let n=I(e?.metadata),r=F(P(t?.conversationId,e?.conversationId,n.conversationId,n.conversation_id)),i=F(P(e?.messageId,t?.messageId,n.messageId,n.message_id)),a=F(P(e?.senderId,t?.senderId,t?.sender_id,n.senderId,n.sender_id,n.SenderId));return{session_key:F(P(e?.sessionKey,t?.sessionKey)),run_id:F(P(e?.runId,t?.runId)),channel_id:F(P(t?.channelId,e?.channelId,n.channelId,n.channel_id)),conversation_id:r,from:F(P(e?.from,n.from)),content:F(P(e?.content,n.content)),to:F(P(e?.to,n.to,n.originatingTo,n.originating_to)),provider:F(P(e?.provider,n.provider,n.messageProvider,n.message_provider)),message_id:i,sender_id:a,sender_name:F(P(e?.senderName,n.senderName,n.sender_name,n.senderUsername,n.sender_username))}}function Yn(e,t){let n=F(t?.sessionId),r=F(t?.sessionKey),i=F(e?.runId??t?.runId),a=Ln(n,i)||L(e,t);return{agent_name:F(t?.agentId),session_id:n,session_key:r,tool_call_id:F(e?.toolCallId),tool_name:F(e?.toolName),tool_args:P(e?.params,{}),run_id:i,llm_call_id:Tn(n,i),parent_tool_call_id:kn(r),...a?{sender_id:a}:{}}}function Xn(e,t){return Yn(e,t)}function Zn(e,t){return{...Yn(e,t),tool_output:P(e?.result,``),tool_error:P(e?.error,``),tool_duration_ms:F(P(e?.durationMs,``))}}function K(e,t,n,r){let i=t,a=t,o=t,s=n;switch(e){case`message_received`:return Jn(o,s);case`before_tool_call`:return Xn(i,s);case`after_tool_call`:return Zn(i,s);case`before_llm_fetch`:return hn(r);case`after_llm_fetch`:case`after_llm_fetch_v2`:return gn(r);case`llm_req_async_detect`:return _n(r??{});case`llm_input`:return Kn(a,s);case`llm_output`:return qn(a,s);default:return I(r)}}function Qn(...e){return e.find(e=>typeof e==`string`)??``}function $n(e){return typeof e==`string`?e.toUpperCase():`PERMIT`}function er(e){if(!(typeof e!=`string`||e.length===0))try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function tr(e){return{effect:$n(e?.effect),denyOutput:Qn(e?.deny_output),rewriteOutput:Qn(e?.rewrite_output)}}function nr(e){let t=$n(e.effect);if(t===`DENY`)return e.denyOutput?{action:`deny`,output:e.denyOutput,returnValue:{block:!0,blockReason:e.denyOutput||`Tool call blocked by detect service`}}:{action:`permit`,returnValue:void 0};if(t===`REWRITE`){if(!e.rewriteOutput)return{action:`permit`,returnValue:void 0};let t=er(e.rewriteOutput);return t?{action:`rewrite`,returnValue:{params:t}}:{action:`rewrite_invalid`,returnValue:void 0}}return{action:`permit`,returnValue:void 0}}function q(e){return`v1:${e}`}function rr(e){if(e.tool_name!==`read`)return null;let t=e.tool_args;return!t||typeof t!=`object`||Array.isArray(t)?null:Object.values(t).find(e=>typeof e==`string`&&e.endsWith(`SKILL.md`))??null}async function ir(e,t,n){let r=i(a(t));try{let t;n&&(t=je(e.runtime.agent.resolveAgentWorkspaceDir(e.config,n)));let i=(await ze(e,t))[r];return!i||!i.skill_hash?null:{skill_name:i.skill_name,skill_hash:q(i.skill_hash)}}catch{return null}}function ar(e,t){let n=F(t.sessionId),r=F(e.runId??t.runId),i=F(e.toolCallId??t.toolCallId),a=kn(F(t.sessionKey));return{conversation_id:n,reply_group_id:r,sender_open_id:Ln(n,r),llm_call_id:Tn(n,r),tool_call_id:i,parent_tool_call_id:a,trace_time:Date.now()}}function or(e){try{return Buffer.from(JSON.stringify(e),`utf8`).toString(`base64url`)}catch{return``}}function sr(e){let t=e.params;if(!t||typeof t!=`object`||Array.isArray(t))return``;let n=t.command;return typeof n==`string`?n:``}async function cr(e,t,n,r){let i=Date.now(),a=or(ar(n,r)),o={modifiedEvent:n,injected:!1,proxyAlive:!1,mitmAuthEnabled:!1};if(await t.isToolCallInjectionEnabled())try{o=await qe(n,a,{appendMitmAuth:await t.shouldAppendMitmAuthForCommand(sr(n))})}catch(t){e.logger.error(M(`[before_tool_call] proxy env patch failed, continue without proxy injection: ${t instanceof Error?t.message:String(t)}`))}let s=o.modifiedEvent;if(o.injected&&e.logger.info(M(`[before_tool_call] prepended trace env to exec command with proxy_alive=${o.proxyAlive} mitm_auth=${o.mitmAuthEnabled}`)),!await t.isHookEnabled(`before_tool_call`)){e.logger.info(M(`[before_tool_call] detect skipped: hook disabled by runtime config`));return}let c=K(`before_tool_call`,s,r),l=rr(c),u=c;if(l){let t=await ir(e,l,r.agentId);t&&(u={...u,...t},e.logger.info(M(`[before_tool_call] skill read detected: skill=${t.skill_name} hash=${t.skill_hash.slice(0,12)}...`)))}let d,f=o.injected;try{let t=tr(await V(e,`before_tool_call`,u)),n=nr(t);e.logger.info(M(`[before_tool_call] detect effect applied: effect=${t.effect} has_return_value=${n.returnValue!==void 0}`)),d=n.returnValue,f&&!n.returnValue&&(d={params:s.params})}catch(t){e.logger.error(M(`[before_tool_call] detect request failed: ${t instanceof Error?t.message:String(t)}`)),f&&(d={params:s.params})}let p=Date.now()-i;return e.logger.info(M(`[before_tool_call] total_elapsed=${p}ms`)),d}function lr(e){let t=setTimeout(e,3e3);typeof t==`object`&&t&&`unref`in t&&t.unref()}async function ur(e,t,n,r,i){if(!await t.isHookEnabled(n)){e.logger.info(M(`[${n}] detect skipped: hook disabled by runtime config`));return}let a=Date.now(),o=K(n,r,i);try{n===`after_tool_call`&&fr(e,r);let t=tr(await V(e,n,o));e.logger.info(M(`[${n}] detect effect observed: effect=${t.effect} (report-only hook)`))}catch(t){e.logger.error(M(`[${n}] detect request failed: ${t instanceof Error?t.message:String(t)}`))}finally{let t=Date.now()-a;e.logger.info(M(`[${n}] total_elapsed=${t}ms`))}}function dr(e){let t=I(e),n=F(I(t.details).childSessionKey);if(n)return n;let r=Array.isArray(t.content)?t.content:[];for(let e of r){let t=F(I(e).text);if(t)try{let e=F(I(JSON.parse(t)).childSessionKey);if(e)return e}catch{}}return``}function fr(e,t){if(t.toolName!==`sessions_spawn`)return;let n=F(t.toolCallId);if(!n)return;let r=dr(t.result);r&&(On(r,n),e.logger.info(M(`[after_tool_call] linked child_session_key=${r} -> parent_tool_call_id=${n}`)))}async function pr(e,t,n,r){let i=I(n.metadata),a=L(n,r,i),o=F(n.messageId??r.messageId??i.messageId??i.message_id);if(o&&a&&Mn(o,a),!await t.isHookEnabled(`message_received`)){e.logger.info(M(`[message_received] detect skipped: hook disabled by runtime config`));return}let s=Date.now(),c=K(`message_received`,n,r);try{let t=tr(await V(e,`message_received`,c));e.logger.info(M(`[message_received] detect effect observed: effect=${t.effect} (report-only hook)`))}catch(t){e.logger.error(M(`[message_received] detect request failed: ${t instanceof Error?t.message:String(t)}`))}finally{let t=Date.now()-s;e.logger.info(M(`[message_received] total_elapsed=${t}ms`))}}async function mr(e,t,n){let r=Fn(String(t.prompt??``));if(!r)return;let i=String(n.sessionId??``),a=String(n.runId??t.runId??``);if(!i||!a)return;let o=Nn(r);o&&(In(i,a,o),lr(()=>{Pn(r)}),e.logger.info(M(`[before_agent_start] linked session_id=${i} run_id=${a} -> message_id=${r} sender_id=${o}`)))}async function hr(e,t,n){let r=F(n.sessionId),i=F(t.runId??n.runId);!r||!i||lr(()=>{let t=Vn(r,i);(t.llmCallIdCount>0||t.sessionRunSenderIdCount>0)&&e.logger.info(M(`[agent_end] cleaned run-scoped caches session_id=${r} run_id=${i} llm_call_id_count=${t.llmCallIdCount} session_run_sender_id_count=${t.sessionRunSenderIdCount}`))})}async function gr(e,t,n){let r=F(t.sessionId??n.sessionId),i=F(t.sessionKey??n.sessionKey);!r&&!i||lr(()=>{let n=Hn(r,i);(n.llmCallIdCount>0||n.sessionRunSenderIdCount>0||n.subagentParentCallIdCount>0)&&e.logger.info(M(`[session_end] cleaned session-scoped caches session_id=${r} session_key=${i} reason=${F(t.reason)} llm_call_id_count=${n.llmCallIdCount} session_run_sender_id_count=${n.sessionRunSenderIdCount} subagent_parent_call_id_count=${n.subagentParentCallIdCount}`))})}async function _r(e,t,n){let r=F(t.targetSessionKey);r&&lr(()=>{let n=Un(r);n.subagentParentCallIdCount>0&&e.logger.info(M(`[subagent_ended] cleaned subagent caches target_session_key=${r} outcome=${F(t.outcome)} reason=${F(t.reason)} subagent_parent_call_id_count=${n.subagentParentCallIdCount}`))})}function vr(e,t){e.on(`llm_input`,async(n,r)=>{await ur(e,t,`llm_input`,n,r)}),e.on(`llm_output`,async(n,r)=>{await ur(e,t,`llm_output`,n,r)}),e.on(`after_tool_call`,async(n,r)=>{await ur(e,t,`after_tool_call`,n,r)}),e.on(`before_tool_call`,async(n,r)=>cr(e,t,n,r)),e.on(`message_received`,async(n,r)=>{await pr(e,t,n,r)}),e.on(`before_agent_start`,async(t,n)=>{await mr(e,t,n)}),e.on(`agent_end`,async(t,n)=>{await hr(e,t,n)}),e.on(`session_end`,async(t,n)=>{await gr(e,t,n)}),e.on(`subagent_ended`,async(t,n)=>{await _r(e,t,n)})}function yr(e){try{let t=new URL(e);return{host:t.host,path:t.pathname||`/`}}catch{return null}}function br(e,t,n,r){if(!n||N()||!t.isNetworkHookEnabledSnapshot())return;let i=yr(n);i&&(async()=>{await t.isNetworkAccessEnabled()&&await V(e,`network_access`,i)})().catch(t=>{e.logger.error(M(`[network_access] report_failed source=${r} error=${t instanceof Error?t.message:String(t)}`))})}function xr(e){return typeof e==`object`&&!!e}function Sr(e){return typeof e==`string`?e:e instanceof URLSearchParams?e.toString():e instanceof Uint8Array?new TextDecoder().decode(e):ArrayBuffer.isView(e)?new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):e instanceof ArrayBuffer?new TextDecoder().decode(new Uint8Array(e)):null}function Cr(e){let t=Sr(e);if(!t)return null;try{let e=JSON.parse(t);return xr(e)?e:null}catch{return null}}function wr(e){return xr(e)?Array.isArray(e.messages)||typeof e.prompt==`string`||typeof e.input==`string`:!1}const J=`network_hook`;function Y(e){return typeof e==`string`?e:e instanceof URL?e.toString():``}function Tr(e){let t=e?.request;if(!t)return`<unknown>`;let n=Y(t.url);if(n)return n;let r=Y(t.origin),i=Y(t.path);if(!r)return i||`<unknown>`;if(!i)return r;try{return new URL(i,r).toString()}catch{return`${r}${i}`}}function Er(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url||``}function Dr(e){return Array.isArray(e)?e.map(e=>String(e)).join(`, `):String(e)}function Or(e){return typeof Buffer<`u`&&Buffer.isBuffer(e)?e.toString(`utf8`):e instanceof Uint8Array?new TextDecoder().decode(e):String(e)}function kr(e,t,n){let r=Or(t),i=Dr(n);r&&(e[r]=e[r]?`${e[r]}, ${i}`:i)}function Ar(e){if(e){if(e instanceof Headers)return Object.fromEntries(e.entries());if(Array.isArray(e)){let t={};if(e.every(e=>Array.isArray(e))){for(let n of e){let[e,r]=n;kr(t,e,r)}return t}for(let n=0;n<e.length;n+=2){let r=e[n];kr(t,r,n+1<e.length?e[n+1]:``)}return t}if(typeof e==`object`)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Dr(t)]))}}function jr(e){return{source:e.source,method:e.method??null,inputType:e.inputType??null}}function Mr(e,t){let n=t?.method??(e instanceof Request?e.method:void 0)??`GET`;return String(n).toUpperCase()}function Nr(e,t){return jr({source:`fetch`,method:Mr(e,t),inputType:e instanceof Request?`Request`:e instanceof URL?`URL`:typeof e})}async function Pr(e,t){let n=Sr(t?.body);if(n)return{rawBody:n,jsonBody:Cr(t?.body)};if(!(e instanceof Request))return{rawBody:null,jsonBody:null};try{let t=await e.clone().text();if(!t)return{rawBody:null,jsonBody:null};try{return{rawBody:t,jsonBody:JSON.parse(t)}}catch{return{rawBody:t,jsonBody:null}}}catch{return{rawBody:null,jsonBody:null}}}function Fr(e){let[t,n]=e;return t&&typeof t==`object`&&!(t instanceof URL)?t:n&&typeof n==`object`?n:null}function Ir(e,t=`GET`){let n=Fr(e);return(n&&typeof n.method==`string`&&n.method?n.method:t).toUpperCase()}function Lr(e,t){return Fr(e),jr({source:t,method:t===`get`?`GET`:Ir(e)})}function Rr(e){return jr({source:`undici_diagnostic`,method:typeof e.method==`string`?e.method.toUpperCase():void 0})}function zr(e){let t=Y(e.origin),n=Y(e.path);if(!t)return n||`<unknown>`;if(!n)return t;try{return new URL(n,t).toString()}catch{return`${t}${n}`}}function Br(e){return jr({source:`undici`,method:typeof e.method==`string`?e.method.toUpperCase():void 0})}function Vr(e){return typeof e==`string`?e:typeof Buffer<`u`&&Buffer.isBuffer(e)?e.toString(`utf8`):e instanceof Uint8Array?new TextDecoder().decode(e):e instanceof ArrayBuffer?new TextDecoder().decode(new Uint8Array(e)):ArrayBuffer.isView(e)?new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):null}function Hr(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function Ur(e){return typeof e==`object`&&!!e&&typeof e[Symbol.iterator]==`function`}function Wr(e){return Hr(e)||Ur(e)}function Gr(e){return typeof e==`string`?Buffer.from(e):typeof Buffer<`u`&&Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(String(e))}async function Kr(e){let t=Vr(e);if(t!==null)return{rawBody:t,body:e};if(!Hr(e)&&!Ur(e))return{rawBody:null,body:e};let n=[];for await(let t of e)n.push(Gr(t));let r=Buffer.concat(n);return{rawBody:r.toString(`utf8`),body:r}}function qr(e,t){let[n,r]=e;if(typeof n==`string`)return n;if(n instanceof URL)return n.toString();let i=n&&typeof n==`object`?n:r&&typeof r==`object`?r:null;if(!i)return``;let a=typeof i.protocol==`string`&&i.protocol?i.protocol:t,o=typeof i.hostname==`string`&&i.hostname?i.hostname:typeof i.host==`string`&&i.host?i.host:typeof i.servername==`string`&&i.servername?i.servername:``,s=typeof i.port==`number`||typeof i.port==`string`?String(i.port):``,c=typeof i.path==`string`&&i.path?i.path:`/`;return o?`${a}//${o}${s?`:${s}`:``}${c}`:c}function Jr(e,t){let n=Object.fromEntries(Object.entries(Ar(e)??{}).filter(([e])=>e.toLowerCase()!==`content-length`));return n[`content-length`]=String(Buffer.byteLength(t)),n}function Yr(e,t,n){if(n==null)return[e,t];let r=Mr(e,t),i=new Headers(Jr(t?.headers??(e instanceof Request?e.headers:void 0),n)),a={...t,headers:i,body:r===`GET`||r===`HEAD`?void 0:n};return e instanceof Request?[new Request(e,a),a.dispatcher?{dispatcher:a.dispatcher}:void 0]:[e,a]}function Xr(e,t){return{...e,body:t,headers:Jr(e.headers,t)}}function Zr(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function Qr(e,t){return e==null?``:typeof e==`string`?e:typeof Buffer<`u`&&Buffer.isBuffer(e)?e.toString(t):e instanceof Uint8Array?new TextDecoder().decode(e):String(e)}const $r=new WeakSet,ei=new WeakMap;function ti(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return``;let n=e[t];return Array.isArray(n)?n.length>0?String(n[0]):``:n==null?``:String(n)}function ni(e){if(e instanceof URL)return e.origin;try{return new URL(e).origin}catch{return`https://${e}`}}function ri(e,t){let n=ti(t,`:path`)||`/`,r=ti(t,`:authority`),i=ti(t,`:scheme`)||`https`;if(r)return`${i}://${r}${n.startsWith(`/`)?n:`/${n}`}`;let a=ei.get(e);return a?`${a}${n.startsWith(`/`)?n:`/${n}`}`:n}function ii(e,t,n,r){if($r.has(n))return;$r.add(n),ei.set(n,r);let i=n.request.bind(n);n.request=((...r)=>{if(N()||!t.isNetworkHookEnabledSnapshot())return i(...r);let a=r[0];return br(e,t,ri(n,a),`http2_hook`),i(...r)})}function ai(e,t){if(globalThis.__openclawGuardianOriginalHttp2Connect){e.logger.info(M(`[${J}] http2_interceptor already_installed`));return}globalThis.__openclawGuardianOriginalHttp2Connect=ie.connect,ie.connect=((...n)=>{let r=globalThis.__openclawGuardianOriginalHttp2Connect(...n);return ii(e,t,r,ni(n[0])),r}),e.logger.info(M(`[${J}] http2_interceptor installed`))}function oi(e){return typeof e==`object`&&!!e}function si(e,t){if(!oi(e))return null;let n=e[t];return oi(n)?n:null}function ci(e){let t=si(si(e,`models`),`providers`);return t?Object.entries(t).map(([e,t])=>{if(!oi(t))return null;let n=t.baseUrl??t.baseURL;return typeof n==`string`&&n?{providerId:e,baseUrl:n}:null}).filter(e=>e!==null):[]}function li(e,t){for(let n of t)if(e.startsWith(n.baseUrl))return n;return null}function ui(e){return typeof e==`string`?e.toUpperCase():``}function di(e){return e===`PERMIT`||e===`DENY`||e===`REWRITE`}function fi(e){let{api:t,requestId:n,pollPayloadBase:r,detectStartTimeMs:i,pollIntervalMs:a,maxPollWaitMs:o,isTerminal:s,parseDecision:c,onDecision:l,onFailedOpen:u}=e,d=null,f=!0,p=Date.now();function m(){f=!0,d&&=(clearTimeout(d),null)}function h(){u(),m()}function g(){if(!(f||s())){if(Date.now()-p>o){t.logger.info(M(`[llm_req_async_detect] async_detect_poll_timeout request_id=${n}`)),h();return}d=setTimeout(async()=>{if(!(f||s()))try{let e=await V(t,`llm_req_async_detect`,K(`llm_req_async_detect`,null,null,{...r,llm_detect_time_ms:i}));if(s())return;if(!e){t.logger.info(M(`[llm_req_async_detect] async_detect_poll request_id=${n} effect=empty`)),g();return}let a=ui(e.effect);if(t.logger.info(M(`[llm_req_async_detect] async_detect_poll request_id=${n} effect=${a||`<empty>`}`)),a===`PENDING`){g();return}if(di(a)){l(c(e));return}if(!a){let r=typeof e.status==`string`?e.status:``;t.logger.warn(M(`[llm_req_async_detect] async_detect_poll_invalid request_id=${n} effect=<empty>${r?` legacy_status=${r}`:``}`)),h();return}t.logger.warn(M(`[llm_req_async_detect] async_detect_poll_invalid request_id=${n} effect=${a}`)),h()}catch(e){t.logger.error(M(`[llm_req_async_detect] async_detect_failed request_id=${n} error=${e instanceof Error?e.message:String(e)}`)),h()}},a),typeof d==`object`&&d&&`unref`in d&&d.unref()}}return{start:()=>{m(),f=!1,p=Date.now(),g()},stop:m}}const pi=[`taken_over`,`completed`,`failed_open`],mi={pending:[`response_ready`,`outputting`,`taken_over`,`completed`,`failed_open`],response_ready:[`outputting`,`taken_over`,`completed`,`failed_open`],outputting:[`taken_over`,`completed`,`failed_open`],taken_over:[],completed:[],failed_open:[]};function X(e){return pi.includes(e)}function Z(e,t){return X(e.state)?!1:e.state===t?!0:mi[e.state].includes(t)?(e.state=t,!0):!1}function hi(...e){return e.find(e=>typeof e==`string`)??``}function gi(e){return typeof e==`string`?e.toUpperCase():`PERMIT`}function Q(e){return{effect:gi(e?.effect),denyOutput:hi(e?.deny_output),rewriteOutput:hi(e?.rewrite_output)}}function $(e){let t=e.effect;return!!(t===`DENY`&&e.denyOutput||t===`REWRITE`&&e.rewriteOutput)}function _i(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):1e3}function vi(e,t,n,r={}){let i=r.decisionMode??`takeover`,a=n&&typeof n==`object`?n:null,o={request_id:t,domain:typeof a?.domain==`string`?a.domain:``,path:typeof a?.path==`string`?a.path:``},s=r.initialDetectPromise,c=typeof r.detectStartTimeMs==`number`&&Number.isFinite(r.detectStartTimeMs)?Math.floor(r.detectStartTimeMs):Date.now(),l=_i(r.pollIntervalMs),u=typeof r.maxPollWaitMs==`number`&&Number.isFinite(r.maxPollWaitMs)&&r.maxPollWaitMs>0?Math.floor(r.maxPollWaitMs):3e4,d=null,f,p=new Promise(e=>{f=e}),m={requestId:t,startedAtMs:Date.now(),state:`pending`,hasOriginalOutput:!1,originalOutputChunks:0,originalOutputBytes:0,flushPendingOutputStats:()=>{},cancelReader:null,takeoverPromise:p,stopPolling:()=>{d?.stop()},cleanup:()=>{if(m.stopPolling(),m.flushPendingOutputStats(),m.cancelReader)try{m.cancelReader()}catch{}}};if(d=fi({api:e,requestId:t,pollPayloadBase:o,detectStartTimeMs:c,pollIntervalMs:l,maxPollWaitMs:u,isTerminal:()=>X(m.state),parseDecision:Q,onDecision:t=>{h(m,t,e)},onFailedOpen:()=>{Z(m,`failed_open`)&&m.stopPolling()}}),e.logger.info(M(`[before_llm_fetch] async_detect_started request_id=${t}`)),s)return s.then(()=>{X(m.state)||d?.start()}).catch(n=>{e.logger.error(M(`[before_llm_fetch] async_detect_failed request_id=${t} error=${n instanceof Error?n.message:String(n)}`)),Z(m,`failed_open`)&&m.stopPolling()}),m;V(e,`before_llm_fetch`,n).then(n=>{if(X(m.state))return;let r=n;if(!r){e.logger.info(M(`[before_llm_fetch] async_detect_init request_id=${t} effect=empty`)),d?.start();return}let i=ui(r.effect);if(e.logger.info(M(`[before_llm_fetch] async_detect_init request_id=${t} effect=${i||`<empty>`}`)),di(i)){h(m,Q(r),e);return}if(i&&i!==`PENDING`){e.logger.warn(M(`[before_llm_fetch] async_detect_init_invalid request_id=${t} effect=${i}`)),Z(m,`failed_open`)&&m.stopPolling();return}d?.start()}).catch(n=>{e.logger.error(M(`[before_llm_fetch] async_detect_failed request_id=${t} error=${n instanceof Error?n.message:String(n)}`)),Z(m,`failed_open`)&&m.stopPolling()});function h(e,t,n){if(n.logger.info(M(`[before_llm_fetch] async_detect_decision request_id=${e.requestId} effect=${t.effect}`)),e.flushPendingOutputStats(),t.effect===`PERMIT`){e.stopPolling();return}if($(t)){if(i===`observe`){e.stopPolling(),n.logger.info(M(`[before_llm_fetch] async_detect_ignored request_id=${e.requestId} effect=${t.effect}`));return}if(e.decision=t,X(e.state))return;if((e.state===`pending`||e.state===`response_ready`||e.state===`outputting`)&&Z(e,`taken_over`)){if(e.stopPolling(),e.flushPendingOutputStats(),e.cancelReader)try{e.cancelReader()}catch{}f(),n.logger.info(M(`[before_llm_fetch] takeover request_id=${e.requestId} phase=${e.state===`pending`?`before_response`:`sse_streaming`} effect=${t.effect} original_chunks=${e.originalOutputChunks} original_bytes=${e.originalOutputBytes}`))}}}return m}function yi(e){let t=new Promise(()=>{});return{requestId:e,startedAtMs:Date.now(),state:`pending`,hasOriginalOutput:!1,originalOutputChunks:0,originalOutputBytes:0,flushPendingOutputStats:()=>{},cancelReader:null,takeoverPromise:t,stopPolling:()=>{},cleanup:()=>{}}}function bi(){return new Promise(e=>{setTimeout(e,0)})}var xi=class{options;pendingRawEvents=[];pendingEventTexts=[];pendingDetectChunks=[];constructor(e){this.options=e}addEvent(e){this.pendingRawEvents.push(`${e}\n\n`),this.pendingEventTexts.push(e),this.collectDetectChunks(e)}addRawRemainder(e){this.pendingRawEvents.push(e)}clear(){this.pendingRawEvents=[],this.pendingEventTexts=[],this.pendingDetectChunks=[]}hasReachedChunkSize(e){return this.pendingDetectChunks.length>=e}async flushDetectedBatch(e){let{api:t,afterDetectEnabled:n,respSyncDetectEnabled:r,session:i}=this.options;if(this.pendingRawEvents.length===0)return this.pendingDetectChunks=[],!1;if(!n||this.pendingDetectChunks.length===0)return this.flushRaw(e),!1;if(!r){let t=[...this.pendingDetectChunks];return this.pendingDetectChunks=[],this.scheduleAsyncAfterDetect(e,t),this.flushRaw(e),!1}let a=[...this.pendingDetectChunks];this.pendingDetectChunks=[];let o=this.buildDetectPayload(a);try{let n=await V(t,`after_llm_fetch_v2`,o);if(i.state===`taken_over`||i.state===`completed`||i.state===`failed_open`)return!1;let r=Q(n);return $(r)?this.options.applyDecision(e,r):(this.flushRaw(e),await bi(),!1)}catch(n){return t.logger.error(M(`[after_llm_fetch_v2] detect failed request_id=${this.options.requestId} error=${n instanceof Error?n.message:String(n)}`)),this.flushRaw(e),!1}}collectDetectChunks(e){let t=e.split(/\r?\n/);for(let e of t){if(!e.startsWith(`data:`))continue;let t=e.slice(5).trim();!t||t===`[DONE]`||this.pendingDetectChunks.push(t)}}flushRaw(e){let{encoder:t,session:n,statsTracker:r}=this.options;if(this.pendingRawEvents.length!==0){if(n.state===`taken_over`&&n.decision){this.clear();return}e.enqueue(t.encode(this.pendingRawEvents.join(``))),r.recordOutputEvents(this.pendingEventTexts),this.clear()}}scheduleAsyncAfterDetect(e,t){let{api:n,session:r}=this.options;!this.options.afterDetectEnabled||t.length===0||V(n,`after_llm_fetch_v2`,this.buildDetectPayload(t)).then(async t=>{if(r.state===`taken_over`||r.state===`completed`||r.state===`failed_open`)return;let n=Q(t);$(n)&&await this.options.applyDecision(e,n)}).catch(e=>{n.logger.error(M(`[after_llm_fetch_v2] detect failed request_id=${this.options.requestId} error=${e instanceof Error?e.message:String(e)}`))})}buildDetectPayload(e){return K(`after_llm_fetch_v2`,null,null,{request_id:this.options.requestId,url:this.options.url,isSse:!0,llm_detect_time_ms:this.options.totalStartMs,chunks:e,originResp:``})}};function Si(e){let t=String(e);function n(e){if(typeof e!=`string`)return JSON.stringify(e);try{let t=JSON.parse(e);return typeof t==`string`?t:JSON.stringify(t)}catch{return e}}function r(e){if(!e||e===`[DONE]`)return!0;try{return JSON.parse(e),!0}catch{return!1}}try{let e=JSON.parse(t);if(Array.isArray(e))return e.map(e=>n(e))}catch{}let i=t.split(/\r?\n\r?\n/).map(e=>e.trim()).filter(e=>e.length>0);if(i.some(e=>e.includes(`data:`))){let e=i.flatMap(e=>e.split(/\r?\n/).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim())).filter(e=>e.length>0);if(e.length>0)return e.map(e=>n(e))}if(i.length>1)return i.map(e=>n(e));let a=t.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0);return a.length>1&&a.every(e=>r(e))?a.map(e=>n(e)):[t]}function Ci(e){let t=Si(e).filter(e=>e.length>0);return(t.at(-1)===`[DONE]`?t:[...t,`[DONE]`]).map(e=>`data: ${e}\n\n`)}var wi=class{buffer=``;push(e){this.buffer+=e;let t=[];for(;;){let e=this.buffer.indexOf(`
4
2
 
5
- `),o=2;if(i<0&&(i=d.indexOf(`\r
3
+ `),n=2;if(e<0&&(e=this.buffer.indexOf(`\r
6
4
  \r
7
- `),o=4),i<0)break;let l=d.slice(0,i);d=d.slice(i+o);let g=`${l}\n\n`;f.push(g);let _=l.split(/\r?\n/);for(let e of _){if(!e.startsWith(`data:`))continue;let t=e.slice(5).trim();!t||t===`[DONE]`||p.push(t)}if(p.length>=s){try{let i=await m(p);if((i.action===`deny`||i.action===`rewrite`)&&i.output){f=[],p=[];let o=await Et(r,i.output).text();t.enqueue(u.encode(o));try{await c.cancel()}catch{}t.close(),e.logger.info(x(`[llm_fetch] total_elapsed=${Date.now()-a}ms request_id=${n}`));return}}catch(t){e.logger.error(x(`[after_llm_fetch] detect failed; passthrough buffered events: ${t instanceof Error?t.message:String(t)}`))}h(t),p=[]}}}if(d&&=(f.push(d),``),p.length>0)try{let i=await m(p);if((i.action===`deny`||i.action===`rewrite`)&&i.output){f=[],p=[];let o=await Et(r,i.output).text();t.enqueue(u.encode(o));try{await c.cancel()}catch{}t.close(),e.logger.info(x(`[llm_fetch] total_elapsed=${Date.now()-a}ms request_id=${n}`));return}}catch(t){e.logger.error(x(`[after_llm_fetch] detect failed; passthrough buffered events: ${t instanceof Error?t.message:String(t)}`))}h(t),t.close(),e.logger.info(x(`[llm_fetch] total_elapsed=${Date.now()-a}ms request_id=${n}`))}catch(e){try{await c.cancel()}catch{}t.error(e)}}}),_=new Headers(r.headers);return _.delete(`content-length`),_.set(`content-type`,`text/event-stream; charset=utf-8`),new Response(g,{status:r.status,statusText:r.statusText,headers:_})}function kt(e,t){let n=globalThis.fetch;if(typeof n!=`function`){e.logger.warn(x(`[before_llm_fetch] global.fetch is unavailable; skipping interceptor`));return}globalThis.__openclawGuardianOriginalFetch||(globalThis.__openclawGuardianOriginalFetch=n,globalThis.fetch=async function(r,i){let a=[r,i],o=r?.toString?.()??``,s=i??{},c=()=>n.call(globalThis,a[0],a[1]);if(a[1]||=s,ft(o))return c();let l,u=null;try{let r=ct(o,st(e.config));if(!r)return e.logger.info(x(`[before_llm_fetch] pass-through: no provider baseUrl match for url=${o}`)),c();e.logger.info(x(`[before_llm_fetch] matched provider=${r.providerId} baseUrl=${r.baseUrl} url=${o}`));let i=ut(s.body);if(!dt(i))return e.logger.info(x(`[before_llm_fetch] pass-through: matched provider=${r.providerId} but request body is not a supported LLM payload shape`)),c();let d={request_id:wt(),url:o,rawBody:lt(s.body)??``,jsonBody:i},f=String(d.request_id);if(u=Date.now(),await t.isHookEnabled(`before_llm_fetch`)){let t=X(`before_llm_fetch`,null,null,d);Ct(e,`before_llm_fetch`,t);let n=bt(await K(e,`before_llm_fetch`,t)),i=xt(n);(i.action===`deny`||i.action===`rewrite`)&&i.output?(s.body=String(i.output),a[1]=s,e.logger.info(x(`[before_llm_fetch] detect effect applied: ${i.action} (use output as new body) provider=${r.providerId}`))):e.logger.info(x(`[before_llm_fetch] detect effect passthrough: effect=${n.effect} provider=${r.providerId}`))}else e.logger.info(x(`[before_llm_fetch] detect skipped: hook disabled by runtime config`));if(l=await n.apply(this,a),!await t.isHookEnabled(`after_llm_fetch`))return u!==null&&e.logger.info(x(`[llm_fetch] total_elapsed=${Date.now()-u}ms request_id=${f}`)),l;if(Dt(l))return await Ot(e,o,f,l,t,u??Date.now());let p=await _t(o,l,await t.getSseChunkSize()),m=X(`after_llm_fetch`,null,null,{...p,request_id:f});Ct(e,`after_llm_fetch`,m);let h=bt(await K(e,`after_llm_fetch`,m)),g=St(h);return(g.action===`deny`||g.action===`rewrite`)&&g.output?(e.logger.info(x(`[after_llm_fetch] detect effect applied: ${g.action} provider=${r.providerId}`)),u!==null&&e.logger.info(x(`[llm_fetch] total_elapsed=${Date.now()-u}ms url=${o}`)),gt(l,g.output,p.isSse)):(e.logger.info(x(`[after_llm_fetch] detect effect passthrough: effect=${h.effect} provider=${r.providerId}`)),u!==null&&e.logger.info(x(`[llm_fetch] total_elapsed=${Date.now()-u}ms request_id=${f}`)),l)}catch(t){return e.logger.error(x(`[llm_fetch] detect request failed, allowing original fetch flow: ${t instanceof Error?t.message:String(t)}`)),l?(u!==null&&e.logger.info(x(`[llm_fetch] total_elapsed=${Date.now()-u}ms request_id=<unknown>`)),l):c()}})}function $(e){return e.replace(/\0/g,``)}function At(e,t){let n=s(),r=new Set,a=e.config??{},c=a?.skills?.load?.extraDirs;if(Array.isArray(c))for(let e of c)typeof e==`string`&&e.trim()&&r.add(o($(e.trim())));r.add(i(n,`.openclaw`,`skills`)),r.add(i(n,`.agents`,`skills`));let l=new Set,u=a?.agents?.defaults?.workspace;if(typeof u==`string`&&u.trim()&&l.add(o($(u.trim()))),Array.isArray(a?.agents?.list))for(let e of a.agents.list)typeof e?.workspace==`string`&&e.workspace.trim()&&l.add(o($(e.workspace.trim())));for(let e of l)r.add(i(e,`skills`)),r.add(i(e,`.agents`,`skills`));let d,f=e.pluginConfig;if(typeof f?.openClawDir==`string`&&f.openClawDir.trim())d=o($(f.openClawDir.trim()));else try{let t=e.runtime?.state?.resolveStateDir?.();typeof t==`string`&&t.trim()&&(d=t)}catch{}d&&(r.add(i(d,`skills`)),r.add(i(d,`.agents`,`skills`)));let p=a?.plugins;if(p?.installs&&typeof p.installs==`object`){for(let e of Object.values(p.installs))if(typeof e?.installPath==`string`&&e.installPath.trim()){let t=i($(e.installPath.trim()),`skills`);r.add(o(t))}}let m=t??i(n,`.openclaw`,`workspace`);r.add(i(m,`.agents`,`skills`)),r.add(i(m,`skills`));let h=Array.from(r),g=h.filter(e=>v(e));return e.logger.info(x(`[skill-scan] resolved ${h.length} skill path(s), ${g.length} exist`)),g}async function jt(e){let t;try{t=await f(e)}catch{return[]}let n=[];for(let r of t){let t=i(e,r),a=await l(t);a.isSymbolicLink()||(a.isDirectory()?n.push(...await jt(t)):a.isFile()&&n.push(t))}return n}const Mt=10*1024*1024;async function Nt(e){let t=await jt(e);if(t.length===0)return _(`sha256`).update(`empty-skill-dir`).digest(`hex`);let r=[],i=0;for(let a of t){let t=await d(a);if(i+=t.length,i>Mt)throw Error(`computeCanonicalHash: skill directory exceeds ${Mt} byte limit: ${e}`);let o=n(a),s=_(`sha256`).update(t).digest(`hex`);r.push(`${o}:${s}`)}return r.sort(),_(`sha256`).update(r.join(`
8
- `)).digest(`hex`)}function Pt(e){let t=/^name:\s*(.+)$/m.exec(e);return t?t[1].trim():null}function Ft(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);return t?t[1]:``}async function It(e,t){let n;try{n=await f(t,{withFileTypes:!0,encoding:`utf8`})}catch{return[]}let r=[];for(let a of n){if(!a.isDirectory())continue;let n=i(t,a.name),o=i(n,`SKILL.md`);try{let e=Pt(Ft(await d(o,`utf-8`)))||a.name,t=await Nt(n);r.push({dirName:a.name,dirPath:n,filePath:o,skillName:e,skillHash:t})}catch(t){t instanceof Error&&t.message.includes(`byte limit`)&&e.logger.warn(x(`[skill-scan] skipping skill '${a.name}': ${t.message}`))}}return r}async function Lt(e,t){let n=At(e,t);e.logger.info(x(`[skill-scan] scanning ${n.length} skill location(s)`));let r=new Map;for(let t of n){let n=await It(e,t);n.length>0&&e.logger.info(x(`[skill-scan] ${t}: ${n.length} skill(s)`));for(let e of n)r.set(e.skillName,e)}let i=Array.from(r.values());return e.logger.info(x(`[skill-scan] scan complete: ${i.length} unique skill(s) across all locations`)),i}function Rt(e,t,n,r,i){e[t]={...n,skill_name:r.skill_name,skill_hash:r.skill_hash,is_detected:i,last_detect_ts:Date.now()}}async function zt(e,t){e.logger.info(x(`[skill-scan] starting skill scan`));let n=Date.now(),r=Ae(t),i=await Lt(e,t);if(i.length===0){e.logger.info(x(`[skill-scan] no skills found, skipping detection`));return}let a=Be(await Re(e,r),i);e.logger.info(x(`[skill-scan] merged state: ${Object.keys(a).length} skill(s)`));let o=new Map(i.map(e=>[e.dirName,e])),s=[];for(let[t,n]of Object.entries(a))if(o.get(t)){if(Pe(n)){e.logger.warn(x(`[skill-scan] ${n.skill_name}: skill_hash missing, skipping`));continue}n.is_detected||(e.logger.info(x(`[skill-scan] ${n.skill_name}: not detected, queuing`)),s.push({dirName:t,entry:n,entity:{skill_name:n.skill_name,skill_hash:n.skill_hash}}))}if(e.logger.info(x(`[skill-scan] ${s.length} skill(s) need detection`)),s.length===0){await ze(e,a,r),e.logger.info(x(`[skill-scan] skill scan complete (nothing to detect) total_elapsed=${Date.now()-n}ms scanned=${i.length}`));return}let c={};for(let{dirName:e}of s)c[e]=a[e];let l={},u=!1;try{l=await Ge(e,c),e.logger.info(x(`[skill-scan] batch_check result: ${JSON.stringify(l)}`))}catch(t){e.logger.error(x(`[skill-scan] batch_check_detection failed: ${t instanceof Error?t.message:String(t)}`)),u=!0}for(let{dirName:t,entry:n,entity:r}of s)l[Z(r.skill_hash)]===!0&&(Rt(a,t,n,r,!0),e.logger.info(x(`[skill-scan] ${r.skill_name}: already known by server (batch_check)`)));if(u){e.logger.warn(x(`[skill-scan] skipping individual detect calls: batch_check_detection was unreachable`)),await ze(e,a,r),e.logger.info(x(`[skill-scan] skill scan complete (partial — batch_check failed) total_elapsed=${Date.now()-n}ms scanned=${i.length}`));return}for(let{dirName:t,entry:n,entity:r}of s){if(l[r.skill_hash]===!0)continue;let n=o.get(t);if(n)try{let i=await Ye(e,n.dirPath,r);Rt(a,t,a[t],r,i),e.logger.info(x(`[skill-scan] detect result for ${r.skill_name}: is_detected=${i}`))}catch(n){e.logger.error(x(`[skill-scan] detect failed for ${r.skill_name}: ${n instanceof Error?n.message:String(n)}`)),Rt(a,t,a[t],r,!1)}}await ze(e,a,r),e.logger.info(x(`[skill-scan] skill scan complete total_elapsed=${Date.now()-n}ms scanned=${i.length} to_detect=${s.length}`))}async function Bt(e,t,n,r){e.logger.info(x(`[gateway_start] gateway ready on port=${n.port} ctx=${JSON.stringify(r)}`))}function Vt(e,t){let n=null,r=!1,i=!1,a;async function o(){if(i)return;let s=await t.getSkillScanIntervalMs();e.logger.info(x(`[skill-scan-service] next scan in ${s/1e3}s`)),n=setTimeout(async()=>{if(!i){if(!await t.isSkillDetectEnabled()){e.logger.info(x(`[skill-scan-service] periodic scan skipped: skill_detect disabled`)),await o();return}if(r){e.logger.info(x(`[skill-scan-service] periodic scan skipped: previous scan still running`)),await o();return}e.logger.info(x(`[skill-scan-service] periodic scan triggered`)),r=!0,zt(e,a).catch(t=>{e.logger.error(x(`[skill-scan-service] periodic scan failed: ${t instanceof Error?t.message:String(t)}`))}).finally(()=>{r=!1,o()})}},s),n.unref()}return{id:`openclaw-guardian-skill-scan`,async start(n){a=n.workspaceDir,e.logger.info(x(`[skill-scan-service] starting with workspaceDir=${a??`(default)`}`)),i=!1,await t.isSkillDetectEnabled()&&(e.logger.info(x(`[skill-scan-service] running initial skill scan`)),r=!0,zt(e,a).catch(t=>{e.logger.error(x(`[skill-scan-service] initial scan failed: ${t instanceof Error?t.message:String(t)}`))}).finally(()=>{r=!1})),await o()},async stop(t){i=!0,n&&=(clearTimeout(n),null),e.logger.info(x(`[skill-scan-service] stopped`))}}}function Ht(e,t){e.on(`gateway_start`,async(n,r)=>{await Bt(e,t,n,r)}),e.registerService(Vt(e,t))}const Ut=[...[`before_tool_call`,`after_tool_call`,`before_llm_fetch`,`after_llm_fetch`,`llm_input`,`llm_output`],`skill_detect`];function Wt(){return Object.fromEntries(Ut.map(e=>[e,!1]))}function Gt(e){let t=Wt(),n=e&&typeof e==`object`?e:{};for(let e of Ut)t[e]=!!n[e];return t}function Kt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):1}function qt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):600}function Jt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):900}function Yt(e){return{enabled:!1,hook_toggles:Wt(),sse_chunk_size:1,skill_scan_duration_second:900,query_duration_second:600,reason:e}}function Xt(e){let t=e&&typeof e==`object`?e:{},n=t.enabled===void 0?!0:!!t.enabled;return{enabled:n,hook_toggles:n?Gt(t.hook_toggles):Wt(),sse_chunk_size:Kt(t.sse_chunk_size),skill_scan_duration_second:Jt(t.skill_scan_duration_second),query_duration_second:qt(t.query_duration_second),reason:n?`remote`:`remote_disabled`}}function Zt(e){return st(e.config).map(e=>e.baseUrl)}async function Qt(e){let t={source:`miaoda`,base_url_list:Zt(e)};return Xt(await G(e,`runtime_config`,se(e),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)},H))}function $t(e){let t=Yt(`not_initialized`),n=!1,r=null,i=null;async function a(){let r=null;for(let i=1;i<=3;i+=1)try{let r=await Qt(e);return t=r,n=!0,e.logger.debug?.(x(`[runtime_config] initial config loaded on attempt=${i} enabled_hooks=${JSON.stringify(r.hook_toggles)}`)),t}catch(t){r=t;let n=V(t);if(e.logger.error(x(`[runtime_config] initial config load failed attempt=${i} errorCode=${n}: ${t instanceof Error?t.message:String(t)}`)),n===`SERVER`||n===`PARSE`)break}return t=Yt(`initial_fetch_failed`),e.logger.warn(x(`[runtime_config] initial config unavailable after 3 attempts; detection disabled by default${r?`: ${r instanceof Error?r.message:String(r)}`:``}`)),t}async function o(){try{let r=await Qt(e);return t=r,n=!0,e.logger.debug?.(x(`[runtime_config] config refreshed enabled_hooks=${JSON.stringify(r.hook_toggles)} sse_chunk_size=${r.sse_chunk_size}`)),t}catch(r){let i=V(r);return n?(e.logger.error(x(`[runtime_config] refresh failed (errorCode=${i}); keeping previous config: ${r instanceof Error?r.message:String(r)}`)),t):(e.logger.error(x(`[runtime_config] refresh failed before first successful load (errorCode=${i}): ${r instanceof Error?r.message:String(r)}`)),t=Yt(`refresh_failed_${i}`),t)}}function s(){r&&clearTimeout(r);let n=t.query_duration_second*1e3;e.logger.debug?.(x(`[runtime_config] next config refresh in ${t.query_duration_second}s`)),r=setTimeout(()=>{e.logger.debug?.(x(`[runtime_config] refresh loop fired`)),o().catch(t=>{e.logger.error(x(`[runtime_config] refresh loop failed: ${t instanceof Error?t.message:String(t)}`))}).finally(()=>{s()})},n),r.unref()}function c(){return i||=a().catch(n=>(e.logger.error(x(`[runtime_config] initialize failed: ${n instanceof Error?n.message:String(n)}`)),t)).finally(()=>{s()}),i}return{async isHookEnabled(e){return await c(),!!(t?.enabled&&t?.hook_toggles?.[e])},async isSkillDetectEnabled(){return await c(),!!(t?.enabled&&t?.hook_toggles?.skill_detect)},async getSseChunkSize(){return await c(),Kt(t?.sse_chunk_size)},async getSkillScanIntervalMs(){return await c(),Jt(t?.skill_scan_duration_second)*1e3}}}var en=t({id:`openclaw-guardian-plugin`,name:`OpenClaw Guardian Plugin`,description:`Reports OpenClaw hook payloads to the trust_layer detect service with remote hook toggles.`,register(e){if(!N(e)){e.logger.debug?.(x(`[plugin] missing Feishu appId/appSecret from api.config.channels.feishu or pluginConfig; skip all hooks and reporting`));return}let t=$t(e);kt(e,t),at(e,t),Ht(e,t)}});export{en as default};
5
+ `),n=4),e<0)break;t.push(this.buffer.slice(0,e)),this.buffer=this.buffer.slice(e+n)}return t}clear(){this.buffer=``}flushRemainder(){if(!this.buffer)return null;let e=this.buffer;return this.buffer=``,e}};function Ti(e){return e.effect===`DENY`?e.denyOutput||null:e.effect===`REWRITE`&&e.rewriteOutput||null}function Ei(e,t,n){let r=Ti(e)??``,i=new Headers;if(i.set(`content-type`,t?`text/event-stream; charset=utf-8`:`application/json; charset=utf-8`),!t)return new Response(r,{status:200,statusText:`OK`,headers:i});let a=new TextEncoder;Ci(r);let o=new ReadableStream({async start(t){try{await Di(t,e,a)}finally{try{t.close()}catch{}n?.()}}});return new Response(o,{status:200,statusText:`OK`,headers:i})}async function Di(e,t,n=new TextEncoder){let r=Ci(t.effect===`DENY`?t.denyOutput:t.rewriteOutput);for(let t=0;t<r.length;t+=1){let i=r[t];e.enqueue(n.encode(i)),t===0&&r.length>1&&await Oi()}}function Oi(){return new Promise(e=>{let t=setTimeout(e,0);typeof t.unref==`function`&&t.unref()})}function ki(e){let t=e.split(`
6
+ `),n=[];for(let e of t)if(e.startsWith(`data:`)){let t=e.slice(5).trim();t&&t!==`[DONE]`&&n.push(t)}if(n.length===0)return 0;let r=n.join(`
7
+ `);try{let e=JSON.parse(r),t=Array.isArray(e?.choices)?e.choices:[],n=0;for(let e of t){let t=e?.delta?.content;typeof t==`string`&&(n+=t.length)}return n}catch{}return 0}function Ai(e,t,n,r){let i=null,a=[],o=!1;function s(){if(i&&=(clearTimeout(i),null),a.length===0)return;let e=a;a=[];for(let n of e)t.originalOutputBytes+=ki(n)}function c(){i||(i=setTimeout(()=>{i=null,s()},0),typeof i.unref==`function`&&i.unref())}function l(e){e.length!==0&&(t.originalOutputChunks+=e.length,t.hasOriginalOutput=!0,a.push(...e),c())}function u(i){o||(o=!0,t.flushPendingOutputStats(),Yt(e,{requestId:n,needBlock:i,outTokenCnt:t.originalOutputBytes,detectDurationMs:Math.max(0,Date.now()-r)}).catch(t=>{e.logger.error(M(`[llm_fetch] stream_tracking_failed request_id=${n} error=${t instanceof Error?t.message:String(t)}`))}))}return{flush:s,recordOutputEvents:l,reportOnce:u}}function ji(e){return(e.headers.get(`content-type`)??``).includes(`text/event-stream`)}function Mi(e,t,n){n.then(async e=>{try{await e.body?.cancel()}catch{}}).catch(e=>{})}async function Ni(e,t){let n=e.read().then(e=>({value:e.value,done:e.done,takeover:!1})),r=t.then(()=>({value:void 0,done:!1,takeover:!0}));return Promise.race([n,r])}async function Pi(e,t,n,r,i,a,o){let s=r.body;if(!s)return r;let c=s.getReader(),l=new TextDecoder,u=new TextEncoder,d=new wi,f=await a.isHookEnabled(`after_llm_fetch_v2`),p=await a.isLlmRespSyncDetectEnabled(),m=Math.max(1,Number(await a.getSseChunkSize())||1),h=Ai(e,i,n,o),g=!1,_=!1;i.cancelReader=()=>{try{c.cancel()}catch{}},i.flushPendingOutputStats=h.flush;async function ee(e){i.decision&&(await Di(e,i.decision,u),g=!0,e.close())}async function v(t){if(!(_||g||!i.decision)){_=!0,y.clear(),await ee(t),h.reportOnce(!0);try{await c.cancel()}catch{}e.logger.info(M(`[llm_fetch] total_elapsed=${Date.now()-o}ms request_id=${n}`))}}async function te(t,r){if(i.decision=r,i.flushPendingOutputStats(),Z(i,`taken_over`)){if(i.stopPolling(),i.cancelReader)try{i.cancelReader()}catch{}e.logger.info(M(`[after_llm_fetch_v2] takeover request_id=${n} effect=${r.effect} original_chunks=${i.originalOutputChunks} original_bytes=${i.originalOutputBytes}`))}return g?(e.logger.info(M(`[after_llm_fetch_v2] async_decision_ignored request_id=${n} effect=${r.effect} is_sse=true reason=stream_closed`)),!1):(await v(t),!0)}let y=new xi({api:e,session:i,url:t,requestId:n,totalStartMs:o,afterDetectEnabled:f,respSyncDetectEnabled:p,encoder:u,statsTracker:h,applyDecision:te}),b=new ReadableStream({async start(t){try{for(;;){if(i.state===`taken_over`&&i.decision){await v(t);return}let e=await Ni(c,i.takeoverPromise);if(e.takeover&&i.state===`taken_over`&&i.decision||i.state===`taken_over`&&i.decision){await v(t);return}if(e.done)break;let n=e.value,r=l.decode(n,{stream:!0});for(let e of d.push(r)){if(i.state===`taken_over`&&i.decision){d.clear(),await v(t);return}if(y.addEvent(e),y.hasReachedChunkSize(m)&&await y.flushDetectedBatch(t))return;Z(i,`outputting`)}}let r=d.flushRemainder();if(r&&y.addRawRemainder(r),await y.flushDetectedBatch(t))return;!i.decision&&i.state!==`failed_open`&&i.state!==`taken_over`&&i.state!==`completed`&&e.logger.info(M(`[before_llm_fetch] async_detect_stopped_on_sse_end request_id=${n} state=${i.state} original_chunks=${i.originalOutputChunks} original_bytes=${i.originalOutputBytes}`)),Z(i,`completed`)&&i.stopPolling(),g=!0,t.close(),h.reportOnce(!1),e.logger.info(M(`[llm_fetch] total_elapsed=${Date.now()-o}ms request_id=${n}`))}catch(e){if(i.state===`taken_over`&&i.decision){await v(t);return}i.state!==`taken_over`&&(Z(i,`completed`),i.stopPolling()),h.reportOnce(!1);try{await c.cancel()}catch{}g=!0,t.error(e)}}}),x=new Headers(r.headers);return x.delete(`content-length`),x.set(`content-type`,`text/event-stream; charset=utf-8`),new Response(b,{status:r.status,statusText:r.statusText,headers:x})}function Fi(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function Ii(e){return!!(e&&typeof e==`object`&&e.stream===!0)}function Li(e){return e.effect===`DENY`?e.denyOutput||null:e.effect===`REWRITE`&&e.rewriteOutput||null}function Ri(e,t,n){let r=ci(e.config),i=N(),a=n&&!i?li(n,r):null;return!n||i?null:a}async function zi(e){let{api:t,configStore:n,hookName:r,url:i,rawBody:a,jsonBody:o}=e;if(N()||!await n.isNetworkHookEnabled()||!(e.provider===void 0?Ri(t,r,i):e.provider)||!wr(o))return null;let s=Date.now(),c=Fi(),l=Ii(o),u=yi(c),d=null,f=null,p=await n.isHookEnabled(`before_llm_fetch`),m=p&&await n.isLlmReqSyncDetectEnabled(),h=p&&await n.isLlmReqAsyncDetectEnabled(),g=K(`before_llm_fetch`,null,null,{request_id:c,url:i,rawBody:a??``,jsonBody:o,llmReqDetectType:m?`sync`:`async`});if(p&&(d=V(t,`before_llm_fetch`,g)),m&&d)try{let e=await Ui(d,await n.getLlmReqSyncDetectTimeoutMs());if(`value`in e){let n=Q(e.value);$(n)&&(f=Li(n),t.logger.info(M(`[before_llm_fetch] request_body_rewritten request_id=${c} hook=${r} effect=${n.effect} body_bytes=${Buffer.byteLength(f??``)}`)))}}catch(e){t.logger.error(M(`[before_llm_fetch] sync_detect_failed request_id=${c} hook=${r} error=${e instanceof Error?e.message:String(e)}`))}return h?u=vi(t,c,g,{initialDetectPromise:d??void 0,pollIntervalMs:await n.getLlmAsyncDetectLoopQueryMs(),detectStartTimeMs:s}):d&&d.catch(e=>{t.logger.error(M(`[before_llm_fetch] detect_failed request_id=${c} hook=${r} error=${e instanceof Error?e.message:String(e)}`))}),{requestId:c,totalStartMs:s,requestIsSse:l,session:u,asyncDetectEnabled:h,beforeRequestBodyOverride:f}}async function Bi(e,t,n,r,i,a){if(!await t.isHookEnabled(`after_llm_fetch_v2`))return i;let o=``;try{o=await i.clone().text()}catch(t){return e.logger.warn(M(`[after_llm_fetch_v2] non_sse_response_clone_failed request_id=${n} error=${t instanceof Error?t.message:String(t)}`)),i}let s=K(`after_llm_fetch_v2`,null,null,{request_id:n,url:r,isSse:!1,llm_detect_time_ms:a,chunks:[],originResp:o});if(!await t.isLlmRespSyncDetectEnabled())return V(e,`after_llm_fetch_v2`,s).then(t=>{let r=Q(t);$(r)&&e.logger.info(M(`[after_llm_fetch_v2] async_decision_ignored request_id=${n} effect=${r.effect} is_sse=false`))}).catch(t=>{e.logger.error(M(`[after_llm_fetch_v2] detect failed request_id=${n} error=${t instanceof Error?t.message:String(t)}`))}),i;try{let t=Q(await V(e,`after_llm_fetch_v2`,s));return $(t)?(e.logger.info(M(`[after_llm_fetch_v2] takeover request_id=${n} effect=${t.effect} is_sse=false`)),Ei(t,!1)):i}catch(t){return e.logger.error(M(`[after_llm_fetch_v2] detect failed request_id=${n} error=${t instanceof Error?t.message:String(t)}`)),i}}async function Vi(e,t,n,r,i){let{requestId:a,totalStartMs:o,requestIsSse:s,session:c}=i;if(N()||!await t.isNetworkHookEnabled())return c.cleanup(),r;if(c.state===`taken_over`&&c.decision)return Mi(e,a,Promise.resolve(r)),c.cleanup(),Ei(c.decision,ji(r)||s);if(!ji(r)){Z(c,`completed`)&&c.stopPolling();let i=await Bi(e,t,a,n,r,o);return e.logger.info(M(`[llm_fetch] total_elapsed=${Date.now()-o}ms request_id=${a}`)),i}return Z(c,`response_ready`),Pi(e,n,a,r,c,t,o)}async function Hi(e){let{api:t,configStore:n,hookName:r,url:i,rawBody:a,jsonBody:o,provider:s,executeOriginal:c}=e;if(N()||!await n.isNetworkHookEnabled())return c(null);let l=await zi({api:t,configStore:n,hookName:r,url:i,rawBody:a,jsonBody:o,provider:s});if(!l)return c(null);let u;try{let e=c(l.beforeRequestBodyOverride);if(l.asyncDetectEnabled){let n=await Promise.race([e.then(e=>({type:`response`,response:e})),l.session.takeoverPromise.then(()=>({type:`takeover`}))]);if(n.type===`takeover`&&l.session.state===`taken_over`&&l.session.decision)return Mi(t,l.requestId,e),t.logger.info(M(`[before_llm_fetch] takeover request_id=${l.requestId} hook=${r} phase=before_response effect=${l.session.decision.effect} original_chunks=${l.session.originalOutputChunks} original_bytes=${l.session.originalOutputBytes}`)),t.logger.info(M(`[llm_fetch] total_elapsed=${Date.now()-l.totalStartMs}ms request_id=${l.requestId}`)),Ei(l.session.decision,l.requestIsSse);if(n.type!==`response`)throw Error(`unexpected before_llm_fetch takeover state`);u=n.response}else u=await e}catch(e){if(l.session.state===`taken_over`&&l.session.decision)return l.session.cleanup(),Ei(l.session.decision,l.requestIsSse);throw l.session.cleanup(),e}return Vi(t,n,i,u,l)}async function Ui(e,t){let n=typeof t==`number`&&Number.isFinite(t)&&t>0?Math.floor(t):R,r=null;try{return await Promise.race([e.then(e=>({timedOut:!1,value:e})),new Promise(e=>{r=setTimeout(()=>e({timedOut:!0}),n),typeof r.unref==`function`&&r.unref()})])}finally{r&&clearTimeout(r)}}function Wi(e){let t=new Headers;for(let[n,r]of Object.entries(e.headers))r!==void 0&&t.set(n,Array.isArray(r)?r.join(`, `):r);return new Response(w.toWeb(e),{status:e.statusCode??200,statusText:e.statusMessage??`OK`,headers:t})}function Gi(e,t,n){let r=new ae;return r.statusCode=n.status,r.statusMessage=n.statusText,r.headers=Object.fromEntries(n.headers.entries()),r.rawHeaders=Array.from(n.headers.entries()).flatMap(([e,t])=>[e,t]),r.httpVersion=`1.1`,r.httpVersionMajor=1,r.httpVersionMinor=1,process.nextTick(()=>{t.call(e,`response`,r);let i=n.body?w.fromWeb(n.body):w.from([]);i.on(`error`,e=>r.destroy(e)),i.pipe(r)}),!0}function Ki(){return{aborted:!1,paused:!1,reason:null,abort(){},pause(){},resume(){}}}function qi(e){let t=new Headers;for(let[n,r]of Object.entries(e))r!==void 0&&t.set(n,Array.isArray(r)?r.join(`, `):r);return t}function Ji(e,t,n,r){return new Response(r,{status:e,statusText:t??`OK`,headers:qi(n)})}async function Yi(e,t){let n=Ki();e.onResponseStart?.(n,t.status,Object.fromEntries(t.headers.entries()),t.statusText);let r=t.body?Buffer.from(await t.arrayBuffer()):Buffer.alloc(0);r.length>0&&e.onResponseData?.(n,r),e.onResponseEnd?.(n,{})}async function Xi(e,t){let n=Ki();if(e.onResponseStart?.(n,t.status,Object.fromEntries(t.headers.entries()),t.statusText),!t.body){e.onResponseEnd?.(n,{});return}let r=t.body.getReader();try{for(;;){let{value:t,done:i}=await r.read();if(i)break;t&&t.length>0&&e.onResponseData?.(n,Buffer.from(t))}e.onResponseEnd?.(n,{})}catch(t){e.onResponseError?.(n,t instanceof Error?t:Error(String(t)))}finally{try{r.releaseLock()}catch{}}}function Zi(e,t){try{e.setHeader(`content-length`,String(Buffer.byteLength(t)))}catch{}}async function Qi(e){let{api:t,configStore:n,url:r,context:i,req:a,originalEmit:o,incoming:s}=e;if(!i){o.call(a,`response`,s);return}try{Gi(a,o,await Vi(t,n,r,Wi(s),i))}catch(e){t.logger.error(M(`[llm_fetch] node_response_process_failed request_id=${i.requestId} hook_error=${e instanceof Error?e.message:String(e)}`)),o.call(a,`response`,s)}}function $i(e,t,n){if(n.getOriginalRequest())return;n.setOriginalRequest(n.module.request),n.setOriginalGet(n.module.get);let r=((...r)=>{if(N()||!t.isNetworkHookEnabledSnapshot())return n.getOriginalRequest()(...r);let i=qr(r,n.defaultProtocol),a=Ri(e,n.hookName,i);if(br(e,t,i,n.hookName),n.hookName,Lr(r,`request`),!a)return n.getOriginalRequest()(...r);let o=n.getOriginalRequest()(...r),s=o.write.bind(o),c=o.end.bind(o),l=o.emit.bind(o),u=[],d=``,f=null,p=!1;return o.emit=((n,...r)=>{if(n!==`response`)return l(n,...r);let a=r[0];return a instanceof S.IncomingMessage?(Qi({api:e,configStore:t,url:i,context:f,req:o,originalEmit:l,incoming:a}),!0):l(n,...r)}),o.write=((e,t,n)=>(d+=Qr(e,typeof t==`string`?t:void 0),u.push([e,t,n]),!0)),o.end=((r,l,m)=>p?o:(p=!0,r!=null&&typeof r!=`function`&&(d+=Qr(r,typeof l==`string`?l:void 0)),(async()=>{if(f=await zi({api:e,configStore:t,hookName:n.hookName,url:i,rawBody:d,jsonBody:Zr(d),provider:a}),f?.beforeRequestBodyOverride!=null){Zi(o,f.beforeRequestBodyOverride),c(f.beforeRequestBodyOverride,typeof l==`string`?l:void 0,typeof l==`function`?l:m);return}for(let e of u)s(...e);c(r,l,m)})().catch(t=>{e.logger.error(M(`[llm_fetch] node_request_detect_failed hook=${n.hookName} error=${t instanceof Error?t.message:String(t)}`));for(let e of u)s(...e);c(r,l,m)}),o)),o}),i=((...e)=>{let t=r(...e);return t.end(),t});n.module.request=r,n.module.get=i}function ea(e,t){$i(e,t,{hookName:`http_hook`,defaultProtocol:`http:`,module:S,getOriginalRequest:()=>globalThis.__openclawGuardianOriginalHttpRequest,setOriginalRequest:e=>{globalThis.__openclawGuardianOriginalHttpRequest=e},getOriginalGet:()=>globalThis.__openclawGuardianOriginalHttpGet,setOriginalGet:e=>{globalThis.__openclawGuardianOriginalHttpGet=e}})}function ta(e,t){$i(e,t,{hookName:`https_hook`,defaultProtocol:`https:`,module:re,getOriginalRequest:()=>globalThis.__openclawGuardianOriginalHttpsRequest,setOriginalRequest:e=>{globalThis.__openclawGuardianOriginalHttpsRequest=e},getOriginalGet:()=>globalThis.__openclawGuardianOriginalHttpsGet,setOriginalGet:e=>{globalThis.__openclawGuardianOriginalHttpsGet=e}})}const na=new C;function ra(e,t,n,r){if(na.getStore()||N()||!r.isNetworkHookEnabledSnapshot())return;let i=e?.request;i&&(br(n,r,t,`undici_diagnostic`),Rr(i))}function ia(e,t){if(globalThis.__openclawGuardianUndiciDiagnosticInterceptorInstalled){e.logger.info(M(`[${J}] undici_diagnostic_interceptor already_installed`));return}globalThis.__openclawGuardianUndiciDiagnosticInterceptorInstalled=!0,E(`undici:request:create`).subscribe(n=>{let r=Tr(n);N()||t.isNetworkHookEnabledSnapshot()&&ra(n,r,e,t)}),e.logger.info(M(`[${J}] undici_diagnostic_interceptor installed`))}function aa(e){let{api:t,configStore:n,url:r,getContext:i,handler:a,onComplete:o,loadContextImmediately:s=!0}=e,c=null,l=null,u=!1,d=!1,f=null;function p(){d||(d=!0,o?.())}async function m(e){d||!e.session.decision||(e.session.cleanup(),await Yi(a,Ei(e.session.decision,e.requestIsSse)),p())}function h(){return f||=i().then(e=>(e&&e.session.takeoverPromise.then(()=>{!u&&e.session.state===`taken_over`&&e.session.decision&&m(e)}),e)),f}s&&h();async function g(e,i,o,s){try{let c=await h();if(d)return;let l=Ji(e,i,o,s);if(!c){await Xi(a,l),p();return}let u=await Vi(t,n,r,l,c);d||(await Xi(a,u),p())}catch(e){d||(a.onResponseError?.(Ki(),e instanceof Error?e:Error(String(e))),p())}}return{onRequestStart:(...e)=>a.onRequestStart?.(...e),onRequestUpgrade:(...e)=>a.onRequestUpgrade?.(...e),onResponseStarted:(...e)=>a.onResponseStarted?.(...e),onBodySent:(...e)=>a.onBodySent?.(...e),onRequestSent:(...e)=>a.onRequestSent?.(...e),onResponseStart(e,t,n,r){if(d){e.abort(Error(`openclaw_guardian_undici_response_completed`));return}u=!0,l=e,g(t,r,n,new ReadableStream({start(e){c=e},cancel(){try{l?.abort(Error(`openclaw_guardian_undici_stream_cancelled`))}catch{}}}))},onResponseData(e,t){if(!(d||!c))try{c.enqueue(Buffer.from(t))}catch{}},onResponseEnd(){if(!d)try{c?.close()}catch{}},onResponseError(e,t){if(!d){if(!c){a.onResponseError?.(e,t),p();return}try{c.error(t)}catch{a.onResponseError?.(e,t),p()}}}}}function oa(e){let{api:t,configStore:n,url:r,context:i,handler:a}=e;return i?aa({api:t,configStore:n,url:r,getContext:()=>Promise.resolve(i),handler:a}):a}async function sa(e){let{api:t,configStore:n,url:r,dispatchOptions:i,handler:a,dispatchOriginal:o}=e;if(N()){o(i,a);return}if(!await n.isNetworkHookEnabled()){o(i,a);return}let s=Ri(t,`undici_hook`,r);if(!s){o(i,a);return}let c=Vr(i.body),l=i;if(c===null&&Wr(i.body)){let e=await Kr(i.body);c=e.rawBody,l={...i,body:e.body}}let u=await zi({api:t,configStore:n,hookName:`undici_hook`,url:r,rawBody:c,jsonBody:Zr(c),provider:s});o(u?.beforeRequestBodyOverride==null?l:Xr(l,u.beforeRequestBodyOverride),oa({api:t,configStore:n,url:r,context:u,handler:a}))}const ca=new C,la=new C,ua=new WeakMap;function da(e){for(let t of Object.getOwnPropertySymbols(e))if(String(t)===`Symbol(url)`)return Y(e[t]);return``}function fa(e,t){let n=da(e);return zr(n?{...t,origin:n}:t)}function pa(e,t,n){let r=ua.get(e);if(r)return r;let i=new Proxy(e,{get(e,t,r){if(t===`dispatch`)return(t,r)=>(N()||!n.isNetworkHookEnabledSnapshot()||fa(e,t),e.dispatch(t,r));let i=Reflect.get(e,t,r);return typeof i==`function`?i.bind(e):i}});return ua.set(e,i),i}function ma(e,t,n){let r=e.prototype.dispatch;e.prototype.dispatch=function(e,i){if(la.getStore()||N()||!n.isNetworkHookEnabledSnapshot())return r.call(this,e,i);let a=fa(this,e);return Br(e),sa({api:t,configStore:n,url:a,dispatchOptions:e,handler:i,dispatchOriginal:(e,t)=>na.run(!0,()=>r.call(this,e,t))}).catch(e=>{i.onResponseError?.(Ki(),e instanceof Error?e:Error(String(e)))}),!0}}function ha(e,t){if(globalThis.__openclawGuardianUndiciPrototypeBlockingInstalled){e.logger.info(M(`[${J}] undici_prototype_interceptor already_installed`));return}globalThis.__openclawGuardianUndiciPrototypeBlockingInstalled=!0,[ce,de,se,pe,oe,fe,ue,T].forEach(n=>ma(n,e,t)),e.logger.info(M(`[${J}] undici_prototype_interceptor installed`))}var ga=class extends le{inner;api;configStore;constructor(e,t,n){super(),this.inner=e,this.api=t,this.configStore=n}dispatch(e,t){let n=zr(e);return ca.getStore()||N()||!this.configStore.isNetworkHookEnabledSnapshot()?na.run(!0,()=>la.run(!0,()=>this.inner.dispatch(e,t))):(this.api,Br(e),sa({api:this.api,configStore:this.configStore,url:n,dispatchOptions:e,handler:t,dispatchOriginal:(e,t)=>na.run(!0,()=>la.run(!0,()=>this.inner.dispatch(e,t)))}).catch(e=>{t.onResponseError?.(Ki(),e instanceof Error?e:Error(String(e)))}),!0)}close(e){return e?this.inner.close(e):this.inner.close()}destroy(e,t){return typeof e==`function`?this.inner.destroy(e):t?this.inner.destroy(e??null,t):e?this.inner.destroy(e):this.inner.destroy()}};function _a(e,t){ha(e,t),ia(e,t),!globalThis.__openclawGuardianUndiciRequestLoggerInstalled&&(globalThis.__openclawGuardianUndiciRequestLoggerInstalled=!0,he(new ga(me(),e,t)),e.logger.info(M(`[${J}] undici_dispatcher installed`)))}const va=t(import.meta.url)(`undici`);function ya(e){return typeof e==`object`&&!!e&&typeof e.dispatch==`function`}function ba(e,t,n){if(typeof e.fetch!=`function`||e.fetch.__openclawGuardianPatched)return;globalThis.__openclawGuardianOriginalUndiciFetch||(globalThis.__openclawGuardianOriginalUndiciFetch=e.fetch);let r=e.fetch.bind(e),i=(async(e,i)=>{if(N()||!n.isNetworkHookEnabledSnapshot())return r(e,i);let a=i,o=Er(e);Nr(e,i);let s=Ri(t,`undici_fetch_hook`,o),c=i=>{let o=Yr(e,ya(a?.dispatcher)?{...a,dispatcher:pa(a.dispatcher,t,n)}:a,i);return ca.run(!0,()=>r(...o))};if(!s)return c(null);let{rawBody:l,jsonBody:u}=await Pr(e,i);return Hi({api:t,configStore:n,hookName:`undici_fetch_hook`,url:o,rawBody:l,jsonBody:u,provider:s,executeOriginal:c})});i.__openclawGuardianPatched=!0,e.fetch=i}function xa(e,t){if(va.fetch.__openclawGuardianPatched){e.logger.info(M(`[${J}] undici_fetch_interceptor already_installed`));return}ba(va,e,t),e.logger.info(M(`[${J}] undici_fetch_interceptor installed`))}function Sa(t,n){if(globalThis.__openclawGuardianOriginalModuleLoad){t.logger.info(M(`[${J}] undici_module_load_hook already_installed`));return}let r=e,i=r._load;globalThis.__openclawGuardianOriginalModuleLoad=i,r._load=function(e,r,a){let o=i.call(this,e,r,a);return e===`undici`&&o&&typeof o==`object`&&ba(o,t,n),o},t.logger.info(M(`[${J}] undici_module_load_hook installed`))}function Ca(e,t){_a(e,t),ea(e,t),ta(e,t),ai(e,t),xa(e,t),Sa(e,t)}var wa=ge(((e,t)=>{function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}let r=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function i(e){if(Buffer.isBuffer(e))return e;if(typeof e==`number`)return Buffer.alloc(e);if(typeof e==`string`)return Buffer.from(e);throw Error(`input must be buffer, number, or string, received `+typeof e)}function a(e){let t=i(4);return t.writeInt32BE(e,0),t}function o(e,t){e=i(e),Buffer.isBuffer(t)&&(t=t.readUInt32BE(0));let n=~~t^-1;for(var a=0;a<e.length;a++)n=r[(n^e[a])&255]^n>>>8;return n^-1}function s(){return a(o.apply(null,arguments))}s.signed=function(){return o.apply(null,arguments)},s.unsigned=function(){return o.apply(null,arguments)>>>0},t.exports=n(s)})),Ta=ge((e=>{var t=D(`fs`),n=D(`stream`).Transform,r=D(`stream`).PassThrough,i=D(`zlib`),a=D(`util`),o=D(`events`).EventEmitter,s=D(`events`).errorMonitor,c=wa();e.ZipFile=l,a.inherits(l,o);function l(){this.outputStream=new r,this.entries=[],this.outputStreamCursor=0,this.ended=!1,this.allDone=!1,this.forceZip64Eocd=!1,this.errored=!1,this.on(s,function(){this.errored=!0})}l.prototype.addFile=function(e,n,r){var i=this;if(n=y(n,!1),r??={},!g(i)){var a=new x(n,!1,r);i.entries.push(a),t.stat(e,function(n,o){if(n)return i.emit(`error`,n);if(!o.isFile())return i.emit(`error`,Error(`not a file: `+e));a.uncompressedSize=o.size,r.mtime??a.setLastModDate(o.mtime),r.mode??a.setFileAttributesMode(o.mode),a.setFileDataPumpFunction(function(){var n=t.createReadStream(e);a.state=x.FILE_DATA_IN_PROGRESS,n.on(`error`,function(e){i.emit(`error`,e)}),f(i,a,n)}),m(i)})}},l.prototype.addReadStream=function(e,t,n){this.addReadStreamLazy(t,n,function(t){t(null,e)})},l.prototype.addReadStreamLazy=function(e,t,n){var r=this;if(typeof t==`function`&&(n=t,t=null),t??={},e=y(e,!1),!g(r)){var i=new x(e,!1,t);r.entries.push(i),i.setFileDataPumpFunction(function(){i.state=x.FILE_DATA_IN_PROGRESS,n(function(e,t){if(e)return r.emit(`error`,e);f(r,i,t)})}),m(r)}},l.prototype.addBuffer=function(e,t,n){var r=this;if(t=y(t,!1),e.length>1073741823)throw Error(`buffer too large: `+e.length+` > 1073741823`);if(n??={},n.size!=null)throw Error(`options.size not allowed`);if(g(r))return;var a=new x(t,!1,n);a.uncompressedSize=e.length,a.crc32=c.unsigned(e),a.crcAndFileSizeKnown=!0,r.entries.push(a),a.compressionLevel===0?o(e):i.deflateRaw(e,{level:a.compressionLevel},function(e,t){o(t)});function o(e){a.compressedSize=e.length,a.setFileDataPumpFunction(function(){d(r,e),d(r,a.getDataDescriptor()),a.state=x.FILE_DATA_DONE,setImmediate(function(){m(r)})}),m(r)}},l.prototype.addEmptyDirectory=function(e,t){var n=this;if(e=y(e,!0),t??={},t.size!=null)throw Error(`options.size not allowed`);if(t.compress!=null)throw Error(`options.compress not allowed`);if(t.compressionLevel!=null)throw Error(`options.compressionLevel not allowed`);if(!g(n)){var r=new x(e,!0,t);n.entries.push(r),r.setFileDataPumpFunction(function(){d(n,r.getDataDescriptor()),r.state=x.FILE_DATA_DONE,m(n)}),m(n)}};var u=k([80,75,5,6]);l.prototype.end=function(e,t){if(typeof e==`function`&&(t=e,e=null),e??={},!this.ended&&(this.ended=!0,!this.errored)){if(this.calculatedTotalSizeCallback=t,this.forceZip64Eocd=!!e.forceZip64Format,e.comment){if(typeof e.comment==`string`?this.comment=ge(e.comment):this.comment=e.comment,this.comment.length>65535)throw Error(`comment is too large`);if(A(this.comment,u))throw Error(`comment contains end of central directory record signature`)}else this.comment=b;m(this)}};function d(e,t){e.outputStream.write(t),e.outputStreamCursor+=t.length}function f(e,t,n){var a=new me,o=new pe,s=t.compressionLevel===0?new r:new i.DeflateRaw({level:t.compressionLevel}),c=new pe;n.pipe(a).pipe(o).pipe(s).pipe(c).pipe(e.outputStream,{end:!1}),c.on(`end`,function(){if(t.crc32=a.crc32,t.uncompressedSize==null)t.uncompressedSize=o.byteCount;else if(t.uncompressedSize!==o.byteCount)return e.emit(`error`,Error(`file data stream has unexpected number of bytes`));t.compressedSize=c.byteCount,e.outputStreamCursor+=t.compressedSize,d(e,t.getDataDescriptor()),t.state=x.FILE_DATA_DONE,m(e)})}function p(e){if(e.compress!=null&&e.compressionLevel!=null&&!!e.compress!=!!e.compressionLevel)throw Error(`conflicting settings for compress and compressionLevel`);return e.compressionLevel==null?e.compress===!1?0:6:e.compressionLevel}function m(e){if(e.allDone||e.errored)return;if(e.ended&&e.calculatedTotalSizeCallback!=null){var t=h(e);t!=null&&(e.calculatedTotalSizeCallback(t),e.calculatedTotalSizeCallback=null)}var n=r();function r(){for(var t=0;t<e.entries.length;t++){var n=e.entries[t];if(n.state<x.FILE_DATA_DONE)return n}return null}if(n!=null){if(n.state<x.READY_TO_PUMP_FILE_DATA||n.state===x.FILE_DATA_IN_PROGRESS)return;n.relativeOffsetOfLocalHeader=e.outputStreamCursor,d(e,n.getLocalFileHeader()),n.doFileDataPump()}else e.ended&&(e.offsetOfStartOfCentralDirectory=e.outputStreamCursor,e.entries.forEach(function(t){d(e,t.getCentralDirectoryRecord())}),d(e,te(e)),e.outputStream.end(),e.allDone=!0)}function h(e){for(var t=0,n=0,r=0;r<e.entries.length;r++){var i=e.entries[r];if(i.compressionLevel!==0)return-1;if(i.state>=x.READY_TO_PUMP_FILE_DATA){if(i.uncompressedSize==null)return-1}else if(i.uncompressedSize==null)return null;i.relativeOffsetOfLocalHeader=t;var a=i.useZip64Format();t+=ne+i.utf8FileName.length,t+=i.uncompressedSize,i.crcAndFileSizeKnown||(a?t+=oe:t+=w),n+=se+i.utf8FileName.length+i.fileComment.length,i.forceDosTimestamp||(n+=ce),a&&(n+=le)}var o=0;return(e.forceZip64Eocd||e.entries.length>=65535||n>=65535||t>=4294967295)&&(o+=_+ee),o+=v+e.comment.length,t+n+o}function g(e){if(e.ended)throw Error(`cannot add entries after calling end()`);return!!e.errored}var _=56,ee=20,v=22;function te(e,t){var n=!1,r=e.entries.length;(e.forceZip64Eocd||e.entries.length>=65535)&&(r=65535,n=!0);var i=e.outputStreamCursor-e.offsetOfStartOfCentralDirectory,a=i;(e.forceZip64Eocd||i>=4294967295)&&(a=4294967295,n=!0);var o=e.offsetOfStartOfCentralDirectory;if((e.forceZip64Eocd||e.offsetOfStartOfCentralDirectory>=4294967295)&&(o=4294967295,n=!0),t)return n?_+ee+v:v;var s=O(v+e.comment.length);if(s.writeUInt32LE(101010256,0),s.writeUInt16LE(0,4),s.writeUInt16LE(0,6),s.writeUInt16LE(r,8),s.writeUInt16LE(r,10),s.writeUInt32LE(a,12),s.writeUInt32LE(o,16),s.writeUInt16LE(e.comment.length,20),e.comment.copy(s,22),!n)return s;var c=O(_);c.writeUInt32LE(101075792,0),T(c,_-12,4),c.writeUInt16LE(re,12),c.writeUInt16LE(C,14),c.writeUInt32LE(0,16),c.writeUInt32LE(0,20),T(c,e.entries.length,24),T(c,e.entries.length,32),T(c,i,40),T(c,e.offsetOfStartOfCentralDirectory,48);var l=O(ee);return l.writeUInt32LE(117853008,0),l.writeUInt32LE(0,4),T(l,e.outputStreamCursor,8),l.writeUInt32LE(1,16),Buffer.concat([c,l,s])}function y(e,t){if(e===``)throw Error(`empty metadataPath`);if(e=e.replace(/\\/g,`/`),/^[a-zA-Z]:/.test(e)||/^\//.test(e))throw Error(`absolute path: `+e);if(e.split(`/`).indexOf(`..`)!==-1)throw Error(`invalid relative path: `+e);var n=/\/$/.test(e);if(t)n||(e+=`/`);else if(n)throw Error(`file path cannot end with '/': `+e);return e}var b=O(0);function x(e,t,n){if(this.utf8FileName=k(e),this.utf8FileName.length>65535)throw Error(`utf8 file name too long. `+utf8FileName.length+` > 65535`);if(this.isDirectory=t,this.state=x.WAITING_FOR_METADATA,this.setLastModDate(n.mtime==null?new Date:n.mtime),this.forceDosTimestamp=!!n.forceDosTimestamp,n.mode==null?this.setFileAttributesMode(t?16893:33204):this.setFileAttributesMode(n.mode),t?(this.crcAndFileSizeKnown=!0,this.crc32=0,this.uncompressedSize=0,this.compressedSize=0):(this.crcAndFileSizeKnown=!1,this.crc32=null,this.uncompressedSize=null,this.compressedSize=null,n.size!=null&&(this.uncompressedSize=n.size)),t?this.compressionLevel=0:this.compressionLevel=p(n),this.forceZip64Format=!!n.forceZip64Format,n.fileComment){if(typeof n.fileComment==`string`?this.fileComment=k(n.fileComment,`utf-8`):this.fileComment=n.fileComment,this.fileComment.length>65535)throw Error(`fileComment is too large`)}else this.fileComment=b}x.WAITING_FOR_METADATA=0,x.READY_TO_PUMP_FILE_DATA=1,x.FILE_DATA_IN_PROGRESS=2,x.FILE_DATA_DONE=3,x.prototype.setLastModDate=function(e){this.mtime=e;var t=fe(e);this.lastModFileTime=t.time,this.lastModFileDate=t.date},x.prototype.setFileAttributesMode=function(e){if((e&65535)!==e)throw Error(`invalid mode. expected: 0 <= `+e+` <= 65535`);this.externalFileAttributes=e<<16>>>0},x.prototype.setFileDataPumpFunction=function(e){this.doFileDataPump=e,this.state=x.READY_TO_PUMP_FILE_DATA},x.prototype.useZip64Format=function(){return this.forceZip64Format||this.uncompressedSize!=null&&this.uncompressedSize>4294967294||this.compressedSize!=null&&this.compressedSize>4294967294||this.relativeOffsetOfLocalHeader!=null&&this.relativeOffsetOfLocalHeader>4294967294};var ne=30,S=20,C=45,re=831,ie=2048,ae=8;x.prototype.getLocalFileHeader=function(){var e=0,t=0,n=0;this.crcAndFileSizeKnown&&(e=this.crc32,t=this.compressedSize,n=this.uncompressedSize);var r=O(ne),i=ie;return this.crcAndFileSizeKnown||(i|=ae),r.writeUInt32LE(67324752,0),r.writeUInt16LE(S,4),r.writeUInt16LE(i,6),r.writeUInt16LE(this.getCompressionMethod(),8),r.writeUInt16LE(this.lastModFileTime,10),r.writeUInt16LE(this.lastModFileDate,12),r.writeUInt32LE(e,14),r.writeUInt32LE(t,18),r.writeUInt32LE(n,22),r.writeUInt16LE(this.utf8FileName.length,26),r.writeUInt16LE(0,28),Buffer.concat([r,this.utf8FileName])};var w=16,oe=24;x.prototype.getDataDescriptor=function(){if(this.crcAndFileSizeKnown)return b;if(this.useZip64Format()){var e=O(oe);return e.writeUInt32LE(134695760,0),e.writeUInt32LE(this.crc32,4),T(e,this.compressedSize,8),T(e,this.uncompressedSize,16),e}else{var e=O(w);return e.writeUInt32LE(134695760,0),e.writeUInt32LE(this.crc32,4),e.writeUInt32LE(this.compressedSize,8),e.writeUInt32LE(this.uncompressedSize,12),e}};var se=46,ce=9,le=28;x.prototype.getCentralDirectoryRecord=function(){var e=O(se),t=ie;this.crcAndFileSizeKnown||(t|=ae);var n=b;if(!this.forceDosTimestamp){n=O(ce),n.writeUInt16LE(21589,0),n.writeUInt16LE(ce-4,2),n.writeUInt8(3,4);var r=Math.floor(this.mtime.getTime()/1e3);r<-2147483648&&(r=-2147483648),r>2147483647&&(r=2147483647),n.writeUInt32LE(r,5)}var i=this.compressedSize,a=this.uncompressedSize,o=this.relativeOffsetOfLocalHeader,s=S,c=b;return this.useZip64Format()&&(i=4294967295,a=4294967295,o=4294967295,s=C,c=O(le),c.writeUInt16LE(1,0),c.writeUInt16LE(le-4,2),T(c,this.uncompressedSize,4),T(c,this.compressedSize,12),T(c,this.relativeOffsetOfLocalHeader,20)),e.writeUInt32LE(33639248,0),e.writeUInt16LE(re,4),e.writeUInt16LE(s,6),e.writeUInt16LE(t,8),e.writeUInt16LE(this.getCompressionMethod(),10),e.writeUInt16LE(this.lastModFileTime,12),e.writeUInt16LE(this.lastModFileDate,14),e.writeUInt32LE(this.crc32,16),e.writeUInt32LE(i,20),e.writeUInt32LE(a,24),e.writeUInt16LE(this.utf8FileName.length,28),e.writeUInt16LE(n.length+c.length,30),e.writeUInt16LE(this.fileComment.length,32),e.writeUInt16LE(0,34),e.writeUInt16LE(0,36),e.writeUInt32LE(this.externalFileAttributes,38),e.writeUInt32LE(o,42),Buffer.concat([e,this.utf8FileName,n,c,this.fileComment])},x.prototype.getCompressionMethod=function(){return this.compressionLevel===0?0:8};var ue=new Date(1980,0,1),de=new Date(2107,11,31,23,59,58);function fe(e){e<ue?e=ue:e>de&&(e=de);var t=0;t|=e.getDate()&31,t|=(e.getMonth()+1&15)<<5,t|=(e.getFullYear()-1980&127)<<9;var n=0;return n|=Math.floor(e.getSeconds()/2),n|=(e.getMinutes()&63)<<5,n|=(e.getHours()&31)<<11,{date:t,time:n}}function T(e,t,n){var r=Math.floor(t/4294967296),i=t%4294967296;e.writeUInt32LE(i,n),e.writeUInt32LE(r,n+4)}a.inherits(pe,n);function pe(e){n.call(this,e),this.byteCount=0}pe.prototype._transform=function(e,t,n){this.byteCount+=e.length,n(null,e)},a.inherits(me,n);function me(e){n.call(this,e),this.crc32=0}me.prototype._transform=function(e,t,n){this.crc32=c.unsigned(e,this.crc32),n(null,e)};var he=`\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`;if(he.length!==256)throw Error(`assertion failure`);var E=null;function ge(e){if(/^[\x20-\x7e]*$/.test(e))return k(e,`utf-8`);if(E==null){E={};for(var t=0;t<he.length;t++)E[he[t]]=t}for(var n=O(e.length),t=0;t<e.length;t++){var r=E[e[t]];if(r==null)throw Error(`character not encodable in CP437: `+JSON.stringify(e[t]));n[t]=r}return n}function O(e){O=t;try{return O(e)}catch{return O=n,O(e)}function t(e){return Buffer.allocUnsafe(e)}function n(e){return new Buffer(e)}}function k(e,t){k=n;try{return k(e,t)}catch{return k=r,k(e,t)}function n(e,t){return Buffer.from(e,t)}function r(e,t){return new Buffer(e,t)}}function A(e,t){A=n;try{return A(e,t)}catch{return A=r,A(e,t)}function n(e,t){return e.includes(t)}function r(e,t){for(var n=0;n<=e.length-t.length;n++)for(var r=0;;r++){if(r===t.length)return!0;if(e[n+r]!==t[r])break}return!1}}}))();function Ea(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))t[n]=r===!0;return t}function Da(e){return{skills:Object.values(e).map(e=>({skill_name:e.skill_name,skill_hash:q(e.skill_hash)}))}}async function Oa(e,t){let n=It(e),r=Da(t),i=await B(e,`batch_check_detection`,n,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r)},R);return i&&typeof i==`object`&&!Array.isArray(i)&&`result`in i?Ea(i.result):Ea(i)}const ka=10*1024*1024;async function Aa(e){let t=await _(e),n=[];for(let r of t){let t=o(e,r),i=await m(t);i.isSymbolicLink()||(i.isDirectory()?n.push(...await Aa(t)):i.isFile()&&n.push(t))}return n}async function ja(e){let t=await v(e).catch(()=>null);if(!t||!t.isDirectory())throw Error(`zipDirectory: path does not exist or is not a directory: ${e}`);let n=await Aa(e);return n.sort((t,n)=>{let r=s(e,t),i=s(e,n);return r<i?-1:+(r>i)}),new Promise((t,r)=>{let i=new Ta.ZipFile,a=[],o=0,c=!1,l=e=>{c||(c=!0,r(e))};i.outputStream.on(`data`,t=>{if(!c){if(o+=t.length,o>ka){l(Error(`zipDirectory: zip exceeds ${ka} bytes limit for ${e} (${o} bytes)`));return}a.push(t)}}),i.outputStream.on(`end`,()=>{c||(c=!0,t(Buffer.concat(a)))}),i.outputStream.on(`error`,l);for(let t of n)i.addFile(t,s(e,t));i.end()})}async function Ma(e,t,n){let r=Lt(e),i=`skill_detect:${n.skill_name}`;e.logger.info(M(`[skill-detect] detect: sending skill=${n.skill_name} hash=${n.skill_hash.slice(0,12)}... dir=${t}`));let a=await ja(t);e.logger.info(M(`[skill-detect] zipped ${t} (${a.length} bytes)`));let o=new FormData,s=new Blob([new Uint8Array(a)],{type:`application/zip`});return o.append(`file`,s,n.skill_name),o.append(`skill`,JSON.stringify({skill_name:n.skill_name,skill_hash:q(n.skill_hash)})),o.append(`payload`,JSON.stringify(Kt())),await B(e,i,r,{method:`POST`,body:o},6e5),e.logger.info(M(`[skill-detect] skill ${n.skill_name} detected successfully`)),!0}function Na(e){return e.replace(/\0/g,``)}function Pa(e,t){let n=x(),i=new Set,a=e.config??{},s=a?.skills?.load?.extraDirs;if(Array.isArray(s))for(let e of s)typeof e==`string`&&e.trim()&&i.add(c(Na(e.trim())));i.add(o(n,`.openclaw`,`skills`)),i.add(o(n,`.agents`,`skills`));let l=new Set,u=a?.agents?.defaults?.workspace;if(typeof u==`string`&&u.trim()&&l.add(c(Na(u.trim()))),Array.isArray(a?.agents?.list))for(let e of a.agents.list)typeof e?.workspace==`string`&&e.workspace.trim()&&l.add(c(Na(e.workspace.trim())));for(let e of l)i.add(o(e,`skills`)),i.add(o(e,`.agents`,`skills`));let d,f=e.pluginConfig;if(typeof f?.openClawDir==`string`&&f.openClawDir.trim())d=c(Na(f.openClawDir.trim()));else try{let t=e.runtime?.state?.resolveStateDir?.();typeof t==`string`&&t.trim()&&(d=t)}catch{}d&&(i.add(o(d,`skills`)),i.add(o(d,`.agents`,`skills`)));let p=a?.plugins;if(p?.installs&&typeof p.installs==`object`){for(let e of Object.values(p.installs))if(typeof e?.installPath==`string`&&e.installPath.trim()){let t=o(Na(e.installPath.trim()),`skills`);i.add(c(t))}}let m=t??o(n,`.openclaw`,`workspace`);i.add(o(m,`.agents`,`skills`)),i.add(o(m,`skills`));let h=Array.from(i),g=h.filter(e=>r(e));return e.logger.info(M(`[skill-scan] resolved ${h.length} skill path(s), ${g.length} exist`)),g}async function Fa(e){let t;try{t=await _(e)}catch{return[]}let n=[];for(let r of t){let t=o(e,r),i=await m(t);i.isSymbolicLink()||(i.isDirectory()?n.push(...await Fa(t)):i.isFile()&&n.push(t))}return n}const Ia=10*1024*1024;async function La(e){let t=await Fa(e);if(t.length===0)return f(`sha256`).update(`empty-skill-dir`).digest(`hex`);let n=[],r=0;for(let a of t){let t=await g(a);if(r+=t.length,r>Ia)throw Error(`computeCanonicalHash: skill directory exceeds ${Ia} byte limit: ${e}`);let o=i(a),s=f(`sha256`).update(t).digest(`hex`);n.push(`${o}:${s}`)}return n.sort(),f(`sha256`).update(n.join(`
8
+ `)).digest(`hex`)}function Ra(e){let t=/^name:\s*(.+)$/m.exec(e);return t?t[1].trim():null}function za(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);return t?t[1]:``}async function Ba(e,t){let n;try{n=await _(t,{withFileTypes:!0,encoding:`utf8`})}catch{return[]}let r=[];for(let i of n){if(!i.isDirectory())continue;let n=o(t,i.name),a=o(n,`SKILL.md`);try{let e=Ra(za(await g(a,`utf-8`)))||i.name,t=await La(n);r.push({dirName:i.name,dirPath:n,filePath:a,skillName:e,skillHash:t})}catch(t){t instanceof Error&&t.message.includes(`byte limit`)&&e.logger.warn(M(`[skill-scan] skipping skill '${i.name}': ${t.message}`))}}return r}async function Va(e,t){let n=Pa(e,t);e.logger.info(M(`[skill-scan] scanning ${n.length} skill location(s)`));let r=new Map;for(let t of n){let n=await Ba(e,t);n.length>0&&e.logger.info(M(`[skill-scan] ${t}: ${n.length} skill(s)`));for(let e of n)r.set(e.skillName,e)}let i=Array.from(r.values());return e.logger.info(M(`[skill-scan] scan complete: ${i.length} unique skill(s) across all locations`)),i}function Ha(e,t,n,r,i){e[t]={...n,skill_name:r.skill_name,skill_hash:r.skill_hash,is_detected:i,last_detect_ts:Date.now()}}async function Ua(e,t){e.logger.info(M(`[skill-scan] starting skill scan`));let n=Date.now(),r=je(t),i=await Va(e,t);if(i.length===0){e.logger.info(M(`[skill-scan] no skills found, skipping detection`));return}let a=Ve(await ze(e,r),i);e.logger.info(M(`[skill-scan] merged state: ${Object.keys(a).length} skill(s)`));let o=new Map(i.map(e=>[e.dirName,e])),s=[];for(let[t,n]of Object.entries(a))if(o.get(t)){if(Fe(n)){e.logger.warn(M(`[skill-scan] ${n.skill_name}: skill_hash missing, skipping`));continue}n.is_detected||(e.logger.info(M(`[skill-scan] ${n.skill_name}: not detected, queuing`)),s.push({dirName:t,entry:n,entity:{skill_name:n.skill_name,skill_hash:n.skill_hash}}))}if(e.logger.info(M(`[skill-scan] ${s.length} skill(s) need detection`)),s.length===0){await Be(e,a,r),e.logger.info(M(`[skill-scan] skill scan complete (nothing to detect) total_elapsed=${Date.now()-n}ms scanned=${i.length}`));return}let c={};for(let{dirName:e}of s)c[e]=a[e];let l={},u=!1;try{l=await Oa(e,c),e.logger.info(M(`[skill-scan] batch_check result: ${JSON.stringify(l)}`))}catch(t){e.logger.error(M(`[skill-scan] batch_check_detection failed: ${t instanceof Error?t.message:String(t)}`)),u=!0}for(let{dirName:t,entry:n,entity:r}of s)l[q(r.skill_hash)]===!0&&(Ha(a,t,n,r,!0),e.logger.info(M(`[skill-scan] ${r.skill_name}: already known by server (batch_check)`)));if(u){e.logger.warn(M(`[skill-scan] skipping individual detect calls: batch_check_detection was unreachable`)),await Be(e,a,r),e.logger.info(M(`[skill-scan] skill scan complete (partial — batch_check failed) total_elapsed=${Date.now()-n}ms scanned=${i.length}`));return}for(let{dirName:t,entry:n,entity:r}of s){if(l[q(r.skill_hash)]===!0)continue;let n=o.get(t);if(n)try{let i=await Ma(e,n.dirPath,r);Ha(a,t,a[t],r,i),e.logger.info(M(`[skill-scan] detect result for ${r.skill_name}: is_detected=${i}`))}catch(n){e.logger.error(M(`[skill-scan] detect failed for ${r.skill_name}: ${n instanceof Error?n.message:String(n)}`)),Ha(a,t,a[t],r,!1)}}await Be(e,a,r),e.logger.info(M(`[skill-scan] skill scan complete total_elapsed=${Date.now()-n}ms scanned=${i.length} to_detect=${s.length}`))}function Wa(e,t){let n=null,r=!1,i=!1,a;async function o(){if(i)return;let s=await t.getSkillScanIntervalMs();e.logger.info(M(`[skill-scan-service] next scan in ${s/1e3}s`)),n=setTimeout(async()=>{if(!i){if(!await t.isSkillDetectEnabled()){e.logger.info(M(`[skill-scan-service] periodic scan skipped: skill_detect disabled`)),await o();return}if(r){e.logger.info(M(`[skill-scan-service] periodic scan skipped: previous scan still running`)),await o();return}e.logger.info(M(`[skill-scan-service] periodic scan triggered`)),r=!0,Ua(e,a).catch(t=>{e.logger.error(M(`[skill-scan-service] periodic scan failed: ${t instanceof Error?t.message:String(t)}`))}).finally(()=>{r=!1,o()})}},s),n.unref()}return{id:`openclaw-guardian-skill-scan`,async start(n){a=n.workspaceDir,e.logger.info(M(`[skill-scan-service] starting with workspaceDir=${a??`(default)`}`)),i=!1,await t.isSkillDetectEnabled()&&(e.logger.info(M(`[skill-scan-service] running initial skill scan`)),r=!0,Ua(e,a).catch(t=>{e.logger.error(M(`[skill-scan-service] initial scan failed: ${t instanceof Error?t.message:String(t)}`))}).finally(()=>{r=!1})),await o()},async stop(t){i=!0,n&&=(clearTimeout(n),null),e.logger.info(M(`[skill-scan-service] stopped`))}}}function Ga(e,t){e.registerService(Wa(e,t))}const Ka=[`message_received`,`before_tool_call`,`after_tool_call`,`before_llm_fetch`,`after_llm_fetch_v2`,`llm_input`,`llm_output`,`skill_detect`],qa=[`network_access`],Ja=[...Ka,...qa];function Ya(){return Object.fromEntries(Ja.map(e=>[e,!1]))}function Xa(e){let t=Ya(),n=e&&typeof e==`object`?e:{};for(let e of Ja)t[e]=!!n[e];return t}function Za(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):1}function Qa(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):600}const $a=1e3,eo=1e3;function to(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function no(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):900}function ro(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function io(e){return e===`black`?`black`:`white`}function ao(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function oo(e){if(!e.enabled||!e.enable_tool_call_injection)return null;let t=e.mitm_tool_list_mode===`black`?e.mitm_tool_black_list:e.mitm_tool_white_list;return t.length===0?null:RegExp(`^(${t.map(ao).join(`|`)})(?:\\s|$)`)}function so(e,t){return!e||!t?!1:t.test(e.trimStart())}function co(e,t,n){if(!e.enabled||!e.enable_tool_call_injection||!t.trim())return!1;let r=so(t,n);return e.mitm_tool_list_mode===`black`?!r:r}function lo(e){return{enabled:!1,hook_toggles:Ya(),sse_chunk_size:1,skill_scan_duration_second:900,query_duration_second:600,enable_llm_req_sync_detect:!1,enable_llm_resp_sync_detect:!1,llm_req_sync_detect_timeout_ms:$a,enable_llm_req_async_detect:!1,llm_async_detect_loop_query_ms:eo,enable_tool_call_injection:!1,mitm_tool_white_list:[],mitm_tool_black_list:[],mitm_tool_list_mode:`white`,enable_network_hook:!1,reason:e}}function uo(e){let t=e&&typeof e==`object`?e:{},n=t.enabled===void 0?!0:!!t.enabled;return{enabled:n,hook_toggles:n?Xa(t.hook_toggles):Ya(),sse_chunk_size:Za(t.sse_chunk_size),skill_scan_duration_second:no(t.skill_scan_duration_second),query_duration_second:Qa(t.query_duration_second),enable_llm_req_sync_detect:n?!!t.enable_llm_req_sync_detect:!1,enable_llm_resp_sync_detect:n?!!t.enable_llm_resp_sync_detect:!1,llm_req_sync_detect_timeout_ms:to(t.llm_req_sync_detect_timeout_ms,$a),enable_llm_req_async_detect:n?!!t.enable_llm_req_async_detect:!1,llm_async_detect_loop_query_ms:to(t.llm_async_detect_loop_query_ms,eo),enable_tool_call_injection:n?!!t.enable_tool_call_injection:!1,mitm_tool_white_list:ro(t.mitm_tool_white_list),mitm_tool_black_list:ro(t.mitm_tool_black_list),mitm_tool_list_mode:io(t.mitm_tool_list_mode),enable_network_hook:n?!!t.enable_network_hook:!1,reason:n?`remote`:`remote_disabled`}}function fo(e){try{return JSON.stringify(e)}catch(e){return`<unserializable_runtime_config:${e instanceof Error?e.message:String(e)}>`}}function po(e){return ci(e.config).map(e=>e.baseUrl)}async function mo(e){let t={source:`miaoda`,base_url_list:po(e),payload:{openclaw_version:e.runtime?.version??``,plugin_version:e.version??``}};return uo(await B(e,`runtime_config`,Pt(e),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)},R))}function ho(e){let t=lo(`not_initialized`),n=oo(t),r=!1,i=null,a=null,o=new Set;function s(e){return t=e,n=oo(e),t}function c(){for(let t of o)try{t()}catch(t){e.logger.error(M(`[runtime_config] config change listener failed: ${t instanceof Error?t.message:String(t)}`))}}async function l(){let n=null;for(let i=1;i<=3;i+=1)try{let n=await mo(e);return s(n),r=!0,c(),e.logger.info(M(`[runtime_config] initial config loaded on attempt=${i} config=${fo(n)}`)),t}catch(t){n=t;let r=kt(t);if(e.logger.error(M(`[runtime_config] initial config load failed attempt=${i} errorCode=${r}: ${t instanceof Error?t.message:String(t)}`)),r===`SERVER`||r===`PARSE`)break}return s(lo(`initial_fetch_failed`)),c(),e.logger.warn(M(`[runtime_config] initial config unavailable after 3 attempts; detection disabled by default${n?`: ${n instanceof Error?n.message:String(n)}`:``}`)),t}async function u(){try{let n=await mo(e);return s(n),r=!0,c(),e.logger.info(M(`[runtime_config] config refreshed config=${fo(n)}`)),t}catch(n){let i=kt(n);return r?(e.logger.error(M(`[runtime_config] refresh failed (errorCode=${i}); keeping previous config: ${n instanceof Error?n.message:String(n)}`)),t):(e.logger.error(M(`[runtime_config] refresh failed before first successful load (errorCode=${i}): ${n instanceof Error?n.message:String(n)}`)),s(lo(`refresh_failed_${i}`)),c(),t)}}function d(){i&&clearTimeout(i);let n=t.query_duration_second*1e3;e.logger.info(M(`[runtime_config] next config refresh in ${t.query_duration_second}s`)),i=setTimeout(()=>{e.logger.info(M(`[runtime_config] refresh loop fired`)),u().catch(t=>{e.logger.error(M(`[runtime_config] refresh loop failed: ${t instanceof Error?t.message:String(t)}`))}).finally(()=>{d()})},n),i.unref()}function f(){return a||=l().catch(n=>(e.logger.error(M(`[runtime_config] initialize failed: ${n instanceof Error?n.message:String(n)}`)),t)).finally(()=>{d()}),a}function p(){return!!(t?.enabled&&t?.enable_network_hook)}function m(){return!!(p()&&t?.hook_toggles?.network_access)}return{onConfigChange(e){return o.add(e),()=>{o.delete(e)}},async isHookEnabled(e){return await f(),!!(t?.enabled&&t?.hook_toggles?.[e])},async isSkillDetectEnabled(){return await f(),!!(t?.enabled&&t?.hook_toggles?.skill_detect)},async getSseChunkSize(){return await f(),Za(t?.sse_chunk_size)},async getSkillScanIntervalMs(){return await f(),no(t?.skill_scan_duration_second)*1e3},async isLlmReqSyncDetectEnabled(){return await f(),!!(t?.enabled&&t?.hook_toggles?.before_llm_fetch&&t?.enable_llm_req_sync_detect)},async isLlmRespSyncDetectEnabled(){return await f(),!!(t?.enabled&&t?.hook_toggles?.after_llm_fetch_v2&&t?.enable_llm_resp_sync_detect)},async getLlmReqSyncDetectTimeoutMs(){return await f(),to(t?.llm_req_sync_detect_timeout_ms,$a)},async isLlmReqAsyncDetectEnabled(){return await f(),!!(t?.enabled&&t?.hook_toggles?.before_llm_fetch&&t?.enable_llm_req_async_detect)},async getLlmAsyncDetectLoopQueryMs(){return await f(),to(t?.llm_async_detect_loop_query_ms,eo)},async isToolCallInjectionEnabled(){return await f(),!!(t?.enabled&&t?.enable_tool_call_injection)},async shouldAppendMitmAuthForCommand(e){return await f(),co(t,e,n)},async isNetworkHookEnabled(){return await f(),p()},isNetworkHookEnabledSnapshot(){return f(),p()},async isNetworkAccessEnabled(){return await f(),m()},isNetworkAccessEnabledSnapshot(){return m()}}}function go(e=6e5){Bn();let t=setInterval(()=>{Bn()},e);typeof t==`object`&&t&&`unref`in t&&t.unref()}var _o=n({id:`openclaw-guardian-plugin`,name:`OpenClaw Guardian Plugin`,description:`Reports OpenClaw hook payloads to the trust_layer detect service with remote hook toggles.`,register(e){if(!vt(e))return;let t=ho(e);go(),pn(e,t),Ca(e,t),vr(e,t),Ga(e,t)}});export{_o as default};
@@ -2,7 +2,7 @@
2
2
  "id": "openclaw-guardian-plugin",
3
3
  "name": "OpenClaw Guardian Plugin",
4
4
  "description": "Reports OpenClaw hook payloads to security_plugin config and detect endpoints.",
5
- "version": "2026.5.7",
5
+ "version": "2026.6.13",
6
6
  "uiHints": {
7
7
  "appId": {
8
8
  "label": "Feishu App ID",
@@ -13,6 +13,9 @@
13
13
  "sensitive": true
14
14
  }
15
15
  },
16
+ "activation": {
17
+ "onStartup": true
18
+ },
16
19
  "configSchema": {
17
20
  "type": "object",
18
21
  "additionalProperties": false,
package/package.json CHANGED
@@ -1,11 +1,17 @@
1
1
  {
2
2
  "name": "@lark-tns/openclaw-guardian-plugin",
3
- "version": "2026.5.7",
3
+ "version": "2026.6.13",
4
4
  "type": "module",
5
5
  "description": "OpenClaw plugin that reports hook payloads to the security_plugin detect service with remote hook toggles.",
6
- "keywords": ["openclaw", "plugin", "security", "guardian"],
6
+ "keywords": [
7
+ "openclaw",
8
+ "plugin",
9
+ "security",
10
+ "guardian"
11
+ ],
7
12
  "files": [
8
13
  "dist",
14
+ "vender",
9
15
  "openclaw.plugin.json",
10
16
  "README.md"
11
17
  ],
@@ -19,23 +25,23 @@
19
25
  "openclaw": {
20
26
  "extensions": [
21
27
  "./dist/index.js"
22
- ]
28
+ ],
29
+ "install": {
30
+ "minHostVersion": ">=2026.3.24"
31
+ }
23
32
  },
24
33
  "devDependencies": {
25
34
  "@types/yazl": "^3.3.0",
26
35
  "tsdown": "^0.12.5",
27
36
  "typescript": "^5.8.3",
28
- "yazl": "^3.3.1"
29
- },
30
- "peerDependencies": {
37
+ "yazl": "^3.3.1",
31
38
  "openclaw": ">=2026.3.24"
32
39
  },
33
- "peerDependenciesMeta": {
34
- "openclaw": {
35
- "optional": false
36
- }
40
+ "dependencies": {
41
+ "undici": "^8.2.0"
37
42
  },
38
43
  "publishConfig": {
44
+ "registry": "https://registry.npmjs.org/",
39
45
  "access": "public"
40
46
  }
41
47
  }
@@ -0,0 +1 @@
1
+ 1.0.4-alpha.20
@@ -0,0 +1,22 @@
1
+ export HTTPS_PROXY="http://trace_id:$AGENT_TRACE$MITM_ENV@127.0.0.1:$CLI_PORT"
2
+
3
+ export NODE_EXTRA_CA_CERTS="$CLI_CERT_PATH"
4
+ export SSL_CERT_FILE="$CLI_CERT_PATH"
5
+ export CURL_CA_BUNDLE="$CLI_CERT_PATH"
6
+ export REQUESTS_CA_BUNDLE="$CLI_CERT_PATH"
7
+ export PIP_CERT="$CLI_CERT_PATH"
8
+ export GIT_SSL_CAINFO="$CLI_CERT_PATH"
9
+ export AWS_CA_BUNDLE="$CLI_CERT_PATH"
10
+ export CARGO_HTTP_CAINFO="$CLI_CERT_PATH"
11
+ export DENO_CERT="$CLI_CERT_PATH"
12
+
13
+ export NO_PROXY="localhost,127.0.0.1,::1,*.local,.local,169.254.0.0/16,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"
14
+ export no_proxy="$NO_PROXY"
15
+
16
+ export HTTP_PROXY="$HTTPS_PROXY"
17
+ export http_proxy="$HTTP_PROXY"
18
+ export https_proxy="$HTTPS_PROXY"
19
+
20
+ export CLOUDSDK_PROXY_TYPE="http"
21
+ export CLOUDSDK_PROXY_ADDRESS="localhost"
22
+ export CLOUDSDK_PROXY_PORT="$CLI_PORT"
@@ -0,0 +1,22 @@
1
+ export HTTPS_PROXY="http://trace_id:$AGENT_TRACE$MITM_ENV@127.0.0.1:$CLI_PORT"
2
+
3
+ export NODE_EXTRA_CA_CERTS="$CLI_CERT_PATH"
4
+ export SSL_CERT_FILE="$CLI_CERT_PATH"
5
+ export CURL_CA_BUNDLE="$CLI_CERT_PATH"
6
+ export REQUESTS_CA_BUNDLE="$CLI_CERT_PATH"
7
+ export PIP_CERT="$CLI_CERT_PATH"
8
+ export GIT_SSL_CAINFO="$CLI_CERT_PATH"
9
+ export AWS_CA_BUNDLE="$CLI_CERT_PATH"
10
+ export CARGO_HTTP_CAINFO="$CLI_CERT_PATH"
11
+ export DENO_CERT="$CLI_CERT_PATH"
12
+
13
+ export NO_PROXY="localhost,127.0.0.1,::1,*.local,.local,169.254.0.0/16,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"
14
+ export no_proxy="$NO_PROXY"
15
+
16
+ export HTTP_PROXY="$HTTPS_PROXY"
17
+ export http_proxy="$HTTP_PROXY"
18
+ export https_proxy="$HTTPS_PROXY"
19
+
20
+ export CLOUDSDK_PROXY_TYPE="http"
21
+ export CLOUDSDK_PROXY_ADDRESS="localhost"
22
+ export CLOUDSDK_PROXY_PORT="$CLI_PORT"