@wps365/openclaw-wpsxiezuo 1.9.0 → 1.9.1-beta.0

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.
Files changed (2) hide show
  1. package/dist/index.js +24 -24
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,37 +1,37 @@
1
- var ro=Object.defineProperty;var we=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pn=(e,t)=>{for(var r in t)ro(e,r,{get:t[r],enumerable:!0})};function ur(e){return e===401?{hint:"invalid/expired token or app credentials",retriable:!1}:e===403?{hint:"permission denied or scope not granted",retriable:!1}:e===404?{hint:"resource not found",retriable:!1}:e===409?{hint:"resource state conflict",retriable:!1}:e===429?{hint:"rate limited by WPS API",retriable:!0}:e>=500?{hint:"WPS API temporarily unavailable",retriable:!0}:{hint:"unexpected WPS API status",retriable:!1}}var Fe,se,kt=we(()=>{"use strict";Fe=class extends Error{detail;name="WpsRequestError";constructor(t,r){super(t),this.detail=r}get retriable(){return this.detail.retriable===!0}get stage(){return this.detail.stage}},se=class extends Error{cause;name="WpsTokenError";constructor(t,r){super(t),this.cause=r}}});function oo(e){return e===401?"invalid app credentials (check client_id/client_secret)":e===403?"app not authorized for this enterprise or scope":e===429?"rate limited by WPS token endpoint":e>=500?"WPS OAuth service unavailable":"unexpected OAuth response"}function j(e){let t=`${e.clientId}@${e.baseUrl}`,r=On.get(t);return r||(r=new Mt(e),On.set(t,r)),r}var no,io,Mt,On,_r=we(()=>{"use strict";kt();no=6e4,io=["/oauth2/token","/openapi/oauth2/token"];Mt=class{creds;token=null;inFlight=null;constructor(t){this.creds=t}async getToken(){if(this.token&&Date.now()<this.token.expiresAt-no)return this.token.accessToken;if(this.inFlight)return this.inFlight;this.inFlight=this.requestToken();try{return await this.inFlight}finally{this.inFlight=null}}invalidate(){this.token=null}async requestToken(){let t=this.creds.baseUrl.replace(/\/$/,""),r="unknown token error";for(let n of io){let o=`${t}${n}`,i;try{i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.creds.clientId,client_secret:this.creds.clientSecret})})}catch(a){r=`Network error requesting token from ${o}: ${String(a)}`;continue}if(!i.ok){let a=await i.text();r=`Token request failed (${i.status}) at ${o}: ${oo(i.status)}; body=${a}`;continue}let s=await i.json();if(s.code!==void 0&&s.code!==0){r=`WPS OAuth error (code ${s.code}): ${s.msg??"unknown"}`;continue}if(!s.access_token||!s.expires_in){r=`Invalid token response from ${o}: missing access_token or expires_in`;continue}return this.token={accessToken:s.access_token,expiresAt:Date.now()+s.expires_in*1e3},this.token.accessToken}throw new se(r)}},On=new Map});import{z as S}from"zod";function zt(e){return Wt}function hr(e){let t=e?.defaultAccountId?.trim();if(t)return t;let r=e?.accounts?Object.keys(e.accounts)[0]:void 0;return r&&r.trim()?r:Ce}function gr(e){return e?e.accounts&&Object.keys(e.accounts).length>0?e.accounts:!(e.appId||e.appSecret||e.companyId||e.webhook||e.sdk||e.groups||e.dmPolicy||e.groupPolicy)?{}:!e.appId||!e.appSecret?{}:{[Ce]:{enabled:e.enabled??!0,appId:e.appId,appSecret:e.appSecret,companyId:e.companyId,baseUrl:e.baseUrl??"https://openapi.wps.cn",enableEncryption:e.enableEncryption??!0,webhook:e.webhook,sdk:e.sdk,dmPolicy:e.dmPolicy,allowFrom:e.allowFrom,groupPolicy:e.groupPolicy,groups:e.groups,instantAck:e.instantAck,robotJoinGroupMessage:e.robotJoinGroupMessage,mcp:e.mcp}}:{}}function _e(e){return!e?.appId||!e?.appSecret?null:{clientId:e.appId,clientSecret:e.appSecret,baseUrl:e.baseUrl??"https://openapi.wps.cn"}}var An,Rn,$n,qn,Cn,Dn,Wt,fr,mr,T,be,Ce,tt=we(()=>{"use strict";An=S.enum(["disabled","open","allowlist","pairing"]).default("pairing"),Rn=S.object({requireMention:S.boolean().optional(),toolPolicy:S.enum(["full","limited","none"]).optional()}).passthrough(),$n=S.object({enabled:S.boolean().default(!1),mode:S.literal("app").default("app"),clientId:S.string().optional(),clientSecret:S.string().optional(),baseUrl:S.string().optional(),toolAllowlist:S.array(S.string()).min(1,"mcp.toolAllowlist must contain at least one tool").default(["wps_user_search","wps_user_get","wps_message_send","wps_calendar_create","wps_calendar_list_events","wps_calendar_search_events","wps_calendar_update_event","wps_calendar_delete_event","wps_calendar_get_event","wps_calendar_list_event_attendees","wps_calendar_add_event_attendees","wps_calendar_list_event_meeting_rooms","wps_calendar_event_meeting_rooms_batch_create","wps_calendar_event_meeting_rooms_batch_delete","wps_calendar_delete_event_attendees","wps_calendar_list_calendar_event_instances","wps_calendar_list_event_instances","wps_calendar_respond_invitation","wps_todo_create_personal_task","wps_todo_list_personal_tasks","wps_todo_get_personal_task","wps_todo_update_personal_task","wps_todo_update_personal_task_status","wps_cloud_doc_list_drives","wps_cloud_doc_list_children_files","wps_cloud_doc_create_file","wps_cloud_doc_upload_file","wps_cloud_doc_extract_file_content","wps_cloud_doc_get_file_meta","wps_cloud_doc_search_files","wps_airpage_create_file","wps_airpage_create_block_content","wps_airpage_query_document_blocks","wps_airpage_batch_query_document_blocks","wps_airpage_delete_block_content","wps_airpage_batch_delete_block_content","wps_airpage_update_document_block","wps_airpage_batch_update_document_blocks","wps_meeting_rooms_list","wps_meeting_rooms_get","wps_meeting_rooms_search","wps_meeting_room_bookings_batch_get","wps_meeting_room_bookings_update_status"])}),qn=S.object({enabled:S.boolean().default(!0),text:S.string().default("\u5185\u5BB9\u5904\u7406\u4E2D\uFF0C\u8BF7\u7A0D\u5019...")}),Cn=S.object({enabled:S.boolean().default(!1),logLevel:S.enum(["debug","info","warn","error"]).default("info"),endpoint:S.string().optional(),connectTimeoutMs:S.number().min(3e3).max(12e4).default(2e4),pongTimeout:S.number().min(3e4).max(3e5).default(15e4),autoReconnect:S.boolean().default(!0),reconnectBaseInterval:S.number().min(500).max(1e4).default(1e3),reconnectMaxInterval:S.number().min(1e4).max(3e5).default(6e4),reconnectMultiplier:S.number().min(1.5).max(3).default(2),reconnectMaxRetry:S.number().min(-1).max(100).default(-1),reconnectJitter:S.number().min(0).max(.5).default(.2)}),Dn=S.object({path:S.string().default("/wps/webhook"),port:S.number().default(3e3)}),Wt="https://o.wpsgo.com/app/41000207/El1ykTHO5aVv/",fr=S.object({enabled:S.boolean().default(!0),appId:S.string().describe("WPS App ID (client_id)"),appSecret:S.string().describe("WPS App Secret (client_secret)"),companyId:S.string().optional().describe("WPS Company ID"),baseUrl:S.string().default("https://openapi.wps.cn"),enableEncryption:S.boolean().default(!0),webhook:Dn.optional(),sdk:Cn.optional(),dmPolicy:An.optional(),allowFrom:S.array(S.string()).optional(),groupPolicy:S.enum(["open","allowlist"]).optional(),groups:S.record(S.string(),Rn).optional(),instantAck:qn.optional(),robotJoinGroupMessage:S.string().optional(),mcp:$n.optional()}),mr=fr.partial().extend({defaultAccountId:S.string().optional(),accounts:S.record(S.string(),fr).optional()});T="wps-xiezuo",be="wps-xiezuo",Ce="default"});function yr(e){St=e}function wr(e,t){rt.set(e,t),Un(e,t)}function xt(e){let t=rt.get(e);return t?Date.now()>=t.expiresAt?(rt.delete(e),Nn(e),null):t.accessToken:null}function Nn(e){let t=Lt.get(e);t&&(clearTimeout(t),Lt.delete(e))}function Un(e,t){if(Nn(e),!t.refreshToken)return;let r=Math.max(t.expiresAt-Date.now()-so,1e4),n=setTimeout(()=>{ao(e).catch(()=>{rt.delete(e),Lt.delete(e)})},r);n.unref?.(),Lt.set(e,n)}async function ao(e){let t=rt.get(e);if(!t?.refreshToken||!St)return;let r=St.baseUrl.replace(/\/$/,""),n=new URLSearchParams({grant_type:"refresh_token",client_id:St.appId,client_secret:St.appSecret,refresh_token:t.refreshToken}),o=await fetch(`${r}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()}),i=await o.text(),s;try{s=JSON.parse(i)}catch{throw new se(`OAuth refresh: non-JSON response (${o.status}): ${i.slice(0,200)}`)}if(!o.ok||typeof s.code=="number"&&s.code!==0)throw new se(`OAuth refresh failed (${o.status}): ${JSON.stringify(s)}`);let a=typeof s.access_token=="string"?s.access_token:"";if(!a)throw new se(`OAuth refresh: missing access_token: ${JSON.stringify(s)}`);let d=typeof s.expires_in=="number"?s.expires_in:7200,l={accessToken:a,refreshToken:typeof s.refresh_token=="string"?s.refresh_token:t.refreshToken,expiresAt:Date.now()+d*1e3,openid:typeof s.openid=="string"?s.openid:t.openid};rt.set(e,l),Un(e,l)}async function br(e){let t=e.baseUrl.replace(/\/$/,""),r=new URLSearchParams({grant_type:"authorization_code",client_id:e.appId,client_secret:e.appSecret,code:e.code,redirect_uri:e.redirectUri??Wt}),n=await fetch(`${t}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()}),o=await n.text(),i;try{i=JSON.parse(o)}catch{throw new se(`OAuth code exchange: non-JSON response (${n.status}): ${o.slice(0,200)}`)}if(!n.ok||typeof i.code=="number"&&i.code!==0)throw new se(`OAuth code exchange failed (${n.status}): ${JSON.stringify(i)}`);let s=typeof i.access_token=="string"?i.access_token:"";if(!s)throw new se(`OAuth code exchange: missing access_token in response: ${JSON.stringify(i)}`);let a=typeof i.expires_in=="number"?i.expires_in:7200;return{accessToken:s,refreshToken:typeof i.refresh_token=="string"?i.refresh_token:"",expiresAt:Date.now()+a*1e3,openid:typeof i.openid=="string"?i.openid:""}}var rt,Lt,so,St,nt=we(()=>{"use strict";kt();tt();rt=new Map,Lt=new Map,so=5*6e4,St=null});function W(e,t){return new vt(e,new Bt(t))}function Ir(e,t){return new vt(e,new Ft(t))}var Bt,Ft,vt,Gt=we(()=>{"use strict";kt();Bt=class{tokenStore;constructor(t){this.tokenStore=t}async getHeaders(){return{Authorization:`Bearer ${await this.tokenStore.getToken()}`}}},Ft=class{accessToken;constructor(t){this.accessToken=t}async getHeaders(){return{Authorization:`Bearer ${this.accessToken}`}}},vt=class{baseUrl;auth;constructor(t,r){this.baseUrl=t,this.auth=r}async request(t){let r=await this.auth.getHeaders(),n=this.buildUrl(t.path,t.query),o=t.method??"GET",i=await fetch(n,{method:o,headers:{"Content-Type":"application/json",...r,...t.headers??{}},body:t.body?JSON.stringify(t.body):void 0}),s=i.headers.get("X-Request-Id")??i.headers.get("x-request-id")??i.headers.get("X-Trace-Id")??i.headers.get("x-trace-id")??void 0;if(!i.ok){let a=await i.text(),d;try{let u=JSON.parse(a);d=u.code??u.result}catch{}let{hint:l,retriable:c}=ur(i.status),p=s?` request_id=${s}`:"";throw console.error(`[WPS-API-ERROR] ${i.status} ${o} ${t.path}${p} body=${a}`),new Fe(`WPS API error (${i.status} ${o} ${t.path}): ${a}`,{stage:"http",method:o,path:t.path,httpStatus:i.status,wpsCode:d,hint:l,retriable:c,requestId:s})}return this.parseResponse(i,o,t.path,s)}buildUrl(t,r){let n=new URL(t,this.baseUrl);if(r){for(let[o,i]of Object.entries(r))if(i!==void 0)if(Array.isArray(i))for(let s of i)n.searchParams.append(o,s);else n.searchParams.set(o,String(i))}return n.toString()}async parseResponse(t,r,n,o){let i=await t.text();if(!i||i.trim()==="")return{};let s;try{s=JSON.parse(i)}catch{throw new Fe(`Failed to parse JSON from ${r} ${n}: ${i.slice(0,200)}`,{stage:"parse",method:r,path:n,hint:"response is not valid JSON",retriable:!1})}let a=s.code??s.result;if(a!==void 0&&a!==0&&a!=="ok"){let d=String(a)==="40300001"?"permission denied by WPS business policy":"WPS business validation failed",l=s.request_id??o,c=l?` request_id=${String(l)}`:"";throw console.error(`[WPS-API-ERROR] biz_code=${String(a)} ${r} ${n}${c} msg=${s.msg??s.message??"unknown"}`),new Fe(`WPS business error code=${String(a)}: ${s.msg??s.message??"unknown"}`,{stage:"business",method:r,path:n,wpsCode:a,hint:d,retriable:!1,requestId:l?String(l):void 0})}return s}}});import{imageSize as co}from"image-size";function Tt(e,t=0){if(!e||typeof e!="object"||t>2)return null;let r=e;for(let n of lo){let o=r[n];if(typeof o=="string"&&o.trim())return o.trim()}return r.data&&typeof r.data=="object"?Tt(r.data,t+1):null}function kr(e){let t=Tt(e);if(!t)throw new Error("cannot resolve download URL from WPS API response");return t}function jn(e){try{let t=co(Buffer.isBuffer(e)?e:Buffer.from(e));return t.width&&t.height?{width:t.width,height:t.height}:null}catch{return null}}var lo,Et=we(()=>{"use strict";lo=["url","download_url","downloadUrl","file_url","fileUrl"]});async function xr(e,t,r){let n=j(e);await W(e.baseUrl,n).request({method:"POST",path:`/v7/chats/${encodeURIComponent(t)}/messages/${encodeURIComponent(r)}/reactions/create`,body:{reaction_type:Sr}})}async function vr(e,t,r,n){try{let o=j(e);await W(e.baseUrl,o).request({method:"POST",path:`/v7/chats/${encodeURIComponent(t)}/messages/${encodeURIComponent(r)}/reactions/delete`,body:{reaction_type:Sr}})}catch(o){let i=String(o);i.includes("msgRecalled")||i.includes("message_not_found")||i.includes("404")?(n?.info??console.log)(`WPS thinking reaction cleanup skipped (message gone): ${i.substring(0,100)}`):(n?.error??console.error)(`WPS thinking reaction cleanup failed: ${i}`)}}var Sr,Tr=we(()=>{"use strict";_r();Gt();Sr="emoji_busy"});var Pt=we(()=>{"use strict";kt();_r();nt();Gt();Et();Tr();tt()});var ci={};Pn(ci,{getDelegatedScopes:()=>$t,getLazyClient:()=>Gr,getLazyCreds:()=>Xt,getLazyLog:()=>at,getLazyWpsCfg:()=>Kr,setDelegatedScopes:()=>Vt,setLazyClient:()=>Fr});function Fr(e,t,r,n){zr=e,ai=t??null,Lr=r??null,Br=n??null}function Gr(){if(!zr)throw new Error("WPS client not initialized yet (startAccount has not been called)");return zr}function at(){return ai}function Kr(){if(!Lr)throw new Error("WPS config not set yet (startAccount has not been called)");return Lr}function Xt(){if(!Br)throw new Error("WPS credentials not set yet (startAccount has not been called)");return Br}function Vt(e){di=e}function $t(){return di}var zr,ai,Lr,Br,di,dt=we(()=>{"use strict";zr=null,ai=null,Lr=null,Br=null;di=[]});var Xr={};Pn(Xr,{buildAuthCard:()=>_i,buildAuthSuccessCard:()=>fi,buildAuthorizeUrl:()=>ui,decodeState:()=>pi,encodeState:()=>li,handleAuthEvent:()=>Ko,sendAuthCard:()=>Jr});import{randomBytes as Bo}from"node:crypto";function li(e){let t=Bo(16).toString("hex");e.nonce=t;let r=t;return qt.set(r,e),setTimeout(()=>qt.delete(r),10*6e4).unref?.(),r}function pi(e){let t=qt.get(e);return t&&qt.delete(e),t??null}function ui(e){let t=new URL("/oauth2/auth",e.baseUrl);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",e.appId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("scope",e.scopes.join(",")),t.searchParams.set("state",e.state),t.toString()}function _i(e,t,r){let n=t.length>Yt,i=(n?t.slice(0,Yt):t).join(`
1
+ var ro=Object.defineProperty;var we=(e,t)=>()=>(e&&(t=e(e=0)),t);var On=(e,t)=>{for(var r in t)ro(e,r,{get:t[r],enumerable:!0})};function _r(e){return e===401?{hint:"invalid/expired token or app credentials",retriable:!1}:e===403?{hint:"permission denied or scope not granted",retriable:!1}:e===404?{hint:"resource not found",retriable:!1}:e===409?{hint:"resource state conflict",retriable:!1}:e===429?{hint:"rate limited by WPS API",retriable:!0}:e>=500?{hint:"WPS API temporarily unavailable",retriable:!0}:{hint:"unexpected WPS API status",retriable:!1}}var Fe,se,St=we(()=>{"use strict";Fe=class extends Error{detail;name="WpsRequestError";constructor(t,r){super(t),this.detail=r}get retriable(){return this.detail.retriable===!0}get stage(){return this.detail.stage}},se=class extends Error{cause;name="WpsTokenError";constructor(t,r){super(t),this.cause=r}}});function oo(e){return e===401?"invalid app credentials (check client_id/client_secret)":e===403?"app not authorized for this enterprise or scope":e===429?"rate limited by WPS token endpoint":e>=500?"WPS OAuth service unavailable":"unexpected OAuth response"}function j(e){let t=`${e.clientId}@${e.baseUrl}`,r=An.get(t);return r||(r=new Wt(e),An.set(t,r)),r}var no,io,Wt,An,fr=we(()=>{"use strict";St();no=6e4,io=["/oauth2/token","/openapi/oauth2/token"];Wt=class{creds;token=null;inFlight=null;constructor(t){this.creds=t}async getToken(){if(this.token&&Date.now()<this.token.expiresAt-no)return this.token.accessToken;if(this.inFlight)return this.inFlight;this.inFlight=this.requestToken();try{return await this.inFlight}finally{this.inFlight=null}}invalidate(){this.token=null}async requestToken(){let t=this.creds.baseUrl.replace(/\/$/,""),r="unknown token error";for(let n of io){let o=`${t}${n}`,i;try{i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.creds.clientId,client_secret:this.creds.clientSecret})})}catch(a){r=`Network error requesting token from ${o}: ${String(a)}`;continue}if(!i.ok){let a=await i.text();r=`Token request failed (${i.status}) at ${o}: ${oo(i.status)}; body=${a}`;continue}let s=await i.json();if(s.code!==void 0&&s.code!==0){r=`WPS OAuth error (code ${s.code}): ${s.msg??"unknown"}`;continue}if(!s.access_token||!s.expires_in){r=`Invalid token response from ${o}: missing access_token or expires_in`;continue}return this.token={accessToken:s.access_token,expiresAt:Date.now()+s.expires_in*1e3},this.token.accessToken}throw new se(r)}},An=new Map});import{z as x}from"zod";function Lt(e){return zt}function gr(e){let t=e?.defaultAccountId?.trim();if(t)return t;let r=e?.accounts?Object.keys(e.accounts)[0]:void 0;return r&&r.trim()?r:Ce}function yr(e){return e?e.accounts&&Object.keys(e.accounts).length>0?e.accounts:!(e.appId||e.appSecret||e.companyId||e.webhook||e.sdk||e.groups||e.dmPolicy||e.groupPolicy)?{}:!e.appId||!e.appSecret?{}:{[Ce]:{enabled:e.enabled??!0,appId:e.appId,appSecret:e.appSecret,companyId:e.companyId,baseUrl:e.baseUrl??"https://openapi.wps.cn",enableEncryption:e.enableEncryption??!0,webhook:e.webhook,sdk:e.sdk,dmPolicy:e.dmPolicy,allowFrom:e.allowFrom,groupPolicy:e.groupPolicy,groups:e.groups,instantAck:e.instantAck,robotJoinGroupMessage:e.robotJoinGroupMessage,mcp:e.mcp}}:{}}function _e(e){return!e?.appId||!e?.appSecret?null:{clientId:e.appId,clientSecret:e.appSecret,baseUrl:e.baseUrl??"https://openapi.wps.cn"}}var Rn,$n,qn,Cn,Dn,Nn,zt,mr,hr,E,be,Ce,rt=we(()=>{"use strict";Rn=x.enum(["disabled","open","allowlist","pairing"]).default("pairing"),$n=x.object({requireMention:x.boolean().optional(),toolPolicy:x.enum(["full","limited","none"]).optional()}).passthrough(),qn=x.object({enabled:x.boolean().default(!1),mode:x.literal("app").default("app"),clientId:x.string().optional(),clientSecret:x.string().optional(),baseUrl:x.string().optional(),toolAllowlist:x.array(x.string()).min(1,"mcp.toolAllowlist must contain at least one tool").default(["wps_user_search","wps_user_get","wps_message_send","wps_calendar_create","wps_calendar_list_events","wps_calendar_search_events","wps_calendar_update_event","wps_calendar_delete_event","wps_calendar_get_event","wps_calendar_list_event_attendees","wps_calendar_add_event_attendees","wps_calendar_list_event_meeting_rooms","wps_calendar_event_meeting_rooms_batch_create","wps_calendar_event_meeting_rooms_batch_delete","wps_calendar_delete_event_attendees","wps_calendar_list_calendar_event_instances","wps_calendar_list_event_instances","wps_calendar_respond_invitation","wps_todo_create_personal_task","wps_todo_list_personal_tasks","wps_todo_get_personal_task","wps_todo_update_personal_task","wps_todo_update_personal_task_status","wps_cloud_doc_list_drives","wps_cloud_doc_list_children_files","wps_cloud_doc_create_file","wps_cloud_doc_upload_file","wps_cloud_doc_extract_file_content","wps_cloud_doc_get_file_meta","wps_cloud_doc_search_files","wps_airpage_create_file","wps_airpage_create_block_content","wps_airpage_query_document_blocks","wps_airpage_batch_query_document_blocks","wps_airpage_delete_block_content","wps_airpage_batch_delete_block_content","wps_airpage_update_document_block","wps_airpage_batch_update_document_blocks","wps_meeting_rooms_list","wps_meeting_rooms_get","wps_meeting_rooms_search","wps_meeting_room_bookings_batch_get","wps_meeting_room_bookings_update_status"])}),Cn=x.object({enabled:x.boolean().default(!0),text:x.string().default("\u5185\u5BB9\u5904\u7406\u4E2D\uFF0C\u8BF7\u7A0D\u5019...")}),Dn=x.object({enabled:x.boolean().default(!1),logLevel:x.enum(["debug","info","warn","error"]).default("info"),endpoint:x.string().optional(),connectTimeoutMs:x.number().min(3e3).max(12e4).default(2e4),pongTimeout:x.number().min(3e4).max(3e5).default(15e4),autoReconnect:x.boolean().default(!0),reconnectBaseInterval:x.number().min(500).max(1e4).default(1e3),reconnectMaxInterval:x.number().min(1e4).max(3e5).default(6e4),reconnectMultiplier:x.number().min(1.5).max(3).default(2),reconnectMaxRetry:x.number().min(-1).max(100).default(-1),reconnectJitter:x.number().min(0).max(.5).default(.2)}),Nn=x.object({path:x.string().default("/wps/webhook"),port:x.number().default(3e3)}),zt="https://o.wpsgo.com/app/41000207/El1ykTHO5aVv/",mr=x.object({enabled:x.boolean().default(!0),appId:x.string().describe("WPS App ID (client_id)"),appSecret:x.string().describe("WPS App Secret (client_secret)"),companyId:x.string().optional().describe("WPS Company ID"),baseUrl:x.string().default("https://openapi.wps.cn"),enableEncryption:x.boolean().default(!0),webhook:Nn.optional(),sdk:Dn.optional(),dmPolicy:Rn.optional(),allowFrom:x.array(x.string()).optional(),groupPolicy:x.enum(["open","allowlist"]).optional(),groups:x.record(x.string(),$n).optional(),instantAck:Cn.optional(),robotJoinGroupMessage:x.string().optional(),mcp:qn.optional()}),hr=mr.partial().extend({defaultAccountId:x.string().optional(),accounts:x.record(x.string(),mr).optional()});E="wps-xiezuo",be="wps-xiezuo",Ce="default"});function wr(e){xt=e}function br(e,t){nt.set(e,t),jn(e,t)}function vt(e){let t=nt.get(e);return t?Date.now()>=t.expiresAt?(nt.delete(e),Un(e),null):t.accessToken:null}function Un(e){let t=Bt.get(e);t&&(clearTimeout(t),Bt.delete(e))}function jn(e,t){if(Un(e),!t.refreshToken)return;let r=Math.max(t.expiresAt-Date.now()-so,1e4),n=setTimeout(()=>{ao(e).catch(()=>{nt.delete(e),Bt.delete(e)})},r);n.unref?.(),Bt.set(e,n)}async function ao(e){let t=nt.get(e);if(!t?.refreshToken||!xt)return;let r=xt.baseUrl.replace(/\/$/,""),n=new URLSearchParams({grant_type:"refresh_token",client_id:xt.appId,client_secret:xt.appSecret,refresh_token:t.refreshToken}),o=await fetch(`${r}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()}),i=await o.text(),s;try{s=JSON.parse(i)}catch{throw new se(`OAuth refresh: non-JSON response (${o.status}): ${i.slice(0,200)}`)}if(!o.ok||typeof s.code=="number"&&s.code!==0)throw new se(`OAuth refresh failed (${o.status}): ${JSON.stringify(s)}`);let a=typeof s.access_token=="string"?s.access_token:"";if(!a)throw new se(`OAuth refresh: missing access_token: ${JSON.stringify(s)}`);let d=typeof s.expires_in=="number"?s.expires_in:7200,l={accessToken:a,refreshToken:typeof s.refresh_token=="string"?s.refresh_token:t.refreshToken,expiresAt:Date.now()+d*1e3,openid:typeof s.openid=="string"?s.openid:t.openid};nt.set(e,l),jn(e,l)}async function Ir(e){let t=e.baseUrl.replace(/\/$/,""),r=new URLSearchParams({grant_type:"authorization_code",client_id:e.appId,client_secret:e.appSecret,code:e.code,redirect_uri:e.redirectUri??zt}),n=await fetch(`${t}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()}),o=await n.text(),i;try{i=JSON.parse(o)}catch{throw new se(`OAuth code exchange: non-JSON response (${n.status}): ${o.slice(0,200)}`)}if(!n.ok||typeof i.code=="number"&&i.code!==0)throw new se(`OAuth code exchange failed (${n.status}): ${JSON.stringify(i)}`);let s=typeof i.access_token=="string"?i.access_token:"";if(!s)throw new se(`OAuth code exchange: missing access_token in response: ${JSON.stringify(i)}`);let a=typeof i.expires_in=="number"?i.expires_in:7200;return{accessToken:s,refreshToken:typeof i.refresh_token=="string"?i.refresh_token:"",expiresAt:Date.now()+a*1e3,openid:typeof i.openid=="string"?i.openid:""}}var nt,Bt,so,xt,it=we(()=>{"use strict";St();rt();nt=new Map,Bt=new Map,so=5*6e4,xt=null});function W(e,t){return new Tt(e,new Ft(t))}function kr(e,t){return new Tt(e,new Gt(t))}var Ft,Gt,Tt,Kt=we(()=>{"use strict";St();Ft=class{tokenStore;constructor(t){this.tokenStore=t}async getHeaders(){return{Authorization:`Bearer ${await this.tokenStore.getToken()}`}}},Gt=class{accessToken;constructor(t){this.accessToken=t}async getHeaders(){return{Authorization:`Bearer ${this.accessToken}`}}},Tt=class{baseUrl;auth;constructor(t,r){this.baseUrl=t,this.auth=r}async request(t){let r=await this.auth.getHeaders(),n=this.buildUrl(t.path,t.query),o=t.method??"GET",i=await fetch(n,{method:o,headers:{"Content-Type":"application/json",...r,...t.headers??{}},body:t.body?JSON.stringify(t.body):void 0}),s=i.headers.get("X-Request-Id")??i.headers.get("x-request-id")??i.headers.get("X-Trace-Id")??i.headers.get("x-trace-id")??void 0;if(!i.ok){let a=await i.text(),d;try{let u=JSON.parse(a);d=u.code??u.result}catch{}let{hint:l,retriable:c}=_r(i.status),p=s?` request_id=${s}`:"";throw console.error(`[WPS-API-ERROR] ${i.status} ${o} ${t.path}${p} body=${a}`),new Fe(`WPS API error (${i.status} ${o} ${t.path}): ${a}`,{stage:"http",method:o,path:t.path,httpStatus:i.status,wpsCode:d,hint:l,retriable:c,requestId:s})}return this.parseResponse(i,o,t.path,s)}buildUrl(t,r){let n=new URL(t,this.baseUrl);if(r){for(let[o,i]of Object.entries(r))if(i!==void 0)if(Array.isArray(i))for(let s of i)n.searchParams.append(o,s);else n.searchParams.set(o,String(i))}return n.toString()}async parseResponse(t,r,n,o){let i=await t.text();if(!i||i.trim()==="")return{};let s;try{s=JSON.parse(i)}catch{throw new Fe(`Failed to parse JSON from ${r} ${n}: ${i.slice(0,200)}`,{stage:"parse",method:r,path:n,hint:"response is not valid JSON",retriable:!1})}let a=s.code??s.result;if(a!==void 0&&a!==0&&a!=="ok"){let d=String(a)==="40300001"?"permission denied by WPS business policy":"WPS business validation failed",l=s.request_id??o,c=l?` request_id=${String(l)}`:"";throw console.error(`[WPS-API-ERROR] biz_code=${String(a)} ${r} ${n}${c} msg=${s.msg??s.message??"unknown"}`),new Fe(`WPS business error code=${String(a)}: ${s.msg??s.message??"unknown"}`,{stage:"business",method:r,path:n,wpsCode:a,hint:d,retriable:!1,requestId:l?String(l):void 0})}return s}}});import{imageSize as co}from"image-size";function Et(e,t=0){if(!e||typeof e!="object"||t>2)return null;let r=e;for(let n of lo){let o=r[n];if(typeof o=="string"&&o.trim())return o.trim()}return r.data&&typeof r.data=="object"?Et(r.data,t+1):null}function Sr(e){let t=Et(e);if(!t)throw new Error("cannot resolve download URL from WPS API response");return t}function Ge(e){try{let t=co(Buffer.isBuffer(e)?e:Buffer.from(e));return t.width&&t.height?{width:t.width,height:t.height}:null}catch{return null}}var lo,Pt=we(()=>{"use strict";lo=["url","download_url","downloadUrl","file_url","fileUrl"]});async function vr(e,t,r){let n=j(e);await W(e.baseUrl,n).request({method:"POST",path:`/v7/chats/${encodeURIComponent(t)}/messages/${encodeURIComponent(r)}/reactions/create`,body:{reaction_type:xr}})}async function Tr(e,t,r,n){try{let o=j(e);await W(e.baseUrl,o).request({method:"POST",path:`/v7/chats/${encodeURIComponent(t)}/messages/${encodeURIComponent(r)}/reactions/delete`,body:{reaction_type:xr}})}catch(o){let i=String(o);i.includes("msgRecalled")||i.includes("message_not_found")||i.includes("404")?(n?.info??console.log)(`WPS thinking reaction cleanup skipped (message gone): ${i.substring(0,100)}`):(n?.error??console.error)(`WPS thinking reaction cleanup failed: ${i}`)}}var xr,Er=we(()=>{"use strict";fr();Kt();xr="emoji_busy"});var Ot=we(()=>{"use strict";St();fr();it();Kt();Pt();Er();rt()});var ci={};On(ci,{getDelegatedScopes:()=>qt,getLazyClient:()=>Kr,getLazyCreds:()=>Vt,getLazyLog:()=>dt,getLazyWpsCfg:()=>Hr,setDelegatedScopes:()=>Yt,setLazyClient:()=>Gr});function Gr(e,t,r,n){Lr=e,ai=t??null,Br=r??null,Fr=n??null}function Kr(){if(!Lr)throw new Error("WPS client not initialized yet (startAccount has not been called)");return Lr}function dt(){return ai}function Hr(){if(!Br)throw new Error("WPS config not set yet (startAccount has not been called)");return Br}function Vt(){if(!Fr)throw new Error("WPS credentials not set yet (startAccount has not been called)");return Fr}function Yt(e){di=e}function qt(){return di}var Lr,ai,Br,Fr,di,ct=we(()=>{"use strict";Lr=null,ai=null,Br=null,Fr=null;di=[]});var Vr={};On(Vr,{buildAuthCard:()=>_i,buildAuthSuccessCard:()=>fi,buildAuthorizeUrl:()=>ui,decodeState:()=>pi,encodeState:()=>li,handleAuthEvent:()=>Ko,sendAuthCard:()=>Xr});import{randomBytes as Bo}from"node:crypto";function li(e){let t=Bo(16).toString("hex");e.nonce=t;let r=t;return Ct.set(r,e),setTimeout(()=>Ct.delete(r),10*6e4).unref?.(),r}function pi(e){let t=Ct.get(e);return t&&Ct.delete(e),t??null}function ui(e){let t=new URL("/oauth2/auth",e.baseUrl);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",e.appId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("scope",e.scopes.join(",")),t.searchParams.set("state",e.state),t.toString()}function _i(e,t,r){let n=t.length>Zt,i=(n?t.slice(0,Zt):t).join(`
2
2
  `)+(n?`
3
3
  ... \u7B49\u5171 ${t.length} \u9879\u6743\u9650`:""),s=r?.totalScopes??t.length,a=r&&r.totalParts>1?`\uFF08\u7B2C ${r.partIndex}/${r.totalParts} \u7EC4\uFF0C\u672C\u7EC4 ${t.length} \u9879\uFF09`:"",d=r&&r.totalParts>1?`\u8BF7\u6388\u6743\u4EE5\u65B9\u4FBF\u7EE7\u7EED\u64CD\u4F5C\uFF08${r.partIndex}/${r.totalParts}\uFF09`:"\u8BF7\u6388\u6743\u4EE5\u65B9\u4FBF\u7EE7\u7EED\u64CD\u4F5C";return{card:{i18n_items:[{key:"zh-CN",value:{elements:[{text:{tag:"text",text:{content:`\u5E94\u7528\u9700\u8981\u6388\u6743 ${s} \u4E2A\u7528\u6237\u6743\u9650${a}\u3002`,text_align:"left",text_size:"small",type:"markdown"}}},{text:{tag:"text",text:{content:`**\u5C06\u8981\u6388\u6743\u7684\u6743\u9650\uFF1A**
4
4
 
5
5
  ${i}
6
6
  `,text_align:"left",text_size:"small",type:"markdown"}}},{action:{actions:[{button:{disabled_tips:{content:"",type:"plain"},hover_tips:{content:"",type:"plain"},link:{url:e,pc_url:e,web_url:e,android_url:e,ios_url:e,harmony_url:e},margin:"0px 0px 0px 0px",style:"normal",tag:"button",text:{content:"\u524D\u5F80\u6388\u6743",type:"plain"}}}],layout:"exclusive_row",tag:"action"}},{text:{tag:"text",text:{content:`<font color='gray'>\u6388\u6743\u94FE\u63A5\u4EC5\u53EF\u4F7F\u7528\u4E00\u6B21\uFF0C10\u5206\u949F\u5185\u672A\u4F7F\u7528\u5C06\u81EA\u52A8\u8FC7\u671F</font>
7
- `,text_align:"left",text_size:"small",type:"markdown"}}}],header:{subtitle:{tag:"text",text:{content:"",type:"plain"}},template:"blue",title:{tag:"text",text:{content:d,type:"plain"}}}}}]}}}function Fo(e){if(e.length===0)return[[]];if(e.length<=Hr)return[e];let t=[];for(let r=0;r<e.length;r+=Hr)t.push(e.slice(r,r+Hr));return t}function fi(e){let t=e.length>Yt;return{card:{i18n_items:[{key:"zh-CN",value:{elements:[{text:{tag:"text",text:{content:`**\u5DF2\u5B8C\u6210\u4EE5\u4E0B\u6743\u9650\u6388\u6743\uFF1A**
7
+ `,text_align:"left",text_size:"small",type:"markdown"}}}],header:{subtitle:{tag:"text",text:{content:"",type:"plain"}},template:"blue",title:{tag:"text",text:{content:d,type:"plain"}}}}}]}}}function Fo(e){if(e.length===0)return[[]];if(e.length<=Jr)return[e];let t=[];for(let r=0;r<e.length;r+=Jr)t.push(e.slice(r,r+Jr));return t}function fi(e){let t=e.length>Zt;return{card:{i18n_items:[{key:"zh-CN",value:{elements:[{text:{tag:"text",text:{content:`**\u5DF2\u5B8C\u6210\u4EE5\u4E0B\u6743\u9650\u6388\u6743\uFF1A**
8
8
 
9
- ${(t?e.slice(0,Yt):e).join(`
9
+ ${(t?e.slice(0,Zt):e).join(`
10
10
  `)+(t?`
11
11
  ... \u7B49\u5171 ${e.length} \u9879\u6743\u9650`:"")}
12
- `,text_align:"left",text_size:"small",type:"markdown"}}},{action:{actions:[{button:{disabled_tips:{content:"",type:"plain"},hover_tips:{content:"",type:"plain"},margin:"0px 0px 0px 0px",style:"disable",tag:"button",text:{content:"\u5DF2\u6388\u6743",type:"plain"}}}],layout:"exclusive_row",tag:"action"}}],header:{subtitle:{tag:"text",text:{content:"",type:"plain"}},template:"green",title:{tag:"text",text:{content:"\u6388\u6743\u5DF2\u5B8C\u6210",type:"plain"}}}}}]}}}async function Jr(e){let t;if(e.scopes&&e.scopes.names.length>0){let d=$t(),l=new Set(d.map(p=>p.name)),c=e.scopes.names.filter(p=>!l.has(p));c.length>0&&d.length>0&&at()?.warn?.(`[OAuth] Requested scopes not in delegated list: ${c.join(", ")}. \u9700\u5728\u5F00\u653E\u5E73\u53F0\u540E\u53F0\u5F00\u901A\u5BF9\u5E94\u80FD\u529B\u6743\u9650\u3002`),t=e.scopes.names}else{let d=$t();if(d.length===0)return at()?.error?.("[OAuth] No delegated scopes available. \u5E94\u7528\u672A\u914D\u7F6E delegated \u6743\u9650\uFF0C\u8BF7\u5728\u5F00\u653E\u5E73\u53F0\u540E\u53F0\u5F00\u901A\u3002"),null;t=d.map(l=>l.name)}let r=zt(e.wpsCfg),n=j(e.creds),o=W(e.creds.baseUrl,n),i=e.wpsCfg.baseUrl??"https://openapi.wps.cn",s=Fo(t),a=null;for(let d=0;d<s.length;d+=1){let l=s[d],c=li({wpsUserId:e.wpsUserId,receiverType:e.receiverType,receiverId:e.receiverId,nonce:"",originalMessage:e.originalMessage,requestedScopeNames:[...l]}),p=ui({baseUrl:i,appId:e.creds.clientId,scopes:l,state:c,redirectUri:r}),u=_i(p,l,{partIndex:d+1,totalParts:s.length,totalScopes:t.length}),_={type:"card",receiver:{type:e.receiverType,receiver_id:e.receiverId},content:u},y=(await o.request({method:"POST",path:"/v7/messages/create",body:_})).data?.message_id??"",h=qt.get(c);h&&(h.messageId=y),a||(a={messageId:y,authorizeUrl:p})}return a}async function Go(e,t,r,n){if(t)try{let o=j(e),i=W(e.baseUrl,o),s=fi(r);await i.request({method:"POST",path:`/v7/messages/${encodeURIComponent(t)}/update`,body:{type:"card",content:s}})}catch(o){n?.warn?.(`Failed to update auth card: ${String(o)}`)}}async function Ko(e){let{code:t,creds:r,log:n}=e,o=e.state?pi(e.state):null,i=o?.wpsUserId??e.userId??"";if(!i){n?.warn?.(`[OAuth] Cannot determine user: state=${e.state}, userId=${e.userId}`);return}n?.info?.(`[OAuth] Auth event for user=${i}, code=${t.slice(0,8)}..., hasState=${!!o}`);let s=zt(e.wpsCfg),a=await br({appId:r.clientId,appSecret:r.clientSecret,baseUrl:r.baseUrl,code:t,redirectUri:s});if(wr(i,a),n?.info?.(`[OAuth] Token exchange success for user=${i}, openid=${a.openid}, expiresAt=${new Date(a.expiresAt).toISOString()}, hasRefresh=${!!a.refreshToken}`),o?.messageId){let d=o.requestedScopeNames&&o.requestedScopeNames.length>0?o.requestedScopeNames.filter(l=>l.length>0):$t().map(l=>l.name).filter(l=>l.length>0);await Go(r,o.messageId,d,n)}}var qt,Yt,Hr,Zt=we(()=>{"use strict";nt();Pt();dt();tt();qt=new Map;Yt=6;Hr=25});Pt();var Ie=null;(async()=>{try{Ie=await import("openclaw/plugin-sdk"),console.log("[sdk-helpers] openclaw/plugin-sdk \u52A0\u8F7D\u6210\u529F")}catch(e){Ie=null,console.log("[sdk-helpers] openclaw/plugin-sdk \u52A0\u8F7D\u5931\u8D25\uFF0C\u4F7F\u7528 fallback:",e instanceof Error?e.message:String(e))}})();function Mn(){return typeof Ie?.emptyPluginConfigSchema=="function"?Ie.emptyPluginConfigSchema():{type:"object",additionalProperties:!1,properties:{}}}function Wn(e){return typeof Ie?.buildChannelConfigSchema=="function"?Ie.buildChannelConfigSchema(e):e}function zn(e){return typeof Ie?.formatPairingApproveHint=="function"?Ie.formatPairingApproveHint(e):`Run pairing approval command for channel '${e}'.`}function Ln(e,t){return typeof Ie?.waitUntilAbort=="function"?Ie.waitUntilAbort(e,t):new Promise(r=>{let n=()=>{e.removeEventListener("abort",n),t().finally(r)};if(e.aborted){n();return}e.addEventListener("abort",n,{once:!0})})}Pt();import{existsSync as cs,readFileSync as ls}from"node:fs";import{readFile as bi}from"node:fs/promises";import{homedir as ps}from"node:os";import er from"node:path";var Kt="kso.app_chat.message";import*as it from"node:crypto";function Bn(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.encrypted_data=="string"&&typeof t.nonce=="string"&&typeof t.signature=="string"&&typeof t.topic=="string"&&typeof t.time=="number"}function Fn(e){let t=`${e.appId}:${e.topic}:${e.nonce}:${e.time}:${e.encryptedData}`,r=it.createHmac("sha256",e.appSecret);return r.update(t),r.digest("base64url").replace(/=+$/,"")===e.signature}function Gn(e,t,r){let n=it.createHash("md5").update(t).digest("hex"),o=Buffer.from(n,"utf-8"),i=Buffer.from(r,"utf-8").subarray(0,16),s=Buffer.from(e,"base64"),a=it.createDecipheriv("aes-256-cbc",o,i),d=a.update(s);return d=Buffer.concat([d,a.final()]),d.toString("utf-8")}function k(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function Q(...e){for(let t of e){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()){let r=Number(t);if(Number.isFinite(r))return r}}}function Pr(e){return{kind:"image",storageKey:k(e.storage_key),name:k(e.name),mimeType:k(e.type),size:Q(e.size),width:Q(e.width),height:Q(e.height),thumbnailStorageKey:k(e.thumbnail_storage_key)}}var po=["elements","paragraphs","blocks","fragments","items","body","children","nodes"];function Er(e){for(let t of po){let r=e[t];if(Array.isArray(r)&&r.length>0)return r}return null}function Kn(e){let t=e.rich_text;if(t&&typeof t=="object"){let n=t,o=Er(n);if(o)return o;if(Array.isArray(n.elements))return n.elements}let r=Er(e);return r||(Array.isArray(e.elements)?e.elements:null)}function Or(e){let t=[],r=[],n=[],o=(i,s)=>{if(s>12||i==null||typeof i!="object")return;if(Array.isArray(i)){for(let f of i)o(f,s+1);return}let a=i,d=typeof a.type=="string"?a.type.toLowerCase():"",l=a.text_content;if(l&&typeof l=="object"){let f=l.content;typeof f=="string"&&f.trim()!==""&&r.push(f);let g=typeof f=="string"?k(f):"";g&&t.push(g)}let c=a.style_text_content;if(c&&typeof c=="object"){let f=c.text,g=typeof f=="string"?k(f):"";g&&t.push(g),typeof f=="string"&&f.trim()!==""&&r.push(f)}let p=a.mention_content;if(p&&typeof p=="object"){let f=p.text,g=typeof f=="string"?k(f):"";g&&t.push(g),typeof f=="string"&&f.trim()!==""&&r.push(f)}let u=a.link_content;if(u&&typeof u=="object"){let f=u,g=f.text,w=f.url,b=typeof g=="string"&&g.trim()!==""?g.trim():"",I=typeof w=="string"&&w.trim()!==""?w.trim():"";b&&t.push(b),b&&I?r.push(`[${b}](${I})`):b?r.push(b):I&&r.push(I)}let _=a.doc_content;if(_&&typeof _=="object"){let f=_,g=f.file;if(g&&typeof g=="object"){let w=k(g.link_url,f.link_url),b=k(g.link_id,f.link_id);n.push({kind:"file",name:k(f.text,a.alt_text),fileId:k(g.id),cloudType:!0,cloudLinkUrl:w||void 0,cloudLinkId:b||void 0})}if(d==="doc"){let w=typeof f.text=="string"?f.text.trim():"\u6587\u6863",b=f.file?.link_url,I=(typeof f.link_url=="string"?f.link_url.trim():"")||(typeof b=="string"?b.trim():"")||"";w&&t.push(w),I?r.push(`[${w}](${I})`):w&&r.push(w)}}let m=a.image_content;if(m&&typeof m=="object"){let f=m,g=typeof f.storage_key=="string"?f.storage_key.trim():"";if(g&&(n.push(Pr(f)),d==="image"||d==="custom_emoji")){let w=typeof f.name=="string"?f.name.trim():"\u56FE\u7247";r.push(`![${w}](storage_key:${g})`)}}if(!(l&&typeof l=="object"||c&&typeof c=="object"||p&&typeof p=="object"||u&&typeof u=="object"||m&&typeof m=="object"||_&&typeof _=="object")&&d!=="nl"&&d!=="ol"&&d!=="ul"){let f=k(a.alt_text);f&&t.push(f)}if(Array.isArray(a.elements))for(let f of a.elements)o(f,s+1);let h=a.runs;if(Array.isArray(h))for(let f of h)o(f,s+1);for(let f of["inline_entities","segments","inlines","spans"]){let g=a[f];if(Array.isArray(g))for(let w of g)o(w,s+1)}};for(let i of e)o(i,0);return{plainTextLines:t,markdownLines:r,attachments:n}}function uo(e){if(!e||typeof e!="object")return null;let t=e,r=Er(t);if(r)return r;let n=t.elements;return Array.isArray(n)?n:null}function Hn(e){let t=uo(e);return t?Or(t).markdownLines:[]}function Jn(e){let t=Kn(e);if(!t)return null;let r=Or(t);return{plainText:r.plainTextLines.join(`
13
- `).trim(),attachments:r.attachments}}function Ar(e){if(typeof e=="string"){let i=e.trim();if(i.startsWith("{"))try{let s=JSON.parse(i);if(s&&typeof s=="object"&&!Array.isArray(s))return Ar(s)}catch{}return i}if(!e||typeof e!="object")return"";let t=e,r=t.text,n="";if(typeof r=="string")n=r.trim();else if(r&&typeof r=="object"&&"content"in r){let i=r.content;typeof i=="string"?n=i.trim():typeof i=="number"&&Number.isFinite(i)&&(n=String(i))}if(n)return n;let o=Kn(t);if(o){let{plainTextLines:i}=Or(o),s=i.join(`
14
- `).trim();if(s)return s}return""}function $r(e){return typeof e=="string"&&e.trim()!==""&&e!==Kt}function Ge(e){return e&&typeof e=="object"?e:{}}function Rr(...e){for(let t of e){if(typeof t=="string"&&t.trim())return t.trim();if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function _o(e){let t=e.content;if(!t||typeof t!="object")return{};let r=t,n=r.text;if(n&&typeof n=="object"&&n!==null&&"content"in n){let a=n.content;if((typeof a=="string"?a.trim():typeof a=="number"&&Number.isFinite(a)?String(a):"")!=="")return r}if(typeof r.text=="string")return{text:{content:r.text,type:"plain"}};let o=r.image;if(o?.file_id)return{image:{storage_key:o.file_id}};let i=r.file;if(i&&typeof i=="object"){let a=typeof i.type=="string"?i.type:"",d=i.cloud;if((a==="cloud"||d)&&d&&typeof d=="object")return{file:{type:"cloud",cloud:d}};let l=i.file_id;if(l)return{file:{type:"local",local:{storage_key:l,name:i.name??"file"}}};let c=i.local;if(c&&typeof c=="object")return{file:{type:"local",local:c}}}let s=r.rich_text;if(s&&typeof s=="object"){let a=Hn(s);if(a.length>0)return{text:{content:a.join(`
15
- `),type:"markdown"}}}return r}function fo(e){if(!Array.isArray(e))return;let t=e.map(r=>Ge(r)).map(r=>{let n=Ge(r.identity),o={id:typeof n.id=="string"?n.id:void 0,app_id:typeof n.app_id=="string"?n.app_id:void 0,name:typeof n.name=="string"?n.name:void 0,type:typeof n.type=="string"?n.type:void 0,company_id:typeof n.company_id=="string"?n.company_id:void 0},i=Object.values(o).some(s=>s!==void 0);return{type:typeof r.type=="string"?r.type:void 0,id:typeof r.id=="string"?r.id:void 0,user_id:typeof r.user_id=="string"?r.user_id:void 0,userId:typeof r.userId=="string"?r.userId:void 0,offset:typeof r.offset=="number"?r.offset:void 0,length:typeof r.length=="number"?r.length:void 0,...i?{identity:o}:{}}}).filter(r=>!!(r.id||r.user_id||r.userId||r.type||r.identity));return t.length>0?t:void 0}function mo(e){let t=Ge(e),r=Ge(t.sender),n=typeof t.sender_id=="string"?t.sender_id:void 0,o=typeof r.id=="string"?r.id:void 0;if(!(!n&&!o))return{sender_id:n,sender:o?{id:o}:void 0}}function Xn(e){let t=Ge(e),r=Ge(e.message),n=e.send_time<1e12?Math.floor(e.send_time*1e3):e.send_time,o=String(e.chat.id),i=String(e.message.id),s=String(e.sender.id);return{topic:typeof t.topic=="string"?t.topic:Kt,event_id:Rr(t.event_id,t.id,i)||void 0,company_id:Rr(t.company_id,t.companyId,t.corp_id)||void 0,chat:{id:o,type:e.chat.type},message:{id:i,type:e.message.type,content:_o(e.message),sender:{id:s,type:e.sender.type},mentions:fo(r.mentions),reply_to:mo(r.reply_to)},quote_msg_id:Rr(t.quote_msg_id,t.quote_message_id,typeof r.quote_msg_id=="string"?r.quote_msg_id:void 0)||void 0,sender:{id:s,type:e.sender.type,name:e.sender.extended_attribute?.name},send_time:n}}function Vn(e,t,r,n){let o=Ge(e);if(typeof o.challenge=="string")return n?.info?.("WPS webhook challenge verification"),{challenge:o.challenge};if(r&&Bn(e)){let s=e;if(s.topic!==Kt)return n?.info?.(`WPS webhook skip non-message topic=${s.topic}`),{ok:!1,error:"skip",status:200};if(!Fn({appId:t.appId,appSecret:t.appSecret,topic:s.topic,nonce:s.nonce,time:s.time,encryptedData:s.encrypted_data,signature:s.signature}))return n?.error?.("WPS signature verification failed"),{ok:!1,error:"Invalid signature",status:403};try{let d=Gn(s.encrypted_data,t.appSecret,s.nonce),l=JSON.parse(d);return l.topic=s.topic,l.event_id||(l.event_id=l.message?.id),n?.info?.(`WPS decrypted event: topic=${s.topic}, operation=${s.operation}`),{ok:!0,payload:l}}catch(d){return n?.error?.("WPS decryption failed:",d),{ok:!1,error:"Decryption failed",status:400}}}let i=e;return $r(i.topic)?(n?.info?.(`WPS webhook skip non-message topic=${String(i.topic)}`),{ok:!1,error:"skip",status:200}):(i.event_id||(i.event_id=i.message?.id),{ok:!0,payload:i})}function Yn(e,t){return{...e,pongTimeout:t?.pongTimeout??15e4,autoReconnect:t?.autoReconnect??!0,reconnectBaseInterval:t?.reconnectBaseInterval??1e3,reconnectMaxInterval:t?.reconnectMaxInterval??6e4,reconnectMultiplier:t?.reconnectMultiplier??2,reconnectMaxRetry:t?.reconnectMaxRetry??-1,reconnectJitter:t?.reconnectJitter??.2}}import{Client as us,Dispatcher as _s}from"open-event-sdk";tt();Pt();tt();var ae=class extends Error{code;name="SessionResolverError";constructor(t,r){super(r),this.code=t}};function fe(...e){for(let t of e){if(typeof t=="string"&&t.trim())return t.trim();if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function ve(e){return e&&typeof e=="object"?e:{}}function Zn(e){return e.trim().replace(/^wps-xiezuo:/i,"").replace(/^wps:/i,"").replace(/^user:/i,"")}function Qn(e,t){let r=Zn(e),n=Zn(t);return r.length>0&&n.length>0&&r===n}function ho(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=ve(r),o=fe(n.type).toLowerCase(),i=ve(n.identity),s=[fe(n.id,n.user_id,n.userId,n.open_id),fe(i.app_id,i.id)].filter(Boolean);for(let a of s)t.push({type:o,id:a})}return t}var Ot=class{config;idempotencyStore;constructor(t,r){this.config=t,this.idempotencyStore=r}normalizeEvent(t){let r=ve(t),n=ve(r.chat),o=ve(r.message),i=ve(r.sender),s=ve(o.sender),a=fe(r.event_id,r.eventId,o.event_id,o.eventId,o.id),d=fe(o.id,r.message_id,r.messageId,a),l=fe(r.company_id,r.companyId),c=fe(n.type).toLowerCase(),p=fe(n.id),u=fe(s.id,i.id,r.user_id,r.userId),_=Ar(o.content),m=fe(_,r.message_text,r.messageText),y=u,h;if(c==="group")h=p;else if(["p2p","single","direct"].includes(c))h=void 0;else throw new ae("E_CHAT_TYPE_INVALID",`\u672A\u77E5\u7684 chat.type: ${c||"(empty)"}`);let f=ho(o.mentions),g=f.some(Z=>Qn(Z.id,this.config.botId)),w=c==="group"&&!g&&f.length===1&&f[0]?.type!=="all",b=g||w,I=ve(o.reply_to),E=ve(I.sender),N=fe(E.id,I.sender_id,I.senderId),re=Qn(N,this.config.botId);return{event_id:a,message_id:d,company_id:l,user_id:y,group_id:h,chat_id:p||void 0,message:m,is_at_bot:b,is_reply_to_bot:re}}resolve(t){let r=t.group_id?"group":"p2p";if(!t.message_id)throw new ae("E_MESSAGE_ID_MISSING","\u7F3A\u5C11 message_id");if(!t.event_id)throw new ae("E_EVENT_ID_MISSING","\u7F3A\u5C11 event_id");if(!t.company_id)throw new ae("E_COMPANY_ID_MISSING","\u7F3A\u5C11 company_id");if(r==="group"&&!t.group_id)throw new ae("E_GROUP_ID_MISSING","\u7FA4\u804A\u6D88\u606F\u7F3A\u5C11 group_id");if(r==="p2p"&&!t.user_id)throw new ae("E_USER_ID_MISSING","\u79C1\u804A\u6D88\u606F\u7F3A\u5C11 user_id");let n=r==="group"?`${T}:${t.company_id}:acct:${this.config.accountId??"default"}:group:${t.group_id}:bot:${this.config.botId}`:`${T}:${t.company_id}:acct:${this.config.accountId??"default"}:p2p:${t.user_id}:bot:${this.config.botId}`;return{scene:r,session_key:n,idempotency_key:t.event_id,message_id:t.message_id,company_id:t.company_id,user_id:t.user_id,group_id:t.group_id,chat_id:t.chat_id}}async checkIdempotency(t){return this.idempotencyStore.check(t)}async markProcessed(t,r=36e5){await this.idempotencyStore.mark(t,r)}};var At=class{store=new Map;async check(t){let r=this.store.get(t);return r?Date.now()>r?(this.store.delete(t),!1):!0:!1}async mark(t,r){this.store.set(t,Date.now()+r)}cleanup(){let t=Date.now();for(let[r,n]of this.store.entries())t>n&&this.store.delete(r)}};function go(e){if(e==null)return{};if(typeof e=="string"){let t=e.trim();if(!t)return{};if(t.startsWith("{"))try{let r=JSON.parse(t);if(r&&typeof r=="object"&&!Array.isArray(r))return r}catch{}return{text:{content:t,type:"plain"}}}return typeof e=="object"&&!Array.isArray(e)?e:{}}var yo=new Set(["text","content","title","caption","desc","description","md","markdown","alt_text"]);function qr(e){let t=[],r=(n,o)=>{if(!(o>6||n==null)){if(typeof n=="string"){n.trim()&&t.push(n.trim());return}if(Array.isArray(n)){for(let i of n)r(i,o+1);return}if(typeof n=="object")for(let[i,s]of Object.entries(n))(yo.has(i.toLowerCase())||typeof s=="object")&&r(s,o+1)}};return r(e,0),Array.from(new Set(t))}function wo(e){let t=String(e.type??"").toLowerCase();return["image","img","pic","picture"].includes(t)?!0:!!(e.image_url??e.pic_url??e.thumb_url??e.preview_url)}function bo(e){let t=String(e.type??"").toLowerCase();return["file","attachment","doc","document"].includes(t)?!0:!!(e.file_id??e.file_name??e.mime_type??e.download_url)}function Cr(e){let t=[],r=(n,o)=>{if(o>8||n==null)return;if(Array.isArray(n)){for(let d of n)r(d,o+1);return}if(typeof n!="object")return;let i=n,s=i.image_content;if(s&&typeof s=="object"&&k(s.storage_key)){t.push(Pr(s));return}let a=i.doc_content;if(a&&typeof a=="object"){let d=a.file;if(d&&typeof d=="object"){let l=k(d.link_url,a.link_url),c=k(d.link_id,a.link_id);t.push({kind:"file",name:k(a.text,i.alt_text),fileId:k(d.id),cloudType:!0,cloudLinkUrl:l||void 0,cloudLinkId:c||void 0})}return}if(wo(i)){let d=k(i.storage_key);t.push({kind:"image",storageKey:d||void 0,name:k(i.name,i.file_name,i.title),fileId:k(i.file_id,i.id),url:k(i.image_url,i.pic_url,i.thumb_url,i.preview_url,i.url),mimeType:k(i.mime_type,i.content_type),size:Q(i.size,i.file_size)})}else if(bo(i)){let d=k(i.storage_key);t.push({kind:"file",storageKey:d||void 0,name:k(i.file_name,i.name,i.title),fileId:k(i.file_id,i.id),url:k(i.download_url,i.url,i.preview_url),mimeType:k(i.mime_type,i.content_type),size:Q(i.size,i.file_size)})}for(let d of Object.values(i))r(d,o+1)};return r(e,0),t}function Ht(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function ot(e){return e.map((t,r)=>{let n=[`#${r+1}`,t.kind==="image"?"\u56FE\u7247":"\u6587\u4EF6"];return t.cloudType&&n.push("type=cloud"),t.name&&n.push(`display_name=${t.name}`),t.storageKey&&n.push(`storage_key=${t.storageKey}`),t.mimeType&&n.push(`mime=${t.mimeType}`),t.size!==void 0&&n.push(`size=${Ht(t.size)}`),t.width!==void 0&&t.height!==void 0&&n.push(`${t.width}x${t.height}`),t.fileId&&n.push(`fileId=${t.fileId}`),t.cloudLinkId&&n.push(`link_id=${t.cloudLinkId}`),t.cloudLinkUrl&&n.push(`link_url=${t.cloudLinkUrl}`),t.url&&n.push(`url=${t.url}`),n.join(" | ")})}function Io(e){let t=e.image;return!t||typeof t!="object"?null:{kind:"image",storageKey:k(t.storage_key),name:k(t.name),mimeType:k(t.type),size:Q(t.size),width:Q(t.width),height:Q(t.height),thumbnailStorageKey:k(t.thumbnail_storage_key)}}function ko(e){let t=e.file;if(!t||typeof t!="object")return null;let r=k(t.type),n=t.cloud;if((r==="cloud"||!r&&n)&&n&&typeof n=="object")return{kind:"file",fileId:k(n.id),cloudType:!0,cloudLinkUrl:k(n.link_url),cloudLinkId:k(n.link_id),name:k(t.name,t.file_name)||void 0};let o=t.local;return o&&typeof o=="object"?{kind:"file",storageKey:k(o.storage_key),name:k(o.name),size:Q(o.size)}:{kind:"file",storageKey:k(t.storage_key),name:k(t.name,t.file_name),size:Q(t.size)}}function So(e){let t=[],r=(n,o)=>{if(o>12||n==null)return;if(typeof n=="string"){n.trim()&&t.push(n.trim());return}if(Array.isArray(n)){for(let l of n)r(l,o+1);return}if(typeof n!="object")return;let i=n,s=String(i.tag??"").toLowerCase();if(s==="hr"||s==="action"||s==="button"||s==="dropdown"||i.config)return;let a=i.text;if(a&&typeof a=="object"&&typeof a.content=="string"){let l=a.content.trim();l&&t.push(l);return}typeof a=="string"&&a.trim()&&t.push(a.trim());let d=i.title;if(d&&typeof d=="object"){let l=d.text;if(l&&typeof l=="object"&&typeof l.content=="string"){let c=l.content.trim();c&&t.push(c)}}typeof i.content=="string"&&i.content.trim()&&t.push(i.content.trim());for(let l of Object.values(i))typeof l=="object"&&r(l,o+1)};for(let n of e)r(n,0);return t}function ti(e){let t=e.card;if(!t||typeof t!="object")return null;let r=t,o=r.i18n_items?.[0]?.value,i=o?.header?.title?.text?.content??r.header?.title?.text?.content??r.header?.title?.content??"",s=o?.elements??r.elements??[],a=Array.from(new Set(So(s))),d=[];i&&d.push(`[\u5361\u7247\u6807\u9898] ${i}`),a.length>0&&d.push(a.join(`
12
+ `,text_align:"left",text_size:"small",type:"markdown"}}},{action:{actions:[{button:{disabled_tips:{content:"",type:"plain"},hover_tips:{content:"",type:"plain"},margin:"0px 0px 0px 0px",style:"disable",tag:"button",text:{content:"\u5DF2\u6388\u6743",type:"plain"}}}],layout:"exclusive_row",tag:"action"}}],header:{subtitle:{tag:"text",text:{content:"",type:"plain"}},template:"green",title:{tag:"text",text:{content:"\u6388\u6743\u5DF2\u5B8C\u6210",type:"plain"}}}}}]}}}async function Xr(e){let t;if(e.scopes&&e.scopes.names.length>0){let d=qt(),l=new Set(d.map(p=>p.name)),c=e.scopes.names.filter(p=>!l.has(p));c.length>0&&d.length>0&&dt()?.warn?.(`[OAuth] Requested scopes not in delegated list: ${c.join(", ")}. \u9700\u5728\u5F00\u653E\u5E73\u53F0\u540E\u53F0\u5F00\u901A\u5BF9\u5E94\u80FD\u529B\u6743\u9650\u3002`),t=e.scopes.names}else{let d=qt();if(d.length===0)return dt()?.error?.("[OAuth] No delegated scopes available. \u5E94\u7528\u672A\u914D\u7F6E delegated \u6743\u9650\uFF0C\u8BF7\u5728\u5F00\u653E\u5E73\u53F0\u540E\u53F0\u5F00\u901A\u3002"),null;t=d.map(l=>l.name)}let r=Lt(e.wpsCfg),n=j(e.creds),o=W(e.creds.baseUrl,n),i=e.wpsCfg.baseUrl??"https://openapi.wps.cn",s=Fo(t),a=null;for(let d=0;d<s.length;d+=1){let l=s[d],c=li({wpsUserId:e.wpsUserId,receiverType:e.receiverType,receiverId:e.receiverId,nonce:"",originalMessage:e.originalMessage,requestedScopeNames:[...l]}),p=ui({baseUrl:i,appId:e.creds.clientId,scopes:l,state:c,redirectUri:r}),u=_i(p,l,{partIndex:d+1,totalParts:s.length,totalScopes:t.length}),_={type:"card",receiver:{type:e.receiverType,receiver_id:e.receiverId},content:u},y=(await o.request({method:"POST",path:"/v7/messages/create",body:_})).data?.message_id??"",h=Ct.get(c);h&&(h.messageId=y),a||(a={messageId:y,authorizeUrl:p})}return a}async function Go(e,t,r,n){if(t)try{let o=j(e),i=W(e.baseUrl,o),s=fi(r);await i.request({method:"POST",path:`/v7/messages/${encodeURIComponent(t)}/update`,body:{type:"card",content:s}})}catch(o){n?.warn?.(`Failed to update auth card: ${String(o)}`)}}async function Ko(e){let{code:t,creds:r,log:n}=e,o=e.state?pi(e.state):null,i=o?.wpsUserId??e.userId??"";if(!i){n?.warn?.(`[OAuth] Cannot determine user: state=${e.state}, userId=${e.userId}`);return}n?.info?.(`[OAuth] Auth event for user=${i}, code=${t.slice(0,8)}..., hasState=${!!o}`);let s=Lt(e.wpsCfg),a=await Ir({appId:r.clientId,appSecret:r.clientSecret,baseUrl:r.baseUrl,code:t,redirectUri:s});if(br(i,a),n?.info?.(`[OAuth] Token exchange success for user=${i}, openid=${a.openid}, expiresAt=${new Date(a.expiresAt).toISOString()}, hasRefresh=${!!a.refreshToken}`),o?.messageId){let d=o.requestedScopeNames&&o.requestedScopeNames.length>0?o.requestedScopeNames.filter(l=>l.length>0):qt().map(l=>l.name).filter(l=>l.length>0);await Go(r,o.messageId,d,n)}}var Ct,Zt,Jr,Qt=we(()=>{"use strict";it();Ot();ct();rt();Ct=new Map;Zt=6;Jr=25});Ot();var Ie=null;(async()=>{try{Ie=await import("openclaw/plugin-sdk"),console.log("[sdk-helpers] openclaw/plugin-sdk \u52A0\u8F7D\u6210\u529F")}catch(e){Ie=null,console.log("[sdk-helpers] openclaw/plugin-sdk \u52A0\u8F7D\u5931\u8D25\uFF0C\u4F7F\u7528 fallback:",e instanceof Error?e.message:String(e))}})();function Mn(){return typeof Ie?.emptyPluginConfigSchema=="function"?Ie.emptyPluginConfigSchema():{type:"object",additionalProperties:!1,properties:{}}}function Wn(e){return typeof Ie?.buildChannelConfigSchema=="function"?Ie.buildChannelConfigSchema(e):e}function zn(e){return typeof Ie?.formatPairingApproveHint=="function"?Ie.formatPairingApproveHint(e):`Run pairing approval command for channel '${e}'.`}function Ln(e,t){return typeof Ie?.waitUntilAbort=="function"?Ie.waitUntilAbort(e,t):new Promise(r=>{let n=()=>{e.removeEventListener("abort",n),t().finally(r)};if(e.aborted){n();return}e.addEventListener("abort",n,{once:!0})})}Ot();import{existsSync as cs,readFileSync as ls}from"node:fs";import{readFile as bi}from"node:fs/promises";import{homedir as ps}from"node:os";import tr from"node:path";var Ht="kso.app_chat.message";import*as ot from"node:crypto";function Bn(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.encrypted_data=="string"&&typeof t.nonce=="string"&&typeof t.signature=="string"&&typeof t.topic=="string"&&typeof t.time=="number"}function Fn(e){let t=`${e.appId}:${e.topic}:${e.nonce}:${e.time}:${e.encryptedData}`,r=ot.createHmac("sha256",e.appSecret);return r.update(t),r.digest("base64url").replace(/=+$/,"")===e.signature}function Gn(e,t,r){let n=ot.createHash("md5").update(t).digest("hex"),o=Buffer.from(n,"utf-8"),i=Buffer.from(r,"utf-8").subarray(0,16),s=Buffer.from(e,"base64"),a=ot.createDecipheriv("aes-256-cbc",o,i),d=a.update(s);return d=Buffer.concat([d,a.final()]),d.toString("utf-8")}function k(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function te(...e){for(let t of e){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()){let r=Number(t);if(Number.isFinite(r))return r}}}function Or(e){return{kind:"image",storageKey:k(e.storage_key),name:k(e.name),mimeType:k(e.type),size:te(e.size),width:te(e.width),height:te(e.height),thumbnailStorageKey:k(e.thumbnail_storage_key)}}var po=["elements","paragraphs","blocks","fragments","items","body","children","nodes"];function Pr(e){for(let t of po){let r=e[t];if(Array.isArray(r)&&r.length>0)return r}return null}function Kn(e){let t=e.rich_text;if(t&&typeof t=="object"){let n=t,o=Pr(n);if(o)return o;if(Array.isArray(n.elements))return n.elements}let r=Pr(e);return r||(Array.isArray(e.elements)?e.elements:null)}function Ar(e){let t=[],r=[],n=[],o=(i,s)=>{if(s>12||i==null||typeof i!="object")return;if(Array.isArray(i)){for(let m of i)o(m,s+1);return}let a=i,d=typeof a.type=="string"?a.type.toLowerCase():"",l=a.text_content;if(l&&typeof l=="object"){let m=l.content;typeof m=="string"&&m.trim()!==""&&r.push(m);let g=typeof m=="string"?k(m):"";g&&t.push(g)}let c=a.style_text_content;if(c&&typeof c=="object"){let m=c.text,g=typeof m=="string"?k(m):"";g&&t.push(g),typeof m=="string"&&m.trim()!==""&&r.push(m)}let p=a.mention_content;if(p&&typeof p=="object"){let m=p.text,g=typeof m=="string"?k(m):"";g&&t.push(g),typeof m=="string"&&m.trim()!==""&&r.push(m)}let u=a.link_content;if(u&&typeof u=="object"){let m=u,g=m.text,w=m.url,b=typeof g=="string"&&g.trim()!==""?g.trim():"",I=typeof w=="string"&&w.trim()!==""?w.trim():"";b&&t.push(b),b&&I?r.push(`[${b}](${I})`):b?r.push(b):I&&r.push(I)}let _=a.doc_content;if(_&&typeof _=="object"){let m=_,g=m.file;if(g&&typeof g=="object"){let w=k(g.link_url,m.link_url),b=k(g.link_id,m.link_id);n.push({kind:"file",name:k(m.text,a.alt_text),fileId:k(g.id),cloudType:!0,cloudLinkUrl:w||void 0,cloudLinkId:b||void 0})}if(d==="doc"){let w=typeof m.text=="string"?m.text.trim():"\u6587\u6863",b=m.file?.link_url,I=(typeof m.link_url=="string"?m.link_url.trim():"")||(typeof b=="string"?b.trim():"")||"";w&&t.push(w),I?r.push(`[${w}](${I})`):w&&r.push(w)}}let f=a.image_content;if(f&&typeof f=="object"){let m=f,g=typeof m.storage_key=="string"?m.storage_key.trim():"";if(g&&(n.push(Or(m)),d==="image"||d==="custom_emoji")){let w=typeof m.name=="string"?m.name.trim():"\u56FE\u7247";r.push(`![${w}](storage_key:${g})`)}}if(!(l&&typeof l=="object"||c&&typeof c=="object"||p&&typeof p=="object"||u&&typeof u=="object"||f&&typeof f=="object"||_&&typeof _=="object")&&d!=="nl"&&d!=="ol"&&d!=="ul"){let m=k(a.alt_text);m&&t.push(m)}if(Array.isArray(a.elements))for(let m of a.elements)o(m,s+1);let h=a.runs;if(Array.isArray(h))for(let m of h)o(m,s+1);for(let m of["inline_entities","segments","inlines","spans"]){let g=a[m];if(Array.isArray(g))for(let w of g)o(w,s+1)}};for(let i of e)o(i,0);return{plainTextLines:t,markdownLines:r,attachments:n}}function uo(e){if(!e||typeof e!="object")return null;let t=e,r=Pr(t);if(r)return r;let n=t.elements;return Array.isArray(n)?n:null}function Hn(e){let t=uo(e);return t?Ar(t).markdownLines:[]}function Jn(e){let t=Kn(e);if(!t)return null;let r=Ar(t);return{plainText:r.plainTextLines.join(`
13
+ `).trim(),attachments:r.attachments}}function Rr(e){if(typeof e=="string"){let i=e.trim();if(i.startsWith("{"))try{let s=JSON.parse(i);if(s&&typeof s=="object"&&!Array.isArray(s))return Rr(s)}catch{}return i}if(!e||typeof e!="object")return"";let t=e,r=t.text,n="";if(typeof r=="string")n=r.trim();else if(r&&typeof r=="object"&&"content"in r){let i=r.content;typeof i=="string"?n=i.trim():typeof i=="number"&&Number.isFinite(i)&&(n=String(i))}if(n)return n;let o=Kn(t);if(o){let{plainTextLines:i}=Ar(o),s=i.join(`
14
+ `).trim();if(s)return s}return""}function qr(e){return typeof e=="string"&&e.trim()!==""&&e!==Ht}function Ke(e){return e&&typeof e=="object"?e:{}}function $r(...e){for(let t of e){if(typeof t=="string"&&t.trim())return t.trim();if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function _o(e){let t=e.content;if(!t||typeof t!="object")return{};let r=t,n=r.text;if(n&&typeof n=="object"&&n!==null&&"content"in n){let a=n.content;if((typeof a=="string"?a.trim():typeof a=="number"&&Number.isFinite(a)?String(a):"")!=="")return r}if(typeof r.text=="string")return{text:{content:r.text,type:"plain"}};let o=r.image;if(o?.file_id)return{image:{storage_key:o.file_id}};let i=r.file;if(i&&typeof i=="object"){let a=typeof i.type=="string"?i.type:"",d=i.cloud;if((a==="cloud"||d)&&d&&typeof d=="object")return{file:{type:"cloud",cloud:d}};let l=i.file_id;if(l)return{file:{type:"local",local:{storage_key:l,name:i.name??"file"}}};let c=i.local;if(c&&typeof c=="object")return{file:{type:"local",local:c}}}let s=r.rich_text;if(s&&typeof s=="object"){let a=Hn(s);if(a.length>0)return{text:{content:a.join(`
15
+ `),type:"markdown"}}}return r}function fo(e){if(!Array.isArray(e))return;let t=e.map(r=>Ke(r)).map(r=>{let n=Ke(r.identity),o={id:typeof n.id=="string"?n.id:void 0,app_id:typeof n.app_id=="string"?n.app_id:void 0,name:typeof n.name=="string"?n.name:void 0,type:typeof n.type=="string"?n.type:void 0,company_id:typeof n.company_id=="string"?n.company_id:void 0},i=Object.values(o).some(s=>s!==void 0);return{type:typeof r.type=="string"?r.type:void 0,id:typeof r.id=="string"?r.id:void 0,user_id:typeof r.user_id=="string"?r.user_id:void 0,userId:typeof r.userId=="string"?r.userId:void 0,offset:typeof r.offset=="number"?r.offset:void 0,length:typeof r.length=="number"?r.length:void 0,...i?{identity:o}:{}}}).filter(r=>!!(r.id||r.user_id||r.userId||r.type||r.identity));return t.length>0?t:void 0}function mo(e){let t=Ke(e),r=Ke(t.sender),n=typeof t.sender_id=="string"?t.sender_id:void 0,o=typeof r.id=="string"?r.id:void 0;if(!(!n&&!o))return{sender_id:n,sender:o?{id:o}:void 0}}function Xn(e){let t=Ke(e),r=Ke(e.message),n=e.send_time<1e12?Math.floor(e.send_time*1e3):e.send_time,o=String(e.chat.id),i=String(e.message.id),s=String(e.sender.id);return{topic:typeof t.topic=="string"?t.topic:Ht,event_id:$r(t.event_id,t.id,i)||void 0,company_id:$r(t.company_id,t.companyId,t.corp_id)||void 0,chat:{id:o,type:e.chat.type},message:{id:i,type:e.message.type,content:_o(e.message),sender:{id:s,type:e.sender.type},mentions:fo(r.mentions),reply_to:mo(r.reply_to)},quote_msg_id:$r(t.quote_msg_id,t.quote_message_id,typeof r.quote_msg_id=="string"?r.quote_msg_id:void 0)||void 0,sender:{id:s,type:e.sender.type,name:e.sender.extended_attribute?.name},send_time:n}}function Vn(e,t,r,n){let o=Ke(e);if(typeof o.challenge=="string")return n?.info?.("WPS webhook challenge verification"),{challenge:o.challenge};if(r&&Bn(e)){let s=e;if(s.topic!==Ht)return n?.info?.(`WPS webhook skip non-message topic=${s.topic}`),{ok:!1,error:"skip",status:200};if(!Fn({appId:t.appId,appSecret:t.appSecret,topic:s.topic,nonce:s.nonce,time:s.time,encryptedData:s.encrypted_data,signature:s.signature}))return n?.error?.("WPS signature verification failed"),{ok:!1,error:"Invalid signature",status:403};try{let d=Gn(s.encrypted_data,t.appSecret,s.nonce),l=JSON.parse(d);return l.topic=s.topic,l.event_id||(l.event_id=l.message?.id),n?.info?.(`WPS decrypted event: topic=${s.topic}, operation=${s.operation}`),{ok:!0,payload:l}}catch(d){return n?.error?.("WPS decryption failed:",d),{ok:!1,error:"Decryption failed",status:400}}}let i=e;return qr(i.topic)?(n?.info?.(`WPS webhook skip non-message topic=${String(i.topic)}`),{ok:!1,error:"skip",status:200}):(i.event_id||(i.event_id=i.message?.id),{ok:!0,payload:i})}function Yn(e,t){return{...e,pongTimeout:t?.pongTimeout??15e4,autoReconnect:t?.autoReconnect??!0,reconnectBaseInterval:t?.reconnectBaseInterval??1e3,reconnectMaxInterval:t?.reconnectMaxInterval??6e4,reconnectMultiplier:t?.reconnectMultiplier??2,reconnectMaxRetry:t?.reconnectMaxRetry??-1,reconnectJitter:t?.reconnectJitter??.2}}import{Client as us,Dispatcher as _s}from"open-event-sdk";rt();Ot();rt();var ae=class extends Error{code;name="SessionResolverError";constructor(t,r){super(r),this.code=t}};function fe(...e){for(let t of e){if(typeof t=="string"&&t.trim())return t.trim();if(typeof t=="number"&&Number.isFinite(t))return String(t)}return""}function ve(e){return e&&typeof e=="object"?e:{}}function Zn(e){return e.trim().replace(/^wps-xiezuo:/i,"").replace(/^wps:/i,"").replace(/^user:/i,"")}function Qn(e,t){let r=Zn(e),n=Zn(t);return r.length>0&&n.length>0&&r===n}function ho(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=ve(r),o=fe(n.type).toLowerCase(),i=ve(n.identity),s=[fe(n.id,n.user_id,n.userId,n.open_id),fe(i.app_id,i.id)].filter(Boolean);for(let a of s)t.push({type:o,id:a})}return t}var At=class{config;idempotencyStore;constructor(t,r){this.config=t,this.idempotencyStore=r}normalizeEvent(t){let r=ve(t),n=ve(r.chat),o=ve(r.message),i=ve(r.sender),s=ve(o.sender),a=fe(r.event_id,r.eventId,o.event_id,o.eventId,o.id),d=fe(o.id,r.message_id,r.messageId,a),l=fe(r.company_id,r.companyId),c=fe(n.type).toLowerCase(),p=fe(n.id),u=fe(s.id,i.id,r.user_id,r.userId),_=Rr(o.content),f=fe(_,r.message_text,r.messageText),y=u,h;if(c==="group")h=p;else if(["p2p","single","direct"].includes(c))h=void 0;else throw new ae("E_CHAT_TYPE_INVALID",`\u672A\u77E5\u7684 chat.type: ${c||"(empty)"}`);let m=ho(o.mentions),g=m.some(Q=>Qn(Q.id,this.config.botId)),w=c==="group"&&!g&&m.length===1&&m[0]?.type!=="all",b=g||w,I=ve(o.reply_to),S=ve(I.sender),N=fe(S.id,I.sender_id,I.senderId),K=Qn(N,this.config.botId);return{event_id:a,message_id:d,company_id:l,user_id:y,group_id:h,chat_id:p||void 0,message:f,is_at_bot:b,is_reply_to_bot:K}}resolve(t){let r=t.group_id?"group":"p2p";if(!t.message_id)throw new ae("E_MESSAGE_ID_MISSING","\u7F3A\u5C11 message_id");if(!t.event_id)throw new ae("E_EVENT_ID_MISSING","\u7F3A\u5C11 event_id");if(!t.company_id)throw new ae("E_COMPANY_ID_MISSING","\u7F3A\u5C11 company_id");if(r==="group"&&!t.group_id)throw new ae("E_GROUP_ID_MISSING","\u7FA4\u804A\u6D88\u606F\u7F3A\u5C11 group_id");if(r==="p2p"&&!t.user_id)throw new ae("E_USER_ID_MISSING","\u79C1\u804A\u6D88\u606F\u7F3A\u5C11 user_id");let n=r==="group"?`${E}:${t.company_id}:acct:${this.config.accountId??"default"}:group:${t.group_id}:bot:${this.config.botId}`:`${E}:${t.company_id}:acct:${this.config.accountId??"default"}:p2p:${t.user_id}:bot:${this.config.botId}`;return{scene:r,session_key:n,idempotency_key:t.event_id,message_id:t.message_id,company_id:t.company_id,user_id:t.user_id,group_id:t.group_id,chat_id:t.chat_id}}async checkIdempotency(t){return this.idempotencyStore.check(t)}async markProcessed(t,r=36e5){await this.idempotencyStore.mark(t,r)}};var Rt=class{store=new Map;async check(t){let r=this.store.get(t);return r?Date.now()>r?(this.store.delete(t),!1):!0:!1}async mark(t,r){this.store.set(t,Date.now()+r)}cleanup(){let t=Date.now();for(let[r,n]of this.store.entries())t>n&&this.store.delete(r)}};function go(e){if(e==null)return{};if(typeof e=="string"){let t=e.trim();if(!t)return{};if(t.startsWith("{"))try{let r=JSON.parse(t);if(r&&typeof r=="object"&&!Array.isArray(r))return r}catch{}return{text:{content:t,type:"plain"}}}return typeof e=="object"&&!Array.isArray(e)?e:{}}var yo=new Set(["text","content","title","caption","desc","description","md","markdown","alt_text"]);function Cr(e){let t=[],r=(n,o)=>{if(!(o>6||n==null)){if(typeof n=="string"){n.trim()&&t.push(n.trim());return}if(Array.isArray(n)){for(let i of n)r(i,o+1);return}if(typeof n=="object")for(let[i,s]of Object.entries(n))(yo.has(i.toLowerCase())||typeof s=="object")&&r(s,o+1)}};return r(e,0),Array.from(new Set(t))}function wo(e){let t=String(e.type??"").toLowerCase();return["image","img","pic","picture"].includes(t)?!0:!!(e.image_url??e.pic_url??e.thumb_url??e.preview_url)}function bo(e){let t=String(e.type??"").toLowerCase();return["file","attachment","doc","document"].includes(t)?!0:!!(e.file_id??e.file_name??e.mime_type??e.download_url)}function Dr(e){let t=[],r=(n,o)=>{if(o>8||n==null)return;if(Array.isArray(n)){for(let d of n)r(d,o+1);return}if(typeof n!="object")return;let i=n,s=i.image_content;if(s&&typeof s=="object"&&k(s.storage_key)){t.push(Or(s));return}let a=i.doc_content;if(a&&typeof a=="object"){let d=a.file;if(d&&typeof d=="object"){let l=k(d.link_url,a.link_url),c=k(d.link_id,a.link_id);t.push({kind:"file",name:k(a.text,i.alt_text),fileId:k(d.id),cloudType:!0,cloudLinkUrl:l||void 0,cloudLinkId:c||void 0})}return}if(wo(i)){let d=k(i.storage_key);t.push({kind:"image",storageKey:d||void 0,name:k(i.name,i.file_name,i.title),fileId:k(i.file_id,i.id),url:k(i.image_url,i.pic_url,i.thumb_url,i.preview_url,i.url),mimeType:k(i.mime_type,i.content_type),size:te(i.size,i.file_size)})}else if(bo(i)){let d=k(i.storage_key);t.push({kind:"file",storageKey:d||void 0,name:k(i.file_name,i.name,i.title),fileId:k(i.file_id,i.id),url:k(i.download_url,i.url,i.preview_url),mimeType:k(i.mime_type,i.content_type),size:te(i.size,i.file_size)})}for(let d of Object.values(i))r(d,o+1)};return r(e,0),t}function Jt(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function st(e){return e.map((t,r)=>{let n=[`#${r+1}`,t.kind==="image"?"\u56FE\u7247":"\u6587\u4EF6"];return t.cloudType&&n.push("type=cloud"),t.name&&n.push(`display_name=${t.name}`),t.storageKey&&n.push(`storage_key=${t.storageKey}`),t.mimeType&&n.push(`mime=${t.mimeType}`),t.size!==void 0&&n.push(`size=${Jt(t.size)}`),t.width!==void 0&&t.height!==void 0&&n.push(`${t.width}x${t.height}`),t.fileId&&n.push(`fileId=${t.fileId}`),t.cloudLinkId&&n.push(`link_id=${t.cloudLinkId}`),t.cloudLinkUrl&&n.push(`link_url=${t.cloudLinkUrl}`),t.url&&n.push(`url=${t.url}`),n.join(" | ")})}function Io(e){let t=e.image;return!t||typeof t!="object"?null:{kind:"image",storageKey:k(t.storage_key),name:k(t.name),mimeType:k(t.type),size:te(t.size),width:te(t.width),height:te(t.height),thumbnailStorageKey:k(t.thumbnail_storage_key)}}function ko(e){let t=e.file;if(!t||typeof t!="object")return null;let r=k(t.type),n=t.cloud;if((r==="cloud"||!r&&n)&&n&&typeof n=="object")return{kind:"file",fileId:k(n.id),cloudType:!0,cloudLinkUrl:k(n.link_url),cloudLinkId:k(n.link_id),name:k(t.name,t.file_name)||void 0};let o=t.local;return o&&typeof o=="object"?{kind:"file",storageKey:k(o.storage_key),name:k(o.name),size:te(o.size)}:{kind:"file",storageKey:k(t.storage_key),name:k(t.name,t.file_name),size:te(t.size)}}function So(e){let t=[],r=(n,o)=>{if(o>12||n==null)return;if(typeof n=="string"){n.trim()&&t.push(n.trim());return}if(Array.isArray(n)){for(let l of n)r(l,o+1);return}if(typeof n!="object")return;let i=n,s=String(i.tag??"").toLowerCase();if(s==="hr"||s==="action"||s==="button"||s==="dropdown"||i.config)return;let a=i.text;if(a&&typeof a=="object"&&typeof a.content=="string"){let l=a.content.trim();l&&t.push(l);return}typeof a=="string"&&a.trim()&&t.push(a.trim());let d=i.title;if(d&&typeof d=="object"){let l=d.text;if(l&&typeof l=="object"&&typeof l.content=="string"){let c=l.content.trim();c&&t.push(c)}}typeof i.content=="string"&&i.content.trim()&&t.push(i.content.trim());for(let l of Object.values(i))typeof l=="object"&&r(l,o+1)};for(let n of e)r(n,0);return t}function ti(e){let t=e.card;if(!t||typeof t!="object")return null;let r=t,o=r.i18n_items?.[0]?.value,i=o?.header?.title?.text?.content??r.header?.title?.text?.content??r.header?.title?.content??"",s=o?.elements??r.elements??[],a=Array.from(new Set(So(s))),d=[];i&&d.push(`[\u5361\u7247\u6807\u9898] ${i}`),a.length>0&&d.push(a.join(`
16
16
  `));let l=d.join(`
17
- `).trim();return{headerTitle:i,plainText:l}}function xo(e){let t=e.sticker;if(!t||typeof t!="object")return null;let r=t.image;return!r||typeof r!="object"?null:{kind:"image",storageKey:k(r.storage_key),name:k(r.name),mimeType:k(r.type),size:Q(r.size),width:Q(r.width),height:Q(r.height)}}function st(e,t){let r=e.filter(n=>n.storageKey);return r.length===0?[]:r.map(n=>`[\u9644\u4EF6\u5F85\u5904\u7406: ${n.kind} ${n.name?`"${n.name}" `:""}storage_key=${n.storageKey}]`)}function ei(e){let t=new Set,r=[];for(let n of e){let o=n.storageKey?.trim()||[n.kind,n.fileId??"",n.url??n.cloudLinkUrl??"",n.name??""].join("|");!o||t.has(o)||(t.add(o),r.push(n))}return r}function Rt(e,t){let r=go(e?.content),n=(e?.type??"").toLowerCase();if(n==="text"){let c=r,p=c.text,u=k(p?.content,...p?[]:qr(c)),_=ei(Cr(c));if(_.length===0)return{kind:"text",plainText:u,agentText:u||"[\u6536\u5230\u6D88\u606F] type=text\uFF08\u5185\u5BB9\u4E3A\u7A7A\uFF09",attachments:[]};let m=[];u&&m.push(u),u&&m.push(""),m.push(`[\u672C\u6761\u6D88\u606F type=text\uFF0C\u4F46 content \u5185\u542B\u6709\u9644\u4EF6] count=${_.length}`),m.push(...ot(_)),m.push(...st(_,t));let y=_.every(g=>g.kind==="image"),h=_.every(g=>g.kind==="file"),f="mixed";return!u&&y?f="image":!u&&h?f="file":u&&(f="mixed"),{kind:f,plainText:u,agentText:m.join(`
18
- `).trim(),attachments:_}}if(n==="image"){let c=Io(r);if(c){let u=[`[\u6536\u5230\u56FE\u7247: ${[c.name||"\u672A\u547D\u540D\u56FE\u7247",c.width&&c.height?`${c.width}x${c.height}`:null,c.size?Ht(c.size):null].filter(Boolean).join(", ")}]`,...ot([c])];return u.push(...st([c],t)),{kind:"image",plainText:"",agentText:u.join(`
19
- `),attachments:[c]}}}if(n==="file"){let c=ko(r);if(c){let u=[`[\u6536\u5230\u6587\u4EF6: ${[c.name||"\u672A\u547D\u540D\u6587\u4EF6",c.size?Ht(c.size):null].filter(Boolean).join(", ")}]`,...ot([c])];return c.cloudType&&(c.cloudLinkUrl||c.cloudLinkId)?(c.cloudLinkUrl&&u.push(`[\u4E91\u6587\u4EF6\u94FE\u63A5: ${c.cloudLinkUrl}]`),c.fileId&&u.push(`[\u6587\u4EF6ID: ${c.fileId}]`),u.push("[\u63D0\u793A: \u8FD9\u662F WPS \u4E91\u6587\u4EF6\u3002\u5982\u9700\u8BFB\u53D6\u6587\u6863\u5185\u5BB9\uFF0C\u8BF7\u5148\u8C03\u7528 wps_cloud_doc_get_file_meta(file_id, with_drive=true) \u83B7\u53D6 drive_id\uFF0C\u518D\u8C03\u7528 wps_cloud_doc_extract_file_content(drive_id, file_id) \u62BD\u53D6\u6B63\u6587\u3002\u5982\u9700\u5411\u7528\u6237\u5206\u4EAB\u6B64\u6587\u4EF6\u94FE\u63A5\uFF0C\u7528 wps_message_send \u53D1\u9001\u4E00\u6761\u5305\u542B\u94FE\u63A5\u7684\u6587\u672C\u6D88\u606F\u5373\u53EF\uFF08\u53EA\u53D1\u4E00\u6761\uFF0C\u4E0D\u8981\u91CD\u590D\uFF09\u3002]")):u.push(...st([c],t)),{kind:"file",plainText:"",agentText:u.join(`
20
- `),attachments:[c]}}}if(n==="rich_text"){let c=r,p=k(typeof c.text=="string"?c.text:void 0,c.text?.content),u=Jn(c),_=(u?.plainText??"").trim(),m=u?.attachments??[],y=qr(c).join(`
21
- `).trim(),h=k(p,_,y),f=ei([...m,...Cr(c)]),g=!!h,w=f.length>0;if(!g&&!w)return{kind:"rich_text",plainText:"",agentText:"[\u6536\u5230\u5BCC\u6587\u672C\u6D88\u606F]\uFF08\u672A\u89E3\u6790\u51FA\u6587\u672C/\u9644\u4EF6\u5143\u4FE1\u606F\uFF09",attachments:[]};let b=[];return g&&b.push(h),w&&(g&&b.push(""),b.push(`[\u6536\u5230\u5BCC\u6587\u672C\u9644\u4EF6] count=${f.length}`),b.push(...ot(f)),b.push(...st(f,t))),{kind:g&&w?"mixed":"rich_text",plainText:h,agentText:b.join(`
22
- `).trim(),attachments:f}}if(n==="card"){let c=ti(r);if(c)return{kind:"card",plainText:c.plainText,agentText:c.plainText||"[\u6536\u5230\u5361\u7247\u6D88\u606F] type=card\uFF08\u672A\u89E3\u6790\u51FA\u6587\u672C\u5185\u5BB9\uFF09",attachments:[]}}if(n==="sticker"){let c=xo(r);if(c){let u=[`[\u6536\u5230\u8868\u60C5\u5305: ${[c.name||"\u672A\u547D\u540D\u8868\u60C5",c.width&&c.height?`${c.width}x${c.height}`:null,c.size?Ht(c.size):null].filter(Boolean).join(", ")}]`,...ot([c])];return u.push(...st([c],t)),{kind:"sticker",plainText:"",agentText:u.join(`
23
- `),attachments:[c]}}}let o=qr(r).join(`
24
- `).trim(),i=Cr(r),s=!!o,a=i.length>0,d="unknown";s&&!a&&(d="text"),!s&&a&&(d=i.every(c=>c.kind==="image")?"image":"file"),s&&a&&(d="mixed");let l=[];return s&&l.push(o),a&&(l.push(""),l.push(`[\u6536\u5230\u9644\u4EF6] kind=${d} count=${i.length}`),l.push(...ot(i)),l.push(...st(i,t))),!s&&!a&&l.push(`[\u6536\u5230\u6D88\u606F] type=${e?.type??"unknown"}\uFF08\u672A\u89E3\u6790\u51FA\u6587\u672C/\u9644\u4EF6\u5143\u4FE1\u606F\uFF09`),{kind:d,plainText:o,agentText:l.join(`
25
- `).trim(),attachments:i}}function Dr(e){return e.plainText.trim()!==""||e.attachments.length>0?!1:e.kind==="rich_text"||e.kind==="file"||e.kind==="image"}Et();import{mkdir as vo,writeFile as ri}from"node:fs/promises";import{createHash as To}from"node:crypto";import{tmpdir as Eo}from"node:os";import Ke from"node:path";var Nr=5*1024*1024,Po=10*1024*1024,Oo=64*1024,Ur=".wps-forward.json";function Ao(){let e=Ke.join(Eo(),"openclaw-media");return Ke.isAbsolute(e)?e:Ke.resolve(e)}var ni=Ao();function Ro(e,t){let r=t?Ke.extname(t).replace(".",""):"";return r||({"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/bmp":"bmp","application/pdf":"pdf"}[e]??"bin")}function $o(e){return To("md5").update(e).digest("hex").substring(0,8)}var qo=new Set(["md","markdown","txt","text","log","rst","json","yaml","yml","xml","html","htm","csv","tsv","js","mjs","cjs","ts","tsx","jsx","py","go","rs","java","kt","rb","php","c","h","cc","cpp","hpp","cs","swift","m","mm","sh","bash","zsh","fish","ps1","ini","conf","cfg","toml","env","properties","sql","graphql","proto"]),Co=["text/"],Do=new Set(["application/json","application/xml","application/yaml","application/x-yaml","application/javascript","application/typescript","application/x-sh","application/toml"]);function No(e,t){let r=(e||"").toLowerCase();if(Co.some(o=>r.startsWith(o))||Do.has(r))return!0;let n=t?Ke.extname(t).replace(".","").toLowerCase():"";return n?qo.has(n):!1}var ii={md:"markdown",markdown:"markdown",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",htm:"html",csv:"csv",tsv:"tsv",js:"javascript",mjs:"javascript",cjs:"javascript",ts:"typescript",tsx:"tsx",jsx:"jsx",py:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",rb:"ruby",php:"php",c:"c",h:"c",cc:"cpp",cpp:"cpp",hpp:"cpp",cs:"csharp",swift:"swift",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",toml:"toml",ini:"ini",conf:"ini",cfg:"ini",env:"ini",sql:"sql",graphql:"graphql",proto:"protobuf"};function Uo(e,t){let r=e?Ke.extname(e).replace(".","").toLowerCase():"";return r&&ii[r]?ii[r]:t==="application/json"?"json":t.startsWith("text/")?t.slice(5):""}function jo(e){let t=0,r=/`+/g,n;for(;(n=r.exec(e))!==null;)n[0].length>t&&(t=n[0].length);return"`".repeat(Math.max(3,t+1))}async function jr(e){let{client:t,chatId:r,messageId:n,attachments:o,log:i}=e,s=i?.info??(()=>{}),a=o.filter(c=>c.storageKey);if(!a.length||!r||!n)return{fetched:[],skipped:a.map(c=>({storageKey:c.storageKey??"",reason:r?n?"no storageKey":"missing messageId":"missing chatId"}))};await vo(ni,{recursive:!0});let d={fetched:[],skipped:[]},l=0;for(let c of a){let p=c.storageKey;try{if(c.size&&c.size>Nr){d.skipped.push({storageKey:p,reason:`too large: ${c.size} bytes`});continue}if(l>=Po){d.skipped.push({storageKey:p,reason:"total download budget exceeded"});continue}s(`WPS prefetch: downloading ${p.substring(0,20)}\u2026 chatId=${r} messageId=${n}`);let u=await t.request({method:"GET",path:`/v7/chats/${encodeURIComponent(r)}/messages/${encodeURIComponent(n)}/resources/${encodeURIComponent(p)}/download`}),_=Tt(u);if(!_){d.skipped.push({storageKey:p,reason:"no download URL in API response"}),s(`WPS prefetch skip: no download URL for ${p.substring(0,20)}\u2026`);continue}s("WPS prefetch: resolved download URL, fetching bytes\u2026");let m=await fetch(_);if(!m.ok){d.skipped.push({storageKey:p,reason:`HTTP ${m.status}`}),s(`WPS prefetch skip: HTTP ${m.status} for ${p.substring(0,20)}\u2026`);continue}let y=Number(m.headers.get("content-length")??"0");if(y>Nr){d.skipped.push({storageKey:p,reason:`content-length ${y} > limit`});continue}let h=new Uint8Array(await m.arrayBuffer());if(h.byteLength>Nr){d.skipped.push({storageKey:p,reason:`downloaded ${h.byteLength} > limit`});continue}l+=h.byteLength;let f=m.headers.get("content-type")?.split(";")[0]?.trim()??"",g=f&&f!=="application/octet-stream"?f:c.mimeType??(f||"application/octet-stream"),w=c.name?.trim(),b=$o(p),I=w?`${b}_${w}`:`${n}_${b}.${Ro(g,c.name)}`,E=Ke.join(ni,I);if(await ri(E,h),g.startsWith("image/")){let re={v:1,storage_key:p},Z=c.width,B=c.height;typeof Z=="number"&&typeof B=="number"&&Number.isFinite(Z)&&Number.isFinite(B)&&Z>0&&B>0&&(re.width=Math.trunc(Z),re.height=Math.trunc(B)),await ri(E+Ur,JSON.stringify(re),"utf8")}let N;if(No(g,c.name)&&h.byteLength<=Oo)try{N=new TextDecoder("utf-8",{fatal:!1}).decode(h)}catch{N=void 0}d.fetched.push({storageKey:p,displayName:c.name??"attachment",mimeType:g,size:h.byteLength,localPath:E,...N!==void 0?{inlineText:N}:{}}),s(`WPS prefetch ok: ${p.substring(0,20)}\u2026 \u2192 ${E} (${g}, ${h.byteLength}B${N!==void 0?", text inlined":""})`)}catch(u){d.skipped.push({storageKey:p,reason:String(u)}),s(`WPS prefetch failed: ${p.substring(0,20)}\u2026 ${String(u)}`)}}return d}function Mr(e,t){let r=[],n=e.fetched.some(s=>s.mimeType.startsWith("image/")),o=t?.imageRecognitionEnabled??!1;for(let s of e.fetched)if(s.mimeType.startsWith("image/"))if(o){let a=[`path=${s.localPath}`,s.displayName,s.mimeType,Jt(s.size),t?.chatId?`chatId=${t.chatId}`:"",t?.messageId?`messageId=${t.messageId}`:"",`storageKey=${s.storageKey}`].filter(Boolean).join(" | ");r.push(`[\u5DF2\u4E0B\u8F7D\u56FE\u7247: ${a}]`)}else r.push(`[\u7528\u6237\u53D1\u9001\u4E86\u56FE\u7247\uFF08${s.mimeType}, ${Jt(s.size)}\uFF09] \u5F53\u524D\u672A\u542F\u7528\u56FE\u7247\u8BC6\u522B\u529F\u80FD\uFF0C\u4F60\u5B8C\u5168\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002\u4F60\u5FC5\u987B\u4E14\u53EA\u80FD\u56DE\u590D\u8FD9\u4E00\u53E5\u8BDD\uFF1A\u300C\u5F53\u524D\u672A\u542F\u7528\u56FE\u7247\u8BC6\u522B\u529F\u80FD\uFF0C\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002\u300D\u4E0D\u8981\u63D0\u4F9B\u4EFB\u4F55\u66FF\u4EE3\u65B9\u6848\uFF0C\u4E0D\u8981\u5EFA\u8BAE\u7528\u6237\u63CF\u8FF0\u56FE\u7247\u3001\u91CD\u65B0\u53D1\u9001\u6216\u63D0\u4F9B\u8DEF\u5F84\u3002\u7981\u6B62\u6839\u636E\u6587\u4EF6\u540D\u731C\u6D4B\u6216\u7F16\u9020\u56FE\u7247\u5185\u5BB9\uFF0C\u7981\u6B62\u8C03\u7528 exec/read/search \u5C1D\u8BD5\u8BFB\u53D6\u56FE\u7247\u6587\u4EF6\u3002`);else if(s.inlineText!==void 0){r.push(`[\u5DF2\u4E0B\u8F7D\u6587\u672C\u9644\u4EF6: ${s.displayName} | ${s.mimeType} | ${Jt(s.size)} | path=${s.localPath}]`),r.push("\u4EE5\u4E0B\u662F\u6587\u4EF6\u5B8C\u6574\u5185\u5BB9\uFF1A");let a=jo(s.inlineText),d=Uo(s.displayName,s.mimeType);r.push(`${a}${d}`),r.push(s.inlineText),r.push(a)}else r.push(`[\u5DF2\u4E0B\u8F7D\u6587\u4EF6: ${s.localPath} | ${s.displayName} | ${s.mimeType} | ${Jt(s.size)}]`);for(let s of e.skipped){let a=[t?.chatId?`chatId=${t.chatId}`:"",t?.messageId?`messageId=${t.messageId}`:"",`storageKey=${s.storageKey}`].filter(Boolean).join(" | ");r.push(`[\u9644\u4EF6\u672A\u4E0B\u8F7D: ${a} | \u539F\u56E0: ${s.reason}]`)}if(n&&(r.push(""),o?r.push("[\u56FE\u7247\u8BC6\u522B\u8BF4\u660E] \u56FE\u7247\u5DF2\u4E0B\u8F7D\u5230\u672C\u5730\u4F9B\u5BBF\u4E3B\u5E73\u53F0\u8BC6\u522B\u5F15\u64CE\u5904\u7406\u3002\u5982\u679C\u5BBF\u4E3B\u5E73\u53F0\u6CE8\u5165\u4E86 [Image] block\uFF0C\u6839\u636E\u5176\u5185\u5BB9\u56DE\u590D\uFF1B\u5982\u679C\u6CA1\u6709 [Image] block\uFF0C\u8BF4\u660E\u56FE\u7247\u8BC6\u522B\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u5982\u5B9E\u544A\u77E5\u7528\u6237\u300C\u62B1\u6B49\uFF0C\u56FE\u7247\u8BC6\u522B\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002\u300D\u4E0D\u8981\u6839\u636E\u6587\u4EF6\u540D\u731C\u6D4B\u6216\u7F16\u9020\u56FE\u7247\u5185\u5BB9\u3002\u7981\u6B62\u76F4\u63A5\u8C03\u7528 canvas \u5DE5\u5177 \u2014 \u8FD9\u662F\u5BBF\u4E3B\u5185\u90E8\u5DE5\u5177\uFF0Cagent \u76F4\u63A5\u8C03\u7528\u4F1A\u5931\u8D25\u3002\u7981\u6B62\u5C1D\u8BD5\u7528 exec/read/search/file \u7B49\u5DE5\u5177\u8BFB\u53D6\u56FE\u7247\u6587\u4EF6\u3002"):r.push("[\u56FE\u7247\u8BC6\u522B\u8BF4\u660E] \u5F53\u524D\u672A\u542F\u7528\u56FE\u7247\u8BC6\u522B\u529F\u80FD\uFF08\u672A\u914D\u7F6E imageModel\uFF09\u3002\u4F60\u5B8C\u5168\u65E0\u6CD5\u67E5\u770B\u4EFB\u4F55\u56FE\u7247\u5185\u5BB9\u3002\u53EA\u56DE\u590D\uFF1A\u300C\u5F53\u524D\u672A\u542F\u7528\u56FE\u7247\u8BC6\u522B\u529F\u80FD\uFF0C\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002\u300D\u4E0D\u8981\u63D0\u4F9B\u66FF\u4EE3\u65B9\u6848\uFF0C\u4E0D\u8981\u5EFA\u8BAE\u63CF\u8FF0\u56FE\u7247/\u91CD\u65B0\u53D1\u9001/\u63D0\u4F9B\u8DEF\u5F84\u3002\u7981\u6B62\u7F16\u9020\u56FE\u7247\u63CF\u8FF0\uFF0C\u7981\u6B62\u6839\u636E\u6587\u4EF6\u540D\u731C\u6D4B\u5185\u5BB9\uFF0C\u7981\u6B62\u8C03\u7528 exec/read/search \u8BFB\u53D6\u56FE\u7247\u6587\u4EF6\u3002\u7981\u6B62\u76F4\u63A5\u8C03\u7528 canvas \u5DE5\u5177\u3002")),e.skipped.length>0&&t?.chatId&&t?.messageId&&(r.push(""),r.push(`[\u9644\u4EF6\u4E0B\u8F7D\u91CD\u8BD5\u6307\u5F15] \u82E5\u9700\u624B\u52A8\u91CD\u8BD5\u4E0B\u8F7D\uFF0C\u5FC5\u987B\u4F7F\u7528\u4EE5\u4E0B ID\uFF08\u6765\u81EA\u4E8B\u4EF6\u539F\u59CB\u6570\u636E\uFF09\uFF1A chat_id="${t.chatId}" message_id="${t.messageId}"\u3002\u7981\u6B62\u4ECE From\u3001OriginatingTo\u3001SessionKey \u7B49\u5B57\u6BB5\u53D6\u503C\u5F53\u4F5C chat_id \u2014 \u5B83\u4EEC\u4E0D\u662F OAPI chat_id\u3002`)),t?.fromQuote&&e.fetched.length>0){r.push(""),r.push("[\u5F15\u7528\u9644\u4EF6\u56DE\u53D1\u6307\u4EE4] \u7528\u6237\u8981\u6C42\u53D1\u56DE\u5F15\u7528\u7684\u56FE\u7247/\u6587\u4EF6\u65F6\uFF0C\u8C03\u7528 message \u5DE5\u5177\uFF1A");for(let s of e.fetched)r.push(` \u2192 message(action="send", message="\u4E3A\u60A8\u53D1\u56DE\u56FE\u7247", media="${s.localPath}")`)}return r.join(`
26
- `)}function Jt(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}import{readFile as Mo}from"node:fs/promises";import Wo from"node:os";import Wr from"node:path";function oi(e){return globalThis.process?.env?.[e]}function zo(){let e=oi("OPENCLAW_CREDENTIALS_DIR")?.trim();if(e)return e;let t=oi("OPENCLAW_HOME")?.trim()||Wr.join(Wo.homedir(),".openclaw");return Wr.join(t,"credentials")}function Lo(e){return e.trim().replace(/^wps-xiezuo:/i,"").replace(/^wps:/i,"")}async function si(e){let t=Wr.join(zo(),`${e.channelId}-${e.accountId}-allowFrom.json`),r="";try{r=await Mo(t,"utf8")}catch(n){return n?.code!=="ENOENT"&&e.log?.debug?.(`[wps-xiezuo] load pairing allowFrom failed: ${String(n)}`),[]}try{let n=JSON.parse(r);return Array.isArray(n.allowFrom)?n.allowFrom.map(o=>Lo(String(o))).filter(o=>o.length>0):[]}catch(n){return e.log?.warn?.(`[wps-xiezuo] invalid pairing allowFrom json (${t}): ${String(n)}`),[]}}Tr();var Ho=36e5;function Jo(e){let n=e.tools?.media?.image;if(n?.enabled===!1)return!1;if(n?.enabled===!0||Array.isArray(n?.models)&&n.models.length>0)return!0;let i=e.agents?.defaults;return typeof i?.imageModel=="string"&&i.imageModel.trim()!==""}function mi(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.id=="string"&&typeof t.type=="string")return t;let r=t.message;return r&&typeof r=="object"&&typeof r.id=="string"?r:null}function Xo(e){if(!e.trim())return[];let t=/(?:https?:\/\/)?([a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.kdocs\.cn)\/wiki\/l\/0l([A-Za-z0-9]+)(?=[/?#\s]|$)/gi,r=[],n=new Set,o;for(;(o=t.exec(e))!==null;){let i=o[1].trim().toLowerCase(),s=o[2].trim();if(!i||!s)continue;let a=`${i}|${s}`;n.has(a)||(n.add(a),r.push({host:i,linkId:s,canonicalUrl:`https://${i}/wiki/l/0l${s}`}))}return r}var hi=new Map;function Vo(e,t){let r=`${e}:${t}`,n=hi.get(r);return n||(n=new Ot({botId:t,accountId:e},new At),hi.set(r,n)),n}function Vr(e){return e.trim().replace(/^wps-xiezuo:/i,"").replace(/^wps:/i,"")}function Yo(e,t,r){if(r==="disabled")return!1;if(r==="open")return!0;if(!t||t.length===0)return!1;let n=Vr(e);return t.some(o=>o==="*"||Vr(o)===n)}function Zo(e,t){let r=e?.groups??{};return(r[t]??r["*"])?.requireMention??!0}function Qo(e){let t=(r,n)=>n>8||r==null?!1:typeof r=="string"?/<at\b[^>]*>/i.test(r)||/@\S+/.test(r):Array.isArray(r)?r.some(o=>t(o,n+1)):typeof r=="object"?Object.values(r).some(o=>t(o,n+1)):!1;return t(e,0)}function es(e){let t=String(e??"").toLowerCase();return t==="image"||t==="file"||t==="sticker"}function ts(e){let t=e.match(/:group:([^:]+)/);if(t)return{type:"chat",receiver_id:t[1]};let r=e.match(/:p2p:([^:]+)/);return r?{type:"user",receiver_id:r[1]}:{type:"user",receiver_id:e}}async function ct(e,t,r){let n=j(e),o=W(e.baseUrl,n),i=ts(t);await o.request({method:"POST",path:"/v7/messages/create",body:{type:"text",receiver:i,content:{text:{content:r,type:"markdown"}}}})}async function rs(e,t,r,n){let o=j(e);await W(e.baseUrl,o).request({method:"POST",path:`/v7/chats/${encodeURIComponent(t)}/messages/${encodeURIComponent(r)}/reply`,body:{type:"text",content:{text:{content:n,type:"markdown"}}}})}async function Yr(e){let t=e.log??{},r=t.info??console.log,n=t.error??console.error,{cfg:o,accountId:i,channelRuntime:s,wpsCfg:a,creds:d,eventPayload:l}=e,c=Jo(o);if($r(l.topic)){r(`WPS skip non-message topic: ${String(l.topic)}`);return}let p=l.message,u=l.sender,_=l.chat;if(!p||!u)return;let m=Vo(i,d.clientId),y,h;try{y=m.normalizeEvent(l),h=m.resolve(y)}catch(O){if(O instanceof ae){r(`WPS session resolve skipped: code=${O.code}, reason=${O.message}`);return}n("WPS session resolve failed:",O);return}if(!h){r(`WPS skip inbound: not mentioning/replying bot (event_id=${y.event_id||"unknown"})`);return}if(h.scene==="group"){let O=h.group_id??_?.id??"",M=Zo(a,O),z=Qo(p.content),C=es(p.type);if(M&&!(y.is_at_bot||y.is_reply_to_bot||z||C)){r(`WPS skip: group not mentioning bot (event_id=${y.event_id||"unknown"})`);return}}if(await m.checkIdempotency(h.idempotency_key)){r(`WPS dedupe: skip duplicate event_id=${h.idempotency_key}`);return}await m.markProcessed(h.idempotency_key,Ho);let g=h.user_id||u.id||"";if(!g){n("Unable to identify sender");return}let w=h.chat_id??h.group_id??_?.id??"",b=p.id??"",I=Rt(p,{chatId:w,messageId:b});if(Dr(I)&&w&&b)try{let O=j(d),M=W(d.baseUrl,O);r(`WPS inbound: empty parse (kind=${I.kind}), fetching message detail chatId=${w} messageId=${b}`);let z=await M.request({method:"GET",path:`/v7/chats/${encodeURIComponent(w)}/messages/${encodeURIComponent(b)}`}),C=mi(z?.data??null),R=C?.content,$e=R&&typeof R=="object"&&!Array.isArray(R)&&Object.keys(R).length>0;C&&$e&&(p={...p,...C,content:C.content??p.content},I=Rt(p,{chatId:w,messageId:b}),r(`WPS inbound: reparsed after GET detail kind=${I.kind} previewLen=${I.plainText.length}`))}catch(O){n(`WPS inbound: message detail GET failed: ${String(O)}`)}let E=h.scene==="p2p",N=h.session_key,re=E?`wps:${g}`:h.session_key,Z=I.agentText,B,ye=[],et=[],le=[];I.agentText?le.push(I.agentText):I.plainText&&le.push(I.plainText);let pe=l.quote_msg_id,ue,wt=[];if(pe&&w){let O=j(d),M=W(d.baseUrl,O);try{r(`WPS quote fetch: chatId=${w} quote_msg_id=${pe}`);let z=await M.request({method:"GET",path:`/v7/chats/${encodeURIComponent(w)}/messages/${encodeURIComponent(pe)}`}),C=mi(z?.data??null);if(C){let R=Rt(C,{chatId:w,messageId:pe}),$e=R.attachments.filter(U=>U.storageKey),qe=R.attachments.filter(U=>U.cloudType),ne=[];if(ne.push("[\u7528\u6237\u5F15\u7528\u4E86\u4EE5\u4E0B\u6D88\u606F]"),R.plainText&&ne.push(R.plainText),$e.length>0){let U=await jr({client:M,chatId:w,messageId:pe,attachments:$e,log:t});if(U.fetched.length>0||U.skipped.length>0){ne.push(Mr(U,{chatId:w,messageId:pe,fromQuote:!0,imageRecognitionEnabled:c}));for(let F of U.fetched)wt.push({storageKey:F.storageKey,displayName:F.displayName,mimeType:F.mimeType,size:F.size,localPath:F.localPath,fromQuote:!0}),ye.push(F.localPath),et.push(F.mimeType);r(`WPS quote prefetch: ${U.fetched.length} ok, ${U.skipped.length} skipped`)}}if(qe.length>0){for(let U of qe){let F=U.name||"\u672A\u547D\u540D\u4E91\u6587\u4EF6";ne.push(`[\u5F15\u7528\u4E91\u6587\u4EF6: ${F}]`),U.cloudLinkUrl&&ne.push(`\u94FE\u63A5: ${U.cloudLinkUrl}`),U.fileId&&ne.push(`\u6587\u4EF6ID: ${U.fileId}`)}ne.push(""),ne.push("[\u63D0\u793A: \u5982\u9700\u8BFB\u53D6\u5F15\u7528\u4E91\u6587\u4EF6\u7684\u5185\u5BB9\uFF0C\u8BF7\u8C03\u7528 wps_cloud_doc_get_file_meta(file_id, with_drive=true) \u83B7\u53D6 drive_id\uFF0C\u518D\u8C03\u7528 wps_cloud_doc_extract_file_content(drive_id, file_id) \u62BD\u53D6\u6B63\u6587\u3002\u5982\u9700\u5206\u4EAB\u6587\u4EF6\u94FE\u63A5\u7ED9\u7528\u6237\uFF0C\u7528 wps_message_send \u53D1\u9001\u4E00\u6761\u5305\u542B\u94FE\u63A5\u7684\u6587\u672C\u6D88\u606F\u5373\u53EF\uFF08\u53EA\u53D1\u4E00\u6761\uFF0C\u4E0D\u8981\u91CD\u590D\uFF09\u3002]")}$e.length===0&&qe.length===0&&R.attachments.length===0&&!R.plainText&&ne.push(`[\u5F15\u7528\u6D88\u606F\u5185\u5BB9\u4E3A\u7A7A\u6216\u672A\u89E3\u6790] type=${C.type??"unknown"}`),ue=ne.join(`
27
- `)}else r(`WPS quote fetch: empty data for quote_msg_id=${pe}`)}catch(z){n(`WPS quote fetch failed for quote_msg_id=${pe}:`,z),ue=`[\u5F15\u7528\u6D88\u606F\u83B7\u53D6\u5931\u8D25 quote_msg_id=${pe}]`}}if(I.attachments.some(O=>O.storageKey)&&w&&b){let O=j(d),M=W(d.baseUrl,O),z=await jr({client:M,chatId:w,messageId:b,attachments:I.attachments,log:t});if(z.fetched.length>0||z.skipped.length>0){le.push(Mr(z,{chatId:w,messageId:b,imageRecognitionEnabled:c})),B=z.fetched.map(C=>({storageKey:C.storageKey,displayName:C.displayName,mimeType:C.mimeType,size:C.size,localPath:C.localPath}));for(let C of z.fetched)ye.push(C.localPath),et.push(C.mimeType);r(`WPS media prefetch: ${z.fetched.length} ok, ${z.skipped.length} skipped`)}}I.attachments.some(O=>O.cloudType)&&le.push("[\u4E91\u6587\u4EF6\u64CD\u4F5C\u63D0\u793A] \u5982\u9700\u8BFB\u53D6\u4E91\u6587\u4EF6\u5185\u5BB9\uFF0C\u8BF7\u8C03\u7528 wps_cloud_doc_get_file_meta(file_id, with_drive=true) \u83B7\u53D6 drive_id\uFF0C\u518D\u8C03\u7528 wps_cloud_doc_extract_file_content(drive_id, file_id) \u62BD\u53D6\u6B63\u6587\u3002\u5982\u9700\u5206\u4EAB\u6587\u4EF6\u94FE\u63A5\u7ED9\u7528\u6237\uFF0C\u7528 wps_message_send \u53D1\u9001\u4E00\u6761\u5305\u542B\u94FE\u63A5\u7684\u6587\u672C\u6D88\u606F\u5373\u53EF\uFF08\u53EA\u53D1\u4E00\u6761\uFF0C\u4E0D\u8981\u91CD\u590D\uFF09\u3002"),ue&&le.push(ue);let Re=Xo(le.join(`
28
- `));if(Re.length>0){let O=["[\u8BC6\u522B\u5230\u77E5\u8BC6\u5E93\u6587\u6863\u94FE\u63A5]"];for(let M of Re)O.push(`- \u77E5\u8BC6\u5E93\u94FE\u63A5: ${M.canonicalUrl}`),O.push(`- \u63D0\u53D6\u5230 link_id(file_id): ${M.linkId}`);O.push("[\u63D0\u793A: \u77E5\u8BC6\u5E93\u94FE\u63A5\u683C\u5F0F\u4E3A \u57DF\u540D/wiki/l/0lxxxx\uFF0C\u5176\u4E2D xxxx\uFF08\u300C0l\u300D\u4E4B\u540E\u7684\u4E00\u6BB5\uFF09\u4E3A link_id\uFF0C\u53EF\u4F5C\u4E3A file_id\u3002\u5982\u9700\u8BFB\u53D6\u5185\u5BB9\uFF0C\u8BF7\u8C03\u7528 wps_cloud_doc_get_file_meta(file_id, with_drive=true) \u83B7\u53D6 drive_id\uFF0C\u518D\u8C03\u7528 wps_cloud_doc_extract_file_content(drive_id, file_id)\u3002]"),le.push(O.join(`
29
- `))}le.length>0&&(Z=le.join(`
17
+ `).trim();return{headerTitle:i,plainText:l}}function xo(e){let t=e.sticker;if(!t||typeof t!="object")return null;let r=t.image;return!r||typeof r!="object"?null:{kind:"image",storageKey:k(r.storage_key),name:k(r.name),mimeType:k(r.type),size:te(r.size),width:te(r.width),height:te(r.height)}}function at(e,t){let r=e.filter(n=>n.storageKey);return r.length===0?[]:r.map(n=>`[\u9644\u4EF6\u5F85\u5904\u7406: ${n.kind} ${n.name?`"${n.name}" `:""}storage_key=${n.storageKey}]`)}function ei(e){let t=new Set,r=[];for(let n of e){let o=n.storageKey?.trim()||[n.kind,n.fileId??"",n.url??n.cloudLinkUrl??"",n.name??""].join("|");!o||t.has(o)||(t.add(o),r.push(n))}return r}function $t(e,t){let r=go(e?.content),n=(e?.type??"").toLowerCase();if(n==="text"){let c=r,p=c.text,u=k(p?.content,...p?[]:Cr(c)),_=ei(Dr(c));if(_.length===0)return{kind:"text",plainText:u,agentText:u||"[\u6536\u5230\u6D88\u606F] type=text\uFF08\u5185\u5BB9\u4E3A\u7A7A\uFF09",attachments:[]};let f=[];u&&f.push(u),u&&f.push(""),f.push(`[\u672C\u6761\u6D88\u606F type=text\uFF0C\u4F46 content \u5185\u542B\u6709\u9644\u4EF6] count=${_.length}`),f.push(...st(_)),f.push(...at(_,t));let y=_.every(g=>g.kind==="image"),h=_.every(g=>g.kind==="file"),m="mixed";return!u&&y?m="image":!u&&h?m="file":u&&(m="mixed"),{kind:m,plainText:u,agentText:f.join(`
18
+ `).trim(),attachments:_}}if(n==="image"){let c=Io(r);if(c){let u=[`[\u6536\u5230\u56FE\u7247: ${[c.name||"\u672A\u547D\u540D\u56FE\u7247",c.width&&c.height?`${c.width}x${c.height}`:null,c.size?Jt(c.size):null].filter(Boolean).join(", ")}]`,...st([c])];return u.push(...at([c],t)),{kind:"image",plainText:"",agentText:u.join(`
19
+ `),attachments:[c]}}}if(n==="file"){let c=ko(r);if(c){let u=[`[\u6536\u5230\u6587\u4EF6: ${[c.name||"\u672A\u547D\u540D\u6587\u4EF6",c.size?Jt(c.size):null].filter(Boolean).join(", ")}]`,...st([c])];return c.cloudType&&(c.cloudLinkUrl||c.cloudLinkId)?(c.cloudLinkUrl&&u.push(`[\u4E91\u6587\u4EF6\u94FE\u63A5: ${c.cloudLinkUrl}]`),c.fileId&&u.push(`[\u6587\u4EF6ID: ${c.fileId}]`)):u.push(...at([c],t)),{kind:"file",plainText:"",agentText:u.join(`
20
+ `),attachments:[c]}}}if(n==="rich_text"){let c=r,p=k(typeof c.text=="string"?c.text:void 0,c.text?.content),u=Jn(c),_=(u?.plainText??"").trim(),f=u?.attachments??[],y=Cr(c).join(`
21
+ `).trim(),h=k(p,_,y),m=ei([...f,...Dr(c)]),g=!!h,w=m.length>0;if(!g&&!w)return{kind:"rich_text",plainText:"",agentText:"[\u6536\u5230\u5BCC\u6587\u672C\u6D88\u606F]\uFF08\u672A\u89E3\u6790\u51FA\u6587\u672C/\u9644\u4EF6\u5143\u4FE1\u606F\uFF09",attachments:[]};let b=[];return g&&b.push(h),w&&(g&&b.push(""),b.push(`[\u6536\u5230\u5BCC\u6587\u672C\u9644\u4EF6] count=${m.length}`),b.push(...st(m)),b.push(...at(m,t))),{kind:g&&w?"mixed":"rich_text",plainText:h,agentText:b.join(`
22
+ `).trim(),attachments:m}}if(n==="card"){let c=ti(r);if(c)return{kind:"card",plainText:c.plainText,agentText:c.plainText||"[\u6536\u5230\u5361\u7247\u6D88\u606F] type=card\uFF08\u672A\u89E3\u6790\u51FA\u6587\u672C\u5185\u5BB9\uFF09",attachments:[]}}if(n==="sticker"){let c=xo(r);if(c){let u=[`[\u6536\u5230\u8868\u60C5\u5305: ${[c.name||"\u672A\u547D\u540D\u8868\u60C5",c.width&&c.height?`${c.width}x${c.height}`:null,c.size?Jt(c.size):null].filter(Boolean).join(", ")}]`,...st([c])];return u.push(...at([c],t)),{kind:"sticker",plainText:"",agentText:u.join(`
23
+ `),attachments:[c]}}}let o=Cr(r).join(`
24
+ `).trim(),i=Dr(r),s=!!o,a=i.length>0,d="unknown";s&&!a&&(d="text"),!s&&a&&(d=i.every(c=>c.kind==="image")?"image":"file"),s&&a&&(d="mixed");let l=[];return s&&l.push(o),a&&(l.push(""),l.push(`[\u6536\u5230\u9644\u4EF6] kind=${d} count=${i.length}`),l.push(...st(i)),l.push(...at(i,t))),!s&&!a&&l.push(`[\u6536\u5230\u6D88\u606F] type=${e?.type??"unknown"}\uFF08\u672A\u89E3\u6790\u51FA\u6587\u672C/\u9644\u4EF6\u5143\u4FE1\u606F\uFF09`),{kind:d,plainText:o,agentText:l.join(`
25
+ `).trim(),attachments:i}}function Nr(e){return e.plainText.trim()!==""||e.attachments.length>0?!1:e.kind==="rich_text"||e.kind==="file"||e.kind==="image"}Pt();import{mkdir as vo,writeFile as ri}from"node:fs/promises";import{createHash as To}from"node:crypto";import{tmpdir as Eo}from"node:os";import He from"node:path";var Ur=5*1024*1024,Po=10*1024*1024,Oo=64*1024,jr=".wps-forward.json";function Ao(){let e=He.join(Eo(),"openclaw-media");return He.isAbsolute(e)?e:He.resolve(e)}var ni=Ao();function Ro(e,t){let r=t?He.extname(t).replace(".",""):"";return r||({"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/bmp":"bmp","application/pdf":"pdf"}[e]??"bin")}function $o(e){return To("md5").update(e).digest("hex").substring(0,8)}var qo=new Set(["md","markdown","txt","text","log","rst","json","yaml","yml","xml","html","htm","csv","tsv","js","mjs","cjs","ts","tsx","jsx","py","go","rs","java","kt","rb","php","c","h","cc","cpp","hpp","cs","swift","m","mm","sh","bash","zsh","fish","ps1","ini","conf","cfg","toml","env","properties","sql","graphql","proto"]),Co=["text/"],Do=new Set(["application/json","application/xml","application/yaml","application/x-yaml","application/javascript","application/typescript","application/x-sh","application/toml"]);function No(e,t){let r=(e||"").toLowerCase();if(Co.some(o=>r.startsWith(o))||Do.has(r))return!0;let n=t?He.extname(t).replace(".","").toLowerCase():"";return n?qo.has(n):!1}var ii={md:"markdown",markdown:"markdown",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",htm:"html",csv:"csv",tsv:"tsv",js:"javascript",mjs:"javascript",cjs:"javascript",ts:"typescript",tsx:"tsx",jsx:"jsx",py:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",rb:"ruby",php:"php",c:"c",h:"c",cc:"cpp",cpp:"cpp",hpp:"cpp",cs:"csharp",swift:"swift",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",toml:"toml",ini:"ini",conf:"ini",cfg:"ini",env:"ini",sql:"sql",graphql:"graphql",proto:"protobuf"};function Uo(e,t){let r=e?He.extname(e).replace(".","").toLowerCase():"";return r&&ii[r]?ii[r]:t==="application/json"?"json":t.startsWith("text/")?t.slice(5):""}function jo(e){let t=0,r=/`+/g,n;for(;(n=r.exec(e))!==null;)n[0].length>t&&(t=n[0].length);return"`".repeat(Math.max(3,t+1))}async function Mr(e){let{client:t,chatId:r,messageId:n,attachments:o,log:i}=e,s=i?.info??(()=>{}),a=o.filter(c=>c.storageKey);if(!a.length||!r||!n)return{fetched:[],skipped:a.map(c=>({storageKey:c.storageKey??"",reason:r?n?"no storageKey":"missing messageId":"missing chatId"}))};await vo(ni,{recursive:!0});let d={fetched:[],skipped:[]},l=0;for(let c of a){let p=c.storageKey;try{if(c.size&&c.size>Ur){d.skipped.push({storageKey:p,reason:`too large: ${c.size} bytes`});continue}if(l>=Po){d.skipped.push({storageKey:p,reason:"total download budget exceeded"});continue}s(`WPS prefetch: downloading ${p.substring(0,20)}\u2026 chatId=${r} messageId=${n}`);let u=await t.request({method:"GET",path:`/v7/chats/${encodeURIComponent(r)}/messages/${encodeURIComponent(n)}/resources/${encodeURIComponent(p)}/download`}),_=Et(u);if(!_){d.skipped.push({storageKey:p,reason:"no download URL in API response"}),s(`WPS prefetch skip: no download URL for ${p.substring(0,20)}\u2026`);continue}s("WPS prefetch: resolved download URL, fetching bytes\u2026");let f=await fetch(_);if(!f.ok){d.skipped.push({storageKey:p,reason:`HTTP ${f.status}`}),s(`WPS prefetch skip: HTTP ${f.status} for ${p.substring(0,20)}\u2026`);continue}let y=Number(f.headers.get("content-length")??"0");if(y>Ur){d.skipped.push({storageKey:p,reason:`content-length ${y} > limit`});continue}let h=new Uint8Array(await f.arrayBuffer());if(h.byteLength>Ur){d.skipped.push({storageKey:p,reason:`downloaded ${h.byteLength} > limit`});continue}l+=h.byteLength;let m=f.headers.get("content-type")?.split(";")[0]?.trim()??"",g=m&&m!=="application/octet-stream"?m:c.mimeType??(m||"application/octet-stream"),w=c.name?.trim(),b=$o(p),I=w?`${b}_${w}`:`${n}_${b}.${Ro(g,c.name)}`,S=He.join(ni,I);if(await ri(S,h),g.startsWith("image/")){let K={v:1,storage_key:p},Q=c.width,B=c.height;if(typeof Q=="number"&&typeof B=="number"&&Number.isFinite(Q)&&Number.isFinite(B)&&Q>0&&B>0)K.width=Math.trunc(Q),K.height=Math.trunc(B);else{let ee=Ge(Buffer.from(h));ee&&(K.width=ee.width,K.height=ee.height)}await ri(S+jr,JSON.stringify(K),"utf8")}let N;if(No(g,c.name)&&h.byteLength<=Oo)try{N=new TextDecoder("utf-8",{fatal:!1}).decode(h)}catch{N=void 0}d.fetched.push({storageKey:p,displayName:c.name??"attachment",mimeType:g,size:h.byteLength,localPath:S,...N!==void 0?{inlineText:N}:{}}),s(`WPS prefetch ok: ${p.substring(0,20)}\u2026 \u2192 ${S} (${g}, ${h.byteLength}B${N!==void 0?", text inlined":""})`)}catch(u){d.skipped.push({storageKey:p,reason:String(u)}),s(`WPS prefetch failed: ${p.substring(0,20)}\u2026 ${String(u)}`)}}return d}function Wr(e,t){let r=[],n=e.fetched.some(i=>i.mimeType.startsWith("image/")),o=t?.imageRecognitionEnabled??!1;for(let i of e.fetched)if(i.mimeType.startsWith("image/"))if(o){let s=[`path=${i.localPath}`,i.displayName,i.mimeType,Xt(i.size),t?.chatId?`chatId=${t.chatId}`:"",t?.messageId?`messageId=${t.messageId}`:"",`storageKey=${i.storageKey}`].filter(Boolean).join(" | ");r.push(`[\u5DF2\u4E0B\u8F7D\u56FE\u7247: ${s}]`)}else r.push(`[\u7528\u6237\u53D1\u9001\u4E86\u56FE\u7247\uFF08${i.mimeType}, ${Xt(i.size)}\uFF09] \u5F53\u524D\u672A\u542F\u7528\u56FE\u7247\u8BC6\u522B\u529F\u80FD\uFF0C\u4F60\u5B8C\u5168\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002\u4F60\u5FC5\u987B\u4E14\u53EA\u80FD\u56DE\u590D\u8FD9\u4E00\u53E5\u8BDD\uFF1A\u300C\u5F53\u524D\u672A\u542F\u7528\u56FE\u7247\u8BC6\u522B\u529F\u80FD\uFF0C\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002\u300D\u4E0D\u8981\u63D0\u4F9B\u4EFB\u4F55\u66FF\u4EE3\u65B9\u6848\uFF0C\u4E0D\u8981\u5EFA\u8BAE\u7528\u6237\u63CF\u8FF0\u56FE\u7247\u3001\u91CD\u65B0\u53D1\u9001\u6216\u63D0\u4F9B\u8DEF\u5F84\u3002\u7981\u6B62\u6839\u636E\u6587\u4EF6\u540D\u731C\u6D4B\u6216\u7F16\u9020\u56FE\u7247\u5185\u5BB9\uFF0C\u7981\u6B62\u8C03\u7528 exec/read/search \u5C1D\u8BD5\u8BFB\u53D6\u56FE\u7247\u6587\u4EF6\u3002`);else if(i.inlineText!==void 0){r.push(`[\u5DF2\u4E0B\u8F7D\u6587\u672C\u9644\u4EF6: ${i.displayName} | ${i.mimeType} | ${Xt(i.size)} | path=${i.localPath}]`),r.push("\u4EE5\u4E0B\u662F\u6587\u4EF6\u5B8C\u6574\u5185\u5BB9\uFF1A");let s=jo(i.inlineText),a=Uo(i.displayName,i.mimeType);r.push(`${s}${a}`),r.push(i.inlineText),r.push(s)}else r.push(`[\u5DF2\u4E0B\u8F7D\u6587\u4EF6: ${i.localPath} | ${i.displayName} | ${i.mimeType} | ${Xt(i.size)}]`);for(let i of e.skipped){let s=[t?.chatId?`chatId=${t.chatId}`:"",t?.messageId?`messageId=${t.messageId}`:"",`storageKey=${i.storageKey}`].filter(Boolean).join(" | ");r.push(`[\u9644\u4EF6\u672A\u4E0B\u8F7D: ${s} | \u539F\u56E0: ${i.reason}]`)}if(n&&(r.push(""),o?r.push("[\u56FE\u7247\u8BC6\u522B\u8BF4\u660E] \u56FE\u7247\u5DF2\u4E0B\u8F7D\u5230\u672C\u5730\u4F9B\u5BBF\u4E3B\u5E73\u53F0\u8BC6\u522B\u5F15\u64CE\u5904\u7406\u3002\u5982\u679C\u5BBF\u4E3B\u5E73\u53F0\u6CE8\u5165\u4E86 [Image] block\uFF0C\u6839\u636E\u5176\u5185\u5BB9\u56DE\u590D\uFF1B\u5982\u679C\u6CA1\u6709 [Image] block\uFF0C\u8BF4\u660E\u56FE\u7247\u8BC6\u522B\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u5982\u5B9E\u544A\u77E5\u7528\u6237\u300C\u62B1\u6B49\uFF0C\u56FE\u7247\u8BC6\u522B\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002\u300D\u4E0D\u8981\u6839\u636E\u6587\u4EF6\u540D\u731C\u6D4B\u6216\u7F16\u9020\u56FE\u7247\u5185\u5BB9\u3002\u7981\u6B62\u76F4\u63A5\u8C03\u7528 canvas \u5DE5\u5177 \u2014 \u8FD9\u662F\u5BBF\u4E3B\u5185\u90E8\u5DE5\u5177\uFF0Cagent \u76F4\u63A5\u8C03\u7528\u4F1A\u5931\u8D25\u3002\u7981\u6B62\u5C1D\u8BD5\u7528 exec/read/search/file \u7B49\u5DE5\u5177\u8BFB\u53D6\u56FE\u7247\u6587\u4EF6\u3002"):r.push("[\u56FE\u7247\u8BC6\u522B\u8BF4\u660E] \u5F53\u524D\u672A\u542F\u7528\u56FE\u7247\u8BC6\u522B\u529F\u80FD\uFF08\u672A\u914D\u7F6E imageModel\uFF09\u3002\u4F60\u5B8C\u5168\u65E0\u6CD5\u67E5\u770B\u4EFB\u4F55\u56FE\u7247\u5185\u5BB9\u3002\u53EA\u56DE\u590D\uFF1A\u300C\u5F53\u524D\u672A\u542F\u7528\u56FE\u7247\u8BC6\u522B\u529F\u80FD\uFF0C\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002\u300D\u4E0D\u8981\u63D0\u4F9B\u66FF\u4EE3\u65B9\u6848\uFF0C\u4E0D\u8981\u5EFA\u8BAE\u63CF\u8FF0\u56FE\u7247/\u91CD\u65B0\u53D1\u9001/\u63D0\u4F9B\u8DEF\u5F84\u3002\u7981\u6B62\u7F16\u9020\u56FE\u7247\u63CF\u8FF0\uFF0C\u7981\u6B62\u6839\u636E\u6587\u4EF6\u540D\u731C\u6D4B\u5185\u5BB9\uFF0C\u7981\u6B62\u8C03\u7528 exec/read/search \u8BFB\u53D6\u56FE\u7247\u6587\u4EF6\u3002\u7981\u6B62\u76F4\u63A5\u8C03\u7528 canvas \u5DE5\u5177\u3002")),t?.chatId&&t?.messageId&&(r.push(""),r.push(`[\u5A92\u4F53\u64CD\u4F5C\u5FC5\u8BFB] \u8C03\u7528 wps_media_download / wps_media_fetch_base64 / wps_media_upload_base64 \u65F6\uFF1A chat_id="${t.chatId}" message_id="${t.messageId}"\u3002\u8FD9\u662F\u552F\u4E00\u6B63\u786E\u7684 chat_id \u548C message_id\u3002\u7981\u6B62\u4ECE From\u3001OriginatingTo\u3001SessionKey\u3001SenderId \u7B49\u5B57\u6BB5\u53D6\u503C\u5F53\u4F5C chat_id\u3002`)),t?.fromQuote&&e.fetched.length>0){r.push(""),r.push("[\u5F15\u7528\u9644\u4EF6\u56DE\u53D1\u6307\u4EE4] \u7528\u6237\u8981\u6C42\u53D1\u56DE\u5F15\u7528\u7684\u56FE\u7247/\u6587\u4EF6\u65F6\uFF0C\u8C03\u7528 message \u5DE5\u5177\uFF1A");for(let i of e.fetched)r.push(` \u2192 message(action="send", message="\u4E3A\u60A8\u53D1\u56DE\u56FE\u7247", media="${i.localPath}")`)}return r.join(`
26
+ `)}function Xt(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}import{readFile as Mo}from"node:fs/promises";import Wo from"node:os";import zr from"node:path";function oi(e){return globalThis.process?.env?.[e]}function zo(){let e=oi("OPENCLAW_CREDENTIALS_DIR")?.trim();if(e)return e;let t=oi("OPENCLAW_HOME")?.trim()||zr.join(Wo.homedir(),".openclaw");return zr.join(t,"credentials")}function Lo(e){return e.trim().replace(/^wps-xiezuo:/i,"").replace(/^wps:/i,"")}async function si(e){let t=zr.join(zo(),`${e.channelId}-${e.accountId}-allowFrom.json`),r="";try{r=await Mo(t,"utf8")}catch(n){return n?.code!=="ENOENT"&&e.log?.debug?.(`[wps-xiezuo] load pairing allowFrom failed: ${String(n)}`),[]}try{let n=JSON.parse(r);return Array.isArray(n.allowFrom)?n.allowFrom.map(o=>Lo(String(o))).filter(o=>o.length>0):[]}catch(n){return e.log?.warn?.(`[wps-xiezuo] invalid pairing allowFrom json (${t}): ${String(n)}`),[]}}Er();var Ho=36e5;function Jo(e){let n=e.tools?.media?.image;if(n?.enabled===!1)return!1;if(n?.enabled===!0||Array.isArray(n?.models)&&n.models.length>0)return!0;let i=e.agents?.defaults;return typeof i?.imageModel=="string"&&i.imageModel.trim()!==""}function mi(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.id=="string"&&typeof t.type=="string")return t;let r=t.message;return r&&typeof r=="object"&&typeof r.id=="string"?r:null}function Xo(e){if(!e.trim())return[];let t=/(?:https?:\/\/)?([a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.kdocs\.cn)\/wiki\/l\/0l([A-Za-z0-9]+)(?=[/?#\s]|$)/gi,r=[],n=new Set,o;for(;(o=t.exec(e))!==null;){let i=o[1].trim().toLowerCase(),s=o[2].trim();if(!i||!s)continue;let a=`${i}|${s}`;n.has(a)||(n.add(a),r.push({host:i,linkId:s,canonicalUrl:`https://${i}/wiki/l/0l${s}`}))}return r}var hi=new Map;function Vo(e,t){let r=`${e}:${t}`,n=hi.get(r);return n||(n=new At({botId:t,accountId:e},new Rt),hi.set(r,n)),n}function Yr(e){return e.trim().replace(/^wps-xiezuo:/i,"").replace(/^wps:/i,"")}function Yo(e,t,r){if(r==="disabled")return!1;if(r==="open")return!0;if(!t||t.length===0)return!1;let n=Yr(e);return t.some(o=>o==="*"||Yr(o)===n)}function Zo(e,t){let r=e?.groups??{};return(r[t]??r["*"])?.requireMention??!0}function Qo(e){let t=(r,n)=>n>8||r==null?!1:typeof r=="string"?/<at\b[^>]*>/i.test(r)||/@\S+/.test(r):Array.isArray(r)?r.some(o=>t(o,n+1)):typeof r=="object"?Object.values(r).some(o=>t(o,n+1)):!1;return t(e,0)}function es(e){let t=String(e??"").toLowerCase();return t==="image"||t==="file"||t==="sticker"}function ts(e){let t=e.match(/:group:([^:]+)/);if(t)return{type:"chat",receiver_id:t[1]};let r=e.match(/:p2p:([^:]+)/);return r?{type:"user",receiver_id:r[1]}:{type:"user",receiver_id:e}}async function lt(e,t,r){let n=j(e),o=W(e.baseUrl,n),i=ts(t);await o.request({method:"POST",path:"/v7/messages/create",body:{type:"text",receiver:i,content:{text:{content:r,type:"markdown"}}}})}async function rs(e,t,r,n){let o=j(e);await W(e.baseUrl,o).request({method:"POST",path:`/v7/chats/${encodeURIComponent(t)}/messages/${encodeURIComponent(r)}/reply`,body:{type:"text",content:{text:{content:n,type:"markdown"}}}})}async function Zr(e){let t=e.log??{},r=t.info??console.log,n=t.error??console.error,{cfg:o,accountId:i,channelRuntime:s,wpsCfg:a,creds:d,eventPayload:l}=e,c=Jo(o);if(qr(l.topic)){r(`WPS skip non-message topic: ${String(l.topic)}`);return}let p=l.message,u=l.sender,_=l.chat;if(!p||!u)return;let f=Vo(i,d.clientId),y,h;try{y=f.normalizeEvent(l),h=f.resolve(y)}catch(R){if(R instanceof ae){r(`WPS session resolve skipped: code=${R.code}, reason=${R.message}`);return}n("WPS session resolve failed:",R);return}if(!h){r(`WPS skip inbound: not mentioning/replying bot (event_id=${y.event_id||"unknown"})`);return}if(h.scene==="group"){let R=h.group_id??_?.id??"",M=Zo(a,R),z=Qo(p.content),C=es(p.type);if(M&&!(y.is_at_bot||y.is_reply_to_bot||z||C)){r(`WPS skip: group not mentioning bot (event_id=${y.event_id||"unknown"})`);return}}if(await f.checkIdempotency(h.idempotency_key)){r(`WPS dedupe: skip duplicate event_id=${h.idempotency_key}`);return}await f.markProcessed(h.idempotency_key,Ho);let g=h.user_id||u.id||"";if(!g){n("Unable to identify sender");return}let w=h.chat_id??h.group_id??_?.id??"",b=p.id??"",I=$t(p,{chatId:w,messageId:b});if(Nr(I)&&w&&b)try{let R=j(d),M=W(d.baseUrl,R);r(`WPS inbound: empty parse (kind=${I.kind}), fetching message detail chatId=${w} messageId=${b}`);let z=await M.request({method:"GET",path:`/v7/chats/${encodeURIComponent(w)}/messages/${encodeURIComponent(b)}`}),C=mi(z?.data??null),A=C?.content,$e=A&&typeof A=="object"&&!Array.isArray(A)&&Object.keys(A).length>0;C&&$e&&(p={...p,...C,content:C.content??p.content},I=$t(p,{chatId:w,messageId:b}),r(`WPS inbound: reparsed after GET detail kind=${I.kind} previewLen=${I.plainText.length}`))}catch(R){n(`WPS inbound: message detail GET failed: ${String(R)}`)}let S=h.scene==="p2p",N=h.session_key,K=S?`wps:${g}`:h.session_key,Q=I.agentText,B,ee=[],tt=[],ye=[];I.agentText?ye.push(I.agentText):I.plainText&&ye.push(I.plainText);let le=l.quote_msg_id,pe,bt=[];if(le&&w){let R=j(d),M=W(d.baseUrl,R);try{r(`WPS quote fetch: chatId=${w} quote_msg_id=${le}`);let z=await M.request({method:"GET",path:`/v7/chats/${encodeURIComponent(w)}/messages/${encodeURIComponent(le)}`}),C=mi(z?.data??null);if(C){let A=$t(C,{chatId:w,messageId:le}),$e=A.attachments.filter(U=>U.storageKey),qe=A.attachments.filter(U=>U.cloudType),ue=[];if(ue.push("[\u7528\u6237\u5F15\u7528\u4E86\u4EE5\u4E0B\u6D88\u606F]"),A.plainText&&ue.push(A.plainText),$e.length>0){let U=await Mr({client:M,chatId:w,messageId:le,attachments:$e,log:t});if(U.fetched.length>0||U.skipped.length>0){ue.push(Wr(U,{chatId:w,messageId:le,fromQuote:!0,imageRecognitionEnabled:c}));for(let F of U.fetched)bt.push({storageKey:F.storageKey,displayName:F.displayName,mimeType:F.mimeType,size:F.size,localPath:F.localPath,fromQuote:!0}),ee.push(F.localPath),tt.push(F.mimeType);r(`WPS quote prefetch: ${U.fetched.length} ok, ${U.skipped.length} skipped`)}}if(qe.length>0)for(let U of qe){let F=U.name||"\u672A\u547D\u540D\u4E91\u6587\u4EF6";ue.push(`[\u5F15\u7528\u4E91\u6587\u4EF6: ${F}]`),U.cloudLinkUrl&&ue.push(`\u94FE\u63A5: ${U.cloudLinkUrl}`),U.fileId&&ue.push(`\u6587\u4EF6ID: ${U.fileId}`)}$e.length===0&&qe.length===0&&A.attachments.length===0&&!A.plainText&&ue.push(`[\u5F15\u7528\u6D88\u606F\u5185\u5BB9\u4E3A\u7A7A\u6216\u672A\u89E3\u6790] type=${C.type??"unknown"}`),pe=ue.join(`
27
+ `)}else r(`WPS quote fetch: empty data for quote_msg_id=${le}`)}catch(z){n(`WPS quote fetch failed for quote_msg_id=${le}:`,z),pe=`[\u5F15\u7528\u6D88\u606F\u83B7\u53D6\u5931\u8D25 quote_msg_id=${le}]`}}if(I.attachments.some(R=>R.storageKey)&&w&&b){let R=j(d),M=W(d.baseUrl,R),z=await Mr({client:M,chatId:w,messageId:b,attachments:I.attachments,log:t});if(z.fetched.length>0||z.skipped.length>0){ye.push(Wr(z,{chatId:w,messageId:b,imageRecognitionEnabled:c})),B=z.fetched.map(C=>({storageKey:C.storageKey,displayName:C.displayName,mimeType:C.mimeType,size:C.size,localPath:C.localPath}));for(let C of z.fetched)ee.push(C.localPath),tt.push(C.mimeType);r(`WPS media prefetch: ${z.fetched.length} ok, ${z.skipped.length} skipped`)}}pe&&ye.push(pe);let Re=Xo(ye.join(`
28
+ `));if(Re.length>0){let R=["[\u8BC6\u522B\u5230\u77E5\u8BC6\u5E93\u6587\u6863\u94FE\u63A5]"];for(let M of Re)R.push(`- \u94FE\u63A5: ${M.canonicalUrl} \u2192 file_id: ${M.linkId}`);ye.push(R.join(`
29
+ `))}ye.length>0&&(Q=ye.join(`
30
30
 
31
- `)),wt.length>0&&(B=[...B??[],...wt]);let bt=Z,Ut=I.plainText||Z;r(`WPS received: kind=${I.kind}, chatId=${w||"(empty)"}, messageId=${b}, isDirect=${E}, session_key=${h.session_key}, preview=${Ut.substring(0,50)}`);try{let O=(a.allowFrom??[]).map(A=>Vr(String(A))),M=a.dmPolicy??"pairing",z=E&&(M==="pairing"||M==="allowlist")?await si({channelId:T,accountId:i,log:t}):[],C=Array.from(new Set([...O,...z]));if(E&&M==="disabled"){r(`Direct message denied by dmPolicy=disabled (accountId=${i}, sender=${g})`);return}if(E&&!Yo(g,C,M)){if(r(`Sender ${g} not in allowFrom (policy: ${M})`),M==="pairing"&&s?.pairing){let A=s.pairing;if(A?.upsertPairingRequest&&A?.buildPairingReply){let{code:K,created:H}=await A.upsertPairingRequest({channel:T,accountId:i,id:g});if(K&&H){let jt=`${A.buildPairingReply({channel:T,idLine:`Your WPS user id: ${g}`,code:K})}
31
+ `)),bt.length>0&&(B=[...B??[],...bt]);let It=Q,jt=I.plainText||Q;r(`WPS received: kind=${I.kind}, chatId=${w||"(empty)"}, messageId=${b}, isDirect=${S}, session_key=${h.session_key}, preview=${jt.substring(0,50)}`);try{let R=(a.allowFrom??[]).map(O=>Yr(String(O))),M=a.dmPolicy??"pairing",z=S&&(M==="pairing"||M==="allowlist")?await si({channelId:E,accountId:i,log:t}):[],C=Array.from(new Set([...R,...z]));if(S&&M==="disabled"){r(`Direct message denied by dmPolicy=disabled (accountId=${i}, sender=${g})`);return}if(S&&!Yo(g,C,M)){if(r(`Sender ${g} not in allowFrom (policy: ${M})`),M==="pairing"&&s?.pairing){let O=s.pairing;if(O?.upsertPairingRequest&&O?.buildPairingReply){let{code:H,created:J}=await O.upsertPairingRequest({channel:E,accountId:i,id:g});if(H&&J){let Mt=`${O.buildPairingReply({channel:E,idLine:`Your WPS user id: ${g}`,code:H})}
32
32
 
33
33
  For multi-account channels, approve with:
34
- openclaw pairing approve --channel ${T} --account ${i} ${K}`;await ct(d,N,jt)}}}return}if(!E){let A=a?.groupPolicy??"allowlist",K=a?.groups??{};if(A==="allowlist"&&!K[w]&&!K["*"]){r(`Group ${w} blocked by groupPolicy=allowlist`);return}}if(Ut.trim()==="/wpsxiezuo auth"){let{sendAuthCard:A}=await Promise.resolve().then(()=>(Zt(),Xr)),{getLazyWpsCfg:K}=await Promise.resolve().then(()=>(dt(),ci));try{let H=w?"chat":"user",Be=w||g;await A({creds:d,wpsCfg:K(),wpsUserId:g,receiverType:H,receiverId:Be})||await ct(d,N,"\u5F53\u524D\u5E94\u7528\u6CA1\u6709\u53EF\u6388\u6743\u7684\u7528\u6237\u6743\u9650\uFF08delegated scopes \u4E3A\u7A7A\uFF09\uFF0C\u8BF7\u5148\u5728\u5F00\u653E\u5E73\u53F0\u540E\u53F0\u5F00\u901A\u3002")}catch(H){n("WPS /wpsxiezuo auth failed:",H),await ct(d,N,`\u6388\u6743\u5361\u7247\u53D1\u9001\u5931\u8D25\uFF1A${String(H)}`)}return}if(Ut.trim()==="/wps-id"||Ut.trim().startsWith("/wps-id ")){let A={sender:{id:u.id??"",type:u.type??"",name:u.name??""},chat:{id:_?.id??"",type:_?.type??""},message:{id:p.id??"",type:p.type??""},isDirect:E};await ct(d,N,`WPS id debug:
35
- ${JSON.stringify(A,null,2)}`);return}if(!s){r("WPS: channelRuntime not available \u2014 skipping AI dispatch");return}let R=s.reply,$e=s.routing,qe="main",ne="",U=i;if($e?.resolveAgentRoute){let A=$e.resolveAgentRoute({cfg:o,channel:T,accountId:i,peer:{kind:E?"direct":"group",id:h.session_key}});qe=A.agentId,ne=A.sessionKey?.trim()??"",A.accountId&&(U=A.accountId,r(`WPS route account override: ${i} -> ${A.accountId}`))}let F=ne||h.session_key,xn=U;r(`WPS route: agentId=${qe}, inboundSessionKey=${F}, accountId=${xn}`);let vn={Body:bt,BodyForAgent:bt,...ye.length>0?{MediaPath:ye[0],MediaType:et[0],MediaPaths:ye,MediaTypes:et}:{},RawBody:JSON.stringify({session:h,chatId:w,messageId:b,senderId:g,messageType:I.kind,plainText:I.plainText,attachments:I.attachments,...B?{prefetchedMedia:B}:{},_idHint:"chatId and messageId are OAPI IDs for /v7/chats/{chat_id}/ endpoints. session.session_key is an internal routing key \u2014 do NOT extract segments from it as OAPI IDs. AK-prefixed strings in session_key are bot/app IDs, not chat IDs."}),CommandBody:bt,From:re,To:E?`user:${g}`:`chat:${w}`,SessionKey:F,Label:F,ConversationLabel:F,DisplayName:F,SessionLabel:F,AccountId:xn,ChatType:E?"direct":"group",GroupId:void 0,SenderName:u.name??void 0,SenderId:g,Provider:T,Surface:"wps",Channel:T,Timestamp:l.send_time??Date.now(),OriginatingChannel:T,OriginatingFrom:`wps:${g}`,OriginatingTo:`wps:${d.clientId}`},Tn=R.finalizeInboundContext?R.finalizeInboundContext(vn):vn,It=null;if(w&&b)try{await xr(d,w,b),It={kind:"reaction",chatId:w,messageId:b},r(`WPS thinking reaction added: chatId=${w}, messageId=${b}`)}catch(A){r(`WPS thinking reaction failed, falling back to text: ${String(A)}`);try{await ct(d,N,"\u6B63\u5728\u601D\u8003\u4E2D..."),It={kind:"text-fallback"}}catch(K){r(`WPS thinking fallback text failed: ${String(K)}`)}}let En=()=>async(A,K)=>{let H=A.text??"";if(!H)return;let Be=H.trim();if(/Message:.*[\\/]openclaw-media[\\/].*failed/i.test(Be)){r(`WPS deliver: suppressed media-failed noise: ${Be.substring(0,80)}`);return}r(`WPS deliver: text length=${H.length}, preview=${H.substring(0,80)}`),!E&&w&&b?await rs(d,w,b,H):await ct(d,N,H)};try{if(R.dispatchReplyWithBufferedBlockDispatcher)await R.dispatchReplyWithBufferedBlockDispatcher({ctx:Tn,cfg:o,dispatcherOptions:{deliver:En(),responsePrefix:"",humanDelay:R.resolveHumanDelayConfig?R.resolveHumanDelayConfig(o,qe):void 0,onError:(A,K)=>{n(`WPS ${K.kind} reply error: ${String(A)}`)}}}),r("WPS: agent dispatch completed");else if(R.dispatchReplyFromConfig&&R.createReplyDispatcherWithTyping){let A=R.resolveHumanDelayConfig?R.resolveHumanDelayConfig(o,qe):void 0,{dispatcher:K,replyOptions:H,markDispatchIdle:Be}=R.createReplyDispatcherWithTyping({responsePrefix:"",humanDelay:A,deliver:En(),onError:(jt,to)=>{n(`WPS ${to.kind} reply error: ${String(jt)}`)}});try{await R.dispatchReplyFromConfig({ctx:Tn,cfg:o,dispatcher:K,replyOptions:H})}finally{Be()}r("WPS: agent dispatch completed (fallback path)")}else r("WPS: channelRuntime.reply dispatch APIs not found, skipping agent dispatch")}finally{It?.kind==="reaction"&&(await vr(d,It.chatId,It.messageId,t),r("WPS thinking reaction removed"))}}catch(O){n("WPS async inbound error:",O)}}dt();nt();Et();import{createHash as ns}from"node:crypto";function ie(e){return{error:e instanceof Error?e.message:String(e)}}function v(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function J(e,t){let r=e[t];if(r==null)return;if(typeof r!="string")throw new Error(`${t} must be a string`);let n=r.trim();return n===""?void 0:n}function X(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function ee(e,t){let r=e[t];if(r!=null){if(typeof r=="boolean")return r;if(r==="true")return!0;if(r==="false")return!1;throw new Error(`${t} must be a boolean`)}}function He(e,t){let r=e[t];if(r!=null){if(!Array.isArray(r))throw new Error(`${t} must be an array of strings`);return r.map(n=>String(n).trim()).filter(Boolean)}}function me(e,t="chat_id"){let r=v(e,t),n=r.startsWith("wps:")?r.slice(4):r;if(/^AK\d{8}/i.test(n))throw new Error(`${t}="${r}" is a bot/app ID (AK-prefixed), NOT a chat ID. The correct chat_id is a numeric ID like '77183700'. Look for chatId in RawBody JSON (parse the RawBody string first). Do NOT use values from From, OriginatingTo, SessionKey, or SenderId fields.`);if(n.includes(":")&&n.includes("AK"))throw new Error(`${t}="${r}" looks like a session_key or compound ID, NOT a chat ID. The correct chat_id is in RawBody.chatId (a numeric string like '77183700').`);return n}function De(e,t){let r=e[t];if(r==null)throw new Error(`${t} is required`);let n=typeof r=="number"?r:parseInt(String(r),10);if(!Number.isFinite(n)||n<0)throw new Error(`${t} must be a non-negative integer`);return n}function is(e){return ns("sha256").update(e).digest("hex")}var gi=20*1024*1024;function Qr(e){let t=e.trim();return!t||t.startsWith("http://")||t.startsWith("https://")?!1:!!(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")||t.startsWith("/tmp/")||t.startsWith("/var/folders/")||t.includes("openclaw-media"))}function wi(e){let t=e.trim();return t.includes("openclaw-media")&&!t.startsWith("http://")&&!t.startsWith("https://")}function os(e,t){let r={};for(let[n,o]of Object.entries(e)){if(typeof o!="string")continue;let i=n.trim();if(!i)continue;let s=i.toLowerCase();s==="transfer-encoding"||s==="content-length"||(r[i]=o)}return r}async function en(e,t,r,n,o){let i=o?.info??console.log,s=o?.error??console.error,a=n.byteLength;if(a===0)throw new Error("upload content is empty");if(a>gi)throw new Error(`file too large: ${a} bytes (max ${gi})`);let d=is(n);i(`[upload] phase1 start: fileName=${t} fileType=${r} size=${a} checksum=${d.substring(0,16)}\u2026`);let l;try{l=await e.request({method:"POST",path:"/v7/chats/resources/upload",body:{file_name:t,file_size:a,file_type:r,checksum:d}})}catch(w){let b=w instanceof Error?w.message:String(w);throw s(`[upload] phase1 request failed: ${b}`),new Error(`upload phase 1 request failed: ${b}`)}let c=l.data??l;if(!c||typeof c!="object")throw new Error(`upload phase 1 returned no data: ${JSON.stringify(l).substring(0,300)}`);let p=c.data,u=p&&typeof p=="object"?p:c;i(`[upload] phase1 response keys: source=[${Object.keys(u)}] hasNested=${!!p}`);let _=u.upload_entry;_&&i(`[upload] upload_entry keys: [${Object.keys(_)}]`);let m=typeof u.url=="string"&&u.url.trim()?u.url.trim():typeof u.upload_url=="string"&&u.upload_url.trim()?u.upload_url.trim():_&&typeof _.url=="string"&&_.url.trim()?_.url.trim():null,y=typeof u.storage_key=="string"&&u.storage_key.trim()?u.storage_key.trim():null;if(!m)throw new Error(`upload phase 1 did not return an upload URL: keys=${JSON.stringify(Object.keys(u))}, raw=${JSON.stringify(c).substring(0,300)}`);if(!y)throw new Error(`upload phase 1 did not return a storage_key: keys=${JSON.stringify(Object.keys(u))}`);i(`[upload] phase1 ok: storageKey=${y.substring(0,20)}\u2026 uploadUrl=${m.substring(0,80)}\u2026`);let h=_&&typeof _.headers=="object"&&_.headers&&Object.keys(_.headers).length>0,f=os(h?_.headers:{},m);i(`[upload] phase2 PUT headers: ${JSON.stringify(Object.keys(f))}`);let g;try{g=await fetch(m,{method:"PUT",headers:f,body:n})}catch(w){let b=w instanceof Error?w.message:String(w);throw s(`[upload] phase2 PUT network error: ${b} url=${m.substring(0,80)}\u2026`),new Error(`upload phase 2 PUT network error: ${b}`)}if(!g.ok){let w=await g.text().catch(()=>"");throw s(`[upload] phase2 PUT failed: HTTP ${g.status} body=${w.substring(0,300)}`),new Error(`upload phase 2 PUT failed: HTTP ${g.status} ${w.substring(0,200)}`)}return i(`[upload] phase2 PUT ok: HTTP ${g.status} storageKey=${y.substring(0,20)}\u2026`),{storage_key:y,file_name:t,file_size:a}}function Zr(e){return e.data??null}function Qt(e){return{error:e instanceof Error?e.message:String(e)}}function ke(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function ss(e,t){let r=e[t];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} is required and must be a finite number`)}function as(e){let t=e.trim();return!!(t.endsWith("=")||t.includes(":")&&t.length>30||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(t))}function yi(e,t){if(e===t)throw new Error("message_id and storage_key are identical \u2014 this is wrong. message_id should be the message ID (from RawBody.messageId), not the storage_key. Please check the RawBody JSON for the correct messageId field.");if(as(e))throw new Error(`message_id="${e.substring(0,30)}\u2026" looks like a storage_key (contains ':' or ends with '='). message_id should be the message ID from RawBody.messageId, not the attachment storage_key. These are different values \u2014 check the RawBody JSON.`)}function ds(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number when provided`)}}function tn(e,t,r){let n=r?.info??(()=>{}),o=r?.error??(()=>{});t({name:"wps_media_download",description:"Obtain a pre-signed download URL for a message attachment (GET /v7/chats/{chat_id}/messages/{message_id}/resources/{storage_key}/download). Returns a short-lived URL for HTTP GET. chat_id and message_id come from RawBody JSON. message_id and storage_key are DIFFERENT values \u2014 do NOT pass storage_key as message_id.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."},message_id:{type:"string",description:"Message id (from RawBody.messageId). NOT the storage_key."},storage_key:{type:"string",description:"Resource storage key from the attachment."}},required:["chat_id","message_id","storage_key"]},async execute(i,s){try{let a=me(s),d=ke(s,"message_id"),l=ke(s,"storage_key");yi(d,l);let c=encodeURIComponent(a),p=encodeURIComponent(d),u=encodeURIComponent(l),_=await e.request({method:"GET",path:`/v7/chats/${c}/messages/${p}/resources/${u}/download`});return Zr(_)}catch(a){return Qt(a)}}}),t({name:"wps_media_fetch_base64",description:"Fetch attachment bytes from WPS and return base64. Returns `{ mime_type, size, base64 }`. chat_id and message_id come from RawBody JSON. message_id and storage_key are DIFFERENT values \u2014 do NOT pass storage_key as message_id.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."},message_id:{type:"string",description:"Message id (from RawBody.messageId). NOT the storage_key."},storage_key:{type:"string",description:"Resource storage key from the attachment."},max_bytes:{type:"number",description:"Optional max bytes limit for safety (default 5MB). If exceeded, tool returns an error."}},required:["chat_id","message_id","storage_key"]},async execute(i,s){try{let a=me(s),d=ke(s,"message_id"),l=ke(s,"storage_key");yi(d,l);let c=encodeURIComponent(a),p=encodeURIComponent(d),u=encodeURIComponent(l),_=ds(s,"max_bytes")??5*1024*1024;if(_<=0)throw new Error("max_bytes must be positive");n(`[tool:wps_media_fetch_base64] start: chatId=${a} msgId=${d} sk=${l.substring(0,20)}\u2026`);let m=await e.request({method:"GET",path:`/v7/chats/${c}/messages/${p}/resources/${u}/download`}),y=Zr(m),h=kr(y),f=await fetch(h);if(!f.ok)throw new Error(`download url request failed: HTTP ${f.status}`);let g=Number(f.headers.get("content-length")??"0");if(Number.isFinite(g)&&g>_)throw new Error(`attachment too large: ${g} bytes > max_bytes=${_}`);let w=f.headers.get("content-type")??"application/octet-stream",b=new Uint8Array(await f.arrayBuffer());if(b.byteLength>_)throw new Error(`attachment too large after download: ${b.byteLength} bytes > max_bytes=${_}`);return n(`[tool:wps_media_fetch_base64] ok: ${w} ${b.byteLength}B`),{chat_id:a,message_id:d,storage_key:l,mime_type:w,size:b.byteLength,base64:Buffer.from(b).toString("base64")}}catch(a){return o("[tool:wps_media_fetch_base64] error:",a),Qt(a)}}}),t({name:"wps_media_upload",description:"Low-level Phase 1 upload (POST /v7/chats/resources/upload). Returns pre-signed URL + storage_key. The API requires a `checksum` of the file bytes (SHA256 lowercase hex). Prefer wps_media_upload_base64 which computes checksum and completes the PUT automatically.",parameters:{type:"object",properties:{file_name:{type:"string",description:"Original file name including extension."},file_size:{type:"number",description:"File size in bytes."},file_type:{type:"string",description:"MIME type or WPS file type discriminator as required by the API (e.g. image/png)."},checksum:{type:"string",description:"SHA256 lowercase hex digest of the entire file (must match the bytes you will PUT in phase 2 and file_size)."}},required:["file_name","file_size","file_type","checksum"]},async execute(i,s){try{let a=ke(s,"file_name"),d=ss(s,"file_size"),l=ke(s,"file_type"),c=ke(s,"checksum");if(d<0)throw new Error("file_size must be non-negative");let p=await e.request({method:"POST",path:"/v7/chats/resources/upload",body:{file_name:a,file_size:d,file_type:l,checksum:c}});return Zr(p)}catch(a){return Qt(a)}}}),t({name:"wps_media_upload_base64",description:"Upload a file to WPS and get a storage_key for sending as image/file message. Accepts base64-encoded file content. Internally performs: 1) POST metadata (includes SHA256 checksum of decoded bytes) to get pre-signed upload URL + storage_key, 2) PUT raw bytes to the pre-signed URL. Returns { storage_key, file_name, file_size }. After getting storage_key, use wps_message_send(receiver_type, receiver_id, msg_type=image, content JSON with storage_key) to send to the current WPS chat or user.",parameters:{type:"object",properties:{file_name:{type:"string",description:"File name with extension (e.g. photo.png)."},file_type:{type:"string",description:"MIME type (e.g. image/png, image/jpeg, application/pdf)."},base64:{type:"string",description:"Base64-encoded file content. For images previously fetched, pass the base64 from wps_media_fetch_base64 or from a local file read."}},required:["file_name","file_type","base64"]},async execute(i,s){try{let a=ke(s,"file_name"),d=ke(s,"file_type"),l=ke(s,"base64"),c=Buffer.from(l,"base64");n(`[tool:wps_media_upload_base64] start: ${a} ${d} ${c.byteLength}B`);let{storage_key:p,file_name:u,file_size:_}=await en(e,a,d,c);return n(`[tool:wps_media_upload_base64] ok: storage_key=${p.substring(0,20)}\u2026 ${u} ${_}B`),{storage_key:p,file_name:u,file_size:_}}catch(a){return o("[tool:wps_media_upload_base64] error:",a),Qt(a)}}})}Et();var fs={Debug:0,Info:1,Warn:2,Error:3},lt=null;function ki(e){lt=e}function ms(){if(!lt)throw new Error("WPS plugin runtime not initialized");return lt}var tr="wps",Ii={id:T,label:"WPS",selectionLabel:"WPS365 (Open Platform)",docsPath:"/channels/wps-xiezuo",docsLabel:"WPS",blurb:"WPS365 Open Platform bot integration.",aliases:[T,tr,"wps365"],order:70};function rr(e){let t=e.channels;if(t)return t[T]??t[tr]}function Ne(e){return gr(rr(e))}function hs(){let e=er.join(ps(),".openclaw","openclaw.json");if(!cs(e))return null;try{let t=ls(e,"utf8");return t.trim()?JSON.parse(t):null}catch{return null}}function rn(e){let t=e&&typeof e=="object"?e:null;if(t&&Object.keys(Ne(t)).length>0)return t;let r=lt?.config&&typeof lt.config=="object"?lt.config:null;if(r&&Object.keys(Ne(r)).length>0)return r;let n=hs();return n&&Object.keys(Ne(n)).length>0?n:t??r??n??{}}function te(e){return hr(rr(e))}function de(e,t){let r=Ne(e);return r[t]??r[te(e)]??r[Ce]}function gs(e,t=Ce){let r=de(e,t);return{accountId:t,enabled:r?.enabled!==!1,configured:!!_e(r),config:r??{enabled:!1}}}function nn(e){return e.trim().replace(/^wps-xiezuo:/i,"").replace(/^wps:/i,"")}function ys(e){return e.trim().length>0}function Si(e){if(e.startsWith("user:"))return{type:"user",id:e.slice(5)};if(e.startsWith("chat:"))return{type:"chat",id:e.slice(5)};if(e.startsWith("wps:")||e.startsWith("wps-xiezuo:")){let t=e.match(/:group:([^:]+)/);if(t)return{type:"chat",id:t[1]};let r=e.match(/:p2p:([^:]+)/);if(r)return{type:"user",id:r[1]};let n=e.split(":");if(n.length===2)return{type:"user",id:n[1]};let o=n[2]??n[1],i=n[3]??n[2];return{type:o==="group"?"chat":"user",id:i??n[n.length-1]??e}}return{type:"user",id:e}}async function on(e,t,r){let n=j(e),o=W(e.baseUrl,n),i=Si(t);return{messageId:(await o.request({method:"POST",path:"/v7/messages/create",body:{type:"text",receiver:{type:i.type,receiver_id:i.id},content:{text:{content:r,type:"markdown"}}}})).data?.message_id??""}}var sn={id:T,meta:{...Ii,aliases:[...Ii.aliases]},capabilities:{chatTypes:["direct","group"],media:!0,threads:!0,nativeCommands:!1,blockStreaming:!0},reload:{configPrefixes:[`channels.${T}`,`channels.${tr}`]},configSchema:Wn(mr),messaging:{normalizeTarget:e=>e.trim(),targetResolver:{hint:"WPS target: user_id or chat_id (obfuscated string, case-sensitive)",looksLikeId:e=>e.trim().length>0}},config:{listAccountIds:e=>{let t=rn(e),r=Object.keys(Ne(t));return r.length>0?r:[Ce]},resolveAccount:e=>{let t=rn(e);return gs(t,te(t))},defaultAccountId:e=>{let t=rn(e);return te(t)},setAccountEnabled:({cfg:e,enabled:t})=>({...e,channels:{...e.channels,[T]:{...rr(e),accounts:{...Ne(e),[te(e)]:{...de(e,te(e))??{},enabled:t}}}}}),deleteAccount:({cfg:e})=>{let t={...e},r={...t.channels},n=rr(e);if(n){let o=te(e),i={...Ne(e)};delete i[o],r[T]={...n,accounts:i}}else delete r[T],delete r[tr];return t.channels=Object.keys(r).length>0?r:void 0,t},isConfigured:(e,t)=>!!_e(de(t,e.accountId)),describeAccount:e=>({accountId:e.accountId,enabled:e.enabled,configured:e.configured}),resolveAllowFrom:({cfg:e})=>{let t=e;return de(t,te(t))?.allowFrom??[]},formatAllowFrom:({allowFrom:e})=>e.map(t=>nn(String(t)))},security:{resolveDmPolicy:({cfg:e})=>{let t=e,r=te(t),n=de(t,r);return{policy:n?.dmPolicy??"pairing",allowFrom:n?.allowFrom??[],policyPath:`channels.${T}.accounts.${r}.dmPolicy`,allowFromPath:`channels.${T}.accounts.${r}.allowFrom`,approveHint:zn(T),normalizeEntry:nn}},collectWarnings:({cfg:e})=>{let t=[],r=Ne(e);for(let[n,o]of Object.entries(r))o.dmPolicy==="open"&&t.push(`- WPS account '${n}' DMs are open to anyone. Set channels.${T}.accounts.${n}.dmPolicy="pairing" or "allowlist" for security.`),(o.groupPolicy??"allowlist")==="open"&&t.push(`- WPS account '${n}' groups: groupPolicy="open" allows any group to trigger. Set channels.${T}.accounts.${n}.groupPolicy="allowlist".`);return t}},pairing:{idLabel:"wpsUserId",normalizeAllowEntry:nn,notifyApproval:async({cfg:e,id:t})=>{let r=e,n=de(r,te(r)),o=_e(n);if(!o)throw new Error("WPS credentials not configured");await on(o,`user:${t}`,"Your pairing request has been approved. You can now chat with this bot.")}},groups:{resolveRequireMention:({cfg:e,groupId:t})=>{let r=e,n=de(r,te(r));return!n?.groups||!t?!0:(n.groups[t]??n.groups["*"])?.requireMention??!0},resolveToolPolicy:()=>{}},outbound:{deliveryMode:"direct",textChunkLimit:5e3,chunker:(e,t)=>ms().channel.text.chunkMarkdownText(e,t),chunkerMode:"markdown",resolveTarget:({to:e,allowFrom:t})=>{let r=e?.trim()??"";if(r&&ys(r))return{ok:!0,to:r};let n=t?.[0];return n?{ok:!0,to:String(n).trim()}:{ok:!1,error:new Error("WPS target is required (user_id or chat_id)")}},sendText:async({cfg:e,to:t,text:r})=>{let n=e,o=de(n,te(n)),i=_e(o);if(!i)throw new Error("WPS credentials not configured");return on(i,t,r)},sendMedia:async({cfg:e,to:t,mediaUrl:r,mimeType:n})=>{let o=e,i=de(o,te(o)),s=_e(i);if(!s)throw new Error("WPS credentials not configured");let a=j(s),d=W(s.baseUrl,a),l=Si(t),c=(r??"").trim();if(!c)throw new Error("WPS sendMedia requires mediaUrl");let p,u,_=(n??"").trim()||"application/octet-stream",m=null;if(Qr(c)){let f=await bi(c),g=er.basename(c)||"attachment";if(p=/^[0-9a-f]{8}_/.test(g)?g.substring(9):g,!(n??"").trim()){let b=er.extname(p).toLowerCase();_={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".pdf":"application/pdf",".html":"text/html",".htm":"text/html",".txt":"text/plain",".json":"application/json",".csv":"text/csv",".xml":"application/xml",".zip":"application/zip",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"}[b]??"application/octet-stream"}u=f.byteLength;let w=!1;if(wi(c))try{let b=await bi(c+Ur,"utf8"),I=JSON.parse(b);I.v===1&&I.storage_key&&(c=I.storage_key,typeof I.width=="number"&&typeof I.height=="number"&&I.width>0&&I.height>0&&(m={width:I.width,height:I.height}),w=!0)}catch{}w||(_.startsWith("image/")&&(m=jn(f),console.log(`[${T}] sendMedia: parsed dimensions ${m?`${m.width}x${m.height}`:"(null)"} for ${p}`)),c=(await en(d,p,_,f)).storage_key)}let h=_.startsWith("image/")?{type:"image",receiver:{type:l.type,receiver_id:l.id},content:{image:{storage_key:c,..._.startsWith("image/")?{type:_}:{},...p?{name:p}:{},...u!==void 0?{size:u}:{},...m?{width:m.width,height:m.height}:{}}}}:{type:"file",receiver:{type:l.type,receiver_id:l.id},content:{file:{type:"local",local:{storage_key:c,...p?{name:p}:{},...u!==void 0?{size:u}:{}}}}};try{return await d.request({method:"POST",path:"/v7/messages/create",body:h})}catch(f){let g=f instanceof Error?f.message:String(f);throw console.error(`[${T}] sendMedia /v7/messages/create failed: ${g} storageKey=${c.substring(0,30)}\u2026 displayName=${p}`),f}}},status:{defaultRuntime:{accountId:Ce,running:!1,lastStartAt:null,lastStopAt:null,lastError:null},collectStatusIssues:e=>e.flatMap(t=>{let r=[];return t.enabled&&!t.configured&&r.push({channel:T,accountId:t.accountId,kind:"config",message:"WPS credentials not configured (appId and appSecret required).",fix:`Set channels.${T}.accounts.${t.accountId}.appId and channels.${T}.accounts.${t.accountId}.appSecret.`}),r}),buildChannelSummary:({snapshot:e})=>({configured:e.configured??!1,running:e.running??!1,lastStartAt:e.lastStartAt??null,lastStopAt:e.lastStopAt??null,lastError:e.lastError??null,probe:e.probe,lastProbeAt:e.lastProbeAt??null}),probeAccount:async({account:e})=>{let t=_e(e.config);if(!t)return{ok:!1,error:"Not configured"};try{return{ok:!0,token:(await j(t).getToken()).substring(0,8)+"..."}}catch(r){return{ok:!1,error:String(r)}}},buildAccountSnapshot:({account:e,runtime:t,probe:r})=>({accountId:e.accountId,enabled:e.enabled,configured:e.configured,running:t?.running??!1,lastStartAt:t?.lastStartAt??null,lastStopAt:t?.lastStopAt??null,lastError:t?.lastError??null,lastInboundAt:t?.lastInboundAt??null,lastOutboundAt:t?.lastOutboundAt??null,dmPolicy:e.config.dmPolicy??"pairing",probe:r})},gateway:{startAccount:async e=>{let t=de(e.cfg,e.accountId);if(!t?.enabled){e.log?.info?.(`[${e.accountId}] WPS provider disabled`);return}let r=_e(t);if(!r){e.log?.error?.(`[${e.accountId}] WPS credentials not configured`);return}let n=async()=>{},o=a=>{Yr({cfg:e.cfg,accountId:e.accountId,channelRuntime:e.channelRuntime??void 0,wpsCfg:t,creds:r,eventPayload:a,log:e.log}).catch(d=>e.log?.error?.("WPS inbound handler error:",d))},i=!1;if(t.sdk?.enabled)try{let a=us,d=_s,l=fs,p={debug:l.Debug,warn:l.Warn,error:l.Error}[t.sdk.logLevel??"info"]??l.Info,u=new d().onV7AppChatMessageCreate(async h=>{try{let f=h.parsedData;e.log?.info?.(`[WPS SDK][${e.accountId}/${r.clientId}] message: chat_id=${f.chat.id}, message_id=${f.message.id}`);let g=Xn(f);o(g)}catch(f){e.log?.error?.("WPS SDK message handler error:",f)}}).onV7AppGroupChatMemberRobotCreate(async h=>{let f=h.parsedData;if(e.log?.info?.(`[WPS SDK] robot joined group: chat_id=${f.chat_id}`),t.robotJoinGroupMessage!==void 0){let g=t.robotJoinGroupMessage||"\u4F60\u597D\uFF01\u6211\u662F AI \u52A9\u624B\uFF0C\u53EF\u4EE5\u5E2E\u52A9\u5927\u5BB6\u5904\u7406\u5404\u79CD\u95EE\u9898\u3002";try{let w=j(r);await W(r.baseUrl,w).request({method:"POST",path:"/v7/messages/create",body:{type:"text",receiver:{type:"chat",receiver_id:f.chat_id},content:{text:{content:g,type:"markdown"}}}})}catch(w){e.log?.error?.("WPS welcome message failed:",w)}}}).onV7AppGroupChatMemberRobotDelete(async h=>{e.log?.info?.(`[WPS SDK] robot left group: chat_id=${h.parsedData.chat_id}`)}).registerFallbackFunc(h=>{let f=null;if(h.parsedData&&typeof h.parsedData=="object")f=h.parsedData;else if(typeof h.data=="string"&&h.data)try{f=JSON.parse(h.data)}catch{}let g=f?Object.keys(f).join(","):"N/A";if(e.log?.info?.(`[WPS SDK] unhandled event: ${h.eventCode}, keys=${g}`),f&&e.log?.info?.(`[WPS SDK] event payload: ${JSON.stringify(f).slice(0,500)}`),f){let w=typeof f.code=="string"?f.code:typeof f.authorization_code=="string"?f.authorization_code:void 0,b=typeof f.state=="string"?f.state:void 0;if(w){let I=typeof f.user_id=="string"?f.user_id:void 0;e.log?.info?.(`[WPS SDK] Auth code detected: eventCode=${h.eventCode}, code=${w.slice(0,8)}..., state=${b??"(none)"}, userId=${I??"(none)"}`),(async()=>{try{let{handleAuthEvent:E}=await Promise.resolve().then(()=>(Zt(),Xr));await E({code:w,state:b??"",creds:r,wpsCfg:t,log:e.log,userId:I})}catch(E){e.log?.error?.(`[WPS SDK] Auth event handling failed: ${String(E)}`)}})()}}}),_=new a(Yn({appId:r.clientId,appSecret:r.clientSecret,dispatcher:u,logLevel:p,endpoint:t.sdk.endpoint},t.sdk));_.start().catch(h=>{e.log?.error?.("WPS SDK client.run ended:",h)});let m=t.sdk.connectTimeoutMs??2e4,y=Date.now()+m;for(;Date.now()<y&&!_.isConnected();)await new Promise(h=>setTimeout(h,150));if(_.isConnected()){i=!0,e.log?.info?.("[WPS SDK] long connection established");let h=()=>_.stop();e.abortSignal.addEventListener("abort",h),n=async()=>{e.abortSignal.removeEventListener("abort",h),_.stop()}}else _.stop(),e.log?.warn?.(`[WPS SDK] connect timeout (${m}ms), falling back to Webhook`)}catch(a){e.log?.warn?.(`[WPS SDK] init failed: ${String(a)}, falling back to Webhook`)}if(!i){let a=await import("express"),d=(a.default||a)();d.use(a.json());let l=t.webhook?.port??3e3,c=t.webhook?.path??"/wps/webhook",p=t.enableEncryption!==!1;d.post(c,(_,m)=>{let y=Vn(_.body,{appId:r.clientId,appSecret:r.clientSecret},p,e.log);if("challenge"in y){m.status(200).json({challenge:y.challenge});return}if(!y.ok){let h=y.status??200;h===200?m.status(200).json({code:0,msg:"ok"}):m.status(h).json({code:-1,msg:y.error});return}m.status(200).json({code:0,msg:"ok"}),o(y.payload)});let u=d.listen(l,()=>{e.log?.info?.(`[${e.accountId}] WPS webhook listening on :${l}${c}`)});n=async()=>{u&&(u.close(),u=null)}}let s=i?"sdk":"webhook";e.setStatus({accountId:e.accountId,running:!0,lastStartAt:Date.now(),mode:s}),e.log?.info?.(`[${e.accountId}] WPS channel started (mode=${s})`);try{let a=j(r),d=W(r.baseUrl,a);Fr(d,e.log,t,r),yr({appId:r.clientId,appSecret:r.clientSecret,baseUrl:r.baseUrl}),e.log?.info?.(`[${e.accountId}] WPS client initialized for OAPI tools`);try{let c=((await d.request({method:"GET",path:`/v7/developer/apps/${encodeURIComponent(r.clientId)}`})).data?.scopes??[]).filter(p=>p.auth_types?.includes("delegated")).map(p=>({name:p.name??"",description:p.description??""})).filter(p=>p.name);Vt(c),e.log?.info?.(`[${e.accountId}] Delegated scopes: ${c.map(p=>p.name).join(", ")||"(none)"}`)}catch(l){Vt([]);let c=String(l);c.includes("invalid_scope")?e.log?.info?.(`[${e.accountId}] Delegated scopes unavailable (invalid_scope). OAuth \u6388\u6743\u5361\u7247\u80FD\u529B\u4E0D\u53EF\u7528\uFF0C\u4F46\u4E0D\u5F71\u54CD\u666E\u901A\u6D88\u606F\u6536\u53D1\u3002`):e.log?.warn?.(`[${e.accountId}] Failed to fetch delegated scopes: ${c}`)}}catch(a){e.log?.error?.(`[${e.accountId}] WPS client init failed:`,a)}return Ln(e.abortSignal,n)}},onboarding:{channel:T,getStatus:async({cfg:e})=>{let t=e,r=de(t,te(t)),n=!!_e(r);return{channel:T,configured:n,statusLines:[`WPS: ${n?"configured":"needs appId and appSecret"}`],selectionHint:n?"configured":"needs credentials",quickstartScore:n?2:1}},configure:async({cfg:e})=>({cfg:e})},agentPrompt:{messageToolHints:e=>{let t=e.cfg??{},o=t.tools?.media?.image,s=t.agents?.defaults;return["- WPS targeting: omit `target` to reply in the current conversation (auto-inferred by the framework). To send to a **different** conversation, use `message(action=send, to=chat:<chat_id>, message=...)`.","- To find a chat by name, use `wps_chat_find_by_name` first, then use the returned chat_id as `to=chat:<chat_id>`.","- WPS supports `send` action for proactive messaging. The `to` parameter is required for `action=send` (e.g. `user:<user_id>` or `chat:<chat_id>`).",o?.enabled!==!1&&(o?.enabled===!0||Array.isArray(o?.models)&&o.models.length>0||typeof s?.imageModel=="string"&&s.imageModel.trim()!=="")?"- IMAGE RECOGNITION: When a user sends an image, it is pre-downloaded to a local temp file. Image recognition is performed ONLY by the host platform via [Image] block injection. If you do NOT see an [Image] block for the image, you CANNOT see its content. In that case you MUST tell the user: '\u62B1\u6B49\uFF0C\u56FE\u7247\u8BC6\u522B\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002' NEVER fabricate or guess image descriptions. NEVER use exec/read/search to find or read image files \u2014 these tools cannot extract image content. NEVER call the `canvas` tool directly \u2014 it is an internal host tool and will fail with 'node required' if invoked by the agent.":"- IMAGE RECOGNITION DISABLED: The host has NOT configured image recognition (no imageModel). You CANNOT see any image content. When a user sends an image, reply ONLY with: '\u5F53\u524D\u672A\u542F\u7528\u56FE\u7247\u8BC6\u522B\u529F\u80FD\uFF0C\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002' Do NOT offer workarounds, do NOT suggest the user describe the image, resend it, or provide a file path. NEVER fabricate, guess, or infer image content from filenames. NEVER use exec/read/search to read image files. NEVER call the `canvas` tool directly."]}},actions:{describeMessageTool:()=>({actions:["send"]}),handleAction:async e=>{if(e.action!=="send")throw new Error(`WPS does not support action: ${e.action}`);let t=e.params.to??e.params.target??e.params.receiver_id,r=e.params.message??e.params.text??e.params.content,n=e.params.media,o=e.cfg,i=de(o,te(o)),s=_e(i);if(!s)throw new Error("WPS credentials not configured");let a=t&&typeof t=="string"&&t.trim()?t.trim():"";if(n&&typeof n=="string"&&n.trim()){let l=n.trim();if(Qr(l)){if(!a)throw new Error("WPS send with media requires 'to' (e.g. 'user:<id>' or 'chat:<id>')");return await sn.outbound.sendMedia({cfg:e.cfg,to:a,mediaUrl:l,mimeType:void 0}),{text:`Media sent (${er.basename(l)||"attachment"})`}}}if(!a)throw new Error("WPS send requires 'to' (e.g. 'user:<id>' or 'chat:<id>')");if(!r||typeof r!="string"||!r.trim())throw new Error("WPS send requires 'message' or 'text'");return{text:`Message sent (id: ${(await on(s,a,r.trim())).messageId})`}}}};dt();function nr(e){return e.data??null}function ir(e){return{error:e instanceof Error?e.message:String(e)}}function Ue(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function an(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function ws(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}function xi(e){try{return JSON.parse(e)}catch{throw new Error("content must be valid JSON matching the WPS message content structure")}}function bs(e,t){if(e==="text"){try{let n=JSON.parse(t);if(n&&typeof n=="object"&&"text"in n)return{type:"text",content:n}}catch{}return{type:"text",content:{text:{content:t,type:"markdown"}}}}let r=xi(t);if(typeof r!="object"||r===null)throw new Error(`content for ${e} must be a JSON object (message content subtree)`);return e==="rich_text"?{type:"rich_text",content:r}:{type:"image",content:r}}function dn(e,t){t({name:"wps_message_send",description:`Send a message to any WPS user or chat via OpenAPI. IMPORTANT: When the user asks to send a message to someone or to a chat/group, use THIS tool. If the user provides a chat name instead of an ID, call wps_chat_find_by_name first to resolve the chat_id, then call this tool with receiver_type='chat'. receiver_type: 'user' (for P2P/DM by user_id) or 'chat' (for group/chat by chat_id). receiver_id MUST be the real WPS chat id or user id (numeric/string id from the WPS API). For replies in the current conversation, read inbound RawBody JSON \`chatId\` and \`SenderId\`: use receiver_type='chat' + receiver_id=chatId when chatId is present, else receiver_type='user' + receiver_id=SenderId. NEVER use SessionKey segments after ':bot:' (often looks like AK\u2026) as receiver_id \u2014 that is a bot/app id, not a chat id, and causes invalid chatId / deMixValue errors. Text: msg_type='text', content='{"text":{"content":"hello","type":"markdown"}}'. Image/file: first call wps_media_upload_base64 for storage_key, then msg_type='image' or 'file' with the matching content JSON. Note: cloud documents (type=cloud) cannot be forwarded via this API; to share a cloud doc, reply with the link URL in a text message instead.`,parameters:{type:"object",properties:{receiver_type:{type:"string",enum:["user","chat"],description:"Target kind: `user` opens or uses p2p with that user id; `chat` sends to a chat id."},receiver_id:{type:"string",description:"WPS user id or chat id from the API (not SessionKey `:bot:` segment). For the active thread, prefer RawBody `chatId` or user id."},msg_type:{type:"string",enum:["text","rich_text","image","file"],description:"WPS message type field sent as `type` in the API body."},content:{type:"string",description:"JSON string for the WPS message `content` object (structure depends on msg_type)."},mentions:{type:"array",description:"Optional mention list for group messages.",items:{type:"object",additionalProperties:!0}}},required:["receiver_type","receiver_id","msg_type","content"]},async execute(r,n){try{let o=Ue(n,"receiver_type");if(o!=="user"&&o!=="chat")throw new Error("receiver_type must be 'user' or 'chat'");let i=Ue(n,"receiver_id");if(i.startsWith("wps:")&&(i=i.slice(4)),/^AK\d{8}/i.test(i))throw new Error(`receiver_id="${i}" is a bot/app ID, not a valid user or chat ID. To reply in the current conversation, use the message tool instead of wps_message_send (e.g. message(action="send", to="user:<SenderId>", message="...")). If you need wps_message_send, use receiver_type='user' with SenderId, or receiver_type='chat' with RawBody.chatId.`);let s=Ue(n,"msg_type");if(!["text","rich_text","image","file"].includes(s))throw new Error("msg_type must be one of: text, rich_text, image, file");let a=Ue(n,"content");if(a.length>5e3)throw new Error("content JSON string exceeds 5000 characters");let d=xi(a);if(typeof d!="object"||d===null)throw new Error("parsed content must be a JSON object");let l={type:s,receiver:{type:o,receiver_id:i},content:d},c=n.mentions;if(c!==void 0){if(!Array.isArray(c))throw new Error("mentions must be an array when provided");l.mentions=c}let p=await e.request({method:"POST",path:"/v7/messages/create",body:l});return nr(p)}catch(o){return ir(o)}}}),t({name:"wps_message_reply",description:"Reply to an existing message in a chat (POST /v7/chats/{chat_id}/messages/{message_id}/reply). Use this to reply in-thread to a specific message. For sending NEW messages (not replies), use wps_message_send instead. Supports msg_type text, rich_text, or image. For text, content can be plain text or JSON content object.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."},message_id:{type:"string",description:"Message id to reply to (from RawBody.messageId)."},msg_type:{type:"string",enum:["text","rich_text","image"],description:"Reply payload type."},content:{type:"string",description:"For text: plain string or JSON string of `content`. For rich_text/image: JSON string of the `content` subtree."}},required:["chat_id","message_id","msg_type","content"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=encodeURIComponent(Ue(n,"message_id")),s=Ue(n,"msg_type");if(s!=="text"&&s!=="rich_text"&&s!=="image")throw new Error("msg_type must be text, rich_text, or image");let a=Ue(n,"content"),d=bs(s,a),l=await e.request({method:"POST",path:`/v7/chats/${o}/messages/${i}/reply`,body:d});return nr(l)}catch(o){return ir(o)}}}),t({name:"wps_message_list",description:"List messages in a chat (GET /v7/chats/{chat_id}/messages). page_size defaults to 50. `start_time` and `end_time` are Unix timestamps in **seconds** (converted to milliseconds for the API). Returns paginated message list; use page_token for next pages.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."},start_time:{type:"number",description:"Optional inclusive range start (Unix seconds); sent as start_time query in ms."},end_time:{type:"number",description:"Optional inclusive range end (Unix seconds); sent as end_time query in ms."},page_size:{type:"number",description:"Page size (default 50, max 100)."},page_token:{type:"string",description:"Pagination cursor from a previous response."}},required:["chat_id"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=an(n,"start_time"),s=an(n,"end_time"),a=an(n,"page_size")??50,d=ws(n,"page_token"),l={page_size:a};d!==void 0&&(l.page_token=d),i!==void 0&&(l.start_time=Math.trunc(i*1e3)),s!==void 0&&(l.end_time=Math.trunc(s*1e3));let c=await e.request({method:"GET",path:`/v7/chats/${o}/messages`,query:l});return nr(c)}catch(o){return ir(o)}}}),t({name:"wps_message_get",description:"Fetch a single message by id within a chat (GET /v7/chats/{chat_id}/messages/{message_id}).",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."},message_id:{type:"string",description:"Message id (from RawBody.messageId)."}},required:["chat_id","message_id"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=encodeURIComponent(Ue(n,"message_id")),s=await e.request({method:"GET",path:`/v7/chats/${o}/messages/${i}`});return nr(s)}catch(o){return ir(o)}}})}function vi(e){return e.data??null}function Ti(e){return{error:e instanceof Error?e.message:String(e)}}function Is(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function ks(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function Ss(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}var xs=["active"],vs=["user_name","email","phone"],Ts=["company_user"],Es=50;function cn(e,t){t({name:"wps_user_get",description:"Get the current authenticated bot/app user profile (GET /v7/users/current). Returns fields such as id, user_name, avatar, and company_id when exposed by the API.",parameters:{type:"object",properties:{},required:[]},async execute(r,n){try{let o=await e.request({method:"GET",path:"/v7/users/current"});return vi(o)}catch(o){return Ti(o)}}}),t({name:"wps_user_search",description:"Search company users by keyword (GET /v7/users/search). Always applies status=active, search_field=user_name+email+phone, and search_source=company_user. page_size defaults to 50 (WPS API requires this field). Returns a paginated user list; use page_token for next pages. If no results found, suggest the user refine the keyword or try email/phone.",parameters:{type:"object",properties:{keyword:{type:"string",description:"Search keyword (name, email fragment, phone, etc.)."},page_size:{type:"number",description:"Page size (default 50, max 100)."},page_token:{type:"string",description:"Pagination token from a prior call."}},required:["keyword"]},async execute(r,n){try{let o=Is(n,"keyword"),i=ks(n,"page_size")??Es,s=Ss(n,"page_token"),a={keyword:o,status:[...xs],search_field:[...vs],search_source:[...Ts],page_size:i};s!==void 0&&(a.page_token=s);let d=await e.request({method:"GET",path:"/v7/users/search",query:a});return vi(d)}catch(o){return Ti(o)}}})}function Ct(e){return e.data??null}function pt(e){return{error:e instanceof Error?e.message:String(e)}}function Ei(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function Pi(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function ln(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}var Oi=50;function Ps(e,t){let r=e[t];if(!Array.isArray(r)||r.length===0)throw new Error(`${t} must be a non-empty array of user id strings`);let n=[];for(let o=0;o<r.length;o++){let i=r[o];if(typeof i!="string"||!i.trim())throw new Error(`${t}[${o}] must be a non-empty string`);n.push(i.trim())}return n}function pn(e,t="user"){return{id:e,type:t}}var or=null;async function Os(e){if(or)return or;let r=(await e.request({method:"GET",path:"/v7/users/current"})).data;if(!r||typeof r.id!="string"||!r.id.trim())throw new Error("Cannot retrieve current operator identity from /v7/users/current. Ensure the app has kso.user_base.read permission.");return or={id:r.id.trim(),type:"user"},or}function un(e,t){t({name:"wps_chat_create",description:"Create a p2p or group chat (POST /v7/chats/create). For P2P: provide exactly 2 user ids in member_ids (no auto-injection). For group: provide other member user ids; the current operator is auto-included and becomes owner. Requires kso.chat.readwrite permission.",parameters:{type:"object",properties:{type:{type:"string",enum:["p2p","group"],description:"Chat kind: p2p or group."},member_ids:{type:"array",items:{type:"string"},description:"For P2P: exactly 2 user ids. For group: other member ids (operator auto-included)."},name:{type:"string",description:"Group chat display name (only for group type)."}},required:["type","member_ids"]},async execute(r,n){try{let o=Ei(n,"type");if(o!=="p2p"&&o!=="group")throw new Error("type must be 'p2p' or 'group'");let i=Ps(n,"member_ids"),s,a={type:o};if(o==="group"){let l=await Os(e),c=new Set;s=[],c.add(l.id),s.push(pn(l.id));for(let u of i)c.has(u)||(s.push(pn(u)),c.add(u));a.owner_id=l.id;let p=ln(n,"name");p!==void 0&&p!==""&&(a.name=p)}else{let l=[...new Set(i)];if(l.length!==2)throw new Error(`P2P chat requires exactly 2 distinct user ids in member_ids. Got ${l.length} after dedup.`);s=l.map(c=>pn(c))}a.account_id_list=s;let d=await e.request({method:"POST",path:"/v7/chats/create",body:a});return Ct(d)}catch(o){return pt(o)}}}),t({name:"wps_chat_list",description:"List chats for the current context (GET /v7/chats). page_size defaults to 50. Returns paginated chat list; use page_token for next pages.",parameters:{type:"object",properties:{page_size:{type:"number",description:"Page size (default 50, max 100)."},page_token:{type:"string",description:"Pagination token from a prior call."}},required:[]},async execute(r,n){try{let o=Pi(n,"page_size")??Oi,i=ln(n,"page_token"),s={page_size:o};i!==void 0&&(s.page_token=i);let a=await e.request({method:"GET",path:"/v7/chats",query:s});return Ct(a)}catch(o){return pt(o)}}}),t({name:"wps_chat_get",description:"Get metadata for a single chat (GET /v7/chats/{chat_id}).",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."}},required:["chat_id"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=await e.request({method:"GET",path:`/v7/chats/${o}`});return Ct(i)}catch(o){return pt(o)}}}),t({name:"wps_chat_members",description:"List members of a chat (GET /v7/chats/{chat_id}/members). page_size defaults to 50. Returns paginated member list; use page_token for next pages.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"Chat session id."},page_size:{type:"number",description:"Page size (default 50, max 100)."},page_token:{type:"string",description:"Pagination token from a prior call."}},required:["chat_id"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=Pi(n,"page_size")??Oi,s=ln(n,"page_token"),a={page_size:i};s!==void 0&&(a.page_token=s);let d=await e.request({method:"GET",path:`/v7/chats/${o}/members`,query:a});return Ct(d)}catch(o){return pt(o)}}}),t({name:"wps_chat_is_member",description:"Check whether the current operator is a member of the chat (GET /v7/chats/{chat_id}/members/is_in_chat).",parameters:{type:"object",properties:{chat_id:{type:"string",description:"Chat session id."}},required:["chat_id"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=await e.request({method:"GET",path:`/v7/chats/${o}/members/is_in_chat`});return Ct(i)}catch(o){return pt(o)}}}),t({name:"wps_chat_find_by_name",description:"Find a WPS chat/group by name. IMPORTANT: When the user says 'send message to <group name>' or '\u7ED9 <\u7FA4\u540D> \u53D1\u6D88\u606F', ALWAYS call this tool first to resolve the chat_id, then use wps_message_send with receiver_type='chat' and the resolved chat_id. Returns matching chats with owner info for disambiguation. If multiple matches, present the list to the user for selection.",parameters:{type:"object",properties:{keyword:{type:"string",description:"Chat name keyword to search for."}},required:["keyword"]},async execute(r,n){try{let o=Ei(n,"keyword").toLowerCase(),i=[],s,a=!1;for(let l=0;l<10;l++){let c={page_size:100};s&&(c.page_token=s);let p=await e.request({method:"GET",path:"/v7/chats",query:c});for(let u of p.data?.items??[])u.chat_id&&u.name?.toLowerCase().includes(o)&&i.push({chat_id:u.chat_id,name:u.name,owner_id:u.owner_id});if(!p.data?.has_more)break;if(s=p.data?.page_token,!s){a=!0;break}}let d={};return a&&(d.warning="Results may be incomplete: pagination was truncated due to missing page_token."),i.length===0?{...d,found:!1,message:`No chats found matching "${o}"`}:i.length===1?{...d,found:!0,match:i[0]}:{...d,found:!0,multiple:!0,matches:i,hint:"Multiple matches found. Present the list to the user with chat name and owner info for selection."}}catch(o){return pt(o)}}})}nt();dt();Gt();Zt();async function ce(e){let t=xt(e.wpsUserId);if(t){let i=Xt(),s=Ir(i.baseUrl,t);return await e.run(s)}let r=Kr(),n=Xt(),o=at();try{await Jr({creds:n,wpsCfg:r,wpsUserId:e.wpsUserId,receiverType:"user",receiverId:e.wpsUserId,originalMessage:e.authCardOriginalMessage})}catch(i){o?.error?.(`[${e.logTag}] Failed to send auth card: ${String(i)}`)}return{needsAuth:!0,message:e.needsAuthMessage}}var Ai=31*24*60*60*1e3,As=100,Ri=200,$i=50,qi=100;function L(e){return{error:e instanceof Error?e.message:String(e)}}function P(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function x(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}function ut(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function _t(e,t){let r=e[t];if(r!=null){if(typeof r=="boolean")return r;if(r==="true"||r==="false")return r==="true";throw new Error(`${t} must be a boolean`)}}function Rs(e,t){let r=e[t];if(r==null)throw new Error(`${t} is required and must be a finite number`);if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}function sr(e,t){let r=new Date(t.trim());if(Number.isNaN(r.getTime()))throw new Error(`${e} must be a valid RFC3339 / ISO 8601 datetime string`);return r}function ft(e){return e.toISOString()}function _n(e){let t=e.now??new Date,r,n,o=!!e.startRfc?.trim(),i=!!e.endRfc?.trim();if(o&&i?(r=sr("start_time",e.startRfc),n=sr("end_time",e.endRfc)):o?(r=sr("start_time",e.startRfc),n=new Date(r.getTime()+14*86400*1e3)):i?(n=sr("end_time",e.endRfc),r=new Date(n.getTime()-14*86400*1e3)):(r=new Date(t.getTime()-86400*1e3),n=new Date(t.getTime()+14*86400*1e3)),n.getTime()<r.getTime())throw new Error("end_time must be >= start_time (RFC3339 range)");return n.getTime()-r.getTime()>Ai&&(n=new Date(r.getTime()+Ai)),{start:r,end:n}}function $s(e){let{start:t,end:r}=_n({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now}),n={start_time:ft(t),end_time:ft(r)},o=e.pageSize??30;return n.page_size=Math.max(1,Math.min(500,Math.trunc(o))),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(n.page_token=e.pageToken.trim()),n}function qs(e){let{start:t,end:r}=_n({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now});return{start_time:ft(t),end_time:ft(r)}}function Cs(e){let t={},r=e.pageSize??30;if(t.page_size=Math.max(1,Math.min(500,Math.trunc(r))),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),e.withCancelled===!0&&(t.with_cancelled=!0),e.syncToken!==void 0&&e.syncToken.trim()!==""&&(t.sync_token=e.syncToken.trim()),e.anchorTime!==void 0&&e.anchorTime.trim()!==""&&(t.anchor_time=e.anchorTime.trim()),t.sync_token)return t;let{start:n,end:o}=_n({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now});return t.start_time=ft(n),t.end_time=ft(o),t}function Ds(e){let t=new Date(e.trim());if(Number.isNaN(t.getTime()))throw new Error("start_time must be a valid ISO 8601 datetime");return t.setTime(t.getTime()+60*60*1e3),t.toISOString()}function Te(e,t){return`/v7/calendars/${encodeURIComponent(e)}/events/${encodeURIComponent(t)}`}function Ns(e,t){return`${Te(e,t)}/respond`}function fn(e,t){return`${Te(e,t)}/attendees`}function Us(e,t){return`${fn(e,t)}/batch_create`}function js(e,t){return`${fn(e,t)}/batch_delete`}function Ms(e,t){return`${Te(e,t)}/meeting_rooms`}function Ws(e,t){return`${Te(e,t)}/meeting_rooms/batch_create`}function zs(e,t){return`${Te(e,t)}/meeting_rooms/batch_delete`}function Ci(e){if(!Array.isArray(e)||e.length===0)throw new Error("room_ids is required and must be a non-empty array");let t=e.map((r,n)=>{if(typeof r!="string")throw new Error(`room_ids[${n}] must be a string`);let o=r.trim();if(!o)throw new Error(`room_ids[${n}] must be non-empty`);return o});if(t.length>qi)throw new Error(`room_ids length must be <= ${qi}`);return{room_ids:t}}function Ls(e){let t=e.pageSize??30,n={page_size:Math.max(1,Math.min(As,Math.trunc(t)))};return e.pageToken!==void 0&&e.pageToken.trim()!==""&&(n.page_token=e.pageToken.trim()),n}function je(e){let t=x(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let r=t.trim();if(r!=="internal"&&r!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":r}}async function V(e,t,r){try{return await ce({wpsUserId:e,authCardOriginalMessage:t,needsAuthMessage:"\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u64CD\u4F5C\u65E5\u7A0B\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5\u3002",logTag:"calendar",run:r})}catch(n){return L(n)}}function mn(e,t){t({name:"wps_calendar_create",description:"Create a calendar event for the current user via WPS OpenAPI. Requires user OAuth authorization. If the user has not authorized, an authorization card will be sent automatically. IMPORTANT: Use the SenderId from the current conversation context as wps_user_id. Do NOT call wps_user_search or wps_user_get to look up the user. If end_time is omitted, it defaults to start_time + 1 hour (computed as UTC ISO).",parameters:{type:"object",properties:{summary:{type:"string",description:"Event title."},start_time:{type:"string",description:"Start time in ISO 8601 with timezone (e.g. '2026-04-22T14:00:00+08:00')."},end_time:{type:"string",description:"End time in ISO 8601 with timezone. Omit to default to start_time + 1 hour."},description:{type:"string",description:"Optional event description."},location:{type:"string",description:"Optional event location."},wps_user_id:{type:"string",description:"WPS user ID. Use SenderId from the conversation context. Do NOT call wps_user_search or wps_user_get for this."}},required:["summary","start_time"]},async execute(o,i){try{let s=P(i,"summary"),a=P(i,"start_time"),d=x(i,"end_time"),l=d&&d.trim()!==""?d.trim():Ds(a),c=x(i,"description"),p=x(i,"location"),u=x(i,"wps_user_id")??"";return u?await V(u,s,async _=>{let m={summary:s,start_time:{datetime:a},end_time:{datetime:l}};c&&(m.description=c),p&&(m.locations=[{name:p}]);let y=await _.request({method:"POST",path:"/v7/calendars/primary/events/create",body:m});return y.data??y}):L(new Error("wps_user_id is required. Use the SenderId from the conversation context."))}catch(s){return L(s)}}}),t({name:"wps_calendar_list_events",description:"List calendar events on the user's primary calendar: GET `/v7/calendars/primary/events` (same as `/v7/calendars/{calendar_id}/events` with calendar_id `primary`). Official doc: https://365.kdocs.cn/3rd/open/documents/app-integration-dev/wps365/server/calendar/calendar-event/get-calendar-event-list Requires user delegated OAuth (same as wps_calendar_create). Use SenderId as wps_user_id. Time range: `start_time` and `end_time` query params are **RFC3339 / ISO8601 strings** (not Unix seconds). If both are omitted, defaults to about last 24 hours through next 14 days, clamped to max 31-day span per API. If `sync_token` is set, incremental sync mode: only sync_token/page_token/page_size/with_cancelled are sent (no automatic time window). Optional: anchor_time (RFC3339), with_cancelled (boolean).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},start_time:{type:"string",description:"Optional range start (RFC3339 / ISO8601). Must be used with end_time for explicit window, or omit both for defaults."},end_time:{type:"string",description:"Optional range end (RFC3339 / ISO8601). API allows 0\u201331 days between start and end; longer ranges are truncated."},page_size:{type:"number",description:"Page size (default 30 per API doc, max 500 client-side cap)."},page_token:{type:"string",description:"Pagination cursor from data.next_page_token."},with_cancelled:{type:"boolean",description:"Include cancelled events (per API)."},sync_token:{type:"string",description:"Incremental sync token from data.next_sync_token; when set, time range is not auto-filled."},anchor_time:{type:"string",description:"Anchor time RFC3339 for incremental sync (per API)."}},required:["wps_user_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=x(i,"start_time"),d=x(i,"end_time"),l=ut(i,"page_size"),c=x(i,"page_token"),p=_t(i,"with_cancelled"),u=x(i,"sync_token"),_=x(i,"anchor_time");return await V(s,"\u67E5\u8BE2\u4E3B\u65E5\u5386\u65E5\u7A0B\u5217\u8868",async m=>{let y=Cs({startRfc:a,endRfc:d,pageSize:l,pageToken:c,withCancelled:p,syncToken:u,anchorTime:_}),h=await m.request({method:"GET",path:"/v7/calendars/primary/events",query:y});return h.data??h})}catch(s){return L(s)}}}),t({name:"wps_calendar_get_event",description:"Get **one** calendar event by id (official \u67E5\u8BE2\u65E5\u7A0B): GET `/v7/calendars/{calendar_id}/events/{event_id}`. Response `data` is a single event object (summary, recurrence, online_meeting, etc.), not `items[]`. Requires `event_id` from `wps_calendar_list_events` (or equivalent). Same delegated Bearer auth as `wps_calendar_create`. Optional `calendar_id` (default `primary`). Optional header `X-Kso-Id-Type`: pass `x_kso_id_type` as `internal` or `external` per API.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from the calendar event list API."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type` header: `internal` or `external` (per WPS API).",enum:["internal","external"]}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary";return await V(s,"\u67E5\u8BE2\u65E5\u7A0B\u8BE6\u60C5",async l=>{let c=await l.request({method:"GET",path:Te(d,a),headers:je(i)});return c.data??c})}catch(s){return L(s)}}}),t({name:"wps_calendar_list_event_attendees",description:"List attendees for one calendar event (official \u83B7\u53D6\u65E5\u7A0B\u53C2\u4E0E\u8005\u5217\u8868): GET `/v7/calendars/{calendar_id}/events/{event_id}/attendees`. Response `data` typically has `items[]` and optional `next_page_token`. Requires `event_id` from `wps_calendar_list_events` or `wps_calendar_get_event`. Same delegated Bearer auth as `wps_calendar_create`. Optional `calendar_id` (default `primary`). Query: optional `page_size` (default 30, max 100 per API), `page_token` from `data.next_page_token`. Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from the calendar event list API."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},page_size:{type:"number",description:"Page size (default 30; API max 100)."},page_token:{type:"string",description:"Pagination cursor from data.next_page_token."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary",l=ut(i,"page_size"),c=x(i,"page_token");return await V(s,"\u83B7\u53D6\u65E5\u7A0B\u53C2\u4E0E\u8005\u5217\u8868",async p=>{let u=Ls({pageSize:l,pageToken:c}),_=await p.request({method:"GET",path:fn(d,a),query:u,headers:je(i)});return _.data??_})}catch(s){return L(s)}}}),t({name:"wps_calendar_add_event_attendees",description:"Batch add attendees to one event (official \u6DFB\u52A0\u65E5\u7A0B\u53C2\u4E0E\u8005): POST `/v7/calendars/{calendar_id}/events/{event_id}/attendees/batch_create`. Requires delegated OAuth (same as `wps_calendar_create`). Body requires `attendees` array (max 200 per request; total attendees per event max 1000). Each attendee item typically includes `type`, `user_id` or `third_party_email`, optional `is_optional` and `response_status`. Optional `is_notification` controls whether attendees receive invitation notifications (default true). Optional `calendar_id` (default `primary`). Optional `x_kso_id_type` maps to `X-Kso-Id-Type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from event list/search/get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},attendees:{type:"array",description:"Attendees to add in batch (required, max 200 per request). Each item supports fields like { type, user_id, third_party_email, is_optional, response_status }.",items:{type:"object",properties:{type:{type:"string"},user_id:{type:"string"},third_party_email:{type:"string"},is_optional:{type:"boolean"},response_status:{type:"string"}}}},is_notification:{type:"boolean",description:"Whether to notify added attendees (default true)."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id","attendees"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary",l=_t(i,"is_notification"),c=i.attendees;if(!Array.isArray(c)||c.length===0)throw new Error("attendees is required and must be a non-empty array");if(c.length>Ri)throw new Error(`attendees length must be <= ${Ri}`);let p=c.map((u,_)=>{if(typeof u!="object"||u===null||Array.isArray(u))throw new Error(`attendees[${_}] must be an object`);let m=u,y={};if(m.type!==void 0){if(typeof m.type!="string"||!m.type.trim())throw new Error(`attendees[${_}].type must be a non-empty string when provided`);y.type=m.type.trim()}if(m.user_id!==void 0){if(typeof m.user_id!="string"||!m.user_id.trim())throw new Error(`attendees[${_}].user_id must be a non-empty string when provided`);y.user_id=m.user_id.trim()}if(m.third_party_email!==void 0){if(typeof m.third_party_email!="string"||!m.third_party_email.trim())throw new Error(`attendees[${_}].third_party_email must be a non-empty string when provided`);y.third_party_email=m.third_party_email.trim()}if(m.is_optional!==void 0){if(typeof m.is_optional!="boolean")throw new Error(`attendees[${_}].is_optional must be a boolean when provided`);y.is_optional=m.is_optional}if(m.response_status!==void 0){if(typeof m.response_status!="string"||!m.response_status.trim())throw new Error(`attendees[${_}].response_status must be a non-empty string when provided`);y.response_status=m.response_status.trim()}if(Object.keys(y).length===0)throw new Error(`attendees[${_}] must contain at least one valid field`);return y});return await V(s,"\u6DFB\u52A0\u65E5\u7A0B\u53C2\u4E0E\u8005",async u=>{let _={attendees:p};l!==void 0&&(_.is_notification=l);let m=await u.request({method:"POST",path:Us(d,a),body:_,headers:je(i)});return m.data??m})}catch(s){return L(s)}}}),t({name:"wps_calendar_list_event_meeting_rooms",description:"List meeting rooms bound to one calendar event (\u83B7\u53D6\u67D0\u4E2A\u65E5\u7A0B\u7684\u4F1A\u8BAE\u5BA4\u5217\u8868): GET `/v7/calendars/{calendar_id}/events/{event_id}/meeting_rooms`. Requires delegated OAuth **`kso.calendar_events.read`** (or `readwrite`) and `event_id`. Optional `calendar_id` (default `primary`). Response `data.items[]` commonly includes room/book fields like `room_id`, `name`, `booking_id`, `result`, `fail_reason`. Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from event list / search / get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary";return await V(s,"\u83B7\u53D6\u65E5\u7A0B\u4F1A\u8BAE\u5BA4\u5217\u8868",async l=>{let c=await l.request({method:"GET",path:Ms(d,a),headers:je(i)});return c.data??c})}catch(s){return L(s)}}}),t({name:"wps_calendar_event_meeting_rooms_batch_create",description:"Batch add meeting rooms to one calendar event (\u6279\u91CF\u6DFB\u52A0\u67D0\u4E2A\u65E5\u7A0B\u7684\u4F1A\u8BAE\u5BA4): POST `/v7/calendars/{calendar_id}/events/{event_id}/meeting_rooms/batch_create`. Requires delegated OAuth **`kso.calendar_events.readwrite`** (per API). Use SenderId as wps_user_id. Required: `event_id`, non-empty **`room_ids`** (string array; room ids from `wps_meeting_rooms_list` / search / get). Optional `calendar_id` (default `primary`). Response `data.items[]` may include `room_id`, `name`, `result`, `booking_id`, `fail_reason`. Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from event list / search / get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},room_ids:{type:"array",description:"Meeting room ids to attach to this event (non-empty; max 100 per request).",items:{type:"string"}},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id","room_ids"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary",l=i.room_ids;if(!Array.isArray(l))throw new Error("room_ids is required and must be an array");let c=Ci(l);return await V(s,"\u6279\u91CF\u6DFB\u52A0\u65E5\u7A0B\u4F1A\u8BAE\u5BA4",async p=>{let u=await p.request({method:"POST",path:Ws(d,a),body:c,headers:je(i)});return u.data??u})}catch(s){return L(s)}}}),t({name:"wps_calendar_event_meeting_rooms_batch_delete",description:"Batch delete meeting rooms from one calendar event (\u6279\u91CF\u5220\u9664\u67D0\u4E2A\u65E5\u7A0B\u7684\u4F1A\u8BAE\u5BA4): POST `/v7/calendars/{calendar_id}/events/{event_id}/meeting_rooms/batch_delete`. Requires delegated OAuth **`kso.calendar_events.readwrite`**. Use SenderId as wps_user_id. Required: `event_id`, non-empty **`room_ids`** (meeting room ids bound to this event). Optional `calendar_id` (default `primary`). Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from event list / search / get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},room_ids:{type:"array",description:"Meeting room ids to remove from this event (non-empty; max 100 per request).",items:{type:"string"}},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id","room_ids"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary",l=i.room_ids;if(!Array.isArray(l))throw new Error("room_ids is required and must be an array");let c=Ci(l);return await V(s,"\u6279\u91CF\u5220\u9664\u65E5\u7A0B\u4F1A\u8BAE\u5BA4",async p=>{let u=await p.request({method:"POST",path:zs(d,a),body:c,headers:je(i)});return u.data??u})}catch(s){return L(s)}}}),t({name:"wps_calendar_delete_event_attendees",description:"Batch delete attendees from one event (official \u5220\u9664\u65E5\u7A0B\u53C2\u4E0E\u8005): POST `/v7/calendars/{calendar_id}/events/{event_id}/attendees/batch_delete`. Requires delegated OAuth (same as `wps_calendar_create`). Body requires `attendees` array and supports optional `attendee_ids` array. Per API, `attendee_ids.length + attendees.length` must be <= 50 in one request. Optional `is_notification` controls whether removed attendees receive notification (default true). Optional `calendar_id` (default `primary`). Optional `x_kso_id_type` maps to `X-Kso-Id-Type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from event list/search/get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},attendee_ids:{type:"array",description:"Optional attendee id list. Combined count with `attendees` must be <= 50.",items:{type:"string"}},attendees:{type:"array",description:"Attendees payload to remove (required). Combined count with `attendee_ids` must be <= 50. Each item supports fields like { type, user_id, third_party_email }.",items:{type:"object",properties:{type:{type:"string"},user_id:{type:"string"},third_party_email:{type:"string"}}}},is_notification:{type:"boolean",description:"Whether to notify removed attendees (default true)."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id","attendees"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary",l=_t(i,"is_notification"),c=i.attendee_ids,p;if(c!==void 0){if(!Array.isArray(c))throw new Error("attendee_ids must be an array of strings when provided");p=c.map((y,h)=>{if(typeof y!="string"||!y.trim())throw new Error(`attendee_ids[${h}] must be a non-empty string`);return y.trim()})}let u=i.attendees;if(!Array.isArray(u)||u.length===0)throw new Error("attendees is required and must be a non-empty array");let _=u.map((y,h)=>{if(typeof y!="object"||y===null||Array.isArray(y))throw new Error(`attendees[${h}] must be an object`);let f=y,g={};if(f.type!==void 0){if(typeof f.type!="string"||!f.type.trim())throw new Error(`attendees[${h}].type must be a non-empty string when provided`);g.type=f.type.trim()}if(f.user_id!==void 0){if(typeof f.user_id!="string"||!f.user_id.trim())throw new Error(`attendees[${h}].user_id must be a non-empty string when provided`);g.user_id=f.user_id.trim()}if(f.third_party_email!==void 0){if(typeof f.third_party_email!="string"||!f.third_party_email.trim())throw new Error(`attendees[${h}].third_party_email must be a non-empty string when provided`);g.third_party_email=f.third_party_email.trim()}if(Object.keys(g).length===0)throw new Error(`attendees[${h}] must contain at least one valid field`);return g});if((p?.length??0)+_.length>$i)throw new Error(`attendee_ids.length + attendees.length must be <= ${$i}`);return await V(s,"\u5220\u9664\u65E5\u7A0B\u53C2\u4E0E\u8005",async y=>{let h={attendees:_};p&&p.length>0&&(h.attendee_ids=p),l!==void 0&&(h.is_notification=l);let f=await y.request({method:"POST",path:js(d,a),body:h,headers:je(i)});return f.data??f})}catch(s){return L(s)}}}),t({name:"wps_calendar_respond_invitation",description:"Reply to a calendar invitation (official \u7B54\u590D\u65E5\u7A0B\u9080\u8BF7): POST `/v7/calendars/{calendar_id}/events/{event_id}/respond`. Requires delegated OAuth (same as `wps_calendar_create`). Body per API: `mod_type` (`normal` = non-recurring reply, `one` = one occurrence of recurring, `all` = entire series), `response_status` (`accepted` | `declined` | `tentative`), `which_day_time` = **start time in milliseconds** (Unix ms) for the occurrence being answered. Use `event_id` from `wps_calendar_list_events` / `wps_calendar_get_event`; for recurring series pick `which_day_time` from instance or event `start_time`. Optional `calendar_id` (default `primary`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Calendar event id (from event list or get-event API)."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},mod_type:{type:"string",description:"Reply scope per WPS API.",enum:["normal","one","all"]},response_status:{type:"string",description:"Invitation response.",enum:["accepted","declined","tentative"]},which_day_time:{type:"number",description:"Schedule start time as **milliseconds since Unix epoch** (per API `which_day_time`). Use the occurrence start from list/get/event_instances."}},required:["wps_user_id","event_id","mod_type","response_status","which_day_time"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary",l=P(i,"mod_type");if(l!=="normal"&&l!=="one"&&l!=="all")throw new Error("mod_type must be normal, one, or all");let c=P(i,"response_status");if(c!=="accepted"&&c!=="declined"&&c!=="tentative")throw new Error("response_status must be accepted, declined, or tentative");let p=Math.trunc(Rs(i,"which_day_time"));return await V(s,"\u7B54\u590D\u65E5\u7A0B\u9080\u8BF7",async u=>{let _=await u.request({method:"POST",path:Ns(d,a),body:{mod_type:l,response_status:c,which_day_time:p}});return _.data??_})}catch(s){return L(s)}}}),t({name:"wps_calendar_list_calendar_event_instances",description:"List expanded **calendar-level** event instances (all occurrences in a time window): GET `/v7/calendars/{calendar_id}/event_instances` (use `calendar_id=primary` for main calendar). Same delegated Bearer auth as `wps_calendar_create`. Query: RFC3339 `start_time` / `end_time` (0\u201331 days), optional `page_size` (default 30), `page_token`. Use when you need many instances across the calendar without a specific `event_id`. To expand **one** recurring event by id, use `wps_calendar_list_event_instances` instead.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},calendar_id:{type:"string",description:"Calendar id or the literal `primary` (default)."},start_time:{type:"string",description:"Optional range start (RFC3339). Omit both for default window."},end_time:{type:"string",description:"Optional range end (RFC3339). Max 31-day span; longer truncated."},page_size:{type:"number",description:"Page size (default 30, max 500)."},page_token:{type:"string",description:"Pagination cursor if returned by API."}},required:["wps_user_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=x(i,"calendar_id")??"primary",d=x(i,"start_time"),l=x(i,"end_time"),c=ut(i,"page_size"),p=x(i,"page_token");return await V(s,"\u67E5\u8BE2\u65E5\u5386\u65E5\u7A0B\u5B9E\u4F8B\u5217\u8868",async u=>{let _=$s({startRfc:d,endRfc:l,pageSize:c,pageToken:p}),m=await u.request({method:"GET",path:`/v7/calendars/${encodeURIComponent(a)}/event_instances`,query:_});return m.data??m})}catch(s){return L(s)}}}),t({name:"wps_calendar_list_event_instances",description:"Query **instances of one calendar event** (expand a recurring series for that event id): GET `/v7/calendars/{calendar_id}/events/{event_id}/event_instances` per WPS365 doc. Requires `event_id` from `wps_calendar_list_events` (or equivalent). Optional query: `start_time` / `end_time` **RFC3339** strings; range 0\u201331 days (truncated if longer); omit both for default window. Same delegated Bearer auth as `wps_calendar_create`. Optional `calendar_id` (default `primary`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Calendar event id from the event list API."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},start_time:{type:"string",description:"Optional query range start (RFC3339). Used with end_time; omit both for defaults."},end_time:{type:"string",description:"Optional query range end (RFC3339)."}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary",l=x(i,"start_time"),c=x(i,"end_time");return await V(s,"\u67E5\u8BE2\u5355\u6761\u65E5\u7A0B\u5B9E\u4F8B",async p=>{let u=qs({startRfc:l,endRfc:c}),_=await p.request({method:"GET",path:`${Te(d,a)}/event_instances`,query:u});return _.data??_})}catch(s){return L(s)}}});let r=100,n=500;t({name:"wps_calendar_search_events",description:"Search calendar events by keyword (official \u641C\u7D22\u65E5\u7A0B): POST `/v7/calendars/{calendar_id}/events/search`. Searches event titles, descriptions, and notes. Requires user delegated OAuth (same as wps_calendar_create). Use SenderId as wps_user_id. Body: `keyword` (required, 1-100 chars), optional `page_size` (default 200, max 500), optional `page_token`. Response: `data.items[]` (event list) and optional `data.next_page_token`. Optional `calendar_id` (default `primary`). Optional header `X-Kso-Id-Type`: pass `x_kso_id_type` as `internal` or `external` per API.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},keyword:{type:"string",description:"Search keyword (1-100 chars). Matches event title, description, notes."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},page_size:{type:"number",description:"Page size (default 200 per API, max 500)."},page_token:{type:"string",description:"Pagination cursor from data.next_page_token."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type` header: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","keyword"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"keyword");if(a.length>r)throw new Error(`keyword must be at most ${r} characters`);let d=x(i,"calendar_id")??"primary",l=ut(i,"page_size"),c=x(i,"page_token");return await V(s,"\u641C\u7D22\u65E5\u7A0B",async p=>{let u={keyword:a},_=l??200;u.page_size=Math.max(1,Math.min(n,Math.trunc(_))),c!==void 0&&c.trim()!==""&&(u.page_token=c.trim());let m=await p.request({method:"POST",path:`/v7/calendars/${encodeURIComponent(d)}/events/search`,body:u,headers:je(i)});return m.data??m})}catch(s){return L(s)}}}),t({name:"wps_calendar_update_event",description:"Update (modify) a calendar event (official \u4FEE\u6539\u65E5\u7A0B): POST `/v7/calendars/{calendar_id}/events/{event_id}/update`. Requires user delegated OAuth (same as wps_calendar_create). Use SenderId as wps_user_id. All body fields are optional \u2014 only pass what needs to change. For recurring events: set `mod_type` to `one` (single occurrence, requires `which_day_time` in ms) or `all` (entire series). Set `is_notification` to false to suppress attendee notifications. Set `online_meeting` to null to clear the meeting. Optional `calendar_id` (default `primary`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from calendar event list or search."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},summary:{type:"string",description:"New event title."},description:{type:"string",description:"New event description / notes."},start_time:{type:"string",description:"New start time in ISO 8601 with timezone (e.g. '2026-05-10T14:00:00+08:00')."},end_time:{type:"string",description:"New end time in ISO 8601 with timezone."},location:{type:"string",description:"New event location (API supports max 1 location)."},free_busy_status:{type:"string",description:"Busy/free status during the event.",enum:["busy","free"]},visibility:{type:"string",description:"Event visibility scope.",enum:["default","public","private"]},attendee_ability:{type:"string",description:"Attendee permission level.",enum:["can_see_others","can_invite_others"]},mod_type:{type:"string",description:"For recurring events only: `one` = edit single occurrence (requires which_day_time), `all` = edit entire series.",enum:["one","all"]},which_day_time:{type:"number",description:"When mod_type=one, the start time of the occurrence to modify in **milliseconds** (Unix epoch ms)."},is_notification:{type:"boolean",description:"Whether to notify attendees about the update (default true)."},is_reinvition:{type:"boolean",description:"When true and time/recurrence changes, reset all attendees to not-accepted (default true)."},reminders:{type:"array",description:"Reminder list (max 10). Each item: { minutes: number }.",items:{type:"object",properties:{minutes:{type:"number"}},required:["minutes"]}}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary",l=x(i,"mod_type");if(l!==void 0&&l!=="one"&&l!=="all")throw new Error("mod_type must be one or all when provided");let c=ut(i,"which_day_time");if(l==="one"&&c==null)throw new Error("which_day_time (ms) is required when mod_type is one");let p=x(i,"free_busy_status");if(p!==void 0&&p!=="busy"&&p!=="free")throw new Error("free_busy_status must be busy or free");let u=x(i,"visibility");if(u!==void 0&&u!=="default"&&u!=="public"&&u!=="private")throw new Error("visibility must be default, public, or private");let _=x(i,"attendee_ability");if(_!==void 0&&_!=="can_see_others"&&_!=="can_invite_others")throw new Error("attendee_ability must be can_see_others or can_invite_others");return await V(s,"\u4FEE\u6539\u65E5\u7A0B",async m=>{let y={},h=x(i,"summary");h!==void 0&&(y.summary=h);let f=x(i,"description");f!==void 0&&(y.description=f);let g=x(i,"start_time");g!==void 0&&(y.start_time={datetime:g});let w=x(i,"end_time");w!==void 0&&(y.end_time={datetime:w});let b=x(i,"location");b!==void 0&&(y.locations=[{name:b}]),p!==void 0&&(y.free_busy_status=p),u!==void 0&&(y.visibility=u),_!==void 0&&(y.attendee_ability=_),l!==void 0&&(y.mod_type=l),c!==void 0&&(y.which_day_time=Math.trunc(c));let I=_t(i,"is_notification");I!==void 0&&(y.is_notification=I);let E=_t(i,"is_reinvition");E!==void 0&&(y.is_reinvition=E);let N=i.reminders;Array.isArray(N)&&(y.reminders=N.slice(0,10).map(Z=>{let B=Z;return{minutes:typeof B.minutes=="number"?Math.trunc(B.minutes):0}}));let re=await m.request({method:"POST",path:`${Te(d,a)}/update`,body:y});return re.data??re})}catch(s){return L(s)}}}),t({name:"wps_calendar_delete_event",description:"Delete a calendar event (official \u5220\u9664\u65E5\u7A0B): POST `/v7/calendars/{calendar_id}/events/{event_id}/delete`. Requires user delegated OAuth (same as wps_calendar_create). Use SenderId as wps_user_id. Optional body: `is_notification` (default true). For recurring events: set `mod_type` to `one` (delete one occurrence, requires `which_day_time` in ms) or `all` (delete entire series). Optional `calendar_id` (default `primary`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from calendar list/search/get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},is_notification:{type:"boolean",description:"Whether to notify attendees about deletion (default true)."},mod_type:{type:"string",description:"For recurring events only: `one` (single occurrence, requires which_day_time) or `all` (entire series).",enum:["one","all"]},which_day_time:{type:"number",description:"When mod_type=one, the start time of occurrence to delete in milliseconds."}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=x(i,"calendar_id")??"primary",l=x(i,"mod_type");if(l!==void 0&&l!=="one"&&l!=="all")throw new Error("mod_type must be one or all when provided");let c=ut(i,"which_day_time");if(l==="one"&&c===void 0)throw new Error("which_day_time (ms) is required when mod_type is one");let p=_t(i,"is_notification");return await V(s,"\u5220\u9664\u65E5\u7A0B",async u=>{let _={};p!==void 0&&(_.is_notification=p),l!==void 0&&(_.mod_type=l),c!==void 0&&(_.which_day_time=Math.trunc(c));let m=await u.request({method:"POST",path:`${Te(d,a)}/delete`,body:_});return m.data??m})}catch(s){return L(s)}}})}var Bs="/v7/todo/personal_tasks",Fs="/v7/todo/personal_tasks/batch_get";function ar(e){return`/v7/todo/personal_tasks/${encodeURIComponent(e.trim())}`}function Gs(e){return`${ar(e.trim())}/update`}function Ks(e){return`${ar(e.trim())}/update_status`}var Di=100,Hs=20,Js=50;function ht(e){return{error:e instanceof Error?e.message:String(e)}}function Ee(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function Y(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}function Je(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function Xs(e,t){let r=e[t];if(r==null)return;if(!Array.isArray(r))throw new Error(`${t} must be an array of strings`);let n=r.map(o=>String(o).trim()).filter(Boolean);return n.length>0?n:void 0}function Vs(e,t){let r=e[t];if(r==null)return;if(!Array.isArray(r))throw new Error(`${t} must be an array of objects with name and value`);let n=[];for(let o of r){if(typeof o!="object"||o===null)continue;let i=o;typeof i.name!="string"||typeof i.value!="string"||n.push({name:i.name.trim(),value:i.value})}return n.length>0?n:void 0}function Ys(e,t){let r=Y(e,t);if(!(r===void 0||r.trim()===""))try{let n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${t} must be a JSON object`);return n}catch(n){throw n instanceof SyntaxError?new Error(`${t} must be valid JSON`):n}}function mt(e){let t=Y(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let r=t.trim();if(r!=="internal"&&r!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":r}}function Zs(e){let t=e.titleSubject.trim();if(!t)throw new Error("title_subject must be non-empty");let r={subject:t};e.titlePrefix!==void 0&&e.titlePrefix.trim()!==""&&(r.prefix=e.titlePrefix.trim());let n={title:r};if(e.description!==void 0&&e.description.trim()!==""&&(n.description=e.description.trim()),e.dueTimeMs!==void 0){if(!Number.isFinite(e.dueTimeMs))throw new Error("due_time_ms must be a finite number");n.due_time=Math.trunc(e.dueTimeMs)}if((e.status==="todo"||e.status==="finish")&&(n.status=e.status),e.executors!==void 0&&e.executors.length>0){if(e.executors.length>Di)throw new Error(`executors must have at most ${Di} entries`);n.executors=[...e.executors]}return n}function Qs(e){let t={};if(e.keyword!==void 0&&e.keyword.trim()!==""&&(t.keyword=e.keyword.trim().slice(0,50)),e.executor!==void 0&&e.executor.trim()!==""&&(t.executor=e.executor.trim()),(e.status==="todo"||e.status==="finish")&&(t.status=e.status),e.pageSize!==void 0){let r=e.pageSize;t.page_size=Math.max(1,Math.min(Js,Math.trunc(r)))}else t.page_size=Hs;if(e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),e.createdTimeStartMs!==void 0||e.createdTimeEndMs!==void 0){let r={};e.createdTimeStartMs!==void 0&&Number.isFinite(e.createdTimeStartMs)&&(r.start_time=Math.trunc(e.createdTimeStartMs)),e.createdTimeEndMs!==void 0&&Number.isFinite(e.createdTimeEndMs)&&(r.end_time=Math.trunc(e.createdTimeEndMs)),Object.keys(r).length>0&&(t.created_time=r)}if(e.dueTimeStartMs!==void 0||e.dueTimeEndMs!==void 0){let r={};e.dueTimeStartMs!==void 0&&Number.isFinite(e.dueTimeStartMs)&&(r.start_time=Math.trunc(e.dueTimeStartMs)),e.dueTimeEndMs!==void 0&&Number.isFinite(e.dueTimeEndMs)&&(r.end_time=Math.trunc(e.dueTimeEndMs)),Object.keys(r).length>0&&(t.due_time=r)}return t}function ea(e){let t={},r=e.titleSubject?.trim()??"",n=e.titlePrefix?.trim()??"";if(r!==""||n!==""){let o={};r!==""&&(o.subject=r),n!==""&&(o.prefix=n),t.title=o}if(e.description!==void 0&&e.description.trim()!==""&&(t.description=e.description.trim()),e.dueTimeMs!==void 0){if(!Number.isFinite(e.dueTimeMs))throw new Error("due_time_ms must be a finite number");t.due_time=Math.trunc(e.dueTimeMs)}if(e.extAttrs!==void 0&&e.extAttrs.length>0&&(t.ext_attrs=e.extAttrs.map(o=>({name:o.name,value:o.value}))),e.notifyConfig!==void 0&&Object.keys(e.notifyConfig).length>0&&(t.notify_config=e.notifyConfig),Object.keys(t).length===0)throw new Error("provide at least one of: title_subject, title_prefix, description, due_time_ms, ext_attrs, notify_config_json");return t}var ta=new Set(["finish","unfinish","finish_all","unfinish_all"]);function ra(e){return ta.has(e)}function Ni(e){let t=e.trim();if(!ra(t))throw new Error("action must be exactly one of: finish, unfinish, finish_all, unfinish_all");return t}function na(e){return{action:Ni(e.action)}}function ia(e){if(e==null||typeof e!="object")return null;let t=e,r=["creator_id","creator_user_id","create_user_id","owner_id"];for(let o of r){let i=t[o];if(typeof i=="string"&&i.trim())return i.trim()}let n=t.creator;if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let o=n;for(let i of["id","user_id","userId"]){let s=o[i];if(typeof s=="string"&&s.trim())return s.trim()}}return null}function oa(e,t){let r=e.trim(),n=t.trim();return r===n?!0:r.toLowerCase()===n.toLowerCase()}function sa(e){let{hasCompletion:t,completionRaw:r,markScopeRaw:n,actionParam:o,isCreator:i,taskId:s,creatorId:a}=e,d=n?.trim()??"";if(t){if(r!=="complete"&&r!=="incomplete")throw new Error("completion must be complete or incomplete");let c=r==="complete";if(i){if(!d||d==="none")return{kind:"needs_confirmation",taskId:s,completion:r,creatorId:a};if(d!=="self"&&d!=="all")throw new Error("mark_scope must be none, self, or all when provided");return{kind:"post",action:d==="all"?c?"finish_all":"unfinish_all":c?"finish":"unfinish"}}return{kind:"post",action:c?"finish":"unfinish"}}let l=Ni(o);if(!i&&(l==="finish_all"||l==="unfinish_all"))throw new Error("\u5F53\u524D\u7528\u6237\u4E0D\u662F\u8BE5\u5F85\u529E\u7684\u521B\u5EFA\u8005\uFF08\u6216\u672A\u89E3\u6790\u5230 creator_id\uFF09\uFF0C\u4E0D\u80FD\u4F7F\u7528 finish_all / unfinish_all\uFF1B\u8BF7\u4F7F\u7528 finish \u6216 unfinish\u3002");return i?{kind:"needs_confirmation",taskId:s,completion:l==="finish"||l==="finish_all"?"complete":"incomplete",creatorId:a,requested_action:l}:{kind:"post",action:l}}async function Dt(e,t,r){try{return await ce({wpsUserId:e,authCardOriginalMessage:t,needsAuthMessage:"\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u4F7F\u7528\u5F85\u529E\u80FD\u529B\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5\u3002",logTag:"todo",run:r})}catch(n){return ht(n)}}function hn(e,t){t({name:"wps_todo_create_personal_task",description:"Create a personal todo/task via WPS OpenAPI (\u521B\u5EFA\u4E2A\u4EBA\u5F85\u529E): POST `/v7/todo/personal_tasks`. Requires user delegated OAuth scope `kso.task.readwrite` (or equivalent per console). Use SenderId as `wps_user_id`. Required: `title_subject` \u2192 body `title.subject`; optional `title_prefix` \u2192 `title.prefix`. Optional: `description`, `due_time_ms` (deadline **milliseconds** Unix epoch), `status` (`todo`|`finish`), `executors` (\u2264100 user ids). Response `data.task_id` is the new task id. Optional `x_kso_id_type`: `internal`|`external` \u2192 header `X-Kso-Id-Type`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},title_subject:{type:"string",description:"Todo title subject (maps to request body title.subject)."},title_prefix:{type:"string",description:"Optional. Maps to title.prefix."},description:{type:"string",description:"Optional todo description."},due_time_ms:{type:"number",description:"Optional deadline as Unix timestamp in **milliseconds** (due_time)."},status:{type:"string",description:"Optional initial status.",enum:["todo","finish"]},executors:{type:"array",items:{type:"string"},description:"Optional executor user ids (max 100)."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","title_subject"]},async execute(r,n){try{let o=Ee(n,"wps_user_id"),i=Ee(n,"title_subject"),s=Y(n,"title_prefix"),a=Y(n,"description"),d=Je(n,"due_time_ms"),l=Y(n,"status"),c=Xs(n,"executors"),p;if(l!==void 0){if(l!=="todo"&&l!=="finish")throw new Error("status must be todo or finish when provided");p=l}let u=Zs({titleSubject:i,titlePrefix:s,description:a,dueTimeMs:d,status:p,executors:c});return await Dt(o,"\u521B\u5EFA\u4E2A\u4EBA\u5F85\u529E",async _=>{let m=await _.request({method:"POST",path:Bs,body:u,headers:mt(n)});return m.data??m})}catch(o){return ht(o)}}}),t({name:"wps_todo_list_personal_tasks",description:"List personal todos via WPS OpenAPI (\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u5217\u8868): POST `/v7/todo/personal_tasks/batch_get`. Requires delegated OAuth (`kso.task.read` / `kso.task.readwrite`). Use SenderId as `wps_user_id`. Body filters are optional: `keyword` (\u226450 chars), `executor`, `status` (`todo`|`finish`), `page_size` (default 20, max 50), `page_token` (from previous `data` pagination field per API). `created_time` / `due_time` ranges use **milliseconds** (`*_start_ms`, `*_end_ms`). Response `data` typically includes `tasks`, `total`, `next_offset`. Optional `x_kso_id_type`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},keyword:{type:"string",description:"Optional. Fuzzy match title/description (max 50 chars)."},executor:{type:"string",description:"Optional. Filter by executor user id."},status:{type:"string",description:"Optional list filter: todo (=\u672A\u5B8C\u6210) or finish (=\u5DF2\u5B8C\u6210).",enum:["todo","finish"]},page_size:{type:"number",description:"Page size (default 20; API max 50)."},page_token:{type:"string",description:"Pagination cursor from previous response (see API field names e.g. next_offset)."},created_time_start_ms:{type:"number",description:"Optional. Creation range start (Unix ms)."},created_time_end_ms:{type:"number",description:"Optional. Creation range end (Unix ms)."},due_time_start_ms:{type:"number",description:"Optional. Due range start (Unix ms)."},due_time_end_ms:{type:"number",description:"Optional. Due range end (Unix ms)."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id"]},async execute(r,n){try{let o=Ee(n,"wps_user_id"),i=Y(n,"keyword"),s=Y(n,"executor"),a=Y(n,"status"),d=Je(n,"page_size"),l=Y(n,"page_token"),c=Je(n,"created_time_start_ms"),p=Je(n,"created_time_end_ms"),u=Je(n,"due_time_start_ms"),_=Je(n,"due_time_end_ms"),m;if(a!==void 0){if(a!=="todo"&&a!=="finish")throw new Error("status must be todo or finish when provided");m=a}let y=Qs({keyword:i,executor:s,status:m,pageSize:d,pageToken:l,createdTimeStartMs:c,createdTimeEndMs:p,dueTimeStartMs:u,dueTimeEndMs:_});return await Dt(o,"\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u5217\u8868",async h=>{let f=await h.request({method:"POST",path:Fs,body:y,headers:mt(n)});return f.data??f})}catch(o){return ht(o)}}}),t({name:"wps_todo_get_personal_task",description:"Get one personal todo by id (\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u8BE6\u60C5): GET `/v7/todo/personal_tasks/{task_id}`. Requires delegated OAuth (`kso.task.read` / `kso.task.readwrite`). Use SenderId as `wps_user_id`. Requires **`task_id`** from `wps_todo_list_personal_tasks` (`tasks[].id`) or create response. Response `data` is a single todo object (`todo_personal_task`). Optional `x_kso_id_type`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},task_id:{type:"string",description:"Todo task id from list or create API."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","task_id"]},async execute(r,n){try{let o=Ee(n,"wps_user_id"),i=Ee(n,"task_id");return await Dt(o,"\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u8BE6\u60C5",async s=>{let a=await s.request({method:"GET",path:ar(i),headers:mt(n)});return a.data??a})}catch(o){return ht(o)}}}),t({name:"wps_todo_update_personal_task_status",description:"POST `/v7/todo/personal_tasks/{task_id}/update_status`. HTTP body: `{ action }`. Enum: `finish`, `unfinish`, `finish_all`, `unfinish_all` (`finish_all`/`unfinish_all` creator-only). **Creators**: without `mark_scope` (or `mark_scope: none`) or `action`-only \u2192 returns `needsUserConfirmation`, ask user to choose scope; then call again with `completion` + `mark_scope: self|all`. **Non-creators**: `completion` or `action` (`finish`|`unfinish`); omit `mark_scope`. Requires delegated `kso.task.readwrite`; `wps_user_id` = SenderId.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},task_id:{type:"string",description:"Todo id to update status."},completion:{type:"string",description:"`complete`/`incomplete`. Creators: omit `mark_scope` or use `none` \u2192 returns `needsUserConfirmation`; after user confirms, call again with `mark_scope: self|all`. Mutually exclusive with `action`.",enum:["complete","incomplete"]},mark_scope:{type:"string",description:"**Creators only**: omit or `none` \u2192 \u89E6\u53D1\u4E8C\u6B21\u786E\u8BA4\uFF1B`self` = \u4EC5\u81EA\u5DF1\uFF1B`all` = \u5168\u90E8\u53C2\u4E0E\u4EBA\u3002\u975E\u521B\u5EFA\u8005\u52FF\u4F20\u3002",enum:["none","self","all"]},action:{type:"string",description:"Maps to HTTP body `action`. `finish`|`unfinish` (single); `finish_all`|`unfinish_all` (creator, all participants). Non-creators: `finish`|`unfinish` only. Creators using `action` alone \u2192 `needsUserConfirmation` (then use `completion`+`mark_scope`).",enum:["finish","unfinish","finish_all","unfinish_all"]},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","task_id"]},async execute(r,n){try{let o=Ee(n,"wps_user_id"),i=Ee(n,"task_id"),s=Y(n,"completion"),a=Y(n,"mark_scope"),d=Y(n,"action"),l=s!==void 0,c=d!==void 0&&d!=="";if(l===c)throw!l&&!c?new Error("Provide exactly one of: completion (complete|incomplete) or action (finish|unfinish|...)"):new Error("Provide only one of: completion or action");if(a!==void 0&&!l)throw new Error("mark_scope is only used together with completion");return await Dt(o,"\u66F4\u65B0\u4E2A\u4EBA\u5F85\u529E\u72B6\u6001",async p=>{let u=await p.request({method:"GET",path:ar(i),headers:mt(n)}),_=u.data??u,m=ia(_),y=m!==null&&oa(o,m),h=sa({hasCompletion:l,completionRaw:s,markScopeRaw:a,actionParam:d,isCreator:y,taskId:i,creatorId:m});if(h.kind==="needs_confirmation")return{needsUserConfirmation:!0,reason:"creator_must_choose_scope",message:"\u60A8\u662F\u8BE5\u5F85\u529E\u7684\u521B\u5EFA\u8005\uFF0C\u8BF7\u5148\u786E\u8BA4\uFF1A\u6807\u8BB0\u300C\u4EC5\u81EA\u5DF1\u300D\u8FD8\u662F\u300C\u5168\u90E8\u53C2\u4E0E\u4EBA\u300D\uFF1F\u786E\u8BA4\u540E\u518D\u6B21\u8C03\u7528\uFF0C\u4F20\u5165 completion + mark_scope\uFF08self \u6216 all\uFF09\u3002",task_id:h.taskId,completion:h.completion,creator_id:h.creatorId,...h.requested_action!==void 0?{requested_action:h.requested_action}:{}};let f=na({action:h.action}),g=await p.request({method:"POST",path:Ks(i),body:f,headers:mt(n)});return g.data??g})}catch(o){return ht(o)}}}),t({name:"wps_todo_update_personal_task",description:"Update a personal todo (\u66F4\u65B0\u4E2A\u4EBA\u5F85\u529E): POST `/v7/todo/personal_tasks/{task_id}/update`. Requires delegated **`kso.task.readwrite`**. Use SenderId as `wps_user_id`. Requires **`task_id`**. Body fields are optional but **at least one** must be provided: `title_subject` / `title_prefix` (maps to `title`), `description`, `due_time_ms` (ms), `ext_attrs` (`[{name,value}]`), or `notify_config_json` (JSON object string for `notify_config`). Response is typically `code` + `msg` only.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},task_id:{type:"string",description:"Todo id to update."},title_subject:{type:"string",description:"Optional. Maps to title.subject."},title_prefix:{type:"string",description:"Optional. Maps to title.prefix."},description:{type:"string",description:"Optional. New description."},due_time_ms:{type:"number",description:"Optional. New deadline as Unix **milliseconds**."},ext_attrs:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:"string"}},required:["name","value"]},description:"Optional. Extension attributes."},notify_config_json:{type:"string",description:"Optional. JSON object string for notify_config (e.g. reminders, switch). Must parse to an object."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","task_id"]},async execute(r,n){try{let o=Ee(n,"wps_user_id"),i=Ee(n,"task_id"),s=Y(n,"title_subject"),a=Y(n,"title_prefix"),d=Y(n,"description"),l=Je(n,"due_time_ms"),c=Vs(n,"ext_attrs"),p=Ys(n,"notify_config_json"),u=ea({titleSubject:s,titlePrefix:a,description:d,dueTimeMs:l,extAttrs:c,notifyConfig:p});return await Dt(o,"\u66F4\u65B0\u4E2A\u4EBA\u5F85\u529E",async _=>{let m=await _.request({method:"POST",path:Gs(i),body:u,headers:mt(n)});return m.data??m})}catch(o){return ht(o)}}})}function Pe(e){return`/v7/coop/dbsheet/${encodeURIComponent(e)}`}function aa(e){return`/v7/dbsheet/${encodeURIComponent(e)}`}function Me(e){let t=e.sheet_id;if(t==null)throw new Error("sheet_id is required");let r=typeof t=="number"?t:parseInt(String(t),10);if(!Number.isFinite(r)||r<=0)throw new Error("sheet_id must be a positive integer");return r}function Ui(e,t="fields_value"){if(typeof e=="string")return e;if(e!==null&&typeof e=="object")return JSON.stringify(e);throw new Error(`${t} must be a JSON string or object`)}async function Se(e,t,r){return ce({wpsUserId:e,authCardOriginalMessage:"",needsAuthMessage:"\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u8BBF\u95EE\u591A\u7EF4\u8868\u683C\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",logTag:t,run:r})}function gn(e,t){t({name:"wps_dbsheet_get_schema",description:"Get DBSheet schema (\u83B7\u53D6\u591A\u7EF4\u8868\u683C Schema): GET `/v7/coop/dbsheet/{file_id}/schema`. Returns all sheets with their fields (name/type/id/data) and views. Use this first to understand the table structure before reading or writing records. Requires delegated OAuth (`kso.dbsheet.read`). Use current SenderId as `wps_user_id`. Do NOT call `wps_user_search` to resolve `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"DBSheet file ID."}},required:["wps_user_id","file_id"]},async execute(r,n){try{let o=v(n,"wps_user_id"),i=v(n,"file_id");return await Se(o,"wps_dbsheet_get_schema",async s=>{let a=await s.request({method:"GET",path:`${Pe(i)}/schema`});return a.data??a})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_batch_create_sheets",description:"Batch create sheets (\u6279\u91CF\u521B\u5EFA\u5DE5\u4F5C\u8868): POST `/v7/dbsheet/{file_id}/sheets/batch_create`. Creates one or more sheets. Each sheet requires `name`; optionally include `fields` (field definitions with name/type/data) and `position` (after_sheet_id or before_sheet_id). Requires delegated OAuth (`kso.dbsheet.readwrite`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheets:{type:"array",description:"Array of sheet definitions. Each: { name: string (required), fields?: [{name, type, data?}], position?: {after_sheet_id?: number, before_sheet_id?: number} }.",items:{type:"object",properties:{name:{type:"string"},fields:{type:"array",items:{type:"object",additionalProperties:!0}},position:{type:"object",additionalProperties:!0}},required:["name"]}}},required:["wps_user_id","file_id","sheets"]},async execute(r,n){try{let o=v(n,"wps_user_id"),i=v(n,"file_id"),s=n.sheets;if(!Array.isArray(s)||s.length===0)throw new Error("sheets must be a non-empty array");return await Se(o,"wps_dbsheet_batch_create_sheets",async a=>{let d=await a.request({method:"POST",path:`${aa(i)}/sheets/batch_create`,body:{sheets:s}});return d.data??d})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_update_sheet",description:"Update sheet (\u66F4\u65B0\u5DE5\u4F5C\u8868): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/update`. Currently supports renaming a sheet. Obtain `sheet_id` (integer) from `wps_dbsheet_get_schema`. Requires delegated OAuth (`kso.dbsheet.readwrite`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer). From wps_dbsheet_get_schema."},name:{type:"string",description:"New sheet name."}},required:["wps_user_id","file_id","sheet_id","name"]},async execute(r,n){try{let o=v(n,"wps_user_id"),i=v(n,"file_id"),s=Me(n),a=v(n,"name");return await Se(o,"wps_dbsheet_update_sheet",async d=>{let l=await d.request({method:"POST",path:`${Pe(i)}/sheets/${s}/update`,body:{name:a}});return l.data??l})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_create_records",description:'Create records (\u521B\u5EFA\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/create`. Creates one or more records. Each record\'s `fields_value` is a JSON string (or object \u2014 auto-stringified) mapping field name to value. Example: `{"\u6587\u672C\u5B57\u6BB5": "hello", "\u6570\u5B57\u5B57\u6BB5": 42}`. Auto fields (Formula/AutoNumber/CreatedBy/CreatedTime/LastModifiedBy/Lookup) must NOT be set. Requires delegated OAuth (`kso.dbsheet.readwrite`). Use current SenderId as `wps_user_id`.',parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer). From wps_dbsheet_get_schema."},records:{type:"array",description:"Array of records to create. Each: { fields_value: string|object }. fields_value maps field names to values as JSON string or object.",items:{type:"object",properties:{fields_value:{type:"string",description:'Field values as JSON string or object. E.g. {"\u6587\u672C": "hello", "\u6570\u5B57": 42}'}},required:["fields_value"]}}},required:["wps_user_id","file_id","sheet_id","records"]},async execute(r,n){try{let o=v(n,"wps_user_id"),i=v(n,"file_id"),s=Me(n),a=n.records;if(!Array.isArray(a)||a.length===0)throw new Error("records must be a non-empty array");let d=a.map((l,c)=>{if(!l||typeof l!="object")throw new Error(`records[${c}] must be an object`);return{fields_value:Ui(l.fields_value,`records[${c}].fields_value`)}});return await Se(o,"wps_dbsheet_create_records",async l=>{let c=await l.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records/create`,body:{records:d}});return c.data??c})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_update_records",description:"Update records (\u66F4\u65B0\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/update`. Updates one or more records by record ID. Each item must include `id` (record ID) and `fields_value`. `fields_value` maps field names to new values (JSON string or object \u2014 auto-stringified). Auto fields (Formula/AutoNumber/CreatedBy/CreatedTime/LastModifiedBy/Lookup) must NOT be updated. Requires delegated OAuth (`kso.dbsheet.readwrite`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer). From wps_dbsheet_get_schema."},records:{type:"array",description:"Array of records to update. Each: { id: string (record ID), fields_value: string|object }.",items:{type:"object",properties:{id:{type:"string",description:"Record ID."},fields_value:{type:"string",description:"Field values as JSON string or object."}},required:["id","fields_value"]}}},required:["wps_user_id","file_id","sheet_id","records"]},async execute(r,n){try{let o=v(n,"wps_user_id"),i=v(n,"file_id"),s=Me(n),a=n.records;if(!Array.isArray(a)||a.length===0)throw new Error("records must be a non-empty array");let d=a.map((l,c)=>{if(!l||typeof l!="object")throw new Error(`records[${c}] must be an object`);let p=l;if(!p.id||typeof p.id!="string")throw new Error(`records[${c}].id is required and must be a string`);return{id:p.id,fields_value:Ui(p.fields_value,`records[${c}].fields_value`)}});return await Se(o,"wps_dbsheet_update_records",async l=>{let c=await l.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records/update`,body:{records:d}});return c.data??c})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_list_records",description:"List records with cursor pagination (\u5217\u4E3E\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records`. Returns records with optional filter and cursor-based pagination (page_token). Use `page_token` from previous response to fetch next page. For page-number pagination use `wps_dbsheet_list_records_by_page`. Requires delegated OAuth (`kso.dbsheet.read`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer)."},fields:{type:"array",items:{type:"string"},description:"Optional. Field names to include. Omit to return all fields."},filter:{type:"object",additionalProperties:!0,description:"Optional filter. Structure: { mode: 'AND'|'OR', criteria: [{ field: string, operator: string, values: string[] }] }. operator: Equals|NotEqu|Greater|GreaterEqu|Less|LessEqu|GreaterEquAndLessEqu|LessOrGreater|BeginWith|EndWith|Contains|NotContains|Intersected|Empty|NotEmpty."},max_records:{type:"integer",description:"Optional. Max records to return."},page_size:{type:"integer",description:"Optional. Records per page, default 100, max 1000."},page_token:{type:"string",description:"Optional. Cursor from previous response."},view_id:{type:"string",description:"Optional. View ID to apply view visibility."},text_value:{type:"string",enum:["original","text","compound"],description:"Optional. Return value format. Default: original."},show_fields_info:{type:"boolean",description:"Optional. Include field schema in response."},show_record_extra_info:{type:"boolean",description:"Optional. Include creator/creation time/last-modifier metadata."}},required:["wps_user_id","file_id","sheet_id"]},async execute(r,n){try{let o=v(n,"wps_user_id"),i=v(n,"file_id"),s=Me(n),a={},d=He(n,"fields");d&&(a.fields=d),n.filter!==void 0&&n.filter!==null&&(a.filter=n.filter);let l=X(n,"max_records");l!==void 0&&(a.max_records=l);let c=X(n,"page_size");c!==void 0&&(a.page_size=c);let p=J(n,"page_token");p!==void 0&&p!==""&&(a.page_token=p);let u=J(n,"view_id");u!==void 0&&u!==""&&(a.view_id=u);let _=J(n,"text_value");_!==void 0&&(a.text_value=_);let m=ee(n,"show_fields_info");m!==void 0&&(a.show_fields_info=m);let y=ee(n,"show_record_extra_info");return y!==void 0&&(a.show_record_extra_info=y),await Se(o,"wps_dbsheet_list_records",async h=>{let f=await h.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records`,body:a});return f.data??f})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_list_records_by_page",description:"List records with page-number pagination (\u6309\u9875\u5217\u4E3E\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/list_by_page`. Uses page_num (starts from 1) / page_size. Also returns total count. For cursor-based pagination use `wps_dbsheet_list_records`. Requires delegated OAuth (`kso.dbsheet.read`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer)."},fields:{type:"array",items:{type:"string"},description:"Optional. Field names to include."},filter:{type:"object",additionalProperties:!0,description:"Optional filter. Structure: { mode: 'AND'|'OR', criteria: [{ field, operator, values[] }] }."},max_records:{type:"integer",description:"Optional. Max records to return."},page_num:{type:"integer",description:"Optional. Page number starting from 1."},page_size:{type:"integer",description:"Optional. Records per page, default 100, max 1000."},view_id:{type:"string",description:"Optional. View ID."},text_value:{type:"string",enum:["original","text","compound"],description:"Optional. Return value format."},show_fields_info:{type:"boolean",description:"Optional. Include field schema."},show_record_extra_info:{type:"boolean",description:"Optional. Include metadata."}},required:["wps_user_id","file_id","sheet_id"]},async execute(r,n){try{let o=v(n,"wps_user_id"),i=v(n,"file_id"),s=Me(n),a={},d=He(n,"fields");d&&(a.fields=d),n.filter!==void 0&&n.filter!==null&&(a.filter=n.filter);let l=X(n,"max_records");l!==void 0&&(a.max_records=l);let c=X(n,"page_num");c!==void 0&&(a.page_num=c);let p=X(n,"page_size");p!==void 0&&(a.page_size=p);let u=J(n,"view_id");u!==void 0&&u!==""&&(a.view_id=u);let _=J(n,"text_value");_!==void 0&&(a.text_value=_);let m=ee(n,"show_fields_info");m!==void 0&&(a.show_fields_info=m);let y=ee(n,"show_record_extra_info");return y!==void 0&&(a.show_record_extra_info=y),await Se(o,"wps_dbsheet_list_records_by_page",async h=>{let f=await h.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records/list_by_page`,body:a});return f.data??f})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_get_records",description:"Get multiple records by ID (\u6309 ID \u6279\u91CF\u68C0\u7D22\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/search`. Retrieves specific records by their IDs. Use when you already know the record IDs. For filter-based listing use `wps_dbsheet_list_records` instead. Requires delegated OAuth (`kso.dbsheet.read`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer)."},records:{type:"array",items:{type:"string"},description:"Array of record IDs to retrieve."},text_value:{type:"string",enum:["original","text","compound"],description:"Optional. Return value format."},show_fields_info:{type:"boolean",description:"Optional. Include field schema."},show_record_extra_info:{type:"boolean",description:"Optional. Include metadata."}},required:["wps_user_id","file_id","sheet_id","records"]},async execute(r,n){try{let o=v(n,"wps_user_id"),i=v(n,"file_id"),s=Me(n),a=He(n,"records");if(!a||a.length===0)throw new Error("records must be a non-empty array of record IDs");let d={records:a},l=J(n,"text_value");l!==void 0&&(d.text_value=l);let c=ee(n,"show_fields_info");c!==void 0&&(d.show_fields_info=c);let p=ee(n,"show_record_extra_info");return p!==void 0&&(d.show_record_extra_info=p),await Se(o,"wps_dbsheet_get_records",async u=>{let _=await u.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records/search`,body:d});return _.data??_})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_get_record",description:"Get a single record (\u68C0\u7D22\u5355\u6761\u8BB0\u5F55): GET `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/{record_id}`. Retrieves a single record by its ID. Requires delegated OAuth (`kso.dbsheet.read`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer)."},record_id:{type:"string",description:"Record ID to retrieve."},text_value:{type:"string",enum:["original","text","compound"],description:"Optional. Return value format."},show_fields_info:{type:"boolean",description:"Optional. Include field schema."},show_record_extra_info:{type:"boolean",description:"Optional. Include metadata."}},required:["wps_user_id","file_id","sheet_id","record_id"]},async execute(r,n){try{let o=v(n,"wps_user_id"),i=v(n,"file_id"),s=Me(n),a=v(n,"record_id"),d={},l=J(n,"text_value");l!==void 0&&(d.text_value=l);let c=ee(n,"show_fields_info");c!==void 0&&(d.show_fields_info=c);let p=ee(n,"show_record_extra_info");return p!==void 0&&(d.show_record_extra_info=p),await Se(o,"wps_dbsheet_get_record",async u=>{let _=await u.request({method:"GET",path:`${Pe(i)}/sheets/${s}/records/${encodeURIComponent(a)}`,query:Object.keys(d).length>0?d:void 0});return _.data??_})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_delete_records",description:"Delete records (\u6279\u91CF\u5220\u9664\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/batch_delete`. Deletes one or more records by their IDs. This operation is irreversible. Requires delegated OAuth (`kso.dbsheet.readwrite`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer)."},records:{type:"array",items:{type:"string"},description:"Array of record IDs to delete."}},required:["wps_user_id","file_id","sheet_id","records"]},async execute(r,n){try{let o=v(n,"wps_user_id"),i=v(n,"file_id"),s=Me(n),a=He(n,"records");if(!a||a.length===0)throw new Error("records must be a non-empty array of record IDs");return await Se(o,"wps_dbsheet_delete_records",async d=>{let l=await d.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records/batch_delete`,body:{records:a}});return l.data??l})}catch(o){return ie(o)}}})}nt();import{createHash as da}from"node:crypto";import{readFile as ca,stat as la}from"node:fs/promises";var pa="/v7/drives",ua="/v7/files/search",_a=50,fa=500,ma=50,ha=500,ga=50,ya=500,ji=["folder","file","shortcut"],dr=["fail","rename","overwrite","replace"],Ki=["kdc","plain","markdown"],Hi=["sync","async","auto"],wa=["para","table","component","textbox","all"],Mi=["file_name","content","all"],Wi=["folder","file","shortcut"],zi=["ctime","mtime","otime","stime"],Li=["desc","asc"],Bi=["ctime","mtime"],Fi=["desc","asc"],Gi=["ctime","mtime","dtime","fname","fsize"],ba=["all","share_by_me","share_to_me","latest","personal_drive","group_drive","recycle","customize","latest_opened","latest_edited"];function ze(e){return{error:e instanceof Error?e.message:String(e)}}function D(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function $(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}function gt(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function oe(e,t){let r=e[t];if(r!=null){if(typeof r=="boolean")return r;if(r==="true"||r==="false")return r==="true";throw new Error(`${t} must be a boolean`)}}function G(e,t){let r=e[t];if(r==null)return;if(!Array.isArray(r))throw new Error(`${t} must be an array of strings`);let n=r.map(o=>String(o).trim()).filter(Boolean);return n.length>0?n:void 0}function We(e){let t=$(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let r=t.trim();if(r!=="internal"&&r!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":r}}function Ia(e){let t={};for(let[r,n]of Object.entries(e.requestHeaders)){let o=r.trim();if(o==="")continue;let i=o.toLowerCase();i==="content-length"||i==="transfer-encoding"||i==="content-type"||(t[o]=n)}return t["Content-Type"]="application/octet-stream",t}function ka(e){let t=e.trim();if(!t)throw new Error("url is required and must be a non-empty string");let r;try{r=new URL(t)}catch{throw new Error("url must be an absolute URL from step-1 data.store_request.url (e.g. https://...); relative paths are not supported")}if(r.protocol!=="https:"&&r.protocol!=="http:")throw new Error(`url must use http: or https: scheme, got: ${r.protocol}`)}function Sa(e){let t={allotee_type:e.alloteeType,page_size:Math.max(1,Math.min(fa,Math.trunc(e.pageSize??_a)))};return e.alloteeId!==void 0&&e.alloteeId.trim()!==""&&(t.allotee_id=e.alloteeId.trim()),e.withExtAttrs!==void 0&&(t.with_ext_attrs=e.withExtAttrs),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),e.sources!==void 0&&e.sources.length>0&&(t.sources=[...e.sources]),t}function xa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/create`}function va(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/children`}function Ta(e){let t={page_size:Math.max(1,Math.min(ya,Math.trunc(e.pageSize??ga)))};return e.withPermission!==void 0&&(t.with_permission=e.withPermission),e.withExtAttrs!==void 0&&(t.with_ext_attrs=e.withExtAttrs),e.filterExts!==void 0&&e.filterExts.trim()!==""&&(t.filter_exts=e.filterExts.trim()),e.filterType!==void 0&&Object.keys(e.filterType).length>0&&(t.filter_type=JSON.stringify(e.filterType)),e.order!==void 0&&(t.order=e.order),e.orderBy!==void 0&&(t.order_by=e.orderBy),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),t}function Ea(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/request_upload`}function Pa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/commit_upload`}function Oa(e){let t=e.name.trim();if(!t)throw new Error("name must be a non-empty string");let r={file_type:e.fileType,name:t};if(e.fileType==="shortcut"){if(!e.fileId||!e.fileId.trim())throw new Error("file_id is required when file_type is shortcut");r.file_id=e.fileId.trim()}else e.fileId!==void 0&&e.fileId.trim()!==""&&(r.file_id=e.fileId.trim());return e.onNameConflict!==void 0&&(r.on_name_conflict=e.onNameConflict),e.parentPath!==void 0&&e.parentPath.length>0&&(r.parent_path=[...e.parentPath]),r}function Aa(e){let t={size:Math.max(0,Math.trunc(e.size))};return e.fileId!==void 0&&e.fileId.trim()!==""&&(t.file_id=e.fileId.trim()),e.hashes!==void 0&&e.hashes.length>0&&(t.hashes=e.hashes.map(r=>({type:r.type,sum:r.sum.trim()}))),e.internal!==void 0&&(t.internal=e.internal),e.name!==void 0&&e.name.trim()!==""&&(t.name=e.name.trim()),e.onNameConflict!==void 0&&(t.on_name_conflict=e.onNameConflict),e.parentPath!==void 0&&e.parentPath.length>0&&(t.parent_path=[...e.parentPath]),e.storageBaseDomain!==void 0&&e.storageBaseDomain.trim()!==""&&(t.storage_base_domain=e.storageBaseDomain.trim()),e.uploadScene!==void 0&&e.uploadScene.trim()!==""&&(t.upload_scene=e.uploadScene.trim()),t}function Ra(e){let t={};return e.id!==void 0&&e.id.trim()!==""&&(t.id=e.id.trim()),e.uploadId!==void 0&&e.uploadId.trim()!==""&&(t.upload_id=e.uploadId.trim()),t}function $a(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/content`}function qa(e){let t={};if(e.format!==void 0&&e.format.trim()!==""){let r=e.format.trim();if(!Ki.includes(r))throw new Error("format must be one of: kdc, plain, markdown");t.format=r}if(e.includeElements!==void 0&&e.includeElements.length>0){let r=e.includeElements.map(n=>n.trim()).filter(Boolean).filter((n,o,i)=>i.indexOf(n)===o);for(let n of r)if(!wa.includes(n))throw new Error("include_elements items must be one of: para, table, component, textbox, all");r.length>0&&(t.include_elements=r)}if(e.mode!==void 0&&e.mode.trim()!==""){let r=e.mode.trim();if(!Hi.includes(r))throw new Error("mode must be one of: sync, async, auto");t.mode=r}return e.taskId!==void 0&&e.taskId.trim()!==""&&(t.task_id=e.taskId.trim()),t}function Ca(e){return`/v7/files/${encodeURIComponent(e.trim())}/meta`}function Da(e){let t={};return e.withPermission!==void 0&&(t.with_permission=e.withPermission),e.withExtAttrs!==void 0&&(t.with_ext_attrs=e.withExtAttrs),e.withDrive!==void 0&&(t.with_drive=e.withDrive),t}function Na(e){let t={type:e.type,page_size:Math.max(1,Math.min(ha,Math.trunc(e.pageSize??ma)))};return e.keyword!==void 0&&e.keyword.trim()!==""&&(t.keyword=e.keyword.trim()),e.fileType!==void 0&&(t.file_type=e.fileType),e.fileExts!==void 0&&e.fileExts.length>0&&(t.file_exts=[...e.fileExts]),e.driveIds!==void 0&&e.driveIds.length>0&&(t.drive_ids=[...e.driveIds]),e.parentIds!==void 0&&e.parentIds.length>0&&(t.parent_ids=[...e.parentIds]),e.creatorIds!==void 0&&e.creatorIds.length>0&&(t.creator_ids=[...e.creatorIds]),e.modifierIds!==void 0&&e.modifierIds.length>0&&(t.modifier_ids=[...e.modifierIds]),e.sharerIds!==void 0&&e.sharerIds.length>0&&(t.sharer_ids=[...e.sharerIds]),e.receiverIds!==void 0&&e.receiverIds.length>0&&(t.receiver_ids=[...e.receiverIds]),e.timeType!==void 0&&(t.time_type=e.timeType),e.startTime!==void 0&&(t.start_time=Math.trunc(e.startTime)),e.endTime!==void 0&&(t.end_time=Math.trunc(e.endTime)),e.withPermission!==void 0&&(t.with_permission=e.withPermission),e.withLink!==void 0&&(t.with_link=e.withLink),e.withTotal!==void 0&&(t.with_total=e.withTotal),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),e.channels!==void 0&&e.channels.length>0&&(t.channels=[...e.channels]),e.deviceIds!==void 0&&e.deviceIds.length>0&&(t.device_ids=[...e.deviceIds]),e.excludeChannels!==void 0&&e.excludeChannels.length>0&&(t.exclude_channels=[...e.excludeChannels]),e.excludeFileExts!==void 0&&e.excludeFileExts.length>0&&(t.exclude_file_exts=[...e.excludeFileExts]),e.filterUserId!==void 0&&(t.filter_user_id=Math.trunc(e.filterUserId)),e.fileExtGroups!==void 0&&e.fileExtGroups.length>0&&(t.file_ext_groups=[...e.fileExtGroups]),e.withFolder!==void 0&&(t.with_folder=e.withFolder),e.withDrive!==void 0&&(t.with_drive=e.withDrive),e.order!==void 0&&(t.order=e.order),e.orderBy!==void 0&&(t.order_by=e.orderBy),e.scope!==void 0&&e.scope.length>0&&(t.scope=[...e.scope]),e.searchOperatorName!==void 0&&(t.search_operator_name=e.searchOperatorName),t}async function Xe(e,t,r,n){try{return await ce({wpsUserId:e,authCardOriginalMessage:t,needsAuthMessage:r,logTag:"drive",run:n})}catch(o){return ze(o)}}function yn(e,t){t({name:"wps_cloud_doc_list_drives",description:"List cloud drives (\u83B7\u53D6\u76D8\u5217\u8868): GET `/v7/drives`. Requires delegated OAuth (`kso.drive.readwrite`). Use SenderId as `wps_user_id`. Required query: `allotee_type` (`user` | `group` | `app`). Optional `allotee_id` can be supplied for user/group/app scopes. Optional: `with_ext_attrs`, `page_size` (default 50, max 500), `page_token`, `sources` (array). Optional `x_kso_id_type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},allotee_type:{type:"string",description:"Drive allocation type.",enum:["user","group","app"]},allotee_id:{type:"string",description:"Optional allocation id for user/group/app scope."},with_ext_attrs:{type:"boolean",description:"Optional. Include ext_attrs in response."},page_size:{type:"number",description:"Optional. Page size (default 50, max 500)."},page_token:{type:"string",description:"Optional pagination token."},sources:{type:"array",items:{type:"string"},description:"Optional source filters."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","allotee_type"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"allotee_type");if(i!=="user"&&i!=="group"&&i!=="app")throw new Error("allotee_type must be user, group, or app");let s=i,a=$(n,"allotee_id"),d=oe(n,"with_ext_attrs"),l=gt(n,"page_size"),c=$(n,"page_token"),p=G(n,"sources");return await Xe(o,"\u83B7\u53D6\u76D8\u5217\u8868","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u8BBF\u95EE\u4E91\u6587\u6863\u76D8\u5217\u8868\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async u=>{let _=Sa({alloteeType:s,alloteeId:a,withExtAttrs:d,pageSize:l,pageToken:c,sources:p}),m=await u.request({method:"GET",path:pa,query:_,headers:We(n)});return m.data??m})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_list_children_files",description:"List child files under a parent folder (\u83B7\u53D6\u5B50\u6587\u4EF6\u5217\u8868): GET `/v7/drives/{drive_id}/files/{parent_id}/children`. Requires delegated OAuth (`kso.file.read`). Use SenderId as `wps_user_id`. Required: `drive_id`, `parent_id` (root parent_id is `0`). Optional query: `with_permission`, `with_ext_attrs`, `filter_exts`, `filter_type`, `order`, `order_by`, `page_size`, `page_token`. Optional `x_kso_id_type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId)."},drive_id:{type:"string",description:"Drive ID."},parent_id:{type:"string",description:"Parent folder id (root is `0`)."},with_permission:{type:"boolean",description:"Optional. Include operation permissions in response."},with_ext_attrs:{type:"boolean",description:"Optional. Include file ext_attrs in response."},filter_exts:{type:"string",description:"Optional. Extension filter string separated by semicolons, e.g. `docx;xlsx`."},filter_type:{type:"object",description:"Optional file type filter object (passed through to API query `filter_type`).",additionalProperties:!0},order:{type:"string",enum:[...Fi],description:"Optional order direction."},order_by:{type:"string",enum:[...Gi],description:"Optional order field."},page_size:{type:"number",description:"Optional page size (default 50, max 500)."},page_token:{type:"string",description:"Optional pagination token."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","drive_id","parent_id"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"drive_id"),s=D(n,"parent_id"),a=oe(n,"with_permission"),d=oe(n,"with_ext_attrs"),l=$(n,"filter_exts"),c=gt(n,"page_size"),p=$(n,"page_token"),u=$(n,"order");if(u!==void 0&&!Fi.includes(u))throw new Error("order must be one of: desc, asc");let _=u,m=$(n,"order_by");if(m!==void 0&&!Gi.includes(m))throw new Error("order_by must be one of: ctime, mtime, dtime, fname, fsize");let y=m,h=n.filter_type,f;if(h!=null){if(typeof h!="object"||Array.isArray(h))throw new Error("filter_type must be an object when provided");f=h}return await Xe(o,"\u83B7\u53D6\u5B50\u6587\u4EF6\u5217\u8868","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u83B7\u53D6\u5B50\u6587\u4EF6\u5217\u8868\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async g=>{let w=Ta({withPermission:a,withExtAttrs:d,filterExts:l,filterType:f,order:_,orderBy:y,pageSize:c,pageToken:p}),b=await g.request({method:"GET",path:va(i,s),query:w,headers:We(n)});return b.data??b})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_create_file",description:"Create file/folder/shortcut (\u65B0\u5EFA\u6587\u4EF6(\u5939)): POST `/v7/drives/{drive_id}/files/{parent_id}/create`. Requires delegated OAuth (`kso.file.readwrite`). Use SenderId as `wps_user_id`. Required: `drive_id`, `parent_id`, `file_type` (`folder` | `file` | `shortcut`), `name`. When `file_type` is `shortcut`, `file_id` is required. Optional: `on_name_conflict` (`fail` | `rename` | `overwrite` | `replace`), `parent_path` (string array). Optional `x_kso_id_type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},drive_id:{type:"string",description:"Drive ID."},parent_id:{type:"string",description:"Parent file/folder ID (root is 0)."},file_type:{type:"string",enum:[...ji],description:"Created resource type: folder, file, or shortcut."},name:{type:"string",description:"Name to create. Include extension for files when needed."},file_id:{type:"string",description:"Required only for file_type=shortcut (target file id)."},on_name_conflict:{type:"string",enum:[...dr],description:"Name conflict behavior."},parent_path:{type:"array",items:{type:"string"},description:"Optional relative nested path array under parent_id."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","drive_id","parent_id","file_type","name"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"drive_id"),s=D(n,"parent_id"),a=D(n,"file_type");if(!ji.includes(a))throw new Error("file_type must be one of: folder, file, shortcut");let d=a,l=D(n,"name"),c=$(n,"file_id"),p=$(n,"on_name_conflict");if(p!==void 0&&!dr.includes(p))throw new Error("on_name_conflict must be one of: fail, rename, overwrite, replace");let u=p,_=G(n,"parent_path");return await Xe(o,"\u65B0\u5EFA\u6587\u4EF6\uFF08\u5939\uFF09","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u65B0\u5EFA\u4E91\u6587\u6863\u6587\u4EF6\uFF08\u5939\uFF09\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async m=>{let y=Oa({fileType:d,name:l,fileId:c,onNameConflict:u,parentPath:_}),h=await m.request({method:"POST",path:xa(i,s),body:y,headers:We(n)});return h.data??h})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_upload_file",description:"**THE ONLY tool for uploading files** (\u4E00\u4F53\u5316\u4E0A\u4F20). Combines step-1 request_upload, step-2 upload bytes, and step-3 commit_upload into a **single tool call**. Pass `file_path` (local file path, e.g. from prefetched attachment `localPath`); the plugin reads the file directly from disk. The plugin computes `size` and `sha256` hash from the actual file bytes \u2014 **no need for the caller to compute or pass `size` / `hashes`**. This avoids `ContentLengthInvalid` and `BadDigest` errors (no base64 encoding, no truncation risk). Requires delegated OAuth (`kso.file.readwrite`). Use SenderId as `wps_user_id`. Returns the final committed file object.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId)."},drive_id:{type:"string",description:"Drive ID."},parent_id:{type:"string",description:"Parent file/folder ID (root is 0)."},file_path:{type:"string",description:"Absolute path to the local file to upload (e.g. from prefetched attachment `localPath`). The plugin reads bytes directly from disk \u2014 no base64 encoding needed, no truncation risk."},name:{type:"string",description:"Filename for the uploaded file (e.g. 'report.doc'). If omitted, the filename is extracted from `file_path`."},on_name_conflict:{type:"string",enum:[...dr],description:"Optional name conflict behavior (default: server decides)."},file_id:{type:"string",description:"Optional target file id for update upload."},internal:{type:"boolean",description:"Optional internal endpoint preference."},upload_scene:{type:"string",description:"Optional upload scene."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","drive_id","parent_id","file_path"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"drive_id"),s=D(n,"parent_id"),a=D(n,"file_path"),d=$(n,"name"),l=$(n,"on_name_conflict");if(l!==void 0&&!dr.includes(l))throw new Error("on_name_conflict must be one of: fail, rename, overwrite, replace");let c=l,p=$(n,"file_id"),u=oe(n,"internal"),_=$(n,"upload_scene"),m=a.trim();try{if(!(await la(m)).isFile())throw new Error("path is not a regular file")}catch(g){throw new Error(`file_path "${m}" is not accessible: ${g instanceof Error?g.message:String(g)}`)}let y=await ca(m);if(!d){let g=Math.max(m.lastIndexOf("/"),m.lastIndexOf("\\")),b=(g>=0?m.substring(g+1):m).replace(/^[0-9a-f]{8}_/i,"");b&&(d=b)}if(y.byteLength===0)throw new Error("upload content is empty (file has zero bytes)");let h=y.byteLength,f=da("sha256").update(y).digest("hex");return await Xe(o,"\u4E00\u4F53\u5316\u4E0A\u4F20\u6587\u4EF6","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u4E0A\u4F20\u4E91\u6587\u6863\u6587\u4EF6\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async g=>{let w=Aa({size:h,fileId:p??void 0,hashes:[{type:"sha256",sum:f}],internal:u??void 0,name:d??void 0,onNameConflict:c,uploadScene:_??void 0}),b=await g.request({method:"POST",path:Ea(i,s),body:w,headers:We(n)}),I=b.data??b,E=I.store_request;if(!E||typeof E.url!="string"||!E.url.trim())throw new Error(`step-1 response missing store_request.url \u2014 cannot proceed with upload. Response: ${JSON.stringify(I).substring(0,300)}`);let N=typeof E.method=="string"?E.method.toUpperCase():"PUT",re=E.url;ka(re);let Z=E.headers??{},B=typeof I.upload_id=="string"?I.upload_id:void 0,ye=xt(o);if(!ye||!ye.trim())throw new Error("delegated access token missing after auth gate");let et=Ia({requestHeaders:Z}),le={Authorization:`Bearer ${ye.trim()}`,...et},pe=new Uint8Array(y.buffer,y.byteOffset,y.byteLength),ue;try{ue=await fetch(re,{method:N,headers:le,body:pe})}catch(Re){let bt=Re instanceof Error?Re.message:String(Re);throw new Error(`upload step-2 fetch failed: ${bt}. Check outbound HTTPS/DNS/firewall from the gateway to the presigned URL.`)}if(!ue.ok){let Re=await ue.text().catch(()=>"");throw new Error(`upload step-2 failed: HTTP ${ue.status} ${Re.substring(0,300)} [diag: size=${h}, sha256=${f}]`)}if(!B)return{step1:I,step2_status:ue.status,etag:ue.headers.get("etag")??void 0,warning:"upload_id missing from step-1 \u2014 skipped commit_upload."};let wt=Ra({uploadId:B}),pr=await g.request({method:"POST",path:Pa(i,s),body:wt,headers:We(n)});return pr.data??pr})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_extract_file_content",description:"Extract file content (\u6587\u6863\u5185\u5BB9\u62BD\u53D6): GET `/v7/drives/{drive_id}/files/{file_id}/content`. Requires delegated OAuth (`kso.file.read`). Use SenderId as `wps_user_id`. Required: `drive_id`, `file_id`. Optional query: `format` (`kdc` | `plain` | `markdown`), `include_elements` (`para` | `table` | `component` | `textbox` | `all`), `mode` (`sync` | `async` | `auto`), `task_id`. Returns upstream `data` as-is (for fields like `task_id`, `task_status`, `doc`, `markdown`, `plain`, etc.).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},drive_id:{type:"string",description:"Drive ID."},file_id:{type:"string",description:"File ID."},format:{type:"string",enum:[...Ki],description:"Optional output format."},include_elements:{type:"array",items:{type:"string"},description:"Optional extracted element types."},mode:{type:"string",enum:[...Hi],description:"Optional extraction mode."},task_id:{type:"string",description:"Optional task id for async/auto result polling."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","drive_id","file_id"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"drive_id"),s=D(n,"file_id"),a=$(n,"format"),d=G(n,"include_elements"),l=$(n,"mode"),c=$(n,"task_id");return await Xe(o,"\u6587\u6863\u5185\u5BB9\u62BD\u53D6","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u8FDB\u884C\u6587\u6863\u5185\u5BB9\u62BD\u53D6\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async p=>{let u=qa({format:a,includeElements:d,mode:l,taskId:c}),_=await p.request({method:"GET",path:$a(i,s),query:Object.keys(u).length>0?u:void 0,headers:We(n)});return _.data??_})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_get_file_meta",description:"Get file metadata (\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F): GET `/v7/files/{file_id}/meta`. Requires delegated OAuth (`kso.file.read`). Use SenderId as `wps_user_id`. Required: `file_id`. Optional query: `with_permission`, `with_ext_attrs`, `with_drive` (boolean). Returns upstream `data` as-is (for fields like `drive`, `permission`, `ext_attrs`, etc.).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"File ID."},with_permission:{type:"boolean",description:"Optional. Include permission field in response."},with_ext_attrs:{type:"boolean",description:"Optional. Include ext_attrs field in response."},with_drive:{type:"boolean",description:"Optional. Include drive field in response."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","file_id"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"file_id"),s=oe(n,"with_permission"),a=oe(n,"with_ext_attrs"),d=oe(n,"with_drive");return await Xe(o,"\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async l=>{let c=Da({withPermission:s,withExtAttrs:a,withDrive:d}),p=await l.request({method:"GET",path:Ca(i),query:Object.keys(c).length>0?c:void 0,headers:We(n)});return p.data??p})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_search_files",description:"Search files (\u6587\u4EF6\u641C\u7D22): GET `/v7/files/search`. Requires delegated OAuth (`kso.file.search`). Use SenderId as `wps_user_id`. Required query: `type` (`file_name` | `content` | `all`), `page_size` (default 50, max 500). Supports optional filters: keyword, file_type, file_exts, drive_ids, parent_ids, creator_ids, modifier_ids, sharer_ids, receiver_ids, time_type/start_time/end_time, with_permission/with_link/with_total, page_token, channels/device_ids/exclude_channels/exclude_file_exts, filter_user_id, file_ext_groups, with_folder, with_drive, order/order_by, scope, search_operator_name.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId)."},keyword:{type:"string",description:"Optional search keyword."},type:{type:"string",enum:[...Mi],description:"Search type."},file_type:{type:"string",enum:[...Wi],description:"Optional file type filter."},file_exts:{type:"array",items:{type:"string"},description:"Optional file extension filters."},drive_ids:{type:"array",items:{type:"string"},description:"Optional drive id filters."},parent_ids:{type:"array",items:{type:"string"},description:"Optional parent id filters."},creator_ids:{type:"array",items:{type:"string"},description:"Optional creator id filters."},modifier_ids:{type:"array",items:{type:"string"},description:"Optional modifier id filters."},sharer_ids:{type:"array",items:{type:"string"},description:"Optional sharer id filters."},receiver_ids:{type:"array",items:{type:"string"},description:"Optional receiver id filters."},time_type:{type:"string",enum:[...zi],description:"Optional time type."},start_time:{type:"number",description:"Optional start time (unix seconds)."},end_time:{type:"number",description:"Optional end time (unix seconds)."},with_permission:{type:"boolean",description:"Optional. Include permission fields."},with_link:{type:"boolean",description:"Optional. Include sharing link fields."},with_total:{type:"boolean",description:"Optional. Include total count in response."},page_size:{type:"number",description:"Optional. Default 50, max 500."},page_token:{type:"string",description:"Optional pagination token."},channels:{type:"array",items:{type:"string"},description:"Optional channel filters."},device_ids:{type:"array",items:{type:"string"},description:"Optional device filters."},exclude_channels:{type:"array",items:{type:"string"},description:"Optional excluded channel filters."},exclude_file_exts:{type:"array",items:{type:"string"},description:"Optional excluded file extension filters."},filter_user_id:{type:"number",description:"Optional filter user id."},file_ext_groups:{type:"array",items:{type:"string"},description:"Optional file extension groups."},with_folder:{type:"boolean",description:"Optional include folder results."},with_drive:{type:"boolean",description:"Optional include drive info."},order:{type:"string",enum:[...Li],description:"Optional order."},order_by:{type:"string",enum:[...Bi],description:"Optional order by field."},scope:{type:"array",items:{type:"string"},description:"Optional search scopes."},search_operator_name:{type:"boolean",description:"Optional search by operator name switch."},x_kso_id_type:{type:"string",enum:["internal","external"],description:"Optional. Sent as X-Kso-Id-Type."}},required:["wps_user_id","type"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"type");if(!Mi.includes(i))throw new Error("type must be one of: file_name, content, all");let s=i,a=$(n,"file_type");if(a!==void 0&&!Wi.includes(a))throw new Error("file_type must be one of: folder, file, shortcut");let d=a,l=$(n,"time_type");if(l!==void 0&&!zi.includes(l))throw new Error("time_type must be one of: ctime, mtime, otime, stime");let c=l,p=$(n,"order");if(p!==void 0&&!Li.includes(p))throw new Error("order must be one of: desc, asc");let u=p,_=$(n,"order_by");if(_!==void 0&&!Bi.includes(_))throw new Error("order_by must be one of: ctime, mtime");let m=_,y=G(n,"scope");if(y!==void 0){for(let h of y)if(!ba.includes(h))throw new Error("scope items must be one of: all, share_by_me, share_to_me, latest, personal_drive, group_drive, recycle, customize, latest_opened, latest_edited")}return await Xe(o,"\u6587\u4EF6\u641C\u7D22","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u641C\u7D22\u4E91\u6587\u6863\u6587\u4EF6\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async h=>{let f=Na({keyword:$(n,"keyword"),type:s,fileType:d,fileExts:G(n,"file_exts"),driveIds:G(n,"drive_ids"),parentIds:G(n,"parent_ids"),creatorIds:G(n,"creator_ids"),modifierIds:G(n,"modifier_ids"),sharerIds:G(n,"sharer_ids"),receiverIds:G(n,"receiver_ids"),timeType:c,startTime:gt(n,"start_time"),endTime:gt(n,"end_time"),withPermission:oe(n,"with_permission"),withLink:oe(n,"with_link"),withTotal:oe(n,"with_total"),pageSize:gt(n,"page_size"),pageToken:$(n,"page_token"),channels:G(n,"channels"),deviceIds:G(n,"device_ids"),excludeChannels:G(n,"exclude_channels"),excludeFileExts:G(n,"exclude_file_exts"),filterUserId:gt(n,"filter_user_id"),fileExtGroups:G(n,"file_ext_groups"),withFolder:oe(n,"with_folder"),withDrive:oe(n,"with_drive"),order:u,orderBy:m,scope:y,searchOperatorName:oe(n,"search_operator_name")}),g=await h.request({method:"GET",path:ua,query:f,headers:We(n)});return g.data??g})}catch(o){return ze(o)}}})}var Ua="/v7/airpage/files";function Ve(e,t){return`/v7/airpage/${encodeURIComponent(e.trim())}${t}`}function Ze(e){return{arg:Buffer.from(JSON.stringify(e),"utf8").toString("base64")}}function Ye(e,t){return e.length>36?`${t} (${e.slice(0,36)}...)`:`${t} (${e})`}function Xi(e,t){let r=e.operation,n=e.blockId;if(typeof r!="string"||!r.trim())throw new Error(`${t}.operation is required and must be a non-empty string`);if(typeof n!="string"||!n.trim())throw new Error(`${t}.blockId is required and must be a non-empty string`)}var wn=["rename","fail","overwrite"];function Oe(e){return{error:e instanceof Error?e.message:String(e)}}function q(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function Ji(e,t){let r=e[t];if(r==null)return;if(typeof r!="string")throw new Error(`${t} must be a string`);let n=r.trim();return n===""?void 0:n}function lr(e,t){let r=e[t];if(!Array.isArray(r))throw new Error(`${t} is required and must be an array`);return r}function ja(e,t){let n=lr(e,t).map(o=>String(o).trim()).filter(Boolean);if(n.length===0)throw new Error(`${t} must contain at least one non-empty string`);return n}function Ma(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return Math.trunc(r);if(typeof r=="string"&&r.trim()!==""){let n=Number(r.trim());if(Number.isFinite(n))return Math.trunc(n)}throw new Error(`${t} must be a finite integer when provided`)}}function cr(e,t){let r=e[t];if(r==null)throw new Error(`${t} is required and must be a finite integer`);if(typeof r=="number"&&Number.isFinite(r))return Math.trunc(r);if(typeof r=="string"&&r.trim()!==""){let n=Number(r.trim());if(Number.isFinite(n))return Math.trunc(n)}throw new Error(`${t} must be a finite integer`)}function Wa(e){let t={blockId:e.blockId.trim(),content:e.content},r=e.index;return r!==void 0&&(t.index=r),Ze(t)}function za(e){let t={blockId:e.blockId.trim()};return Ze(t)}function La(e){let t={blockIds:e.blockIds.map(r=>r.trim()).filter(Boolean)};if(t.blockIds.length===0)throw new Error("blockIds must contain at least one non-empty id");return Ze(t)}function Ba(e){if(e.endIndex<=e.startIndex)throw new Error("endIndex must be greater than startIndex");let t={blockId:e.blockId.trim(),startIndex:Math.trunc(e.startIndex),endIndex:Math.trunc(e.endIndex)};if(!t.blockId)throw new Error("blockId must be non-empty");return Ze(t)}function Fa(e){if(!Array.isArray(e)||e.length===0)throw new Error("delete_items must contain at least one delete range");let t=e.map(r=>{let n=r.blockId.trim(),o=Math.trunc(r.startIndex),i=Math.trunc(r.endIndex);if(!n)throw new Error("delete_items.blockId must be non-empty");if(i<=o)throw new Error("delete_items.endIndex must be greater than delete_items.startIndex");return{blockId:n,startIndex:o,endIndex:i}});return Ze(t)}function Ga(e){return Xi(e,"operation"),Ze(e)}function Ka(e){if(!Array.isArray(e)||e.length===0)throw new Error("operations must contain at least one operation object");for(let[t,r]of e.entries()){if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`operations[${t}] must be an object`);Xi(r,`operations[${t}]`)}return Ze(e)}function Ha(e){let t=e.trim().toLowerCase();if(wn.includes(t))return t;throw new Error(`on_name_conflict must be one of: ${wn.join(", ")} (got: ${e})`)}function Ja(e){let t={drive_id:e.driveId,name:e.name,on_name_conflict:e.onNameConflict};return e.parentId!==void 0&&(t.parent_id=e.parentId),e.templateId!==void 0&&(t.template_id=e.templateId),t}async function Le(e,t,r){try{return await ce({wpsUserId:e,authCardOriginalMessage:t,needsAuthMessage:"\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u64CD\u4F5C\u667A\u80FD\u6587\u6863\uFF08Airpage\uFF09\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5\u3002",logTag:"airpage",run:r})}catch(n){return Oe(n)}}function bn(e,t){t({name:"wps_airpage_create_file",description:"Create a blank Smart Document (Airpage / \u667A\u80FD\u6587\u6863) via WPS OpenAPI: POST `/v7/airpage/files`. Requires user delegated OAuth with scope `kso.airpage.readwrite` (or equivalent). Use SenderId as `wps_user_id`. Required: `drive_id`, `name` (document title without file extension), `on_name_conflict` (`rename` | `fail` | `overwrite`). Optional: `parent_id` (parent folder id), `template_id` (create from template). Obtain `drive_id` via `wps_cloud_doc_list_drives`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},drive_id:{type:"string",description:"Target drive id (from wps_cloud_doc_list_drives)."},name:{type:"string",description:"Document name without extension (per API)."},on_name_conflict:{type:"string",enum:[...wn],description:"Strategy when the name already exists: rename, fail, or overwrite."},parent_id:{type:"string",description:"Optional parent folder id."},template_id:{type:"string",description:"Optional template id to create from."}},required:["wps_user_id","drive_id","name","on_name_conflict"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"drive_id"),s=q(n,"name"),a=q(n,"on_name_conflict"),d=Ha(a),l=Ji(n,"parent_id"),c=Ji(n,"template_id"),p=`\u521B\u5EFA\u667A\u80FD\u6587\u6863: ${s}`;return await Le(o,p,async u=>{let _=Ja({driveId:i,name:s,onNameConflict:d,parentId:l,templateId:c}),m=await u.request({method:"POST",path:Ua,body:_});return m.data??m})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_create_block_content",description:'Insert block content into a Smart Document (Airpage): POST `/v7/airpage/{file_id}/blocks/create`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON). JSON fields: `blockId` (parent block; use literal `doc` for document root), optional `index` (insert position; omit for API default 0), required `content` (array of child block nodes). Requires delegated `kso.airpage.readwrite`. Use SenderId as `wps_user_id`.\n\n## Block node types (used in `content` array):\nEach node: `{ type, attrs?, content? }`. `content` is an array of child blocks or inline nodes.\n\n- **title**: Document title (unique, must be first child of doc). attrs: `align` (1=left,2=center,3=right). content: inline nodes.\n- **paragraph**: Paragraph (also used for lists). attrs: `indent` (0|1), `contentIndent` (>=0), `align` (1|2|3), `listAttrs` `{id,type(1=unordered,2=ordered,3=task),styleType(1-13),level,styleFormat(1-9)}`. content: inline nodes.\n- **heading**: Heading h1-h6. attrs: `level` (1-6), `indent`, `contentIndent`, `align`, `listAttrs` (same as paragraph). content: inline nodes.\n- **blockQuote**: Quote block. attrs: `indent`, `contentIndent`, `align`. content: block nodes (paragraph, heading, etc.). Inline `br` for line breaks inside.\n- **codeBlock**: Code block. attrs: `lang` (1=plaintext,2=css,3=go,4=python,5=shell,...19=javascript,12=typescript,17=json,43=yaml, etc.), `autoWrap` (bool), `theme` (1=light,2=dark). content: text nodes (may contain `\\n`).\n- **highLightBlock**: Highlight block. attrs: `emoji` (required), `style {fontColor(1-12),backgroundColor(1-6),borderColor}`. content: block nodes. Cannot contain title, table, column, highLightBlock, lockBlock.\n- **lockBlock**: Content protection area (only file creator can edit). No attrs. content: block nodes. Cannot contain title, lockBlock.\n- **table**: Table. attrs: `borderStyle` (1=none,2=solid). content: tableRow nodes.\n - **tableRow**: Table row. No attrs. content: tableCell nodes.\n - **tableCell**: Cell. attrs: `width`, `height`, `colspan` (>=1), `rowspan` (>=1), `verticalAlign` (1=top,2=middle,3=bottom). content: block nodes.\n- **column**: Column layout (1-10 columns). attrs: `backgroundColor` (1-12). content: columnItem nodes.\n - **columnItem**: Column item. attrs: `width` (percent string e.g. "50.00%"), `backgroundColor` (1-42). content: block nodes.\n- **pictureColumn**: Side-by-side images (2-5). attrs: `width` (percent), `align` (1|2|3). content: picture nodes.\n- **picture**: Image. attrs (required: sourceKey, width, height): `sourceKey` (image resource id from attachment upload), `width`, `height`, `renderWidth`, `caption`, `rotate` (0|-90|-180|-270), `borderType` (0|1), `align`. No content.\n- **blockAnchor**: Placeholder. attrs (required: id, aimType, width, height): `id`, `aimType` (\'picture\'|\'video\'|\'processon\'|\'spreadsheet\'), `width`, `height`. No content.\n- **hr**: Horizontal rule. No attrs, no content.\n- **video**: Video. attrs (required: sourceId, sourceKey, width, height): `sourceId`, `sourceKey` (cover image id), `width`, `height`, `title`, `align`.\n- **audio**: Audio. attrs (required: sourceId): `sourceId`, `title`.\n- **videoLink**: Video link. attrs (required: url): `url`, `platform` (1=bilibili), `align`.\n- **countdown**: Countdown. attrs (required: type): `type` (1=date,2=time), `duration` (ms, 0-86399999000).\n- **map**: Map (Amap). attrs (required: lng, lat, address, addressName): `lng`, `lat`, `address`, `addressName`, `platform` (1), `mapZoom`, `align`.\n- **thirdResource**: 3rd-party embed. attrs (required: url): `url`, `type` (1=mooc,2=modao,3=masterGo,4=netease,5=aliyun,6=survey,7=figma,8=pixso,9=xiaohuazhuo), `align`.\n- **dbsheet**: Multi-dim table. attrs (required: sourceId): `sourceId`, `width`, `height`.\n- **spreadsheet**: Spreadsheet. attrs (required: sourceId): `sourceId`, `sheetId`.\n- **groupCard**: Group card. attrs (required: id, name, masterName): `id`, `name`, `masterName`.\n- **appComponent**: App plugin. attrs: `type` (1=vote,2=video_channel,...8=canvas).\n- **processon**: Flowchart/mindmap. attrs (required: type, sourceId, sourceKey, width, height): `type` (1=flow,2=mind), `sourceId`, `sourceKey`, `caption`, `rotate`, `width`, `height`, `renderWidth`, `borderType`, `align`.\n\n## Inline node types (used in content of paragraph, heading, blockQuote, title, codeBlock):\n- **text**: Text. `content` field is a non-empty string (only in codeBlock may contain `\\n`). Common attrs: `bold`, `italic`, `underline`, `strike`, `sup`, `sub` (all bool); `fontSize {fontSize: 9|11|13|15|16|19|22}`; `color {fontColor,backgroundColor,fontGradientColor(1-6)}`.\n- **emoji**: Emoji. attrs (required: emoji): single emoji character.\n- **br**: Line break (used inside blockQuote). No attrs.\n- **latex**: Formula. attrs (required: width, height, latexStr): `width`, `height`, `latexStr`.\n- **linkView**: Hyperlink view. attrs (required: title, url, viewType, sourceKey, description): `title`, `url`, `viewType` (1=title,2=card \u2014 card requires paragraph parent with no siblings), `sourceKey` (icon id), `description`.\n- **schedule**: Schedule. attrs (required: id, name, startTime, endTime): `id` (taskId|sid|teamId), `name`, `startTime` (unix ms), `endTime` (unix ms), `actionType` (1=partial,2=allday).\n- **staticTime**: Date. attrs (required: time): `time` (unix ms), `timeType` (1=date,2=datetime).\n- **WPSUser**: @mention. attrs (required: userId, name): `userId`, `name`, `avatar`.\n- **WPSDocument**: Cloud doc / local file. attrs (required: wpsDocumentId, wpsDocumentName, wpsDocumentType): `wpsDocumentId`, `wpsDocumentName`, `wpsDocumentType`, `wpsDocumentLink` (required for cloud doc), `viewType` (1=title,2=preview,3=card,4=attachment \u2014 2/3/4 require paragraph parent with no siblings), `size` (bytes, required for local file), `width`, `height`, `align`.\n\n## Examples:\nParagraph: `{"type":"paragraph","content":[{"type":"text","content":"Hello"}]}`\nHeading h2: `{"type":"heading","attrs":{"level":2},"content":[{"type":"text","content":"Title"}]}`\nBold text: `{"type":"paragraph","content":[{"type":"text","attrs":{"bold":true},"content":"bold text"}]}`\nOrdered list: `{"type":"paragraph","attrs":{"listAttrs":{"type":2,"styleType":4,"level":0}},"content":[{"type":"text","content":"item 1"}]}`\nCode block: `{"type":"codeBlock","attrs":{"lang":19},"content":[{"type":"text","content":"console.log(\'hi\')"}]}`\nTable 2x2: `{"type":"table","attrs":{"borderStyle":2},"content":[{"type":"tableRow","content":[{"type":"tableCell","attrs":{"width":200,"height":40},"content":[{"type":"paragraph","content":[{"type":"text","content":"A1"}]}]},{"type":"tableCell","attrs":{"width":200,"height":40},"content":[{"type":"paragraph","content":[{"type":"text","content":"B1"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"width":200,"height":40},"content":[{"type":"paragraph","content":[{"type":"text","content":"A2"}]}]},{"type":"tableCell","attrs":{"width":200,"height":40},"content":[{"type":"paragraph","content":[{"type":"text","content":"B2"}]}]}]}]}`',parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/create)."},block_id:{type:"string",description:"Parent block id. Use the string `doc` to insert under the document root; otherwise use a block id from the query-document-blocks API."},index:{type:"integer",description:"Optional insert position (< 0 = before first child; beyond length = append to end). Omit to use API default (0)."},content:{type:"array",description:"Required array of block nodes to insert. Each node has `type` (string), optional `attrs` (object), and optional `content` (child nodes or text string for text nodes). See description above for all supported block and inline types.",items:{type:"object",additionalProperties:!0}}},required:["wps_user_id","file_id","block_id","content"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),s=q(n,"block_id"),a=lr(n,"content"),d=Ma(n,"index"),l=Wa({blockId:s,content:a,index:d}),c=Ye(i,"\u667A\u80FD\u6587\u6863\u521B\u5EFA\u5757\u5185\u5BB9");return await Le(o,c,async p=>{let u=await p.request({method:"POST",path:Ve(i,"/blocks/create"),body:l});return u.data??u})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_query_document_blocks",description:"Query blocks from a Smart Document (Airpage): POST `/v7/airpage/{file_id}/blocks`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON). JSON fields: required `blockId` (use literal `doc` to query the whole document tree, or pass a specific block id to query its children). Requires delegated Airpage permission (`kso.airpage.read` or `kso.airpage.readwrite` depending on app grants). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks)."},block_id:{type:"string",description:"Target block id mapped to request JSON field blockId. Use doc to query entire document blocks."}},required:["wps_user_id","file_id","block_id"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),s=q(n,"block_id"),a=za({blockId:s}),d=Ye(i,"\u667A\u80FD\u6587\u6863\u67E5\u8BE2\u6587\u6863\u5757");return await Le(o,d,async l=>{let c=await l.request({method:"POST",path:Ve(i,"/blocks"),body:a});return c.data??c})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_batch_query_document_blocks",description:"Batch query blocks from a Smart Document (Airpage): POST `/v7/airpage/{file_id}/blocks/batch_get`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON), with JSON field `blockIds` (string array). Use this when querying multiple specific block ids in one request. Requires delegated Airpage permission (`kso.airpage.read` or `kso.airpage.readwrite`). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/batch_get)."},block_ids:{type:"array",description:"Required block id list mapped to JSON blockIds for batch query.",items:{type:"string"}}},required:["wps_user_id","file_id","block_ids"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),s=ja(n,"block_ids"),a=La({blockIds:s}),d=Ye(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u67E5\u8BE2\u6587\u6863\u5757");return await Le(o,d,async l=>{let c=await l.request({method:"POST",path:Ve(i,"/blocks/batch_get"),body:a});return c.data??c})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_delete_block_content",description:"Delete block content from a Smart Document (Airpage): POST `/v7/airpage/{file_id}/blocks/delete`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON), with JSON fields: `blockId`, `startIndex`, `endIndex` (`endIndex` must be > `startIndex`). Use SenderId as `wps_user_id`. Requires delegated `kso.airpage.readwrite`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/delete)."},block_id:{type:"string",description:"Parent block id mapped to JSON field blockId. Commonly use doc for document root."},start_index:{type:"integer",description:"Required delete start position (mapped to JSON startIndex)."},end_index:{type:"integer",description:"Required delete end position (mapped to JSON endIndex), must be greater than start_index."}},required:["wps_user_id","file_id","block_id","start_index","end_index"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),s=q(n,"block_id"),a=cr(n,"start_index"),d=cr(n,"end_index"),l=Ba({blockId:s,startIndex:a,endIndex:d}),c=Ye(i,"\u667A\u80FD\u6587\u6863\u5220\u9664\u5757\u5185\u5BB9");return await Le(o,c,async p=>{let u=await p.request({method:"POST",path:Ve(i,"/blocks/delete"),body:l});return u.data??u})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_batch_delete_block_content",description:"Batch delete block content ranges from a Smart Document (Airpage): POST `/v7/airpage/{file_id}/blocks/batch_delete`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON), with JSON as an array of delete-range objects: `[{ blockId, startIndex, endIndex }]` and each item requires `endIndex > startIndex`. Use SenderId as `wps_user_id`. Requires delegated `kso.airpage.readwrite`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/batch_delete)."},delete_items:{type:"array",description:"Required delete range array. Each item: block_id, start_index, end_index (end_index > start_index).",items:{type:"object",properties:{block_id:{type:"string"},start_index:{type:"integer"},end_index:{type:"integer"}},required:["block_id","start_index","end_index"]}}},required:["wps_user_id","file_id","delete_items"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),a=lr(n,"delete_items").map((c,p)=>{if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`delete_items[${p}] must be an object`);let u=c,_=q(u,"block_id"),m=cr(u,"start_index"),y=cr(u,"end_index");return{blockId:_,startIndex:m,endIndex:y}}),d=Fa(a),l=Ye(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u5220\u9664\u5757\u5185\u5BB9");return await Le(o,l,async c=>{let p=await c.request({method:"POST",path:Ve(i,"/blocks/batch_delete"),body:d});return p.data??p})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_update_document_block",description:"Update Smart Document blocks via Airpage operation object: POST `/v7/airpage/{file_id}/blocks/update`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON) of ONE operation object (e.g. update_content, update_attrs, insert_table_rows, insert_table_columns, delete_table_rows, delete_table_columns, merge_table_cells, split_table_cell, replace_anchor, replace_feature). At minimum operation JSON should contain `operation` and `blockId`; other fields depend on operation type. Use SenderId as `wps_user_id`. Requires delegated `kso.airpage.readwrite`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/update)."},operation:{type:"object",description:"Required operation object that will be encoded as arg JSON. Must include operation + blockId. Example: {operation:'update_content', blockId:'xxx', content:[...]}",additionalProperties:!0}},required:["wps_user_id","file_id","operation"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),s=n.operation;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("operation is required and must be an object");let d=Ga(s),l=Ye(i,"\u667A\u80FD\u6587\u6863\u66F4\u65B0\u6587\u6863\u5757");return await Le(o,l,async c=>{let p=await c.request({method:"POST",path:Ve(i,"/blocks/update"),body:d});return p.data??p})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_batch_update_document_blocks",description:"Batch update Smart Document blocks via Airpage operation array: POST `/v7/airpage/{file_id}/blocks/batch_update`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON) of an operation object array. Each operation object must include `operation` + `blockId`; other fields depend on operation type (update_content, update_attrs, insert_table_rows, insert_table_columns, delete_table_rows, delete_table_columns, merge_table_cells, split_table_cell, replace_anchor, replace_feature). Use SenderId as `wps_user_id`. Requires delegated `kso.airpage.readwrite`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/batch_update)."},operations:{type:"array",description:"Required operation object array. Each item must include operation + blockId; extra fields depend on operation type.",items:{type:"object",additionalProperties:!0}}},required:["wps_user_id","file_id","operations"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),a=lr(n,"operations").map((c,p)=>{if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`operations[${p}] must be an object`);return c}),d=Ka(a),l=Ye(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u66F4\u65B0\u6587\u6863\u5757");return await Le(o,l,async c=>{let p=await c.request({method:"POST",path:Ve(i,"/blocks/batch_update"),body:d});return p.data??p})}catch(o){return Oe(o)}}})}var Xa="/v7/meeting_rooms",Va="/v7/meeting_rooms/search",Ya="/v7/meeting_room_bookings/batch_get",Za=["success","failed"];var Zi=["success","failed","approving"];function Nt(e){return{error:e instanceof Error?e.message:String(e)}}function Ae(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function yt(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}function In(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function Vi(e,t){let r=e[t];if(r==null)throw new Error(`${t} is required and must be a finite number`);if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}function Qa(e,t){let r=e[t];if(r!=null){if(typeof r=="boolean")return r;if(r==="true"||r==="false")return r==="true";throw new Error(`${t} must be a boolean`)}}function Qi(e,t){let r=e[t];if(r==null)return;if(!Array.isArray(r))throw new Error(`${t} must be an array`);let n=[];for(let o of r){if(typeof o!="string")throw new Error(`${t} entries must be strings`);let i=o.trim();i!==""&&n.push(i)}return n.length>0?n:void 0}function ed(e,t){let r=Qi(e,t);if(r===void 0)return;let n=new Set(Zi),o=r.filter(i=>n.has(i));return o.length>0?o:void 0}function Yi(e){let t=yt(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let r=t.trim();if(r!=="internal"&&r!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":r}}function td(e){let t=e.pageSize??20,n={page_size:Math.max(1,Math.min(500,Math.trunc(t)))};return e.roomLevelId!==void 0&&e.roomLevelId.trim()!==""&&(n.room_level_id=e.roomLevelId.trim()),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(n.page_token=e.pageToken.trim()),n}function rd(e){let t=e.trim();if(!t)throw new Error("room_id must be a non-empty string");return`/v7/meeting_rooms/${encodeURIComponent(t)}`}function nd(e){let t=e.keyword.trim();if(!t)throw new Error("keyword is required and must be a non-empty string");let r=e.pageSize??20,n=Math.max(1,Math.min(100,Math.trunc(r))),o={keyword:t,page_size:n};return e.pageToken!==void 0&&e.pageToken.trim()!==""&&(o.page_token=e.pageToken.trim()),o}function id(e){let t=Math.trunc(Number(e.startTimeSec)),r=Math.trunc(Number(e.endTimeSec));if(!Number.isFinite(t)||!Number.isFinite(r))throw new Error("start_time and end_time must be finite Unix timestamps in seconds");if(r<t)throw new Error("end_time must be >= start_time (Unix seconds)");let n=e.roomLevelId?.trim()??"",o=n!=="",i=e.roomIds?.filter(c=>c.trim()!=="").map(c=>c.trim())??[],s=i.length>0;if(o&&s)throw new Error("Provide either room_ids or room_level_id, not both");if(!o&&!s)throw new Error("Provide exactly one of room_ids (non-empty array) or room_level_id");let a=e.pageSize??20,d=Math.max(1,Math.min(500,Math.trunc(Number(a))));if(!Number.isFinite(d))throw new Error("page_size must be finite");let l={start_time:t,end_time:r,page_size:d};return o&&(l.room_level_id=n),s&&(l.room_ids=i),e.includeDeleted===!0&&(l.include_deleted=!0),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(l.page_token=e.pageToken.trim()),e.results!==void 0&&e.results.length>0&&(l.results=[...e.results]),l}function od(e){let t=e.trim();if(!t)throw new Error("booking_id must be a non-empty string");return`/v7/meeting_room_bookings/${encodeURIComponent(t)}/update_status`}function sd(e){let t=e.trim();if(t!=="success"&&t!=="failed")throw new Error("status must be success or failed");return{status:t}}function kn(e,t){t({name:"wps_meeting_rooms_list",description:"List meeting rooms (\u67E5\u8BE2\u4F1A\u8BAE\u5BA4\u5217\u8868): GET `/v7/meeting_rooms`. Uses **application** access_token (client_credentials); requires app scopes **`kso.meeting_rooms.read`** or **`kso.meeting_rooms.readwrite`** on the Open Platform (often **app-only**, not user OAuth). Still pass SenderId as `wps_user_id` for session context (not sent as HTTP user identity). Optional: `room_level_id` (\u4F1A\u8BAE\u5BA4\u5C42\u7EA7 id), `page_size` (default 20, max 500), `page_token` (omit on first page). Response `data` typically includes `items[]` (id, name, capacity, level_id, disable, remark, device_list, tag_list) and `next_page_token`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},room_level_id:{type:"string",description:"Optional. Meeting room level id (\u4F1A\u8BAE\u5BA4\u5C42\u7EA7 id)."},page_size:{type:"number",description:"Optional. Items per page (default 20 per API, max 500 client cap)."},page_token:{type:"string",description:"Optional. Pagination token from data.next_page_token; omit for first request."}},required:["wps_user_id"]},async execute(r,n){try{Ae(n,"wps_user_id");let o=yt(n,"room_level_id"),i=In(n,"page_size"),s=yt(n,"page_token"),a=td({roomLevelId:o,pageSize:i,pageToken:s}),d=await e.request({method:"GET",path:Xa,query:a});return d.data??d}catch(o){return Nt(o)}}}),t({name:"wps_meeting_rooms_get",description:"Get meeting room details (\u67E5\u8BE2\u4F1A\u8BAE\u5BA4\u8BE6\u60C5): GET `/v7/meeting_rooms/{room_id}`. Uses **application** access_token; requires app **`kso.meeting_rooms.read`** or **`kso.meeting_rooms.readwrite`**. Pass SenderId as `wps_user_id` for context only. Required: `room_id` from `wps_meeting_rooms_list` items[]. Response `data` is a single room object (id, name, capacity, level_id, disable, remark, device_list, tag_list).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},room_id:{type:"string",description:"Meeting room id from the meeting room list (\u4F1A\u8BAE\u5BA4 id\uFF0C\u53EF\u901A\u8FC7\u4F1A\u8BAE\u5BA4\u5217\u8868\u67E5\u8BE2)."}},required:["wps_user_id","room_id"]},async execute(r,n){try{Ae(n,"wps_user_id");let o=Ae(n,"room_id"),i=await e.request({method:"GET",path:rd(o)});return i.data??i}catch(o){return Nt(o)}}}),t({name:"wps_meeting_rooms_search",description:"Search meeting rooms by keyword (\u641C\u7D22\u4F1A\u8BAE\u5BA4): POST `/v7/meeting_rooms/search`. Uses **application** access_token; requires app **`kso.meeting_rooms.read`** or **`kso.meeting_rooms.readwrite`**. Pass SenderId as `wps_user_id` for context only. Required body: `keyword` (meeting room name search). Optional: `page_size` (default 20, max 100 per API), `page_token` (omit on first page; use data.next_page_token). Response `data` typically includes `items[]` and `next_page_token`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},keyword:{type:"string",description:"Search keyword; supports meeting room name (\u641C\u7D22\u5173\u952E\u8BCD\uFF0C\u652F\u6301\u4F1A\u8BAE\u5BA4\u540D\u79F0\u641C\u7D22)."},page_size:{type:"number",description:"Optional. Items per page (default 20 per API, max 100)."},page_token:{type:"string",description:"Optional. Pagination token from data.next_page_token; omit for first request."}},required:["wps_user_id","keyword"]},async execute(r,n){try{Ae(n,"wps_user_id");let o=Ae(n,"keyword"),i=In(n,"page_size"),s=yt(n,"page_token"),a=nd({keyword:o,pageSize:i,pageToken:s}),d=await e.request({method:"POST",path:Va,body:a});return d.data??d}catch(o){return Nt(o)}}}),t({name:"wps_meeting_room_bookings_batch_get",description:"Batch query meeting room bookings (\u6279\u91CF\u67E5\u8BE2\u4F1A\u8BAE\u5BA4\u9884\u7EA6): POST `/v7/meeting_room_bookings/batch_get`. Uses **application** access_token; requires app **`kso.meeting_rooms.read`** or **`kso.meeting_rooms.readwrite`**. Pass SenderId as `wps_user_id` for context only. Required JSON body params: `start_time`, `end_time` (**Unix timestamps in seconds**). Exactly one of: non-empty **`room_ids`** (string[]) **or** **`room_level_id`** (string)\u2014not both, not neither. Optional: `include_deleted` (boolean, default false), `page_size` (default 20, max 500), `page_token`, `results` filter array (`success`|`failed`|`approving`). Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},start_time:{type:"number",description:"Query window start (**Unix timestamp in seconds**, \u5FC5\u586B)."},end_time:{type:"number",description:"Query window end (**Unix timestamp in seconds**, \u5FC5\u586B)."},room_ids:{type:"array",items:{type:"string"},description:"Meeting room id list. Mutually exclusive with room_level_id."},room_level_id:{type:"string",description:"Meeting room level id. Mutually exclusive with room_ids."},include_deleted:{type:"boolean",description:"Whether to include deleted bookings (\u9ED8\u8BA4 false)."},page_size:{type:"number",description:"Page size (default 20 per API, max 500 client cap)."},page_token:{type:"string",description:"Pagination token; omit on first page when unused."},results:{type:"array",items:{type:"string",enum:[...Zi]},description:"Optional filter by reservation result: success, failed, approving."},x_kso_id_type:{type:"string",enum:["internal","external"],description:"Optional. Maps to HTTP header X-Kso-Id-Type."}},required:["wps_user_id","start_time","end_time"]},async execute(r,n){try{Ae(n,"wps_user_id");let o=Vi(n,"start_time"),i=Vi(n,"end_time"),s=Qi(n,"room_ids"),a=yt(n,"room_level_id"),d=Qa(n,"include_deleted"),l=In(n,"page_size"),c=yt(n,"page_token"),p=ed(n,"results"),u=id({startTimeSec:o,endTimeSec:i,roomIds:s,roomLevelId:a,includeDeleted:d,pageSize:l,pageToken:c,results:p??void 0}),_=await e.request({method:"POST",path:Ya,body:u,headers:Yi(n)});return _.data??_}catch(o){return Nt(o)}}}),t({name:"wps_meeting_room_bookings_update_status",description:"Update meeting room booking status (\u66F4\u65B0\u4F1A\u8BAE\u5BA4\u9884\u7EA6\u72B6\u6001): POST `/v7/meeting_room_bookings/{booking_id}/update_status`. Uses **application** access_token; requires app **`kso.meeting_rooms.readwrite`** (per API). Pass SenderId as `wps_user_id` for context only. Path: **`booking_id`** from booking list / batch query (`items[].id`). JSON body: **`status`** enum **`success`** (\u9884\u7EA6\u6210\u529F) or **`failed`** (\u9884\u7EA6\u5931\u8D25). Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},booking_id:{type:"string",description:"Meeting room booking id (\u4F1A\u8BAE\u5BA4\u9884\u7EA6 id\uFF0C\u53EF\u4ECE\u6279\u91CF\u67E5\u8BE2\u9884\u7EA6\u7B49\u63A5\u53E3 items[].id \u53D6\u5F97)."},status:{type:"string",enum:[...Za],description:"Updated reservation outcome: success or failed."},x_kso_id_type:{type:"string",enum:["internal","external"],description:"Optional. Maps to HTTP header X-Kso-Id-Type."}},required:["wps_user_id","booking_id","status"]},async execute(r,n){try{Ae(n,"wps_user_id");let o=Ae(n,"booking_id"),i=Ae(n,"status"),s=sd(i),a=await e.request({method:"POST",path:od(o),body:s,headers:Yi(n)});return a.data??a}catch(o){return Nt(o)}}})}var he={type:"string",description:"WPS user ID (current SenderId). Do NOT call wps_user_search for this."},xe={type:"string",description:"Smart Sheet file ID."},Qe={type:["integer","string"],description:"Worksheet ID (integer). From wps_airsheet_list_worksheets."};async function ad(e,t,r){return ce({wpsUserId:e,authCardOriginalMessage:"",needsAuthMessage:"\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u64CD\u4F5C\u667A\u80FD\u8868\u683C\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",logTag:t,run:r})}function ge(e,t){return async(r,n)=>{try{let o=v(n,"wps_user_id");return await ad(o,e,i=>t(n,i))}catch(o){return ie(o)}}}function Sn(e,t){t({name:"wps_airsheet_create_file",description:"Create a Smart Sheet (\u667A\u80FD\u8868\u683C / AirSheet): POST `/v7/airsheet/files`. Creates a new smart sheet file in the specified drive. Required: `drive_id` (from `wps_cloud_doc_list_drives`), `name` (file name, may omit extension; if extension is provided it must be `ksheet`). Optional: `on_name_conflict` (`rename` (default) | `fail`), `parent_id` (folder id, empty = root), `parent_path` (string array of folder names as relative path; auto-created if not exists). Requires delegated OAuth with scope `kso.airsheet.readwrite`. Use SenderId as `wps_user_id`. Response includes `id`, `link_id`, `link_url`, `name`, `parent_id`.",parameters:{type:"object",properties:{wps_user_id:he,drive_id:{type:"string",description:"Target drive id (from wps_cloud_doc_list_drives)."},name:{type:"string",description:"File name. May omit extension; if extension is provided it must be ksheet."},on_name_conflict:{type:"string",enum:["rename","fail"],description:"Optional. Strategy when name conflicts: rename (default) or fail."},parent_id:{type:"string",description:"Optional. Parent folder id. Empty means root directory."},parent_path:{type:"array",items:{type:"string"},description:"Optional. Relative path as array of folder names (not ids). If the path does not exist, the system will auto-create it."}},required:["wps_user_id","drive_id","name"]},execute:ge("wps_airsheet_create_file",async(r,n)=>{let o=v(r,"drive_id"),i=v(r,"name"),s=J(r,"on_name_conflict"),a=J(r,"parent_id"),d=He(r,"parent_path");if(s&&s!=="rename"&&s!=="fail")throw new Error("on_name_conflict must be 'rename' or 'fail'");let l={drive_id:o,name:i};s&&(l.on_name_conflict=s),a!==void 0&&(l.parent_id=a),d&&d.length>0&&(l.parent_path=d);let c=await n.request({method:"POST",path:"/v7/airsheet/files",body:l});return c.data??c})}),t({name:"wps_airsheet_create_worksheet",description:"Create a worksheet in a Smart Sheet (\u521B\u5EFA\u5DE5\u4F5C\u8868): POST `/v7/airsheet/{file_id}/worksheets`. Creates a new worksheet (tab) inside an existing smart sheet file. Required: `file_id`, `position` (object \u2014 at least one of `after_sheet_id`, `before_sheet_id`, or `end` must be set). Optional: `name` (worksheet name), `col_width` (default column width in pixels). Position rules: set `end: true` to append at the end; or use `after_sheet_id`/`before_sheet_id` (integer) to place relative to an existing sheet. Requires delegated OAuth with scope `kso.airsheet.readwrite`. Use SenderId as `wps_user_id`. Response includes `data.sheet_id` (integer).",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,name:{type:"string",description:"Optional. Worksheet name."},col_width:{type:"number",description:"Optional. Default column width in pixels."},position:{type:"object",description:"Insertion position. Must provide at least one of: after_sheet_id (integer), before_sheet_id (integer), end (boolean, true = append).",properties:{after_sheet_id:{type:"integer",description:"Insert after this sheet id."},before_sheet_id:{type:"integer",description:"Insert before this sheet id."},end:{type:"boolean",description:"If true, append at the end."}}}},required:["wps_user_id","file_id","position"]},execute:ge("wps_airsheet_create_worksheet",async(r,n)=>{let o=v(r,"file_id"),i=J(r,"name"),s=X(r,"col_width"),a=r.position;if(!a||typeof a!="object")throw new Error("position is required and must be an object");let d=a,l={},c=X(d,"after_sheet_id");c!==void 0&&(l.after_sheet_id=c);let p=X(d,"before_sheet_id");p!==void 0&&(l.before_sheet_id=p);let u=ee(d,"end");u!==void 0&&(l.end=u);let _={position:l};i!==void 0&&(_.name=i),s!==void 0&&(_.col_width=s);let m=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets`,body:_});return m.data??m})}),t({name:"wps_airsheet_list_worksheets",description:"List worksheets in a Smart Sheet (\u83B7\u53D6 Sheet \u5217\u8868\u4FE1\u606F): GET `/v7/airsheet/{file_id}/worksheets`. Returns all worksheets (tabs) in the specified smart sheet file. Each sheet includes: `sheet_id` (integer), `name`, `index`, `hidden`, `empty`, `max_row`, `max_col`, `resource_type` (et = normal spreadsheet), and `active_area` (col_from, col_to, row_from, row_to \u2014 the editing region). Use this to discover `sheet_id` before reading/writing data. Requires delegated OAuth (`kso.airsheet.read` or `kso.airsheet.readwrite`). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe},required:["wps_user_id","file_id"]},execute:ge("wps_airsheet_list_worksheets",async(r,n)=>{let o=v(r,"file_id"),i=await n.request({method:"GET",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets`});return i.data??i})}),t({name:"wps_airsheet_copy_worksheet",description:"Copy a worksheet (\u590D\u5236\u5DE5\u4F5C\u8868): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/copy`. Duplicates an existing worksheet within the same smart sheet file. Required: `file_id`, `worksheet_id` (integer, from `wps_airsheet_list_worksheets`). Optional: `copy_first_sheet` (boolean \u2014 if true, copies the first sheet regardless of `worksheet_id`). Requires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`. Response includes `data.sheet_id` (integer) \u2014 the new copied sheet's id.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:Qe,copy_first_sheet:{type:"boolean",description:"Optional. If true, copies the first sheet."}},required:["wps_user_id","file_id","worksheet_id"]},execute:ge("wps_airsheet_copy_worksheet",async(r,n)=>{let o=v(r,"file_id"),i=De(r,"worksheet_id"),s=ee(r,"copy_first_sheet"),a={};s!==void 0&&(a.copy_first_sheet=s);let d=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/copy`,body:a});return d.data??d})}),t({name:"wps_airsheet_update_worksheet",description:"Update a worksheet (\u66F4\u65B0\u5DE5\u4F5C\u8868): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/update`. Renames or moves a worksheet within the same smart sheet file. Required: `file_id`, `worksheet_id` (integer). Optional: `name` (new worksheet name), `move_sheet_id` (integer \u2014 reference sheet id for move), `move_type` (`sheet_move_type_before` | `sheet_move_type_after` \u2014 move before/after the reference sheet). Requires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`. Response: `{ code, msg }`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:Qe,name:{type:"string",description:"Optional. New worksheet name."},move_sheet_id:{type:["integer","string"],description:"Optional. Reference sheet id for repositioning."},move_type:{type:"string",enum:["sheet_move_type_before","sheet_move_type_after"],description:"Optional. Move before or after the reference sheet."}},required:["wps_user_id","file_id","worksheet_id"]},execute:ge("wps_airsheet_update_worksheet",async(r,n)=>{let o=v(r,"file_id"),i=De(r,"worksheet_id"),s=J(r,"name"),a=X(r,"move_sheet_id"),d=J(r,"move_type");if(d&&d!=="sheet_move_type_before"&&d!=="sheet_move_type_after")throw new Error("move_type must be 'sheet_move_type_before' or 'sheet_move_type_after'");let l={};s!==void 0&&(l.name=s),a!==void 0&&(l.move_sheet_id=a),d!==void 0&&(l.move_type=d);let c=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/update`,body:l});return c.data??c})}),t({name:"wps_airsheet_delete_worksheets",description:"Delete worksheets (\u5220\u9664\u5DE5\u4F5C\u8868): POST `/v7/airsheet/{file_id}/worksheets/batch_delete`. Batch-deletes one or more worksheets by their IDs. **This operation is irreversible.** Required: `file_id`, `worksheet_ids` (array of integers \u2014 sheet IDs from `wps_airsheet_list_worksheets`). Requires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`. Response: `{ code, msg }`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_ids:{type:"array",items:{type:"integer"},description:"Array of worksheet IDs (integers) to delete."}},required:["wps_user_id","file_id","worksheet_ids"]},execute:ge("wps_airsheet_delete_worksheets",async(r,n)=>{let o=v(r,"file_id"),i=r.worksheet_ids;if(!Array.isArray(i)||i.length===0)throw new Error("worksheet_ids must be a non-empty array of integers");let s=i.map((d,l)=>{let c=typeof d=="number"?d:parseInt(String(d),10);if(!Number.isFinite(c)||c<0)throw new Error(`worksheet_ids[${l}] must be a non-negative integer`);return c}),a=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/batch_delete`,body:{worksheet_ids:s}});return a.data??a})}),t({name:"wps_airsheet_create_rows",description:"Create rows in a worksheet (\u521B\u5EFA\u884C): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/rows`. Inserts one or more rows with cell data into the specified worksheet. Required: `file_id`, `worksheet_id` (integer). Optional: `range_data` (array of cell objects). Each cell object can include: `col` (integer, 0-based column index), `formula` (string, cell formula or plain value), `op_type` (string, e.g. `cell_operation_type_formula`), `cell_pic_info` (object for image cells: `{ height, width, pic_content, tag }` where tag = `sheet_pic_type_local`). If `range_data` is omitted, an empty row is appended. Requires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`. Response: `{ code, msg }`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:Qe,range_data:{type:"array",description:"Optional. Array of cell data objects. Each: { col: integer (0-based), formula?: string, op_type?: string, cell_pic_info?: { height: number, width: number, pic_content: string, tag: string } }.",items:{type:"object",properties:{col:{type:"integer",description:"0-based column index."},formula:{type:"string",description:"Cell formula or plain text value."},op_type:{type:"string",description:"Operation type, e.g. cell_operation_type_formula."},cell_pic_info:{type:"object",description:"Image cell info: { height, width, pic_content, tag }.",properties:{height:{type:"number"},width:{type:"number"},pic_content:{type:"string"},tag:{type:"string",description:"e.g. sheet_pic_type_local"}}}}}}},required:["wps_user_id","file_id","worksheet_id"]},execute:ge("wps_airsheet_create_rows",async(r,n)=>{let o=v(r,"file_id"),i=De(r,"worksheet_id"),s={},a=r.range_data;if(a!=null){if(!Array.isArray(a))throw new Error("range_data must be an array");s.range_data=a}let d=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/rows`,body:s});return d.data??d})}),t({name:"wps_airsheet_get_range_data",description:"Get cell range data (\u83B7\u53D6\u5355\u5143\u683C\u9009\u533A\u6570\u636E): GET `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/range_data`. Reads cell values from a rectangular region defined by row/col indices (0-based). Required: `file_id`, `worksheet_id` (integer), `row_from`, `row_to`, `col_from`, `col_to` (all integers). Use `wps_airsheet_list_worksheets` first to get `sheet_id` and `active_area` for valid ranges. Response: `data.range_data` array of cell objects, each with: `cell_text` (display value), `col_from`, `col_to`, `row_from`, `row_to`, `is_cell_pic` (boolean), `num_format`, `original_cell_value` (formula bar value), `pic_content`, `pic_data` (image id for online files), `sha1` (image hash for local images), `tag`. Requires delegated OAuth (`kso.airsheet.read` or `kso.airsheet.readwrite`). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:Qe,row_from:{type:"integer",description:"Start row index (0-based, inclusive)."},row_to:{type:"integer",description:"End row index (0-based, inclusive)."},col_from:{type:"integer",description:"Start column index (0-based, inclusive)."},col_to:{type:"integer",description:"End column index (0-based, inclusive)."}},required:["wps_user_id","file_id","worksheet_id","row_from","row_to","col_from","col_to"]},execute:ge("wps_airsheet_get_range_data",async(r,n)=>{let o=v(r,"file_id"),i=De(r,"worksheet_id"),s=X(r,"row_from"),a=X(r,"row_to"),d=X(r,"col_from"),l=X(r,"col_to");if(s===void 0||a===void 0||d===void 0||l===void 0)throw new Error("row_from, row_to, col_from, col_to are all required");let c=await n.request({method:"GET",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/range_data`,query:{row_from:s,row_to:a,col_from:d,col_to:l}});return c.data??c})}),t({name:"wps_airsheet_find_cells",description:"Find cells in a worksheet (\u67E5\u627E\u5355\u5143\u683C): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/range_data/find`. Searches cells within a specified range using filter conditions, with optional pagination and deduplication. Required: `file_id`, `worksheet_id`, `filter` (object), `range` (object with row_from/row_to/col_from/col_to). Optional: `ignore_hidden_cell` (boolean, default false \u2014 skip hidden cells), `option_cols` (array of integers \u2014 column indices to get option/dropdown values for), `page` (object: { page: integer (min 1), page_size: integer (default 100) }), `show_total` (boolean, default false \u2014 include total count in response). \n\n**filter structure**: `{ condition: [{ col: integer, info: [{ value: string }], mode: 'filter_mode_and' | 'filter_mode_or' }], duplicates: { col: [integer] }, search: [{ col: integer, value: [string] }] }`. All sub-fields in filter are optional. \n\nResponse: `data.range_data` (matched cells), `data.merge_range_data` (merged cell data), `data.option_col` (option column results with texts/count), `data.result_type` (0=fail, 1=success), `data.total`. Requires delegated OAuth (`kso.airsheet.read` or `kso.airsheet.readwrite`). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:Qe,filter:{type:"object",description:"Filter conditions. Structure: { condition?: [{ col: int, info: [{ value: string }], mode: 'filter_mode_and'|'filter_mode_or' }], duplicates?: { col: [int] }, search?: [{ col: int, value: [string] }] }."},range:{type:"object",description:"Search range (required). { row_from: int, row_to: int, col_from: int, col_to: int }.",properties:{row_from:{type:"integer",description:"Start row index (0-based)."},row_to:{type:"integer",description:"End row index (0-based)."},col_from:{type:"integer",description:"Start column index (0-based)."},col_to:{type:"integer",description:"End column index (0-based)."}},required:["row_from","row_to","col_from","col_to"]},ignore_hidden_cell:{type:"boolean",description:"Optional. If true, skip hidden cells. Default false."},option_cols:{type:"array",items:{type:"integer"},description:"Optional. Column indices to retrieve option/dropdown values for (relative to range)."},page:{type:"object",description:"Optional pagination. { page: integer (min 1), page_size: integer (default 100) }.",properties:{page:{type:"integer",description:"Page number, min 1."},page_size:{type:"integer",description:"Page size, default 100."}}},show_total:{type:"boolean",description:"Optional. If true, include total count in response. Default false."}},required:["wps_user_id","file_id","worksheet_id","filter","range"]},execute:ge("wps_airsheet_find_cells",async(r,n)=>{let o=v(r,"file_id"),i=De(r,"worksheet_id"),s=r.filter;if(!s||typeof s!="object")throw new Error("filter is required and must be an object");let a=r.range;if(!a||typeof a!="object")throw new Error("range is required and must be an object");let d={filter:s,range:a},l=ee(r,"ignore_hidden_cell");l!==void 0&&(d.ignore_hidden_cell=l);let c=r.option_cols;if(c!=null){if(!Array.isArray(c))throw new Error("option_cols must be an array of integers");d.option_cols=c.map((m,y)=>{let h=typeof m=="number"?m:parseInt(String(m),10);if(!Number.isFinite(h)||h<0)throw new Error(`option_cols[${y}] must be a non-negative integer`);return h})}let p=r.page;if(p!=null){if(typeof p!="object")throw new Error("page must be an object");d.page=p}let u=ee(r,"show_total");u!==void 0&&(d.show_total=u);let _=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/range_data/find`,body:d});return _.data??_})}),t({name:"wps_airsheet_batch_update_cells",description:"Batch update cell range data (\u66F4\u65B0\u5355\u5143\u683C\u9009\u533A\u6570\u636E): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/range_data/batch_update`. Updates one or more cells in a worksheet. Each cell in `range_data` specifies its position (row_from, row_to, col_from, col_to) and operation type (`op_type`). \n\n**op_type values**: `cell_operation_type_formula` \u2014 set cell value/formula (use `formula` field), `cell_operation_type_picture` \u2014 set cell image (use `cell_pic_info` with height/width/pic_content/tag), `cell_operation_type_format` \u2014 set cell formatting (use `xf` field for styles), `cell_operation_type_merge` \u2014 merge cells (use `merge_type`: merge_type_center / merge_type_content / merge_type_same / merge_type_columns). \n\n**cell_pic_info.tag values**: `sheet_pic_type_local`, `sheet_pic_type_attachment`, `sheet_pic_type_url`. \n\n**xf (format) object** includes: `alc_h` (horizontal align), `alc_v` (vertical align), border colors (`clr_bottom/clr_top/clr_left/clr_right/clr_diag_down/clr_diag_up/clr_inside_horz/clr_inside_vert` \u2014 each `{tint,type,value}`), border styles (`dg_bottom/dg_top/dg_left/dg_right/dg_diag_down/dg_diag_up/dg_inside_horz/dg_inside_vert`), `fill` ({back:{tint,type,value}, fore:{tint,type,value}, type}), `font` ({bls,char_set,color:{tint,type,value},dy_height,italic,name,sss,strikeout,theme_font,uls}), `hidden`, `indent`, `locked`, `mask_cats`, `mask_cats_font`, `numfmt`, `reading_order`, `shrink_to_fit`, `trot`, `wrap`. \n\nRequires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`. Response: `{ code, msg }`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:Qe,range_data:{type:"array",description:"Array of cell update objects. Each must include: row_from (int), row_to (int), col_from (int), col_to (int), op_type (string). Depending on op_type, also include: formula (string), cell_pic_info (object), merge_type (string), xf (format object).",items:{type:"object",properties:{row_from:{type:"integer",description:"Start row (0-based)."},row_to:{type:"integer",description:"End row (0-based)."},col_from:{type:"integer",description:"Start column (0-based)."},col_to:{type:"integer",description:"End column (0-based)."},op_type:{type:"string",enum:["cell_operation_type_formula","cell_operation_type_picture","cell_operation_type_format","cell_operation_type_merge"],description:"Cell operation type."},formula:{type:"string",description:"Cell value or formula (for op_type=formula)."},cell_pic_info:{type:"object",description:"Image info (for op_type=picture): { height, width, pic_content, tag }."},merge_type:{type:"string",enum:["merge_type_center","merge_type_content","merge_type_same","merge_type_columns"],description:"Merge type (for op_type=merge)."},xf:{type:"object",description:"Format/style object (for op_type=format). See tool description for full structure."}},required:["row_from","row_to","col_from","col_to","op_type"]}}},required:["wps_user_id","file_id","worksheet_id","range_data"]},execute:ge("wps_airsheet_batch_update_cells",async(r,n)=>{let o=v(r,"file_id"),i=De(r,"worksheet_id"),s=r.range_data;if(!Array.isArray(s)||s.length===0)throw new Error("range_data must be a non-empty array");let a=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/range_data/batch_update`,body:{range_data:s}});return a.data??a})}),t({name:"wps_airsheet_batch_delete_cells",description:"Batch delete cell range data (\u5220\u9664\u5355\u5143\u683C\u9009\u533A\u6570\u636E): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/range_data/batch_delete`. Deletes data in specified cell ranges. Caller must ensure row/col indices are within the worksheet's max row/col limits (obtainable via getSheetInfo). \n\nRequired: `file_id`, `worksheet_id`, `range_data` (array of range objects, each with `col_from`, `col_to`, `row_from`, `row_to` \u2014 all integers, required). \n\nOptional: `shift_type` \u2014 how remaining cells shift after deletion. Values: `shift_up` (default, shift up) or `shift_left` (shift left). \n\nResponse: `{ code, msg }`. Requires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:Qe,range_data:{type:"array",description:"Array of range objects to delete. Each must include col_from, col_to, row_from, row_to (all integers).",items:{type:"object",properties:{col_from:{type:"integer",description:"Start column index (0-based)."},col_to:{type:"integer",description:"End column index (0-based)."},row_from:{type:"integer",description:"Start row index (0-based)."},row_to:{type:"integer",description:"End row index (0-based)."}},required:["col_from","col_to","row_from","row_to"]}},shift_type:{type:"string",enum:["shift_up","shift_left"],description:"Optional. How remaining cells shift after deletion. Default: shift_up."}},required:["wps_user_id","file_id","worksheet_id","range_data"]},execute:ge("wps_airsheet_batch_delete_cells",async(r,n)=>{let o=v(r,"file_id"),i=De(r,"worksheet_id"),s=r.range_data;if(!Array.isArray(s)||s.length===0)throw new Error("range_data must be a non-empty array");let a={range_data:s},d=J(r,"shift_type");d!==void 0&&(a.shift_type=d);let l=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/range_data/batch_delete`,body:a});return l.data??l})})}function dd(){return new Proxy({},{get(e,t,r){let n=Gr(),o=Reflect.get(n,t,r);return typeof o=="function"?o.bind(n):o}})}function eo(e){let t=[],r=o=>{e(()=>({name:o.name,label:o.name,description:o.description,parameters:o.parameters,async execute(s,a){let d=await o.execute(s,a);if(d&&typeof d=="object"&&"error"in d)throw new Error(d.error);return{content:[{type:"text",text:JSON.stringify(d,null,2)}],details:d}}}),{name:o.name}),t.push(o.name)},n=dd();return dn(n,r),cn(n,r),un(n,r),tn(n,r),mn(n,r),hn(n,r),yn(n,r),gn(n,r),bn(n,r),kn(n,r),Sn(n,r),console.log(`[wps-xiezuo] OAPI tools registered: ${t.length} tools`),t.length}var cd={id:be,name:"WPS Xiezuo",description:"WPS365 Open Platform channel plugin for OpenClaw",configSchema:Mn(),register(e){ki(e.runtime);let t=e.logger??{info:()=>{},warn:()=>{},error:()=>{}};if(e.registerChannel({plugin:sn}),typeof e.registerTool=="function"){t.info(`[${be}] registerTool is available (type: ${typeof e.registerTool})`);try{let r=eo(e.registerTool);t.info(`[${be}] registered ${r} WPS OAPI tool factories`)}catch(r){t.error(`[${be}] tool registration failed: ${r}`)}}else t.warn(`[${be}] registerTool not available (type: ${typeof e.registerTool})`);typeof e.on=="function"?(e.on("before_prompt_build",async(r,n)=>{let o=n;if(o.channelId==="wps-xiezuo"||o.messageProvider==="wps-xiezuo")return{appendSystemContext:["","## WPS \u6D88\u606F\u8DEF\u7531","- \u53D1\u6587\u672C\u5230\u7FA4\u804A/\u7528\u6237\uFF1A`wps_message_send(receiver_type, receiver_id, msg_type='text', content=...)`","- \u6309\u540D\u5B57\u627E\u7FA4\uFF1A\u5148 `wps_chat_find_by_name(keyword=<\u540D\u79F0>)` \u62FF chat_id","- \u56DE\u5F53\u524D\u4F1A\u8BDD\uFF1Areceiver_id \u7528 RawBody \u7684 `chatId`\uFF08\u7FA4\u804A\uFF09\u6216 `SenderId`\uFF08\u5355\u804A\uFF09","","## WPS365 \u65E5\u7A0B / \u65E5\u5386","\u610F\u56FE\u2192\u5DE5\u5177\u3001\u53C2\u6570\u4E0E\u793A\u4F8B\u4EE5 **`skills/wps-calendar/SKILL.md`** \u4E3A\u51C6\uFF08\u968F\u63D2\u4EF6\u52A0\u8F7D\uFF09\u3002\u4EC5\u5141\u8BB8\u901A\u8FC7 **`wps_calendar_*`** \u8C03\u7528\u5F00\u653E\u5E73\u53F0\u7528\u6237\u65E5\u5386\uFF1B\u67D0\u6761\u65E5\u7A0B\u4E0A\u4F1A\u8BAE\u5BA4**\u5217\u8868**/\u6279\u91CF**\u6DFB\u52A0**/\u6279\u91CF**\u5220\u9664**\u5206\u522B\u7528 **`wps_calendar_list_event_meeting_rooms`** / **`wps_calendar_event_meeting_rooms_batch_create`** / **`wps_calendar_event_meeting_rooms_batch_delete`**\uFF1B**\u7981\u6B62**\u7528 .ics\u3001\u672C\u5730\u811A\u672C\u6216\u5176\u5B83\u6377\u5F84\u5192\u5145\u5DF2\u521B\u5EFA/\u5DF2\u67E5\u8BE2\u3002","## WPS365 \u65E5\u7A0B\u4F1A\u8BAE\u5BA4","\u4EE5 **`skills/wps-meeting-room/SKILL.md`** \u4E3A\u51C6\uFF1A\u5217\u8868 **`wps_meeting_rooms_list`**\uFF1B\u641C\u7D22 **`wps_meeting_rooms_search`**\uFF1B\u8BE6\u60C5 **`wps_meeting_rooms_get`**\uFF1B\u6279\u91CF\u9884\u7EA6 **`wps_meeting_room_bookings_batch_get`**\uFF08Unix \u79D2\u65F6\u95F4\u7A97\uFF0C`room_ids`/`room_level_id` \u4E8C\u9009\u4E00\uFF09\uFF1B\u66F4\u65B0\u9884\u7EA6\u72B6\u6001 **`wps_meeting_room_bookings_update_status`**\uFF08`booking_id`\uFF0C`status`=`success`|`failed`\uFF0C\u987B **readwrite**\uFF09\u3002`wps_user_id` \u4F7F\u7528 **SenderId**\uFF1B\u53EF\u9009 **`x_kso_id_type`**\uFF1B\u672A\u6388\u6743\u65F6\u8FD4\u56DE `needsAuth`\u3002","## WPS365 \u4E2A\u4EBA\u5F85\u529E","\u610F\u56FE\u4E0E\u53C2\u6570\u4EE5 **`skills/wps-todo/SKILL.md`** \u4E3A\u51C6\u3002\u521B\u5EFA **`wps_todo_create_personal_task`**\uFF0C\u5217\u4E3E **`wps_todo_list_personal_tasks`**\uFF0C\u8BE6\u60C5 **`wps_todo_get_personal_task`**\uFF0C\u66F4\u65B0 **`wps_todo_update_personal_task`**\uFF0C\u72B6\u6001\u66F4\u65B0 **`wps_todo_update_personal_task_status`**\uFF1B`wps_user_id` \u4F7F\u7528 **SenderId**\uFF0C\u672A\u6388\u6743\u65F6\u540C\u6837\u8FD4\u56DE `needsAuth`\u3002","## WPS365 \u667A\u80FD\u6587\u6863\uFF08Airpage\uFF09","\u4EE5 **`skills/wps-airpage/SKILL.md`** \u4E3A\u51C6\u3002\u65B0\u5EFA\u6587\u6863\uFF1A**`wps_airpage_create_file`**\uFF08`POST /v7/airpage/files`\uFF09\uFF1B\u5411\u6587\u6863\u63D2\u5165\u5757\uFF1A**`wps_airpage_create_block_content`**\uFF08`POST /v7/airpage/{file_id}/blocks/create`\uFF09\uFF1B\u67E5\u8BE2\u6587\u6863\u5757\uFF1A**`wps_airpage_query_document_blocks`**\uFF08`POST /v7/airpage/{file_id}/blocks`\uFF09\uFF1B\u6279\u91CF\u67E5\u8BE2\uFF1A**`wps_airpage_batch_query_document_blocks`**\uFF08`POST /v7/airpage/{file_id}/blocks/batch_get`\uFF09\uFF1B\u5220\u9664\u5757\u5185\u5BB9\uFF1A**`wps_airpage_delete_block_content`**\uFF08`POST /v7/airpage/{file_id}/blocks/delete`\uFF09\uFF1B\u6279\u91CF\u5220\u9664\uFF1A**`wps_airpage_batch_delete_block_content`**\uFF08`POST /v7/airpage/{file_id}/blocks/batch_delete`\uFF09\uFF1B\u66F4\u65B0\u6587\u6863\u5757\uFF1A**`wps_airpage_update_document_block`**\uFF08`POST /v7/airpage/{file_id}/blocks/update`\uFF09\uFF1B\u6279\u91CF\u66F4\u65B0\uFF1A**`wps_airpage_batch_update_document_blocks`**\uFF08`POST /v7/airpage/{file_id}/blocks/batch_update`\uFF09\u3002\u5757\u76F8\u5173\u63A5\u53E3 Body \u5185 **`arg`** \u5747\u4E3A Base64(JSON)\uFF0C\u542B **`blockId`** / **`blockIds`** / `startIndex` / `endIndex` / operation \u6216 operation \u6570\u7EC4\u7ED3\u6784\u3002\u9700 Airpage delegated \u6743\u9650\uFF08\u8BFB\u5199\u6216\u53EA\u8BFB\uFF09\uFF1B\u65B0\u5EFA\u524D\u7528 **`wps_cloud_doc_list_drives`** \u53D6 **`drive_id`**\u3002`wps_user_id` \u4F7F\u7528 **SenderId**\uFF1B\u672A\u6388\u6743\u65F6\u8FD4\u56DE `needsAuth`\u3002","## WPS365 \u4E91\u6587\u6863","\u4E91\u6587\u6863\u53C2\u6570\u4E0E\u7EA6\u675F\u4EE5 **`skills/wps-cloud-doc/SKILL.md`** \u4E3A\u51C6\u3002\u83B7\u53D6\u76D8\u5217\u8868\u7528 **`wps_cloud_doc_list_drives`**\uFF08\u53C2\u6570\u540D `allotee_type/allotee_id`\uFF09\uFF1B\u83B7\u53D6\u5B50\u6587\u4EF6\u5217\u8868\u7528 **`wps_cloud_doc_list_children_files`**\uFF08`drive_id`\u3001`parent_id`\uFF09\uFF1B\u65B0\u5EFA\u6587\u4EF6\uFF08\u5939\uFF09\u7528 **`wps_cloud_doc_create_file`**\uFF1B\u6587\u6863\u5185\u5BB9\u62BD\u53D6\u7528 **`wps_cloud_doc_extract_file_content`**\uFF1B\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F\u7528 **`wps_cloud_doc_get_file_meta`**\uFF1B\u6587\u4EF6\u641C\u7D22\u7528 **`wps_cloud_doc_search_files`**\u3002`wps_user_id` \u5FC5\u987B\u4F7F\u7528 **SenderId**\uFF0C\u672A\u6388\u6743\u65F6\u5DE5\u5177\u8FD4\u56DE `needsAuth` \u5E76\u81EA\u52A8\u4E0B\u53D1\u6388\u6743\u5361\u7247\u3002","`wps_user_id` \u4F7F\u7528\u5165\u7AD9\u4E0A\u4E0B\u6587\u7684 **SenderId**\uFF1B\u4E0D\u8981\u4E3A\u6B64\u8C03\u7528 `wps_user_search`\u3002\u672A\u6388\u6743\u65F6\u5DE5\u5177\u8FD4\u56DE `needsAuth` \u5E76\u5DF2\u53D1\u6388\u6743\u5361\u7247\uFF0C\u5F15\u5BFC\u7528\u6237\u5B8C\u6210\u6388\u6743\u540E\u518D\u8BD5\u3002","","## \u53D1\u56FE\u7247/\u6587\u4EF6\uFF08\u672C\u5730\u5DF2\u4E0B\u8F7D\u8DEF\u5F84\uFF09","\u5F53 Body \u4E2D\u51FA\u73B0 `[\u5DF2\u4E0B\u8F7D\u56FE\u7247: ...]` \u6216 `[\u5DF2\u4E0B\u8F7D\u6587\u4EF6: ...]` \u6216\u5F15\u7528\u9644\u4EF6\u56DE\u53D1\u6307\u4EE4\u4E2D\u7ED9\u51FA\u4E86\u8DEF\u5F84\uFF0C\u8981\u53D1\u56DE\u7ED9\u7528\u6237\u65F6\uFF1A","\u7528 `message` \u5DE5\u5177\uFF08\u53C2\u6570\u540D\u662F `to` \u548C `message`\uFF0C\u4E0D\u662F receiver_id \u548C content\uFF09\uFF1A",' message(action="send", to="user:<SenderId>", message="\u4E3A\u60A8\u53D1\u56DE\u56FE\u7247", media="<\u8DEF\u5F84>")',"\u26A0\uFE0F `to` \u53C2\u6570\u662F**\u5FC5\u586B**\u7684\uFF01\u7EDD\u5BF9\u4E0D\u80FD\u7701\u7565 `to`\uFF0C\u5426\u5219\u4F1A\u5BFC\u81F4 deMixValue \u9519\u8BEF\u3002","\u26A0\uFE0F `to` \u7684\u503C\u5FC5\u987B\u662F `user:<\u7528\u6237ID>` \u6216 `chat:<\u7FA4ID>`\uFF0C\u4E14 `<...>` \u5185\u53EA\u80FD\u662F **\u88F8 id**\uFF08\u4E0E RawBody \u7684 `chatId` / `SenderId` \u4E00\u81F4\uFF09\u3002","\u26A0\uFE0F \u7981\u6B62\u5199\u6210 `chat:wps:...` \u6216 `user:wps:...`\uFF1A\u4E0D\u8981\u628A `OriginatingFrom` \u91CC\u7684 `wps:` \u524D\u7F00\u62FC\u8FDB id\uFF08\u63D2\u4EF6\u4F1A\u5C3D\u91CF\u7EA0\u6B63\uFF0C\u4F46\u8BEF\u7528 SessionKey \u91CC `:bot:` \u540E\u7684 AK\u2026 \u4ECD\u4F1A\u5931\u8D25\uFF09\u3002","\u63D2\u4EF6\u4F1A\u81EA\u52A8\u5B8C\u6210\u4E0A\u4F20\u548C\u53D1\u9001\uFF0C\u4E0D\u9700\u8981\u4F60\u624B\u52A8\u8C03\u7528 upload\u3002","","## \u6536\u5230\u56FE\u7247/\u6587\u4EF6\u65F6\u7684\u884C\u4E3A\u51C6\u5219","- \u7528\u6237\u76F4\u63A5\u53D1\u9001\u56FE\u7247\u6216\u6587\u4EF6\u65F6\uFF08\u6CA1\u6709\u9644\u52A0\u6587\u5B57\u6307\u4EE4\uFF09\uFF0C**\u4E0D\u8981\u81EA\u52A8\u53D1\u56DE**\uFF0C\u5E94\u8BE2\u95EE\u7528\u6237\u9700\u8981\u4EC0\u4E48\u64CD\u4F5C\u3002","- \u53EA\u6709\u5F53\u7528\u6237\u660E\u786E\u8981\u6C42\u300C\u53D1\u56DE\u6765\u300D\u300C\u8F6C\u53D1\u300D\u300C\u53D1\u7ED9\u6211\u300D\u7B49\u64CD\u4F5C\u65F6\uFF0C\u624D\u4F7F\u7528 message \u5DE5\u5177\u53D1\u56DE\u3002","","## \u4E91\u6587\u4EF6\uFF08cloud file\uFF09","\u5F53 Body \u4E2D\u51FA\u73B0 `[\u5F15\u7528\u4E91\u6587\u4EF6: ...]` \u6216 `[\u4E91\u6587\u4EF6\u94FE\u63A5: ...]` \u65F6\uFF0C\u8FD9\u662F WPS \u4E91\u6587\u4EF6\uFF08\u65E0\u672C\u5730\u8DEF\u5F84\uFF09\u3002","\u5F53 Body \u4E2D\u51FA\u73B0\u77E5\u8BC6\u5E93\u94FE\u63A5\uFF08\u5982 `www.kdocs.cn/wiki/l/0lxxxx` \u6216 `{\u4F01\u4E1A\u57DF\u540D}.kdocs.cn/wiki/l/0lxxxx`\uFF09\u65F6\uFF0C\u8DEF\u5F84\u4E2D **`0l` \u4E4B\u540E\u7684 xxxx** \u4E3A link_id\uFF0C\u53EF\u4F5C\u4E3A file_id \u4F7F\u7528\u3002","\u7981\u6B62\u4F7F\u7528 wps_message_send \u4EE5 msg_type='file' + cloud \u7ED3\u6784\u8F6C\u53D1\u4E91\u6587\u4EF6\uFF08\u5E94\u7528 token \u4E0D\u652F\u6301\uFF0C\u4F1A\u8FD4\u56DE 400 InvalidMessage\uFF09\u3002","\u5982\u9700\u8BFB\u53D6\u4E91\u6587\u4EF6\u5185\u5BB9\uFF0C\u8C03\u7528 wps_cloud_doc_get_file_meta(file_id, with_drive=true) \u83B7\u53D6 drive_id\uFF0C\u518D\u8C03\u7528 wps_cloud_doc_extract_file_content(drive_id, file_id) \u62BD\u53D6\u6B63\u6587\u3002","\u5982\u9700\u5411\u7528\u6237\u5206\u4EAB\u4E91\u6587\u4EF6\uFF0C\u7528 wps_message_send \u53D1\u9001\u4E00\u6761\u5305\u542B link_url \u7684\u6587\u672C\u6D88\u606F\u5373\u53EF\uFF08\u53EA\u53D1\u4E00\u6761\uFF0C\u4E0D\u8981\u91CD\u590D\u53D1\u9001\uFF09\u3002","","\u26A0\uFE0F \u7981\u6B62\u4F7F\u7528 sessions_send \u5411 WPS \u4F1A\u8BDD\u53D1\u6D88\u606F\uFF08sessions_send \u4EC5\u7528\u4E8E OpenClaw \u5185\u90E8\u4F1A\u8BDD\u95F4\u901A\u4FE1\uFF0C\u65E0\u6CD5\u6295\u9012\u5230 WPS \u5BA2\u6237\u7AEF\uFF09\u3002\u7981\u6B62\u628A\u672C\u5730\u6587\u4EF6\u8DEF\u5F84\u5F53\u7EAF\u6587\u672C\u56DE\u590D\u3002","\u26A0\uFE0F \u7981\u6B62\u544A\u8BC9\u7528\u6237\u53BB WPS \u754C\u9762\u624B\u52A8\u53D1\u9001\uFF1B\u6709 **`wps_message_send`** / **`message`** \u80FD\u529B\u65F6\u5FC5\u987B\u76F4\u63A5\u6267\u884C\u3002"].join(`
36
- `)}}),t.info(`[${be}] before_prompt_build hook registered`)):t.warn(`[${be}] api.on not available, cannot register prompt hook`),t.info(`[${be}] plugin registered`)}},tp=cd;export{tp as default};
34
+ openclaw pairing approve --channel ${E} --account ${i} ${H}`;await lt(d,N,Mt)}}}return}if(!S){let O=a?.groupPolicy??"allowlist",H=a?.groups??{};if(O==="allowlist"&&!H[w]&&!H["*"]){r(`Group ${w} blocked by groupPolicy=allowlist`);return}}if(jt.trim()==="/wpsxiezuo auth"){let{sendAuthCard:O}=await Promise.resolve().then(()=>(Qt(),Vr)),{getLazyWpsCfg:H}=await Promise.resolve().then(()=>(ct(),ci));try{let J=w?"chat":"user",Be=w||g;await O({creds:d,wpsCfg:H(),wpsUserId:g,receiverType:J,receiverId:Be})||await lt(d,N,"\u5F53\u524D\u5E94\u7528\u6CA1\u6709\u53EF\u6388\u6743\u7684\u7528\u6237\u6743\u9650\uFF08delegated scopes \u4E3A\u7A7A\uFF09\uFF0C\u8BF7\u5148\u5728\u5F00\u653E\u5E73\u53F0\u540E\u53F0\u5F00\u901A\u3002")}catch(J){n("WPS /wpsxiezuo auth failed:",J),await lt(d,N,`\u6388\u6743\u5361\u7247\u53D1\u9001\u5931\u8D25\uFF1A${String(J)}`)}return}if(jt.trim()==="/wps-id"||jt.trim().startsWith("/wps-id ")){let O={sender:{id:u.id??"",type:u.type??"",name:u.name??""},chat:{id:_?.id??"",type:_?.type??""},message:{id:p.id??"",type:p.type??""},isDirect:S};await lt(d,N,`WPS id debug:
35
+ ${JSON.stringify(O,null,2)}`);return}if(!s){r("WPS: channelRuntime not available \u2014 skipping AI dispatch");return}let A=s.reply,$e=s.routing,qe="main",ue="",U=i;if($e?.resolveAgentRoute){let O=$e.resolveAgentRoute({cfg:o,channel:E,accountId:i,peer:{kind:S?"direct":"group",id:h.session_key}});qe=O.agentId,ue=O.sessionKey?.trim()??"",O.accountId&&(U=O.accountId,r(`WPS route account override: ${i} -> ${O.accountId}`))}let F=ue||h.session_key,vn=U;r(`WPS route: agentId=${qe}, inboundSessionKey=${F}, accountId=${vn}`);let Tn={Body:It,BodyForAgent:It,...ee.length>0?{MediaPath:ee[0],MediaType:tt[0],MediaPaths:ee,MediaTypes:tt}:{},RawBody:JSON.stringify({session:h,chatId:w,messageId:b,senderId:g,messageType:I.kind,plainText:I.plainText,attachments:I.attachments,...B?{prefetchedMedia:B}:{},_idHint:"chatId and messageId are OAPI IDs for /v7/chats/{chat_id}/ endpoints. session.session_key is an internal routing key \u2014 do NOT extract segments from it as OAPI IDs. AK-prefixed strings in session_key are bot/app IDs, not chat IDs."}),CommandBody:It,From:K,To:S?`user:${g}`:`chat:${w}`,SessionKey:F,Label:F,ConversationLabel:F,DisplayName:F,SessionLabel:F,AccountId:vn,ChatType:S?"direct":"group",GroupId:void 0,SenderName:u.name??void 0,SenderId:g,Provider:E,Surface:"wps",Channel:E,Timestamp:l.send_time??Date.now(),OriginatingChannel:E,OriginatingFrom:`wps:${g}`,OriginatingTo:`wps:${d.clientId}`},En=A.finalizeInboundContext?A.finalizeInboundContext(Tn):Tn,kt=null;if(w&&b)try{await vr(d,w,b),kt={kind:"reaction",chatId:w,messageId:b},r(`WPS thinking reaction added: chatId=${w}, messageId=${b}`)}catch(O){r(`WPS thinking reaction failed, falling back to text: ${String(O)}`);try{await lt(d,N,"\u6B63\u5728\u601D\u8003\u4E2D..."),kt={kind:"text-fallback"}}catch(H){r(`WPS thinking fallback text failed: ${String(H)}`)}}let Pn=()=>async(O,H)=>{let J=O.text??"";if(!J)return;let Be=J.trim();if(/Message:.*[\\/]openclaw-media[\\/].*failed/i.test(Be)){r(`WPS deliver: suppressed media-failed noise: ${Be.substring(0,80)}`);return}r(`WPS deliver: text length=${J.length}, preview=${J.substring(0,80)}`),!S&&w&&b?await rs(d,w,b,J):await lt(d,N,J)};try{if(A.dispatchReplyWithBufferedBlockDispatcher)await A.dispatchReplyWithBufferedBlockDispatcher({ctx:En,cfg:o,dispatcherOptions:{deliver:Pn(),responsePrefix:"",humanDelay:A.resolveHumanDelayConfig?A.resolveHumanDelayConfig(o,qe):void 0,onError:(O,H)=>{n(`WPS ${H.kind} reply error: ${String(O)}`)}}}),r("WPS: agent dispatch completed");else if(A.dispatchReplyFromConfig&&A.createReplyDispatcherWithTyping){let O=A.resolveHumanDelayConfig?A.resolveHumanDelayConfig(o,qe):void 0,{dispatcher:H,replyOptions:J,markDispatchIdle:Be}=A.createReplyDispatcherWithTyping({responsePrefix:"",humanDelay:O,deliver:Pn(),onError:(Mt,to)=>{n(`WPS ${to.kind} reply error: ${String(Mt)}`)}});try{await A.dispatchReplyFromConfig({ctx:En,cfg:o,dispatcher:H,replyOptions:J})}finally{Be()}r("WPS: agent dispatch completed (fallback path)")}else r("WPS: channelRuntime.reply dispatch APIs not found, skipping agent dispatch")}finally{kt?.kind==="reaction"&&(await Tr(d,kt.chatId,kt.messageId,t),r("WPS thinking reaction removed"))}}catch(R){n("WPS async inbound error:",R)}}ct();it();Pt();import{createHash as ns}from"node:crypto";function ie(e){return{error:e instanceof Error?e.message:String(e)}}function T(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function X(e,t){let r=e[t];if(r==null)return;if(typeof r!="string")throw new Error(`${t} must be a string`);let n=r.trim();return n===""?void 0:n}function V(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function re(e,t){let r=e[t];if(r!=null){if(typeof r=="boolean")return r;if(r==="true")return!0;if(r==="false")return!1;throw new Error(`${t} must be a boolean`)}}function Je(e,t){let r=e[t];if(r!=null){if(!Array.isArray(r))throw new Error(`${t} must be an array of strings`);return r.map(n=>String(n).trim()).filter(Boolean)}}function me(e,t="chat_id"){let r=T(e,t),n=r.startsWith("wps:")?r.slice(4):r;if(/^AK\d{8}/i.test(n))throw new Error(`${t}="${r}" is a bot/app ID (AK-prefixed), NOT a chat ID. The correct chat_id is a numeric ID like '77183700'. Look for chatId in RawBody JSON (parse the RawBody string first). Do NOT use values from From, OriginatingTo, SessionKey, or SenderId fields.`);if(n.includes(":")&&n.includes("AK"))throw new Error(`${t}="${r}" looks like a session_key or compound ID, NOT a chat ID. The correct chat_id is in RawBody.chatId (a numeric string like '77183700').`);return n}function De(e,t){let r=e[t];if(r==null)throw new Error(`${t} is required`);let n=typeof r=="number"?r:parseInt(String(r),10);if(!Number.isFinite(n)||n<0)throw new Error(`${t} must be a non-negative integer`);return n}function is(e){return ns("sha256").update(e).digest("hex")}var gi=20*1024*1024;function en(e){let t=e.trim();return!t||t.startsWith("http://")||t.startsWith("https://")?!1:!!(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")||t.startsWith("/tmp/")||t.startsWith("/var/folders/")||t.includes("openclaw-media"))}function wi(e){let t=e.trim();return t.includes("openclaw-media")&&!t.startsWith("http://")&&!t.startsWith("https://")}function os(e,t){let r={};for(let[n,o]of Object.entries(e)){if(typeof o!="string")continue;let i=n.trim();if(!i)continue;let s=i.toLowerCase();s==="transfer-encoding"||s==="content-length"||(r[i]=o)}return r}async function tn(e,t,r,n,o){let i=o?.info??console.log,s=o?.error??console.error,a=n.byteLength;if(a===0)throw new Error("upload content is empty");if(a>gi)throw new Error(`file too large: ${a} bytes (max ${gi})`);let d=is(n);i(`[upload] phase1 start: fileName=${t} fileType=${r} size=${a} checksum=${d.substring(0,16)}\u2026`);let l;try{l=await e.request({method:"POST",path:"/v7/chats/resources/upload",body:{file_name:t,file_size:a,file_type:r,checksum:d}})}catch(w){let b=w instanceof Error?w.message:String(w);throw s(`[upload] phase1 request failed: ${b}`),new Error(`upload phase 1 request failed: ${b}`)}let c=l.data??l;if(!c||typeof c!="object")throw new Error(`upload phase 1 returned no data: ${JSON.stringify(l).substring(0,300)}`);let p=c.data,u=p&&typeof p=="object"?p:c;i(`[upload] phase1 response keys: source=[${Object.keys(u)}] hasNested=${!!p}`);let _=u.upload_entry;_&&i(`[upload] upload_entry keys: [${Object.keys(_)}]`);let f=typeof u.url=="string"&&u.url.trim()?u.url.trim():typeof u.upload_url=="string"&&u.upload_url.trim()?u.upload_url.trim():_&&typeof _.url=="string"&&_.url.trim()?_.url.trim():null,y=typeof u.storage_key=="string"&&u.storage_key.trim()?u.storage_key.trim():null;if(!f)throw new Error(`upload phase 1 did not return an upload URL: keys=${JSON.stringify(Object.keys(u))}, raw=${JSON.stringify(c).substring(0,300)}`);if(!y)throw new Error(`upload phase 1 did not return a storage_key: keys=${JSON.stringify(Object.keys(u))}`);i(`[upload] phase1 ok: storageKey=${y.substring(0,20)}\u2026 uploadUrl=${f.substring(0,80)}\u2026`);let h=_&&typeof _.headers=="object"&&_.headers&&Object.keys(_.headers).length>0,m=os(h?_.headers:{},f);i(`[upload] phase2 PUT headers: ${JSON.stringify(Object.keys(m))}`);let g;try{g=await fetch(f,{method:"PUT",headers:m,body:n})}catch(w){let b=w instanceof Error?w.message:String(w);throw s(`[upload] phase2 PUT network error: ${b} url=${f.substring(0,80)}\u2026`),new Error(`upload phase 2 PUT network error: ${b}`)}if(!g.ok){let w=await g.text().catch(()=>"");throw s(`[upload] phase2 PUT failed: HTTP ${g.status} body=${w.substring(0,300)}`),new Error(`upload phase 2 PUT failed: HTTP ${g.status} ${w.substring(0,200)}`)}return i(`[upload] phase2 PUT ok: HTTP ${g.status} storageKey=${y.substring(0,20)}\u2026`),{storage_key:y,file_name:t,file_size:a}}function Qr(e){return e.data??null}function er(e){return{error:e instanceof Error?e.message:String(e)}}function ke(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function ss(e,t){let r=e[t];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} is required and must be a finite number`)}function as(e){let t=e.trim();return!!(t.endsWith("=")||t.includes(":")&&t.length>30||/^[A-Za-z0-9+/]{40,}={0,2}$/.test(t))}function yi(e,t){if(e===t)throw new Error("message_id and storage_key are identical \u2014 this is wrong. message_id should be the message ID (from RawBody.messageId), not the storage_key. Please check the RawBody JSON for the correct messageId field.");if(as(e))throw new Error(`message_id="${e.substring(0,30)}\u2026" looks like a storage_key (contains ':' or ends with '='). message_id should be the message ID from RawBody.messageId, not the attachment storage_key. These are different values \u2014 check the RawBody JSON.`)}function ds(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number when provided`)}}function rn(e,t,r){let n=r?.info??(()=>{}),o=r?.error??(()=>{});t({name:"wps_media_download",description:"Obtain a pre-signed download URL for a message attachment (GET /v7/chats/{chat_id}/messages/{message_id}/resources/{storage_key}/download). Returns a short-lived URL for HTTP GET. chat_id and message_id come from RawBody JSON. message_id and storage_key are DIFFERENT values \u2014 do NOT pass storage_key as message_id.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."},message_id:{type:"string",description:"Message id (from RawBody.messageId). NOT the storage_key."},storage_key:{type:"string",description:"Resource storage key from the attachment."}},required:["chat_id","message_id","storage_key"]},async execute(i,s){try{let a=me(s),d=ke(s,"message_id"),l=ke(s,"storage_key");yi(d,l);let c=encodeURIComponent(a),p=encodeURIComponent(d),u=encodeURIComponent(l),_=await e.request({method:"GET",path:`/v7/chats/${c}/messages/${p}/resources/${u}/download`});return Qr(_)}catch(a){return er(a)}}}),t({name:"wps_media_fetch_base64",description:"Fetch attachment bytes from WPS and return base64. Returns `{ mime_type, size, base64 }`. chat_id and message_id come from RawBody JSON. message_id and storage_key are DIFFERENT values \u2014 do NOT pass storage_key as message_id.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."},message_id:{type:"string",description:"Message id (from RawBody.messageId). NOT the storage_key."},storage_key:{type:"string",description:"Resource storage key from the attachment."},max_bytes:{type:"number",description:"Optional max bytes limit for safety (default 5MB). If exceeded, tool returns an error."}},required:["chat_id","message_id","storage_key"]},async execute(i,s){try{let a=me(s),d=ke(s,"message_id"),l=ke(s,"storage_key");yi(d,l);let c=encodeURIComponent(a),p=encodeURIComponent(d),u=encodeURIComponent(l),_=ds(s,"max_bytes")??5*1024*1024;if(_<=0)throw new Error("max_bytes must be positive");n(`[tool:wps_media_fetch_base64] start: chatId=${a} msgId=${d} sk=${l.substring(0,20)}\u2026`);let f=await e.request({method:"GET",path:`/v7/chats/${c}/messages/${p}/resources/${u}/download`}),y=Qr(f),h=Sr(y),m=await fetch(h);if(!m.ok)throw new Error(`download url request failed: HTTP ${m.status}`);let g=Number(m.headers.get("content-length")??"0");if(Number.isFinite(g)&&g>_)throw new Error(`attachment too large: ${g} bytes > max_bytes=${_}`);let w=m.headers.get("content-type")??"application/octet-stream",b=new Uint8Array(await m.arrayBuffer());if(b.byteLength>_)throw new Error(`attachment too large after download: ${b.byteLength} bytes > max_bytes=${_}`);let I=w.startsWith("image/")?Ge(Buffer.from(b)):null;return n(`[tool:wps_media_fetch_base64] ok: ${w} ${b.byteLength}B${I?` ${I.width}x${I.height}`:""}`),{chat_id:a,message_id:d,storage_key:l,mime_type:w,size:b.byteLength,base64:Buffer.from(b).toString("base64"),...I?{width:I.width,height:I.height}:{}}}catch(a){return o("[tool:wps_media_fetch_base64] error:",a),er(a)}}}),t({name:"wps_media_upload",description:"Low-level Phase 1 upload (POST /v7/chats/resources/upload). Returns pre-signed URL + storage_key. The API requires a `checksum` of the file bytes (SHA256 lowercase hex). Prefer wps_media_upload_base64 which computes checksum and completes the PUT automatically.",parameters:{type:"object",properties:{file_name:{type:"string",description:"Original file name including extension."},file_size:{type:"number",description:"File size in bytes."},file_type:{type:"string",description:"MIME type or WPS file type discriminator as required by the API (e.g. image/png)."},checksum:{type:"string",description:"SHA256 lowercase hex digest of the entire file (must match the bytes you will PUT in phase 2 and file_size)."}},required:["file_name","file_size","file_type","checksum"]},async execute(i,s){try{let a=ke(s,"file_name"),d=ss(s,"file_size"),l=ke(s,"file_type"),c=ke(s,"checksum");if(d<0)throw new Error("file_size must be non-negative");let p=await e.request({method:"POST",path:"/v7/chats/resources/upload",body:{file_name:a,file_size:d,file_type:l,checksum:c}});return Qr(p)}catch(a){return er(a)}}}),t({name:"wps_media_upload_base64",description:`Upload a file to WPS and get a storage_key for sending as image/file message. Accepts base64-encoded file content. Internally performs: 1) POST metadata (includes SHA256 checksum of decoded bytes) to get pre-signed upload URL + storage_key, 2) PUT raw bytes to the pre-signed URL. Returns { storage_key, file_name, file_size, width?, height? }. For images, width and height are auto-detected from bytes. After getting storage_key, use wps_message_send with msg_type='image' and include width/height in the content: content='{"image":{"storage_key":"...","width":W,"height":H}}'.`,parameters:{type:"object",properties:{file_name:{type:"string",description:"File name with extension (e.g. photo.png)."},file_type:{type:"string",description:"MIME type (e.g. image/png, image/jpeg, application/pdf)."},base64:{type:"string",description:"Base64-encoded file content. For images previously fetched, pass the base64 from wps_media_fetch_base64 or from a local file read."}},required:["file_name","file_type","base64"]},async execute(i,s){try{let a=ke(s,"file_name"),d=ke(s,"file_type"),l=ke(s,"base64"),c=Buffer.from(l,"base64");n(`[tool:wps_media_upload_base64] start: ${a} ${d} ${c.byteLength}B`);let{storage_key:p,file_name:u,file_size:_}=await tn(e,a,d,c),f=d.startsWith("image/")?Ge(c):null;return n(`[tool:wps_media_upload_base64] ok: storage_key=${p.substring(0,20)}\u2026 ${u} ${_}B${f?` ${f.width}x${f.height}`:""}`),{storage_key:p,file_name:u,file_size:_,...f?{width:f.width,height:f.height}:{}}}catch(a){return o("[tool:wps_media_upload_base64] error:",a),er(a)}}})}Pt();var fs={Debug:0,Info:1,Warn:2,Error:3},pt=null;function ki(e){pt=e}function ms(){if(!pt)throw new Error("WPS plugin runtime not initialized");return pt}var rr="wps",Ii={id:E,label:"WPS",selectionLabel:"WPS365 (Open Platform)",docsPath:"/channels/wps-xiezuo",docsLabel:"WPS",blurb:"WPS365 Open Platform bot integration.",aliases:[E,rr,"wps365"],order:70};function nr(e){let t=e.channels;if(t)return t[E]??t[rr]}function Ne(e){return yr(nr(e))}function hs(){let e=tr.join(ps(),".openclaw","openclaw.json");if(!cs(e))return null;try{let t=ls(e,"utf8");return t.trim()?JSON.parse(t):null}catch{return null}}function nn(e){let t=e&&typeof e=="object"?e:null;if(t&&Object.keys(Ne(t)).length>0)return t;let r=pt?.config&&typeof pt.config=="object"?pt.config:null;if(r&&Object.keys(Ne(r)).length>0)return r;let n=hs();return n&&Object.keys(Ne(n)).length>0?n:t??r??n??{}}function ne(e){return gr(nr(e))}function de(e,t){let r=Ne(e);return r[t]??r[ne(e)]??r[Ce]}function gs(e,t=Ce){let r=de(e,t);return{accountId:t,enabled:r?.enabled!==!1,configured:!!_e(r),config:r??{enabled:!1}}}function on(e){return e.trim().replace(/^wps-xiezuo:/i,"").replace(/^wps:/i,"")}function ys(e){return e.trim().length>0}function Si(e){if(e.startsWith("user:"))return{type:"user",id:e.slice(5)};if(e.startsWith("chat:"))return{type:"chat",id:e.slice(5)};if(e.startsWith("wps:")||e.startsWith("wps-xiezuo:")){let t=e.match(/:group:([^:]+)/);if(t)return{type:"chat",id:t[1]};let r=e.match(/:p2p:([^:]+)/);if(r)return{type:"user",id:r[1]};let n=e.split(":");if(n.length===2)return{type:"user",id:n[1]};let o=n[2]??n[1],i=n[3]??n[2];return{type:o==="group"?"chat":"user",id:i??n[n.length-1]??e}}return{type:"user",id:e}}async function sn(e,t,r){let n=j(e),o=W(e.baseUrl,n),i=Si(t);return{messageId:(await o.request({method:"POST",path:"/v7/messages/create",body:{type:"text",receiver:{type:i.type,receiver_id:i.id},content:{text:{content:r,type:"markdown"}}}})).data?.message_id??""}}var an={id:E,meta:{...Ii,aliases:[...Ii.aliases]},capabilities:{chatTypes:["direct","group"],media:!0,threads:!0,nativeCommands:!1,blockStreaming:!0},reload:{configPrefixes:[`channels.${E}`,`channels.${rr}`]},configSchema:Wn(hr),messaging:{normalizeTarget:e=>e.trim(),targetResolver:{hint:"WPS target: user_id or chat_id (obfuscated string, case-sensitive)",looksLikeId:e=>e.trim().length>0}},config:{listAccountIds:e=>{let t=nn(e),r=Object.keys(Ne(t));return r.length>0?r:[Ce]},resolveAccount:e=>{let t=nn(e);return gs(t,ne(t))},defaultAccountId:e=>{let t=nn(e);return ne(t)},setAccountEnabled:({cfg:e,enabled:t})=>({...e,channels:{...e.channels,[E]:{...nr(e),accounts:{...Ne(e),[ne(e)]:{...de(e,ne(e))??{},enabled:t}}}}}),deleteAccount:({cfg:e})=>{let t={...e},r={...t.channels},n=nr(e);if(n){let o=ne(e),i={...Ne(e)};delete i[o],r[E]={...n,accounts:i}}else delete r[E],delete r[rr];return t.channels=Object.keys(r).length>0?r:void 0,t},isConfigured:(e,t)=>!!_e(de(t,e.accountId)),describeAccount:e=>({accountId:e.accountId,enabled:e.enabled,configured:e.configured}),resolveAllowFrom:({cfg:e})=>{let t=e;return de(t,ne(t))?.allowFrom??[]},formatAllowFrom:({allowFrom:e})=>e.map(t=>on(String(t)))},security:{resolveDmPolicy:({cfg:e})=>{let t=e,r=ne(t),n=de(t,r);return{policy:n?.dmPolicy??"pairing",allowFrom:n?.allowFrom??[],policyPath:`channels.${E}.accounts.${r}.dmPolicy`,allowFromPath:`channels.${E}.accounts.${r}.allowFrom`,approveHint:zn(E),normalizeEntry:on}},collectWarnings:({cfg:e})=>{let t=[],r=Ne(e);for(let[n,o]of Object.entries(r))o.dmPolicy==="open"&&t.push(`- WPS account '${n}' DMs are open to anyone. Set channels.${E}.accounts.${n}.dmPolicy="pairing" or "allowlist" for security.`),(o.groupPolicy??"allowlist")==="open"&&t.push(`- WPS account '${n}' groups: groupPolicy="open" allows any group to trigger. Set channels.${E}.accounts.${n}.groupPolicy="allowlist".`);return t}},pairing:{idLabel:"wpsUserId",normalizeAllowEntry:on,notifyApproval:async({cfg:e,id:t})=>{let r=e,n=de(r,ne(r)),o=_e(n);if(!o)throw new Error("WPS credentials not configured");await sn(o,`user:${t}`,"Your pairing request has been approved. You can now chat with this bot.")}},groups:{resolveRequireMention:({cfg:e,groupId:t})=>{let r=e,n=de(r,ne(r));return!n?.groups||!t?!0:(n.groups[t]??n.groups["*"])?.requireMention??!0},resolveToolPolicy:()=>{}},outbound:{deliveryMode:"direct",textChunkLimit:5e3,chunker:(e,t)=>ms().channel.text.chunkMarkdownText(e,t),chunkerMode:"markdown",resolveTarget:({to:e,allowFrom:t})=>{let r=e?.trim()??"";if(r&&ys(r))return{ok:!0,to:r};let n=t?.[0];return n?{ok:!0,to:String(n).trim()}:{ok:!1,error:new Error("WPS target is required (user_id or chat_id)")}},sendText:async({cfg:e,to:t,text:r})=>{let n=e,o=de(n,ne(n)),i=_e(o);if(!i)throw new Error("WPS credentials not configured");return sn(i,t,r)},sendMedia:async({cfg:e,to:t,mediaUrl:r,mimeType:n})=>{let o=e,i=de(o,ne(o)),s=_e(i);if(!s)throw new Error("WPS credentials not configured");let a=j(s),d=W(s.baseUrl,a),l=Si(t),c=(r??"").trim();if(!c)throw new Error("WPS sendMedia requires mediaUrl");let p,u,_=(n??"").trim()||"application/octet-stream",f=null;if(en(c)){let g=await bi(c),w=tr.basename(c)||"attachment";if(p=/^[0-9a-f]{8}_/.test(w)?w.substring(9):w,!(n??"").trim()){let I=tr.extname(p).toLowerCase();_={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".pdf":"application/pdf",".html":"text/html",".htm":"text/html",".txt":"text/plain",".json":"application/json",".csv":"text/csv",".xml":"application/xml",".zip":"application/zip",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"}[I]??"application/octet-stream"}u=g.byteLength;let b=!1;if(wi(c))try{let I=await bi(c+jr,"utf8"),S=JSON.parse(I);S.v===1&&S.storage_key&&(c=S.storage_key,typeof S.width=="number"&&typeof S.height=="number"&&S.width>0&&S.height>0&&(f={width:S.width,height:S.height}),b=!0)}catch{}b||(c=(await tn(d,p,_,g)).storage_key),!f&&_.startsWith("image/")&&(f=Ge(g),console.log(`[${E}] sendMedia: parsed dimensions ${f?`${f.width}x${f.height}`:"(null)"} for ${p}`))}let y=_.startsWith("image/"),h={type:"file",receiver:{type:l.type,receiver_id:l.id},content:{file:{type:"local",local:{storage_key:c,...p?{name:p}:{},...u!==void 0?{size:u}:{}}}}},m={type:"image",receiver:{type:l.type,receiver_id:l.id},content:{image:{storage_key:c,..._.startsWith("image/")?{type:_}:{},...p?{name:p}:{},...u!==void 0?{size:u}:{},...f?{width:f.width,height:f.height}:{}}}};if(y)try{return await d.request({method:"POST",path:"/v7/messages/create",body:m})}catch(g){let w=g instanceof Error?g.message:String(g);throw console.error(`[${E}] sendMedia image failed: ${w} storageKey=${c.substring(0,30)}\u2026 displayName=${p}`),g}try{return await d.request({method:"POST",path:"/v7/messages/create",body:h})}catch(g){let w=g instanceof Error?g.message:String(g);if(!(/\b400\b/.test(w)||/InvalidMessage|invalid.*file_type/i.test(w)))throw console.error(`[${E}] sendMedia file failed (non-retryable): ${w}`),g;console.log(`[${E}] sendMedia file rejected (400), retrying as image: ${w} displayName=${p}`);try{return await d.request({method:"POST",path:"/v7/messages/create",body:m})}catch(I){let S=I instanceof Error?I.message:String(I);throw console.error(`[${E}] sendMedia image fallback also failed: ${S} displayName=${p}`),I}}}},status:{defaultRuntime:{accountId:Ce,running:!1,lastStartAt:null,lastStopAt:null,lastError:null},collectStatusIssues:e=>e.flatMap(t=>{let r=[];return t.enabled&&!t.configured&&r.push({channel:E,accountId:t.accountId,kind:"config",message:"WPS credentials not configured (appId and appSecret required).",fix:`Set channels.${E}.accounts.${t.accountId}.appId and channels.${E}.accounts.${t.accountId}.appSecret.`}),r}),buildChannelSummary:({snapshot:e})=>({configured:e.configured??!1,running:e.running??!1,lastStartAt:e.lastStartAt??null,lastStopAt:e.lastStopAt??null,lastError:e.lastError??null,probe:e.probe,lastProbeAt:e.lastProbeAt??null}),probeAccount:async({account:e})=>{let t=_e(e.config);if(!t)return{ok:!1,error:"Not configured"};try{return{ok:!0,token:(await j(t).getToken()).substring(0,8)+"..."}}catch(r){return{ok:!1,error:String(r)}}},buildAccountSnapshot:({account:e,runtime:t,probe:r})=>({accountId:e.accountId,enabled:e.enabled,configured:e.configured,running:t?.running??!1,lastStartAt:t?.lastStartAt??null,lastStopAt:t?.lastStopAt??null,lastError:t?.lastError??null,lastInboundAt:t?.lastInboundAt??null,lastOutboundAt:t?.lastOutboundAt??null,dmPolicy:e.config.dmPolicy??"pairing",probe:r})},gateway:{startAccount:async e=>{let t=de(e.cfg,e.accountId);if(!t?.enabled){e.log?.info?.(`[${e.accountId}] WPS provider disabled`);return}let r=_e(t);if(!r){e.log?.error?.(`[${e.accountId}] WPS credentials not configured`);return}let n=async()=>{},o=a=>{Zr({cfg:e.cfg,accountId:e.accountId,channelRuntime:e.channelRuntime??void 0,wpsCfg:t,creds:r,eventPayload:a,log:e.log}).catch(d=>e.log?.error?.("WPS inbound handler error:",d))},i=!1;if(t.sdk?.enabled)try{let a=us,d=_s,l=fs,p={debug:l.Debug,warn:l.Warn,error:l.Error}[t.sdk.logLevel??"info"]??l.Info,u=new d().onV7AppChatMessageCreate(async h=>{try{let m=h.parsedData;e.log?.info?.(`[WPS SDK][${e.accountId}/${r.clientId}] message: chat_id=${m.chat.id}, message_id=${m.message.id}`);let g=Xn(m);o(g)}catch(m){e.log?.error?.("WPS SDK message handler error:",m)}}).onV7AppGroupChatMemberRobotCreate(async h=>{let m=h.parsedData;if(e.log?.info?.(`[WPS SDK] robot joined group: chat_id=${m.chat_id}`),t.robotJoinGroupMessage!==void 0){let g=t.robotJoinGroupMessage||"\u4F60\u597D\uFF01\u6211\u662F AI \u52A9\u624B\uFF0C\u53EF\u4EE5\u5E2E\u52A9\u5927\u5BB6\u5904\u7406\u5404\u79CD\u95EE\u9898\u3002";try{let w=j(r);await W(r.baseUrl,w).request({method:"POST",path:"/v7/messages/create",body:{type:"text",receiver:{type:"chat",receiver_id:m.chat_id},content:{text:{content:g,type:"markdown"}}}})}catch(w){e.log?.error?.("WPS welcome message failed:",w)}}}).onV7AppGroupChatMemberRobotDelete(async h=>{e.log?.info?.(`[WPS SDK] robot left group: chat_id=${h.parsedData.chat_id}`)}).registerFallbackFunc(h=>{let m=null;if(h.parsedData&&typeof h.parsedData=="object")m=h.parsedData;else if(typeof h.data=="string"&&h.data)try{m=JSON.parse(h.data)}catch{}let g=m?Object.keys(m).join(","):"N/A";if(e.log?.info?.(`[WPS SDK] unhandled event: ${h.eventCode}, keys=${g}`),m&&e.log?.info?.(`[WPS SDK] event payload: ${JSON.stringify(m).slice(0,500)}`),m){let w=typeof m.code=="string"?m.code:typeof m.authorization_code=="string"?m.authorization_code:void 0,b=typeof m.state=="string"?m.state:void 0;if(w){let I=typeof m.user_id=="string"?m.user_id:void 0;e.log?.info?.(`[WPS SDK] Auth code detected: eventCode=${h.eventCode}, code=${w.slice(0,8)}..., state=${b??"(none)"}, userId=${I??"(none)"}`),(async()=>{try{let{handleAuthEvent:S}=await Promise.resolve().then(()=>(Qt(),Vr));await S({code:w,state:b??"",creds:r,wpsCfg:t,log:e.log,userId:I})}catch(S){e.log?.error?.(`[WPS SDK] Auth event handling failed: ${String(S)}`)}})()}}}),_=new a(Yn({appId:r.clientId,appSecret:r.clientSecret,dispatcher:u,logLevel:p,endpoint:t.sdk.endpoint},t.sdk));_.start().catch(h=>{e.log?.error?.("WPS SDK client.run ended:",h)});let f=t.sdk.connectTimeoutMs??2e4,y=Date.now()+f;for(;Date.now()<y&&!_.isConnected();)await new Promise(h=>setTimeout(h,150));if(_.isConnected()){i=!0,e.log?.info?.("[WPS SDK] long connection established");let h=()=>_.stop();e.abortSignal.addEventListener("abort",h),n=async()=>{e.abortSignal.removeEventListener("abort",h),_.stop()}}else _.stop(),e.log?.warn?.(`[WPS SDK] connect timeout (${f}ms), falling back to Webhook`)}catch(a){e.log?.warn?.(`[WPS SDK] init failed: ${String(a)}, falling back to Webhook`)}if(!i){let a=await import("express"),d=(a.default||a)();d.use(a.json());let l=t.webhook?.port??3e3,c=t.webhook?.path??"/wps/webhook",p=t.enableEncryption!==!1;d.post(c,(_,f)=>{let y=Vn(_.body,{appId:r.clientId,appSecret:r.clientSecret},p,e.log);if("challenge"in y){f.status(200).json({challenge:y.challenge});return}if(!y.ok){let h=y.status??200;h===200?f.status(200).json({code:0,msg:"ok"}):f.status(h).json({code:-1,msg:y.error});return}f.status(200).json({code:0,msg:"ok"}),o(y.payload)});let u=d.listen(l,()=>{e.log?.info?.(`[${e.accountId}] WPS webhook listening on :${l}${c}`)});n=async()=>{u&&(u.close(),u=null)}}let s=i?"sdk":"webhook";e.setStatus({accountId:e.accountId,running:!0,lastStartAt:Date.now(),mode:s}),e.log?.info?.(`[${e.accountId}] WPS channel started (mode=${s})`);try{let a=j(r),d=W(r.baseUrl,a);Gr(d,e.log,t,r),wr({appId:r.clientId,appSecret:r.clientSecret,baseUrl:r.baseUrl}),e.log?.info?.(`[${e.accountId}] WPS client initialized for OAPI tools`);try{let c=((await d.request({method:"GET",path:`/v7/developer/apps/${encodeURIComponent(r.clientId)}`})).data?.scopes??[]).filter(p=>p.auth_types?.includes("delegated")).map(p=>({name:p.name??"",description:p.description??""})).filter(p=>p.name);Yt(c),e.log?.info?.(`[${e.accountId}] Delegated scopes: ${c.map(p=>p.name).join(", ")||"(none)"}`)}catch(l){Yt([]);let c=String(l);c.includes("invalid_scope")?e.log?.info?.(`[${e.accountId}] Delegated scopes unavailable (invalid_scope). OAuth \u6388\u6743\u5361\u7247\u80FD\u529B\u4E0D\u53EF\u7528\uFF0C\u4F46\u4E0D\u5F71\u54CD\u666E\u901A\u6D88\u606F\u6536\u53D1\u3002`):e.log?.warn?.(`[${e.accountId}] Failed to fetch delegated scopes: ${c}`)}}catch(a){e.log?.error?.(`[${e.accountId}] WPS client init failed:`,a)}return Ln(e.abortSignal,n)}},onboarding:{channel:E,getStatus:async({cfg:e})=>{let t=e,r=de(t,ne(t)),n=!!_e(r);return{channel:E,configured:n,statusLines:[`WPS: ${n?"configured":"needs appId and appSecret"}`],selectionHint:n?"configured":"needs credentials",quickstartScore:n?2:1}},configure:async({cfg:e})=>({cfg:e})},agentPrompt:{messageToolHints:e=>{let t=e.cfg??{},o=t.tools?.media?.image,s=t.agents?.defaults;return["- WPS targeting: omit `target` to reply in the current conversation (auto-inferred by the framework). To send to a **different** conversation, use `message(action=send, to=chat:<chat_id>, message=...)`.","- To find a chat by name, use `wps_chat_find_by_name` first, then use the returned chat_id as `to=chat:<chat_id>`.","- WPS supports `send` action for proactive messaging. The `to` parameter is required for `action=send` (e.g. `user:<user_id>` or `chat:<chat_id>`).",o?.enabled!==!1&&(o?.enabled===!0||Array.isArray(o?.models)&&o.models.length>0||typeof s?.imageModel=="string"&&s.imageModel.trim()!=="")?"- IMAGE RECOGNITION: When a user sends an image, it is pre-downloaded to a local temp file. Image recognition is performed ONLY by the host platform via [Image] block injection. If you do NOT see an [Image] block for the image, you CANNOT see its content. In that case you MUST tell the user: '\u62B1\u6B49\uFF0C\u56FE\u7247\u8BC6\u522B\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002' NEVER fabricate or guess image descriptions. NEVER use exec/read/search to find or read image files \u2014 these tools cannot extract image content. NEVER call the `canvas` tool directly \u2014 it is an internal host tool and will fail with 'node required' if invoked by the agent.":"- IMAGE RECOGNITION DISABLED: The host has NOT configured image recognition (no imageModel). You CANNOT see any image content. When a user sends an image, reply ONLY with: '\u5F53\u524D\u672A\u542F\u7528\u56FE\u7247\u8BC6\u522B\u529F\u80FD\uFF0C\u65E0\u6CD5\u67E5\u770B\u56FE\u7247\u5185\u5BB9\u3002' Do NOT offer workarounds, do NOT suggest the user describe the image, resend it, or provide a file path. NEVER fabricate, guess, or infer image content from filenames. NEVER use exec/read/search to read image files. NEVER call the `canvas` tool directly."]}},actions:{describeMessageTool:()=>({actions:["send"]}),handleAction:async e=>{if(e.action!=="send")throw new Error(`WPS does not support action: ${e.action}`);let t=e.params.to??e.params.target??e.params.receiver_id,r=e.params.message??e.params.text??e.params.content,n=e.params.media,o=e.cfg,i=de(o,ne(o)),s=_e(i);if(!s)throw new Error("WPS credentials not configured");let a=t&&typeof t=="string"&&t.trim()?t.trim():"";if(n&&typeof n=="string"&&n.trim()){let l=n.trim();if(en(l)){if(!a)throw new Error("WPS send with media requires 'to' (e.g. 'user:<id>' or 'chat:<id>')");return await an.outbound.sendMedia({cfg:e.cfg,to:a,mediaUrl:l,mimeType:void 0}),{text:`Media sent (${tr.basename(l)||"attachment"})`}}}if(!a)throw new Error("WPS send requires 'to' (e.g. 'user:<id>' or 'chat:<id>')");if(!r||typeof r!="string"||!r.trim())throw new Error("WPS send requires 'message' or 'text'");return{text:`Message sent (id: ${(await sn(s,a,r.trim())).messageId})`}}}};ct();function ir(e){return e.data??null}function or(e){return{error:e instanceof Error?e.message:String(e)}}function Ue(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function dn(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function ws(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}function xi(e){try{return JSON.parse(e)}catch{throw new Error("content must be valid JSON matching the WPS message content structure")}}function bs(e,t){if(e==="file"){let r=t.file;if(!r){let n=t.storage_key;if(n)return{file:{type:"local",local:{storage_key:n,...t.name?{name:t.name}:{},...t.size!==void 0?{size:t.size}:{}}}};throw new Error(`file content must contain a 'file' object. Required structure: {"file":{"type":"local","local":{"storage_key":"..."}}}`)}if(r.type||(r.type="local"),r.type==="local"&&!r.local){let n=r.storage_key;if(n)r.local={storage_key:n,...r.name?{name:r.name}:{},...r.size!==void 0?{size:r.size}:{}},delete r.storage_key,delete r.name,delete r.size;else throw new Error(`file.local is required for type='local'. Expected: {"file":{"type":"local","local":{"storage_key":"..."}}}`)}return t}if(e==="image"){if(!t.image){let n=t.storage_key;if(n)return{image:{storage_key:n,...typeof t.width=="number"?{width:t.width}:{},...typeof t.height=="number"?{height:t.height}:{}}};throw new Error(`image content must contain an 'image' object. Required structure: {"image":{"storage_key":"..."}}`)}return t}return t}function Is(e,t){if(e==="text"){try{let n=JSON.parse(t);if(n&&typeof n=="object"&&"text"in n)return{type:"text",content:n}}catch{}return{type:"text",content:{text:{content:t,type:"markdown"}}}}let r=xi(t);if(typeof r!="object"||r===null)throw new Error(`content for ${e} must be a JSON object (message content subtree)`);return e==="rich_text"?{type:"rich_text",content:r}:{type:"image",content:r}}function cn(e,t){t({name:"wps_message_send",description:`Send a message to any WPS user or chat via OpenAPI. IMPORTANT: When the user asks to send a message to someone or to a chat/group, use THIS tool. If the user provides a chat name instead of an ID, call wps_chat_find_by_name first to resolve the chat_id, then call this tool with receiver_type='chat'. receiver_type: 'user' (for P2P/DM by user_id) or 'chat' (for group/chat by chat_id). receiver_id MUST be the real WPS chat id or user id (numeric/string id from the WPS API). For replies in the current conversation, read inbound RawBody JSON \`chatId\` and \`SenderId\`: use receiver_type='chat' + receiver_id=chatId when chatId is present, else receiver_type='user' + receiver_id=SenderId. NEVER use SessionKey segments after ':bot:' (often looks like AK\u2026) as receiver_id \u2014 that is a bot/app id, not a chat id, and causes invalid chatId / deMixValue errors. Text: msg_type='text', content='{"text":{"content":"hello","type":"markdown"}}'. Image: first call wps_media_upload_base64 for storage_key (it also returns width & height), then msg_type='image', content='{"image":{"storage_key":"...","width":W,"height":H}}'. File: first call wps_media_upload_base64 for storage_key, then msg_type='file', content='{"file":{"type":"local","local":{"storage_key":"...","name":"filename.ext"}}}'. CRITICAL: cloud documents (type=cloud) CANNOT be sent or forwarded via this API. To share a cloud doc with the user, use msg_type='text' and include the link URL in the text content. NEVER attempt to send cloud files with msg_type='file' or msg_type='image' \u2014 it will always fail.`,parameters:{type:"object",properties:{receiver_type:{type:"string",enum:["user","chat"],description:"Target kind: `user` opens or uses p2p with that user id; `chat` sends to a chat id."},receiver_id:{type:"string",description:"WPS user id or chat id from the API (not SessionKey `:bot:` segment). For the active thread, prefer RawBody `chatId` or user id."},msg_type:{type:"string",enum:["text","rich_text","image","file"],description:"WPS message type field sent as `type` in the API body."},content:{type:"string",description:"JSON string for the WPS message `content` object (structure depends on msg_type)."},mentions:{type:"array",description:"Optional mention list for group messages.",items:{type:"object",additionalProperties:!0}}},required:["receiver_type","receiver_id","msg_type","content"]},async execute(r,n){try{let o=Ue(n,"receiver_type");if(o!=="user"&&o!=="chat")throw new Error("receiver_type must be 'user' or 'chat'");let i=Ue(n,"receiver_id");if(i.startsWith("wps:")&&(i=i.slice(4)),/^AK\d{8}/i.test(i))throw new Error(`receiver_id="${i}" is a bot/app ID, not a valid user or chat ID. To reply in the current conversation, use the message tool instead of wps_message_send (e.g. message(action="send", to="user:<SenderId>", message="...")). If you need wps_message_send, use receiver_type='user' with SenderId, or receiver_type='chat' with RawBody.chatId.`);let s=Ue(n,"msg_type");if(!["text","rich_text","image","file"].includes(s))throw new Error("msg_type must be one of: text, rich_text, image, file");let a=Ue(n,"content");if(a.length>5e3)throw new Error("content JSON string exceeds 5000 characters");let d=xi(a);if(typeof d!="object"||d===null)throw new Error("parsed content must be a JSON object");let l=s==="file"||s==="image"?bs(s,d):d,c={type:s,receiver:{type:o,receiver_id:i},content:l},p=n.mentions;if(p!==void 0){if(!Array.isArray(p))throw new Error("mentions must be an array when provided");c.mentions=p}let u=await e.request({method:"POST",path:"/v7/messages/create",body:c});return ir(u)}catch(o){return or(o)}}}),t({name:"wps_message_reply",description:"Reply to an existing message in a chat (POST /v7/chats/{chat_id}/messages/{message_id}/reply). Use this to reply in-thread to a specific message. For sending NEW messages (not replies), use wps_message_send instead. Supports msg_type text, rich_text, or image. For text, content can be plain text or JSON content object.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."},message_id:{type:"string",description:"Message id to reply to (from RawBody.messageId)."},msg_type:{type:"string",enum:["text","rich_text","image"],description:"Reply payload type."},content:{type:"string",description:"For text: plain string or JSON string of `content`. For rich_text/image: JSON string of the `content` subtree."}},required:["chat_id","message_id","msg_type","content"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=encodeURIComponent(Ue(n,"message_id")),s=Ue(n,"msg_type");if(s!=="text"&&s!=="rich_text"&&s!=="image")throw new Error("msg_type must be text, rich_text, or image");let a=Ue(n,"content"),d=Is(s,a),l=await e.request({method:"POST",path:`/v7/chats/${o}/messages/${i}/reply`,body:d});return ir(l)}catch(o){return or(o)}}}),t({name:"wps_message_list",description:"List messages in a chat (GET /v7/chats/{chat_id}/messages). page_size defaults to 50. `start_time` and `end_time` are Unix timestamps in **seconds** (converted to milliseconds for the API). Returns paginated message list; use page_token for next pages.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."},start_time:{type:"number",description:"Optional inclusive range start (Unix seconds); sent as start_time query in ms."},end_time:{type:"number",description:"Optional inclusive range end (Unix seconds); sent as end_time query in ms."},page_size:{type:"number",description:"Page size (default 50, max 100)."},page_token:{type:"string",description:"Pagination cursor from a previous response."}},required:["chat_id"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=dn(n,"start_time"),s=dn(n,"end_time"),a=dn(n,"page_size")??50,d=ws(n,"page_token"),l={page_size:a};d!==void 0&&(l.page_token=d),i!==void 0&&(l.start_time=Math.trunc(i*1e3)),s!==void 0&&(l.end_time=Math.trunc(s*1e3));let c=await e.request({method:"GET",path:`/v7/chats/${o}/messages`,query:l});return ir(c)}catch(o){return or(o)}}}),t({name:"wps_message_get",description:"Fetch a single message by id within a chat (GET /v7/chats/{chat_id}/messages/{message_id}).",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."},message_id:{type:"string",description:"Message id (from RawBody.messageId)."}},required:["chat_id","message_id"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=encodeURIComponent(Ue(n,"message_id")),s=await e.request({method:"GET",path:`/v7/chats/${o}/messages/${i}`});return ir(s)}catch(o){return or(o)}}})}function vi(e){return e.data??null}function Ti(e){return{error:e instanceof Error?e.message:String(e)}}function ks(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function Ss(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function xs(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}var vs=["active"],Ts=["user_name","email","phone"],Es=["company_user"],Ps=50;function ln(e,t){t({name:"wps_user_get",description:"Get the current authenticated bot/app user profile (GET /v7/users/current). Returns fields such as id, user_name, avatar, and company_id when exposed by the API.",parameters:{type:"object",properties:{},required:[]},async execute(r,n){try{let o=await e.request({method:"GET",path:"/v7/users/current"});return vi(o)}catch(o){return Ti(o)}}}),t({name:"wps_user_search",description:"Search company users by keyword (GET /v7/users/search). Always applies status=active, search_field=user_name+email+phone, and search_source=company_user. page_size defaults to 50 (WPS API requires this field). Returns a paginated user list; use page_token for next pages. If no results found, suggest the user refine the keyword or try email/phone.",parameters:{type:"object",properties:{keyword:{type:"string",description:"Search keyword (name, email fragment, phone, etc.)."},page_size:{type:"number",description:"Page size (default 50, max 100)."},page_token:{type:"string",description:"Pagination token from a prior call."}},required:["keyword"]},async execute(r,n){try{let o=ks(n,"keyword"),i=Ss(n,"page_size")??Ps,s=xs(n,"page_token"),a={keyword:o,status:[...vs],search_field:[...Ts],search_source:[...Es],page_size:i};s!==void 0&&(a.page_token=s);let d=await e.request({method:"GET",path:"/v7/users/search",query:a});return vi(d)}catch(o){return Ti(o)}}})}function Dt(e){return e.data??null}function ut(e){return{error:e instanceof Error?e.message:String(e)}}function Ei(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function Pi(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function pn(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}var Oi=50;function Os(e,t){let r=e[t];if(!Array.isArray(r)||r.length===0)throw new Error(`${t} must be a non-empty array of user id strings`);let n=[];for(let o=0;o<r.length;o++){let i=r[o];if(typeof i!="string"||!i.trim())throw new Error(`${t}[${o}] must be a non-empty string`);n.push(i.trim())}return n}function un(e,t="user"){return{id:e,type:t}}var sr=null;async function As(e){if(sr)return sr;let r=(await e.request({method:"GET",path:"/v7/users/current"})).data;if(!r||typeof r.id!="string"||!r.id.trim())throw new Error("Cannot retrieve current operator identity from /v7/users/current. Ensure the app has kso.user_base.read permission.");return sr={id:r.id.trim(),type:"user"},sr}function _n(e,t){t({name:"wps_chat_create",description:"Create a p2p or group chat (POST /v7/chats/create). For P2P: provide exactly 2 user ids in member_ids (no auto-injection). For group: provide other member user ids; the current operator is auto-included and becomes owner. Requires kso.chat.readwrite permission.",parameters:{type:"object",properties:{type:{type:"string",enum:["p2p","group"],description:"Chat kind: p2p or group."},member_ids:{type:"array",items:{type:"string"},description:"For P2P: exactly 2 user ids. For group: other member ids (operator auto-included)."},name:{type:"string",description:"Group chat display name (only for group type)."}},required:["type","member_ids"]},async execute(r,n){try{let o=Ei(n,"type");if(o!=="p2p"&&o!=="group")throw new Error("type must be 'p2p' or 'group'");let i=Os(n,"member_ids"),s,a={type:o};if(o==="group"){let l=await As(e),c=new Set;s=[],c.add(l.id),s.push(un(l.id));for(let u of i)c.has(u)||(s.push(un(u)),c.add(u));a.owner_id=l.id;let p=pn(n,"name");p!==void 0&&p!==""&&(a.name=p)}else{let l=[...new Set(i)];if(l.length!==2)throw new Error(`P2P chat requires exactly 2 distinct user ids in member_ids. Got ${l.length} after dedup.`);s=l.map(c=>un(c))}a.account_id_list=s;let d=await e.request({method:"POST",path:"/v7/chats/create",body:a});return Dt(d)}catch(o){return ut(o)}}}),t({name:"wps_chat_list",description:"List chats for the current context (GET /v7/chats). page_size defaults to 50. Returns paginated chat list; use page_token for next pages.",parameters:{type:"object",properties:{page_size:{type:"number",description:"Page size (default 50, max 100)."},page_token:{type:"string",description:"Pagination token from a prior call."}},required:[]},async execute(r,n){try{let o=Pi(n,"page_size")??Oi,i=pn(n,"page_token"),s={page_size:o};i!==void 0&&(s.page_token=i);let a=await e.request({method:"GET",path:"/v7/chats",query:s});return Dt(a)}catch(o){return ut(o)}}}),t({name:"wps_chat_get",description:"Get metadata for a single chat (GET /v7/chats/{chat_id}).",parameters:{type:"object",properties:{chat_id:{type:"string",description:"OAPI chat id (from RawBody.chatId)."}},required:["chat_id"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=await e.request({method:"GET",path:`/v7/chats/${o}`});return Dt(i)}catch(o){return ut(o)}}}),t({name:"wps_chat_members",description:"List members of a chat (GET /v7/chats/{chat_id}/members). page_size defaults to 50. Returns paginated member list; use page_token for next pages.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"Chat session id."},page_size:{type:"number",description:"Page size (default 50, max 100)."},page_token:{type:"string",description:"Pagination token from a prior call."}},required:["chat_id"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=Pi(n,"page_size")??Oi,s=pn(n,"page_token"),a={page_size:i};s!==void 0&&(a.page_token=s);let d=await e.request({method:"GET",path:`/v7/chats/${o}/members`,query:a});return Dt(d)}catch(o){return ut(o)}}}),t({name:"wps_chat_is_member",description:"Check whether the current operator is a member of the chat (GET /v7/chats/{chat_id}/members/is_in_chat).",parameters:{type:"object",properties:{chat_id:{type:"string",description:"Chat session id."}},required:["chat_id"]},async execute(r,n){try{let o=encodeURIComponent(me(n)),i=await e.request({method:"GET",path:`/v7/chats/${o}/members/is_in_chat`});return Dt(i)}catch(o){return ut(o)}}}),t({name:"wps_chat_find_by_name",description:"Find a WPS chat/group by name. IMPORTANT: When the user says 'send message to <group name>' or '\u7ED9 <\u7FA4\u540D> \u53D1\u6D88\u606F', ALWAYS call this tool first to resolve the chat_id, then use wps_message_send with receiver_type='chat' and the resolved chat_id. Returns matching chats with owner info for disambiguation. If multiple matches, present the list to the user for selection.",parameters:{type:"object",properties:{keyword:{type:"string",description:"Chat name keyword to search for."}},required:["keyword"]},async execute(r,n){try{let o=Ei(n,"keyword").toLowerCase(),i=[],s,a=!1;for(let l=0;l<10;l++){let c={page_size:100};s&&(c.page_token=s);let p=await e.request({method:"GET",path:"/v7/chats",query:c});for(let u of p.data?.items??[])u.chat_id&&u.name?.toLowerCase().includes(o)&&i.push({chat_id:u.chat_id,name:u.name,owner_id:u.owner_id});if(!p.data?.has_more)break;if(s=p.data?.page_token,!s){a=!0;break}}let d={};return a&&(d.warning="Results may be incomplete: pagination was truncated due to missing page_token."),i.length===0?{...d,found:!1,message:`No chats found matching "${o}"`}:i.length===1?{...d,found:!0,match:i[0]}:{...d,found:!0,multiple:!0,matches:i,hint:"Multiple matches found. Present the list to the user with chat name and owner info for selection."}}catch(o){return ut(o)}}})}it();ct();Kt();Qt();async function ce(e){let t=vt(e.wpsUserId);if(t){let i=Vt(),s=kr(i.baseUrl,t);return await e.run(s)}let r=Hr(),n=Vt(),o=dt();try{await Xr({creds:n,wpsCfg:r,wpsUserId:e.wpsUserId,receiverType:"user",receiverId:e.wpsUserId,originalMessage:e.authCardOriginalMessage})}catch(i){o?.error?.(`[${e.logTag}] Failed to send auth card: ${String(i)}`)}return{needsAuth:!0,message:e.needsAuthMessage}}var Ai=31*24*60*60*1e3,Rs=100,Ri=200,$i=50,qi=100;function L(e){return{error:e instanceof Error?e.message:String(e)}}function P(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function v(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}function _t(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function ft(e,t){let r=e[t];if(r!=null){if(typeof r=="boolean")return r;if(r==="true"||r==="false")return r==="true";throw new Error(`${t} must be a boolean`)}}function $s(e,t){let r=e[t];if(r==null)throw new Error(`${t} is required and must be a finite number`);if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}function ar(e,t){let r=new Date(t.trim());if(Number.isNaN(r.getTime()))throw new Error(`${e} must be a valid RFC3339 / ISO 8601 datetime string`);return r}function mt(e){return e.toISOString()}function fn(e){let t=e.now??new Date,r,n,o=!!e.startRfc?.trim(),i=!!e.endRfc?.trim();if(o&&i?(r=ar("start_time",e.startRfc),n=ar("end_time",e.endRfc)):o?(r=ar("start_time",e.startRfc),n=new Date(r.getTime()+14*86400*1e3)):i?(n=ar("end_time",e.endRfc),r=new Date(n.getTime()-14*86400*1e3)):(r=new Date(t.getTime()-86400*1e3),n=new Date(t.getTime()+14*86400*1e3)),n.getTime()<r.getTime())throw new Error("end_time must be >= start_time (RFC3339 range)");return n.getTime()-r.getTime()>Ai&&(n=new Date(r.getTime()+Ai)),{start:r,end:n}}function qs(e){let{start:t,end:r}=fn({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now}),n={start_time:mt(t),end_time:mt(r)},o=e.pageSize??30;return n.page_size=Math.max(1,Math.min(500,Math.trunc(o))),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(n.page_token=e.pageToken.trim()),n}function Cs(e){let{start:t,end:r}=fn({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now});return{start_time:mt(t),end_time:mt(r)}}function Ds(e){let t={},r=e.pageSize??30;if(t.page_size=Math.max(1,Math.min(500,Math.trunc(r))),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),e.withCancelled===!0&&(t.with_cancelled=!0),e.syncToken!==void 0&&e.syncToken.trim()!==""&&(t.sync_token=e.syncToken.trim()),e.anchorTime!==void 0&&e.anchorTime.trim()!==""&&(t.anchor_time=e.anchorTime.trim()),t.sync_token)return t;let{start:n,end:o}=fn({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now});return t.start_time=mt(n),t.end_time=mt(o),t}function Ns(e){let t=new Date(e.trim());if(Number.isNaN(t.getTime()))throw new Error("start_time must be a valid ISO 8601 datetime");return t.setTime(t.getTime()+60*60*1e3),t.toISOString()}function Te(e,t){return`/v7/calendars/${encodeURIComponent(e)}/events/${encodeURIComponent(t)}`}function Us(e,t){return`${Te(e,t)}/respond`}function mn(e,t){return`${Te(e,t)}/attendees`}function js(e,t){return`${mn(e,t)}/batch_create`}function Ms(e,t){return`${mn(e,t)}/batch_delete`}function Ws(e,t){return`${Te(e,t)}/meeting_rooms`}function zs(e,t){return`${Te(e,t)}/meeting_rooms/batch_create`}function Ls(e,t){return`${Te(e,t)}/meeting_rooms/batch_delete`}function Ci(e){if(!Array.isArray(e)||e.length===0)throw new Error("room_ids is required and must be a non-empty array");let t=e.map((r,n)=>{if(typeof r!="string")throw new Error(`room_ids[${n}] must be a string`);let o=r.trim();if(!o)throw new Error(`room_ids[${n}] must be non-empty`);return o});if(t.length>qi)throw new Error(`room_ids length must be <= ${qi}`);return{room_ids:t}}function Bs(e){let t=e.pageSize??30,n={page_size:Math.max(1,Math.min(Rs,Math.trunc(t)))};return e.pageToken!==void 0&&e.pageToken.trim()!==""&&(n.page_token=e.pageToken.trim()),n}function je(e){let t=v(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let r=t.trim();if(r!=="internal"&&r!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":r}}async function Y(e,t,r){try{return await ce({wpsUserId:e,authCardOriginalMessage:t,needsAuthMessage:"\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u64CD\u4F5C\u65E5\u7A0B\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5\u3002",logTag:"calendar",run:r})}catch(n){return L(n)}}function hn(e,t){t({name:"wps_calendar_create",description:"Create a calendar event for the current user via WPS OpenAPI. Requires user OAuth authorization. If the user has not authorized, an authorization card will be sent automatically. IMPORTANT: Use the SenderId from the current conversation context as wps_user_id. Do NOT call wps_user_search or wps_user_get to look up the user. If end_time is omitted, it defaults to start_time + 1 hour (computed as UTC ISO).",parameters:{type:"object",properties:{summary:{type:"string",description:"Event title."},start_time:{type:"string",description:"Start time in ISO 8601 with timezone (e.g. '2026-04-22T14:00:00+08:00')."},end_time:{type:"string",description:"End time in ISO 8601 with timezone. Omit to default to start_time + 1 hour."},description:{type:"string",description:"Optional event description."},location:{type:"string",description:"Optional event location."},wps_user_id:{type:"string",description:"WPS user ID. Use SenderId from the conversation context. Do NOT call wps_user_search or wps_user_get for this."}},required:["summary","start_time"]},async execute(o,i){try{let s=P(i,"summary"),a=P(i,"start_time"),d=v(i,"end_time"),l=d&&d.trim()!==""?d.trim():Ns(a),c=v(i,"description"),p=v(i,"location"),u=v(i,"wps_user_id")??"";return u?await Y(u,s,async _=>{let f={summary:s,start_time:{datetime:a},end_time:{datetime:l}};c&&(f.description=c),p&&(f.locations=[{name:p}]);let y=await _.request({method:"POST",path:"/v7/calendars/primary/events/create",body:f});return y.data??y}):L(new Error("wps_user_id is required. Use the SenderId from the conversation context."))}catch(s){return L(s)}}}),t({name:"wps_calendar_list_events",description:"List calendar events on the user's primary calendar: GET `/v7/calendars/primary/events` (same as `/v7/calendars/{calendar_id}/events` with calendar_id `primary`). Official doc: https://365.kdocs.cn/3rd/open/documents/app-integration-dev/wps365/server/calendar/calendar-event/get-calendar-event-list Requires user delegated OAuth (same as wps_calendar_create). Use SenderId as wps_user_id. Time range: `start_time` and `end_time` query params are **RFC3339 / ISO8601 strings** (not Unix seconds). If both are omitted, defaults to about last 24 hours through next 14 days, clamped to max 31-day span per API. If `sync_token` is set, incremental sync mode: only sync_token/page_token/page_size/with_cancelled are sent (no automatic time window). Optional: anchor_time (RFC3339), with_cancelled (boolean).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},start_time:{type:"string",description:"Optional range start (RFC3339 / ISO8601). Must be used with end_time for explicit window, or omit both for defaults."},end_time:{type:"string",description:"Optional range end (RFC3339 / ISO8601). API allows 0\u201331 days between start and end; longer ranges are truncated."},page_size:{type:"number",description:"Page size (default 30 per API doc, max 500 client-side cap)."},page_token:{type:"string",description:"Pagination cursor from data.next_page_token."},with_cancelled:{type:"boolean",description:"Include cancelled events (per API)."},sync_token:{type:"string",description:"Incremental sync token from data.next_sync_token; when set, time range is not auto-filled."},anchor_time:{type:"string",description:"Anchor time RFC3339 for incremental sync (per API)."}},required:["wps_user_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=v(i,"start_time"),d=v(i,"end_time"),l=_t(i,"page_size"),c=v(i,"page_token"),p=ft(i,"with_cancelled"),u=v(i,"sync_token"),_=v(i,"anchor_time");return await Y(s,"\u67E5\u8BE2\u4E3B\u65E5\u5386\u65E5\u7A0B\u5217\u8868",async f=>{let y=Ds({startRfc:a,endRfc:d,pageSize:l,pageToken:c,withCancelled:p,syncToken:u,anchorTime:_}),h=await f.request({method:"GET",path:"/v7/calendars/primary/events",query:y});return h.data??h})}catch(s){return L(s)}}}),t({name:"wps_calendar_get_event",description:"Get **one** calendar event by id (official \u67E5\u8BE2\u65E5\u7A0B): GET `/v7/calendars/{calendar_id}/events/{event_id}`. Response `data` is a single event object (summary, recurrence, online_meeting, etc.), not `items[]`. Requires `event_id` from `wps_calendar_list_events` (or equivalent). Same delegated Bearer auth as `wps_calendar_create`. Optional `calendar_id` (default `primary`). Optional header `X-Kso-Id-Type`: pass `x_kso_id_type` as `internal` or `external` per API.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from the calendar event list API."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type` header: `internal` or `external` (per WPS API).",enum:["internal","external"]}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary";return await Y(s,"\u67E5\u8BE2\u65E5\u7A0B\u8BE6\u60C5",async l=>{let c=await l.request({method:"GET",path:Te(d,a),headers:je(i)});return c.data??c})}catch(s){return L(s)}}}),t({name:"wps_calendar_list_event_attendees",description:"List attendees for one calendar event (official \u83B7\u53D6\u65E5\u7A0B\u53C2\u4E0E\u8005\u5217\u8868): GET `/v7/calendars/{calendar_id}/events/{event_id}/attendees`. Response `data` typically has `items[]` and optional `next_page_token`. Requires `event_id` from `wps_calendar_list_events` or `wps_calendar_get_event`. Same delegated Bearer auth as `wps_calendar_create`. Optional `calendar_id` (default `primary`). Query: optional `page_size` (default 30, max 100 per API), `page_token` from `data.next_page_token`. Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from the calendar event list API."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},page_size:{type:"number",description:"Page size (default 30; API max 100)."},page_token:{type:"string",description:"Pagination cursor from data.next_page_token."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary",l=_t(i,"page_size"),c=v(i,"page_token");return await Y(s,"\u83B7\u53D6\u65E5\u7A0B\u53C2\u4E0E\u8005\u5217\u8868",async p=>{let u=Bs({pageSize:l,pageToken:c}),_=await p.request({method:"GET",path:mn(d,a),query:u,headers:je(i)});return _.data??_})}catch(s){return L(s)}}}),t({name:"wps_calendar_add_event_attendees",description:"Batch add attendees to one event (official \u6DFB\u52A0\u65E5\u7A0B\u53C2\u4E0E\u8005): POST `/v7/calendars/{calendar_id}/events/{event_id}/attendees/batch_create`. Requires delegated OAuth (same as `wps_calendar_create`). Body requires `attendees` array (max 200 per request; total attendees per event max 1000). Each attendee item typically includes `type`, `user_id` or `third_party_email`, optional `is_optional` and `response_status`. Optional `is_notification` controls whether attendees receive invitation notifications (default true). Optional `calendar_id` (default `primary`). Optional `x_kso_id_type` maps to `X-Kso-Id-Type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from event list/search/get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},attendees:{type:"array",description:"Attendees to add in batch (required, max 200 per request). Each item supports fields like { type, user_id, third_party_email, is_optional, response_status }.",items:{type:"object",properties:{type:{type:"string"},user_id:{type:"string"},third_party_email:{type:"string"},is_optional:{type:"boolean"},response_status:{type:"string"}}}},is_notification:{type:"boolean",description:"Whether to notify added attendees (default true)."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id","attendees"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary",l=ft(i,"is_notification"),c=i.attendees;if(!Array.isArray(c)||c.length===0)throw new Error("attendees is required and must be a non-empty array");if(c.length>Ri)throw new Error(`attendees length must be <= ${Ri}`);let p=c.map((u,_)=>{if(typeof u!="object"||u===null||Array.isArray(u))throw new Error(`attendees[${_}] must be an object`);let f=u,y={};if(f.type!==void 0){if(typeof f.type!="string"||!f.type.trim())throw new Error(`attendees[${_}].type must be a non-empty string when provided`);y.type=f.type.trim()}if(f.user_id!==void 0){if(typeof f.user_id!="string"||!f.user_id.trim())throw new Error(`attendees[${_}].user_id must be a non-empty string when provided`);y.user_id=f.user_id.trim()}if(f.third_party_email!==void 0){if(typeof f.third_party_email!="string"||!f.third_party_email.trim())throw new Error(`attendees[${_}].third_party_email must be a non-empty string when provided`);y.third_party_email=f.third_party_email.trim()}if(f.is_optional!==void 0){if(typeof f.is_optional!="boolean")throw new Error(`attendees[${_}].is_optional must be a boolean when provided`);y.is_optional=f.is_optional}if(f.response_status!==void 0){if(typeof f.response_status!="string"||!f.response_status.trim())throw new Error(`attendees[${_}].response_status must be a non-empty string when provided`);y.response_status=f.response_status.trim()}if(Object.keys(y).length===0)throw new Error(`attendees[${_}] must contain at least one valid field`);return y});return await Y(s,"\u6DFB\u52A0\u65E5\u7A0B\u53C2\u4E0E\u8005",async u=>{let _={attendees:p};l!==void 0&&(_.is_notification=l);let f=await u.request({method:"POST",path:js(d,a),body:_,headers:je(i)});return f.data??f})}catch(s){return L(s)}}}),t({name:"wps_calendar_list_event_meeting_rooms",description:"List meeting rooms bound to one calendar event (\u83B7\u53D6\u67D0\u4E2A\u65E5\u7A0B\u7684\u4F1A\u8BAE\u5BA4\u5217\u8868): GET `/v7/calendars/{calendar_id}/events/{event_id}/meeting_rooms`. Requires delegated OAuth **`kso.calendar_events.read`** (or `readwrite`) and `event_id`. Optional `calendar_id` (default `primary`). Response `data.items[]` commonly includes room/book fields like `room_id`, `name`, `booking_id`, `result`, `fail_reason`. Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from event list / search / get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary";return await Y(s,"\u83B7\u53D6\u65E5\u7A0B\u4F1A\u8BAE\u5BA4\u5217\u8868",async l=>{let c=await l.request({method:"GET",path:Ws(d,a),headers:je(i)});return c.data??c})}catch(s){return L(s)}}}),t({name:"wps_calendar_event_meeting_rooms_batch_create",description:"Batch add meeting rooms to one calendar event (\u6279\u91CF\u6DFB\u52A0\u67D0\u4E2A\u65E5\u7A0B\u7684\u4F1A\u8BAE\u5BA4): POST `/v7/calendars/{calendar_id}/events/{event_id}/meeting_rooms/batch_create`. Requires delegated OAuth **`kso.calendar_events.readwrite`** (per API). Use SenderId as wps_user_id. Required: `event_id`, non-empty **`room_ids`** (string array; room ids from `wps_meeting_rooms_list` / search / get). Optional `calendar_id` (default `primary`). Response `data.items[]` may include `room_id`, `name`, `result`, `booking_id`, `fail_reason`. Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from event list / search / get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},room_ids:{type:"array",description:"Meeting room ids to attach to this event (non-empty; max 100 per request).",items:{type:"string"}},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id","room_ids"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary",l=i.room_ids;if(!Array.isArray(l))throw new Error("room_ids is required and must be an array");let c=Ci(l);return await Y(s,"\u6279\u91CF\u6DFB\u52A0\u65E5\u7A0B\u4F1A\u8BAE\u5BA4",async p=>{let u=await p.request({method:"POST",path:zs(d,a),body:c,headers:je(i)});return u.data??u})}catch(s){return L(s)}}}),t({name:"wps_calendar_event_meeting_rooms_batch_delete",description:"Batch delete meeting rooms from one calendar event (\u6279\u91CF\u5220\u9664\u67D0\u4E2A\u65E5\u7A0B\u7684\u4F1A\u8BAE\u5BA4): POST `/v7/calendars/{calendar_id}/events/{event_id}/meeting_rooms/batch_delete`. Requires delegated OAuth **`kso.calendar_events.readwrite`**. Use SenderId as wps_user_id. Required: `event_id`, non-empty **`room_ids`** (meeting room ids bound to this event). Optional `calendar_id` (default `primary`). Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from event list / search / get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},room_ids:{type:"array",description:"Meeting room ids to remove from this event (non-empty; max 100 per request).",items:{type:"string"}},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id","room_ids"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary",l=i.room_ids;if(!Array.isArray(l))throw new Error("room_ids is required and must be an array");let c=Ci(l);return await Y(s,"\u6279\u91CF\u5220\u9664\u65E5\u7A0B\u4F1A\u8BAE\u5BA4",async p=>{let u=await p.request({method:"POST",path:Ls(d,a),body:c,headers:je(i)});return u.data??u})}catch(s){return L(s)}}}),t({name:"wps_calendar_delete_event_attendees",description:"Batch delete attendees from one event (official \u5220\u9664\u65E5\u7A0B\u53C2\u4E0E\u8005): POST `/v7/calendars/{calendar_id}/events/{event_id}/attendees/batch_delete`. Requires delegated OAuth (same as `wps_calendar_create`). Body requires `attendees` array and supports optional `attendee_ids` array. Per API, `attendee_ids.length + attendees.length` must be <= 50 in one request. Optional `is_notification` controls whether removed attendees receive notification (default true). Optional `calendar_id` (default `primary`). Optional `x_kso_id_type` maps to `X-Kso-Id-Type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from event list/search/get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},attendee_ids:{type:"array",description:"Optional attendee id list. Combined count with `attendees` must be <= 50.",items:{type:"string"}},attendees:{type:"array",description:"Attendees payload to remove (required). Combined count with `attendee_ids` must be <= 50. Each item supports fields like { type, user_id, third_party_email }.",items:{type:"object",properties:{type:{type:"string"},user_id:{type:"string"},third_party_email:{type:"string"}}}},is_notification:{type:"boolean",description:"Whether to notify removed attendees (default true)."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type`: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","event_id","attendees"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary",l=ft(i,"is_notification"),c=i.attendee_ids,p;if(c!==void 0){if(!Array.isArray(c))throw new Error("attendee_ids must be an array of strings when provided");p=c.map((y,h)=>{if(typeof y!="string"||!y.trim())throw new Error(`attendee_ids[${h}] must be a non-empty string`);return y.trim()})}let u=i.attendees;if(!Array.isArray(u)||u.length===0)throw new Error("attendees is required and must be a non-empty array");let _=u.map((y,h)=>{if(typeof y!="object"||y===null||Array.isArray(y))throw new Error(`attendees[${h}] must be an object`);let m=y,g={};if(m.type!==void 0){if(typeof m.type!="string"||!m.type.trim())throw new Error(`attendees[${h}].type must be a non-empty string when provided`);g.type=m.type.trim()}if(m.user_id!==void 0){if(typeof m.user_id!="string"||!m.user_id.trim())throw new Error(`attendees[${h}].user_id must be a non-empty string when provided`);g.user_id=m.user_id.trim()}if(m.third_party_email!==void 0){if(typeof m.third_party_email!="string"||!m.third_party_email.trim())throw new Error(`attendees[${h}].third_party_email must be a non-empty string when provided`);g.third_party_email=m.third_party_email.trim()}if(Object.keys(g).length===0)throw new Error(`attendees[${h}] must contain at least one valid field`);return g});if((p?.length??0)+_.length>$i)throw new Error(`attendee_ids.length + attendees.length must be <= ${$i}`);return await Y(s,"\u5220\u9664\u65E5\u7A0B\u53C2\u4E0E\u8005",async y=>{let h={attendees:_};p&&p.length>0&&(h.attendee_ids=p),l!==void 0&&(h.is_notification=l);let m=await y.request({method:"POST",path:Ms(d,a),body:h,headers:je(i)});return m.data??m})}catch(s){return L(s)}}}),t({name:"wps_calendar_respond_invitation",description:"Reply to a calendar invitation (official \u7B54\u590D\u65E5\u7A0B\u9080\u8BF7): POST `/v7/calendars/{calendar_id}/events/{event_id}/respond`. Requires delegated OAuth (same as `wps_calendar_create`). Body per API: `mod_type` (`normal` = non-recurring reply, `one` = one occurrence of recurring, `all` = entire series), `response_status` (`accepted` | `declined` | `tentative`), `which_day_time` = **start time in milliseconds** (Unix ms) for the occurrence being answered. Use `event_id` from `wps_calendar_list_events` / `wps_calendar_get_event`; for recurring series pick `which_day_time` from instance or event `start_time`. Optional `calendar_id` (default `primary`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Calendar event id (from event list or get-event API)."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},mod_type:{type:"string",description:"Reply scope per WPS API.",enum:["normal","one","all"]},response_status:{type:"string",description:"Invitation response.",enum:["accepted","declined","tentative"]},which_day_time:{type:"number",description:"Schedule start time as **milliseconds since Unix epoch** (per API `which_day_time`). Use the occurrence start from list/get/event_instances."}},required:["wps_user_id","event_id","mod_type","response_status","which_day_time"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary",l=P(i,"mod_type");if(l!=="normal"&&l!=="one"&&l!=="all")throw new Error("mod_type must be normal, one, or all");let c=P(i,"response_status");if(c!=="accepted"&&c!=="declined"&&c!=="tentative")throw new Error("response_status must be accepted, declined, or tentative");let p=Math.trunc($s(i,"which_day_time"));return await Y(s,"\u7B54\u590D\u65E5\u7A0B\u9080\u8BF7",async u=>{let _=await u.request({method:"POST",path:Us(d,a),body:{mod_type:l,response_status:c,which_day_time:p}});return _.data??_})}catch(s){return L(s)}}}),t({name:"wps_calendar_list_calendar_event_instances",description:"List expanded **calendar-level** event instances (all occurrences in a time window): GET `/v7/calendars/{calendar_id}/event_instances` (use `calendar_id=primary` for main calendar). Same delegated Bearer auth as `wps_calendar_create`. Query: RFC3339 `start_time` / `end_time` (0\u201331 days), optional `page_size` (default 30), `page_token`. Use when you need many instances across the calendar without a specific `event_id`. To expand **one** recurring event by id, use `wps_calendar_list_event_instances` instead.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},calendar_id:{type:"string",description:"Calendar id or the literal `primary` (default)."},start_time:{type:"string",description:"Optional range start (RFC3339). Omit both for default window."},end_time:{type:"string",description:"Optional range end (RFC3339). Max 31-day span; longer truncated."},page_size:{type:"number",description:"Page size (default 30, max 500)."},page_token:{type:"string",description:"Pagination cursor if returned by API."}},required:["wps_user_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=v(i,"calendar_id")??"primary",d=v(i,"start_time"),l=v(i,"end_time"),c=_t(i,"page_size"),p=v(i,"page_token");return await Y(s,"\u67E5\u8BE2\u65E5\u5386\u65E5\u7A0B\u5B9E\u4F8B\u5217\u8868",async u=>{let _=qs({startRfc:d,endRfc:l,pageSize:c,pageToken:p}),f=await u.request({method:"GET",path:`/v7/calendars/${encodeURIComponent(a)}/event_instances`,query:_});return f.data??f})}catch(s){return L(s)}}}),t({name:"wps_calendar_list_event_instances",description:"Query **instances of one calendar event** (expand a recurring series for that event id): GET `/v7/calendars/{calendar_id}/events/{event_id}/event_instances` per WPS365 doc. Requires `event_id` from `wps_calendar_list_events` (or equivalent). Optional query: `start_time` / `end_time` **RFC3339** strings; range 0\u201331 days (truncated if longer); omit both for default window. Same delegated Bearer auth as `wps_calendar_create`. Optional `calendar_id` (default `primary`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Calendar event id from the event list API."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},start_time:{type:"string",description:"Optional query range start (RFC3339). Used with end_time; omit both for defaults."},end_time:{type:"string",description:"Optional query range end (RFC3339)."}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary",l=v(i,"start_time"),c=v(i,"end_time");return await Y(s,"\u67E5\u8BE2\u5355\u6761\u65E5\u7A0B\u5B9E\u4F8B",async p=>{let u=Cs({startRfc:l,endRfc:c}),_=await p.request({method:"GET",path:`${Te(d,a)}/event_instances`,query:u});return _.data??_})}catch(s){return L(s)}}});let r=100,n=500;t({name:"wps_calendar_search_events",description:"Search calendar events by keyword (official \u641C\u7D22\u65E5\u7A0B): POST `/v7/calendars/{calendar_id}/events/search`. Searches event titles, descriptions, and notes. Requires user delegated OAuth (same as wps_calendar_create). Use SenderId as wps_user_id. Body: `keyword` (required, 1-100 chars), optional `page_size` (default 200, max 500), optional `page_token`. Response: `data.items[]` (event list) and optional `data.next_page_token`. Optional `calendar_id` (default `primary`). Optional header `X-Kso-Id-Type`: pass `x_kso_id_type` as `internal` or `external` per API.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},keyword:{type:"string",description:"Search keyword (1-100 chars). Matches event title, description, notes."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},page_size:{type:"number",description:"Page size (default 200 per API, max 500)."},page_token:{type:"string",description:"Pagination cursor from data.next_page_token."},x_kso_id_type:{type:"string",description:"Optional. When set, sent as `X-Kso-Id-Type` header: `internal` or `external`.",enum:["internal","external"]}},required:["wps_user_id","keyword"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"keyword");if(a.length>r)throw new Error(`keyword must be at most ${r} characters`);let d=v(i,"calendar_id")??"primary",l=_t(i,"page_size"),c=v(i,"page_token");return await Y(s,"\u641C\u7D22\u65E5\u7A0B",async p=>{let u={keyword:a},_=l??200;u.page_size=Math.max(1,Math.min(n,Math.trunc(_))),c!==void 0&&c.trim()!==""&&(u.page_token=c.trim());let f=await p.request({method:"POST",path:`/v7/calendars/${encodeURIComponent(d)}/events/search`,body:u,headers:je(i)});return f.data??f})}catch(s){return L(s)}}}),t({name:"wps_calendar_update_event",description:"Update (modify) a calendar event (official \u4FEE\u6539\u65E5\u7A0B): POST `/v7/calendars/{calendar_id}/events/{event_id}/update`. Requires user delegated OAuth (same as wps_calendar_create). Use SenderId as wps_user_id. All body fields are optional \u2014 only pass what needs to change. For recurring events: set `mod_type` to `one` (single occurrence, requires `which_day_time` in ms) or `all` (entire series). Set `is_notification` to false to suppress attendee notifications. Set `online_meeting` to null to clear the meeting. Optional `calendar_id` (default `primary`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from calendar event list or search."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},summary:{type:"string",description:"New event title."},description:{type:"string",description:"New event description / notes."},start_time:{type:"string",description:"New start time in ISO 8601 with timezone (e.g. '2026-05-10T14:00:00+08:00')."},end_time:{type:"string",description:"New end time in ISO 8601 with timezone."},location:{type:"string",description:"New event location (API supports max 1 location)."},free_busy_status:{type:"string",description:"Busy/free status during the event.",enum:["busy","free"]},visibility:{type:"string",description:"Event visibility scope.",enum:["default","public","private"]},attendee_ability:{type:"string",description:"Attendee permission level.",enum:["can_see_others","can_invite_others"]},mod_type:{type:"string",description:"For recurring events only: `one` = edit single occurrence (requires which_day_time), `all` = edit entire series.",enum:["one","all"]},which_day_time:{type:"number",description:"When mod_type=one, the start time of the occurrence to modify in **milliseconds** (Unix epoch ms)."},is_notification:{type:"boolean",description:"Whether to notify attendees about the update (default true)."},is_reinvition:{type:"boolean",description:"When true and time/recurrence changes, reset all attendees to not-accepted (default true)."},reminders:{type:"array",description:"Reminder list (max 10). Each item: { minutes: number }.",items:{type:"object",properties:{minutes:{type:"number"}},required:["minutes"]}}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary",l=v(i,"mod_type");if(l!==void 0&&l!=="one"&&l!=="all")throw new Error("mod_type must be one or all when provided");let c=_t(i,"which_day_time");if(l==="one"&&c==null)throw new Error("which_day_time (ms) is required when mod_type is one");let p=v(i,"free_busy_status");if(p!==void 0&&p!=="busy"&&p!=="free")throw new Error("free_busy_status must be busy or free");let u=v(i,"visibility");if(u!==void 0&&u!=="default"&&u!=="public"&&u!=="private")throw new Error("visibility must be default, public, or private");let _=v(i,"attendee_ability");if(_!==void 0&&_!=="can_see_others"&&_!=="can_invite_others")throw new Error("attendee_ability must be can_see_others or can_invite_others");return await Y(s,"\u4FEE\u6539\u65E5\u7A0B",async f=>{let y={},h=v(i,"summary");h!==void 0&&(y.summary=h);let m=v(i,"description");m!==void 0&&(y.description=m);let g=v(i,"start_time");g!==void 0&&(y.start_time={datetime:g});let w=v(i,"end_time");w!==void 0&&(y.end_time={datetime:w});let b=v(i,"location");b!==void 0&&(y.locations=[{name:b}]),p!==void 0&&(y.free_busy_status=p),u!==void 0&&(y.visibility=u),_!==void 0&&(y.attendee_ability=_),l!==void 0&&(y.mod_type=l),c!==void 0&&(y.which_day_time=Math.trunc(c));let I=ft(i,"is_notification");I!==void 0&&(y.is_notification=I);let S=ft(i,"is_reinvition");S!==void 0&&(y.is_reinvition=S);let N=i.reminders;Array.isArray(N)&&(y.reminders=N.slice(0,10).map(Q=>{let B=Q;return{minutes:typeof B.minutes=="number"?Math.trunc(B.minutes):0}}));let K=await f.request({method:"POST",path:`${Te(d,a)}/update`,body:y});return K.data??K})}catch(s){return L(s)}}}),t({name:"wps_calendar_delete_event",description:"Delete a calendar event (official \u5220\u9664\u65E5\u7A0B): POST `/v7/calendars/{calendar_id}/events/{event_id}/delete`. Requires user delegated OAuth (same as wps_calendar_create). Use SenderId as wps_user_id. Optional body: `is_notification` (default true). For recurring events: set `mod_type` to `one` (delete one occurrence, requires `which_day_time` in ms) or `all` (delete entire series). Optional `calendar_id` (default `primary`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},event_id:{type:"string",description:"Event id from calendar list/search/get-event APIs."},calendar_id:{type:"string",description:"Calendar id or `primary` (default)."},is_notification:{type:"boolean",description:"Whether to notify attendees about deletion (default true)."},mod_type:{type:"string",description:"For recurring events only: `one` (single occurrence, requires which_day_time) or `all` (entire series).",enum:["one","all"]},which_day_time:{type:"number",description:"When mod_type=one, the start time of occurrence to delete in milliseconds."}},required:["wps_user_id","event_id"]},async execute(o,i){try{let s=P(i,"wps_user_id"),a=P(i,"event_id"),d=v(i,"calendar_id")??"primary",l=v(i,"mod_type");if(l!==void 0&&l!=="one"&&l!=="all")throw new Error("mod_type must be one or all when provided");let c=_t(i,"which_day_time");if(l==="one"&&c===void 0)throw new Error("which_day_time (ms) is required when mod_type is one");let p=ft(i,"is_notification");return await Y(s,"\u5220\u9664\u65E5\u7A0B",async u=>{let _={};p!==void 0&&(_.is_notification=p),l!==void 0&&(_.mod_type=l),c!==void 0&&(_.which_day_time=Math.trunc(c));let f=await u.request({method:"POST",path:`${Te(d,a)}/delete`,body:_});return f.data??f})}catch(s){return L(s)}}})}var Fs="/v7/todo/personal_tasks",Gs="/v7/todo/personal_tasks/batch_get";function dr(e){return`/v7/todo/personal_tasks/${encodeURIComponent(e.trim())}`}function Ks(e){return`${dr(e.trim())}/update`}function Hs(e){return`${dr(e.trim())}/update_status`}var Di=100,Js=20,Xs=50;function gt(e){return{error:e instanceof Error?e.message:String(e)}}function Ee(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function Z(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}function Xe(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function Vs(e,t){let r=e[t];if(r==null)return;if(!Array.isArray(r))throw new Error(`${t} must be an array of strings`);let n=r.map(o=>String(o).trim()).filter(Boolean);return n.length>0?n:void 0}function Ys(e,t){let r=e[t];if(r==null)return;if(!Array.isArray(r))throw new Error(`${t} must be an array of objects with name and value`);let n=[];for(let o of r){if(typeof o!="object"||o===null)continue;let i=o;typeof i.name!="string"||typeof i.value!="string"||n.push({name:i.name.trim(),value:i.value})}return n.length>0?n:void 0}function Zs(e,t){let r=Z(e,t);if(!(r===void 0||r.trim()===""))try{let n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${t} must be a JSON object`);return n}catch(n){throw n instanceof SyntaxError?new Error(`${t} must be valid JSON`):n}}function ht(e){let t=Z(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let r=t.trim();if(r!=="internal"&&r!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":r}}function Qs(e){let t=e.titleSubject.trim();if(!t)throw new Error("title_subject must be non-empty");let r={subject:t};e.titlePrefix!==void 0&&e.titlePrefix.trim()!==""&&(r.prefix=e.titlePrefix.trim());let n={title:r};if(e.description!==void 0&&e.description.trim()!==""&&(n.description=e.description.trim()),e.dueTimeMs!==void 0){if(!Number.isFinite(e.dueTimeMs))throw new Error("due_time_ms must be a finite number");n.due_time=Math.trunc(e.dueTimeMs)}if((e.status==="todo"||e.status==="finish")&&(n.status=e.status),e.executors!==void 0&&e.executors.length>0){if(e.executors.length>Di)throw new Error(`executors must have at most ${Di} entries`);n.executors=[...e.executors]}return n}function ea(e){let t={};if(e.keyword!==void 0&&e.keyword.trim()!==""&&(t.keyword=e.keyword.trim().slice(0,50)),e.executor!==void 0&&e.executor.trim()!==""&&(t.executor=e.executor.trim()),(e.status==="todo"||e.status==="finish")&&(t.status=e.status),e.pageSize!==void 0){let r=e.pageSize;t.page_size=Math.max(1,Math.min(Xs,Math.trunc(r)))}else t.page_size=Js;if(e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),e.createdTimeStartMs!==void 0||e.createdTimeEndMs!==void 0){let r={};e.createdTimeStartMs!==void 0&&Number.isFinite(e.createdTimeStartMs)&&(r.start_time=Math.trunc(e.createdTimeStartMs)),e.createdTimeEndMs!==void 0&&Number.isFinite(e.createdTimeEndMs)&&(r.end_time=Math.trunc(e.createdTimeEndMs)),Object.keys(r).length>0&&(t.created_time=r)}if(e.dueTimeStartMs!==void 0||e.dueTimeEndMs!==void 0){let r={};e.dueTimeStartMs!==void 0&&Number.isFinite(e.dueTimeStartMs)&&(r.start_time=Math.trunc(e.dueTimeStartMs)),e.dueTimeEndMs!==void 0&&Number.isFinite(e.dueTimeEndMs)&&(r.end_time=Math.trunc(e.dueTimeEndMs)),Object.keys(r).length>0&&(t.due_time=r)}return t}function ta(e){let t={},r=e.titleSubject?.trim()??"",n=e.titlePrefix?.trim()??"";if(r!==""||n!==""){let o={};r!==""&&(o.subject=r),n!==""&&(o.prefix=n),t.title=o}if(e.description!==void 0&&e.description.trim()!==""&&(t.description=e.description.trim()),e.dueTimeMs!==void 0){if(!Number.isFinite(e.dueTimeMs))throw new Error("due_time_ms must be a finite number");t.due_time=Math.trunc(e.dueTimeMs)}if(e.extAttrs!==void 0&&e.extAttrs.length>0&&(t.ext_attrs=e.extAttrs.map(o=>({name:o.name,value:o.value}))),e.notifyConfig!==void 0&&Object.keys(e.notifyConfig).length>0&&(t.notify_config=e.notifyConfig),Object.keys(t).length===0)throw new Error("provide at least one of: title_subject, title_prefix, description, due_time_ms, ext_attrs, notify_config_json");return t}var ra=new Set(["finish","unfinish","finish_all","unfinish_all"]);function na(e){return ra.has(e)}function Ni(e){let t=e.trim();if(!na(t))throw new Error("action must be exactly one of: finish, unfinish, finish_all, unfinish_all");return t}function ia(e){return{action:Ni(e.action)}}function oa(e){if(e==null||typeof e!="object")return null;let t=e,r=["creator_id","creator_user_id","create_user_id","owner_id"];for(let o of r){let i=t[o];if(typeof i=="string"&&i.trim())return i.trim()}let n=t.creator;if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let o=n;for(let i of["id","user_id","userId"]){let s=o[i];if(typeof s=="string"&&s.trim())return s.trim()}}return null}function sa(e,t){let r=e.trim(),n=t.trim();return r===n?!0:r.toLowerCase()===n.toLowerCase()}function aa(e){let{hasCompletion:t,completionRaw:r,markScopeRaw:n,actionParam:o,isCreator:i,taskId:s,creatorId:a}=e,d=n?.trim()??"";if(t){if(r!=="complete"&&r!=="incomplete")throw new Error("completion must be complete or incomplete");let c=r==="complete";if(i){if(!d||d==="none")return{kind:"needs_confirmation",taskId:s,completion:r,creatorId:a};if(d!=="self"&&d!=="all")throw new Error("mark_scope must be none, self, or all when provided");return{kind:"post",action:d==="all"?c?"finish_all":"unfinish_all":c?"finish":"unfinish"}}return{kind:"post",action:c?"finish":"unfinish"}}let l=Ni(o);if(!i&&(l==="finish_all"||l==="unfinish_all"))throw new Error("\u5F53\u524D\u7528\u6237\u4E0D\u662F\u8BE5\u5F85\u529E\u7684\u521B\u5EFA\u8005\uFF08\u6216\u672A\u89E3\u6790\u5230 creator_id\uFF09\uFF0C\u4E0D\u80FD\u4F7F\u7528 finish_all / unfinish_all\uFF1B\u8BF7\u4F7F\u7528 finish \u6216 unfinish\u3002");return i?{kind:"needs_confirmation",taskId:s,completion:l==="finish"||l==="finish_all"?"complete":"incomplete",creatorId:a,requested_action:l}:{kind:"post",action:l}}async function Nt(e,t,r){try{return await ce({wpsUserId:e,authCardOriginalMessage:t,needsAuthMessage:"\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u4F7F\u7528\u5F85\u529E\u80FD\u529B\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5\u3002",logTag:"todo",run:r})}catch(n){return gt(n)}}function gn(e,t){t({name:"wps_todo_create_personal_task",description:"Create a personal todo/task via WPS OpenAPI (\u521B\u5EFA\u4E2A\u4EBA\u5F85\u529E): POST `/v7/todo/personal_tasks`. Requires user delegated OAuth scope `kso.task.readwrite` (or equivalent per console). Use SenderId as `wps_user_id`. Required: `title_subject` \u2192 body `title.subject`; optional `title_prefix` \u2192 `title.prefix`. Optional: `description`, `due_time_ms` (deadline **milliseconds** Unix epoch), `status` (`todo`|`finish`), `executors` (\u2264100 user ids). Response `data.task_id` is the new task id. Optional `x_kso_id_type`: `internal`|`external` \u2192 header `X-Kso-Id-Type`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},title_subject:{type:"string",description:"Todo title subject (maps to request body title.subject)."},title_prefix:{type:"string",description:"Optional. Maps to title.prefix."},description:{type:"string",description:"Optional todo description."},due_time_ms:{type:"number",description:"Optional deadline as Unix timestamp in **milliseconds** (due_time)."},status:{type:"string",description:"Optional initial status.",enum:["todo","finish"]},executors:{type:"array",items:{type:"string"},description:"Optional executor user ids (max 100)."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","title_subject"]},async execute(r,n){try{let o=Ee(n,"wps_user_id"),i=Ee(n,"title_subject"),s=Z(n,"title_prefix"),a=Z(n,"description"),d=Xe(n,"due_time_ms"),l=Z(n,"status"),c=Vs(n,"executors"),p;if(l!==void 0){if(l!=="todo"&&l!=="finish")throw new Error("status must be todo or finish when provided");p=l}let u=Qs({titleSubject:i,titlePrefix:s,description:a,dueTimeMs:d,status:p,executors:c});return await Nt(o,"\u521B\u5EFA\u4E2A\u4EBA\u5F85\u529E",async _=>{let f=await _.request({method:"POST",path:Fs,body:u,headers:ht(n)});return f.data??f})}catch(o){return gt(o)}}}),t({name:"wps_todo_list_personal_tasks",description:"List personal todos via WPS OpenAPI (\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u5217\u8868): POST `/v7/todo/personal_tasks/batch_get`. Requires delegated OAuth (`kso.task.read` / `kso.task.readwrite`). Use SenderId as `wps_user_id`. Body filters are optional: `keyword` (\u226450 chars), `executor`, `status` (`todo`|`finish`), `page_size` (default 20, max 50), `page_token` (from previous `data` pagination field per API). `created_time` / `due_time` ranges use **milliseconds** (`*_start_ms`, `*_end_ms`). Response `data` typically includes `tasks`, `total`, `next_offset`. Optional `x_kso_id_type`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},keyword:{type:"string",description:"Optional. Fuzzy match title/description (max 50 chars)."},executor:{type:"string",description:"Optional. Filter by executor user id."},status:{type:"string",description:"Optional list filter: todo (=\u672A\u5B8C\u6210) or finish (=\u5DF2\u5B8C\u6210).",enum:["todo","finish"]},page_size:{type:"number",description:"Page size (default 20; API max 50)."},page_token:{type:"string",description:"Pagination cursor from previous response (see API field names e.g. next_offset)."},created_time_start_ms:{type:"number",description:"Optional. Creation range start (Unix ms)."},created_time_end_ms:{type:"number",description:"Optional. Creation range end (Unix ms)."},due_time_start_ms:{type:"number",description:"Optional. Due range start (Unix ms)."},due_time_end_ms:{type:"number",description:"Optional. Due range end (Unix ms)."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id"]},async execute(r,n){try{let o=Ee(n,"wps_user_id"),i=Z(n,"keyword"),s=Z(n,"executor"),a=Z(n,"status"),d=Xe(n,"page_size"),l=Z(n,"page_token"),c=Xe(n,"created_time_start_ms"),p=Xe(n,"created_time_end_ms"),u=Xe(n,"due_time_start_ms"),_=Xe(n,"due_time_end_ms"),f;if(a!==void 0){if(a!=="todo"&&a!=="finish")throw new Error("status must be todo or finish when provided");f=a}let y=ea({keyword:i,executor:s,status:f,pageSize:d,pageToken:l,createdTimeStartMs:c,createdTimeEndMs:p,dueTimeStartMs:u,dueTimeEndMs:_});return await Nt(o,"\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u5217\u8868",async h=>{let m=await h.request({method:"POST",path:Gs,body:y,headers:ht(n)});return m.data??m})}catch(o){return gt(o)}}}),t({name:"wps_todo_get_personal_task",description:"Get one personal todo by id (\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u8BE6\u60C5): GET `/v7/todo/personal_tasks/{task_id}`. Requires delegated OAuth (`kso.task.read` / `kso.task.readwrite`). Use SenderId as `wps_user_id`. Requires **`task_id`** from `wps_todo_list_personal_tasks` (`tasks[].id`) or create response. Response `data` is a single todo object (`todo_personal_task`). Optional `x_kso_id_type`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},task_id:{type:"string",description:"Todo task id from list or create API."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","task_id"]},async execute(r,n){try{let o=Ee(n,"wps_user_id"),i=Ee(n,"task_id");return await Nt(o,"\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u8BE6\u60C5",async s=>{let a=await s.request({method:"GET",path:dr(i),headers:ht(n)});return a.data??a})}catch(o){return gt(o)}}}),t({name:"wps_todo_update_personal_task_status",description:"POST `/v7/todo/personal_tasks/{task_id}/update_status`. HTTP body: `{ action }`. Enum: `finish`, `unfinish`, `finish_all`, `unfinish_all` (`finish_all`/`unfinish_all` creator-only). **Creators**: without `mark_scope` (or `mark_scope: none`) or `action`-only \u2192 returns `needsUserConfirmation`, ask user to choose scope; then call again with `completion` + `mark_scope: self|all`. **Non-creators**: `completion` or `action` (`finish`|`unfinish`); omit `mark_scope`. Requires delegated `kso.task.readwrite`; `wps_user_id` = SenderId.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},task_id:{type:"string",description:"Todo id to update status."},completion:{type:"string",description:"`complete`/`incomplete`. Creators: omit `mark_scope` or use `none` \u2192 returns `needsUserConfirmation`; after user confirms, call again with `mark_scope: self|all`. Mutually exclusive with `action`.",enum:["complete","incomplete"]},mark_scope:{type:"string",description:"**Creators only**: omit or `none` \u2192 \u89E6\u53D1\u4E8C\u6B21\u786E\u8BA4\uFF1B`self` = \u4EC5\u81EA\u5DF1\uFF1B`all` = \u5168\u90E8\u53C2\u4E0E\u4EBA\u3002\u975E\u521B\u5EFA\u8005\u52FF\u4F20\u3002",enum:["none","self","all"]},action:{type:"string",description:"Maps to HTTP body `action`. `finish`|`unfinish` (single); `finish_all`|`unfinish_all` (creator, all participants). Non-creators: `finish`|`unfinish` only. Creators using `action` alone \u2192 `needsUserConfirmation` (then use `completion`+`mark_scope`).",enum:["finish","unfinish","finish_all","unfinish_all"]},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","task_id"]},async execute(r,n){try{let o=Ee(n,"wps_user_id"),i=Ee(n,"task_id"),s=Z(n,"completion"),a=Z(n,"mark_scope"),d=Z(n,"action"),l=s!==void 0,c=d!==void 0&&d!=="";if(l===c)throw!l&&!c?new Error("Provide exactly one of: completion (complete|incomplete) or action (finish|unfinish|...)"):new Error("Provide only one of: completion or action");if(a!==void 0&&!l)throw new Error("mark_scope is only used together with completion");return await Nt(o,"\u66F4\u65B0\u4E2A\u4EBA\u5F85\u529E\u72B6\u6001",async p=>{let u=await p.request({method:"GET",path:dr(i),headers:ht(n)}),_=u.data??u,f=oa(_),y=f!==null&&sa(o,f),h=aa({hasCompletion:l,completionRaw:s,markScopeRaw:a,actionParam:d,isCreator:y,taskId:i,creatorId:f});if(h.kind==="needs_confirmation")return{needsUserConfirmation:!0,reason:"creator_must_choose_scope",message:"\u60A8\u662F\u8BE5\u5F85\u529E\u7684\u521B\u5EFA\u8005\uFF0C\u8BF7\u5148\u786E\u8BA4\uFF1A\u6807\u8BB0\u300C\u4EC5\u81EA\u5DF1\u300D\u8FD8\u662F\u300C\u5168\u90E8\u53C2\u4E0E\u4EBA\u300D\uFF1F\u786E\u8BA4\u540E\u518D\u6B21\u8C03\u7528\uFF0C\u4F20\u5165 completion + mark_scope\uFF08self \u6216 all\uFF09\u3002",task_id:h.taskId,completion:h.completion,creator_id:h.creatorId,...h.requested_action!==void 0?{requested_action:h.requested_action}:{}};let m=ia({action:h.action}),g=await p.request({method:"POST",path:Hs(i),body:m,headers:ht(n)});return g.data??g})}catch(o){return gt(o)}}}),t({name:"wps_todo_update_personal_task",description:"Update a personal todo (\u66F4\u65B0\u4E2A\u4EBA\u5F85\u529E): POST `/v7/todo/personal_tasks/{task_id}/update`. Requires delegated **`kso.task.readwrite`**. Use SenderId as `wps_user_id`. Requires **`task_id`**. Body fields are optional but **at least one** must be provided: `title_subject` / `title_prefix` (maps to `title`), `description`, `due_time_ms` (ms), `ext_attrs` (`[{name,value}]`), or `notify_config_json` (JSON object string for `notify_config`). Response is typically `code` + `msg` only.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},task_id:{type:"string",description:"Todo id to update."},title_subject:{type:"string",description:"Optional. Maps to title.subject."},title_prefix:{type:"string",description:"Optional. Maps to title.prefix."},description:{type:"string",description:"Optional. New description."},due_time_ms:{type:"number",description:"Optional. New deadline as Unix **milliseconds**."},ext_attrs:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:"string"}},required:["name","value"]},description:"Optional. Extension attributes."},notify_config_json:{type:"string",description:"Optional. JSON object string for notify_config (e.g. reminders, switch). Must parse to an object."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","task_id"]},async execute(r,n){try{let o=Ee(n,"wps_user_id"),i=Ee(n,"task_id"),s=Z(n,"title_subject"),a=Z(n,"title_prefix"),d=Z(n,"description"),l=Xe(n,"due_time_ms"),c=Ys(n,"ext_attrs"),p=Zs(n,"notify_config_json"),u=ta({titleSubject:s,titlePrefix:a,description:d,dueTimeMs:l,extAttrs:c,notifyConfig:p});return await Nt(o,"\u66F4\u65B0\u4E2A\u4EBA\u5F85\u529E",async _=>{let f=await _.request({method:"POST",path:Ks(i),body:u,headers:ht(n)});return f.data??f})}catch(o){return gt(o)}}})}function Pe(e){return`/v7/coop/dbsheet/${encodeURIComponent(e)}`}function da(e){return`/v7/dbsheet/${encodeURIComponent(e)}`}function Me(e){let t=e.sheet_id;if(t==null)throw new Error("sheet_id is required");let r=typeof t=="number"?t:parseInt(String(t),10);if(!Number.isFinite(r)||r<=0)throw new Error("sheet_id must be a positive integer");return r}function Ui(e,t="fields_value"){if(typeof e=="string")return e;if(e!==null&&typeof e=="object")return JSON.stringify(e);throw new Error(`${t} must be a JSON string or object`)}async function Se(e,t,r){return ce({wpsUserId:e,authCardOriginalMessage:"",needsAuthMessage:"\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u8BBF\u95EE\u591A\u7EF4\u8868\u683C\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",logTag:t,run:r})}function yn(e,t){t({name:"wps_dbsheet_get_schema",description:"Get DBSheet schema (\u83B7\u53D6\u591A\u7EF4\u8868\u683C Schema): GET `/v7/coop/dbsheet/{file_id}/schema`. Returns all sheets with their fields (name/type/id/data) and views. Use this first to understand the table structure before reading or writing records. Requires delegated OAuth (`kso.dbsheet.read`). Use current SenderId as `wps_user_id`. Do NOT call `wps_user_search` to resolve `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"DBSheet file ID."}},required:["wps_user_id","file_id"]},async execute(r,n){try{let o=T(n,"wps_user_id"),i=T(n,"file_id");return await Se(o,"wps_dbsheet_get_schema",async s=>{let a=await s.request({method:"GET",path:`${Pe(i)}/schema`});return a.data??a})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_batch_create_sheets",description:"Batch create sheets (\u6279\u91CF\u521B\u5EFA\u5DE5\u4F5C\u8868): POST `/v7/dbsheet/{file_id}/sheets/batch_create`. Creates one or more sheets. Each sheet requires `name`; optionally include `fields` (field definitions with name/type/data) and `position` (after_sheet_id or before_sheet_id). Requires delegated OAuth (`kso.dbsheet.readwrite`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheets:{type:"array",description:"Array of sheet definitions. Each: { name: string (required), fields?: [{name, type, data?}], position?: {after_sheet_id?: number, before_sheet_id?: number} }.",items:{type:"object",properties:{name:{type:"string"},fields:{type:"array",items:{type:"object",additionalProperties:!0}},position:{type:"object",additionalProperties:!0}},required:["name"]}}},required:["wps_user_id","file_id","sheets"]},async execute(r,n){try{let o=T(n,"wps_user_id"),i=T(n,"file_id"),s=n.sheets;if(!Array.isArray(s)||s.length===0)throw new Error("sheets must be a non-empty array");return await Se(o,"wps_dbsheet_batch_create_sheets",async a=>{let d=await a.request({method:"POST",path:`${da(i)}/sheets/batch_create`,body:{sheets:s}});return d.data??d})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_update_sheet",description:"Update sheet (\u66F4\u65B0\u5DE5\u4F5C\u8868): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/update`. Currently supports renaming a sheet. Obtain `sheet_id` (integer) from `wps_dbsheet_get_schema`. Requires delegated OAuth (`kso.dbsheet.readwrite`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer). From wps_dbsheet_get_schema."},name:{type:"string",description:"New sheet name."}},required:["wps_user_id","file_id","sheet_id","name"]},async execute(r,n){try{let o=T(n,"wps_user_id"),i=T(n,"file_id"),s=Me(n),a=T(n,"name");return await Se(o,"wps_dbsheet_update_sheet",async d=>{let l=await d.request({method:"POST",path:`${Pe(i)}/sheets/${s}/update`,body:{name:a}});return l.data??l})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_create_records",description:'Create records (\u521B\u5EFA\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/create`. Creates one or more records. Each record\'s `fields_value` is a JSON string (or object \u2014 auto-stringified) mapping field name to value. Example: `{"\u6587\u672C\u5B57\u6BB5": "hello", "\u6570\u5B57\u5B57\u6BB5": 42}`. Auto fields (Formula/AutoNumber/CreatedBy/CreatedTime/LastModifiedBy/Lookup) must NOT be set. Requires delegated OAuth (`kso.dbsheet.readwrite`). Use current SenderId as `wps_user_id`.',parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer). From wps_dbsheet_get_schema."},records:{type:"array",description:"Array of records to create. Each: { fields_value: string|object }. fields_value maps field names to values as JSON string or object.",items:{type:"object",properties:{fields_value:{type:"string",description:'Field values as JSON string or object. E.g. {"\u6587\u672C": "hello", "\u6570\u5B57": 42}'}},required:["fields_value"]}}},required:["wps_user_id","file_id","sheet_id","records"]},async execute(r,n){try{let o=T(n,"wps_user_id"),i=T(n,"file_id"),s=Me(n),a=n.records;if(!Array.isArray(a)||a.length===0)throw new Error("records must be a non-empty array");let d=a.map((l,c)=>{if(!l||typeof l!="object")throw new Error(`records[${c}] must be an object`);return{fields_value:Ui(l.fields_value,`records[${c}].fields_value`)}});return await Se(o,"wps_dbsheet_create_records",async l=>{let c=await l.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records/create`,body:{records:d}});return c.data??c})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_update_records",description:"Update records (\u66F4\u65B0\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/update`. Updates one or more records by record ID. Each item must include `id` (record ID) and `fields_value`. `fields_value` maps field names to new values (JSON string or object \u2014 auto-stringified). Auto fields (Formula/AutoNumber/CreatedBy/CreatedTime/LastModifiedBy/Lookup) must NOT be updated. Requires delegated OAuth (`kso.dbsheet.readwrite`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer). From wps_dbsheet_get_schema."},records:{type:"array",description:"Array of records to update. Each: { id: string (record ID), fields_value: string|object }.",items:{type:"object",properties:{id:{type:"string",description:"Record ID."},fields_value:{type:"string",description:"Field values as JSON string or object."}},required:["id","fields_value"]}}},required:["wps_user_id","file_id","sheet_id","records"]},async execute(r,n){try{let o=T(n,"wps_user_id"),i=T(n,"file_id"),s=Me(n),a=n.records;if(!Array.isArray(a)||a.length===0)throw new Error("records must be a non-empty array");let d=a.map((l,c)=>{if(!l||typeof l!="object")throw new Error(`records[${c}] must be an object`);let p=l;if(!p.id||typeof p.id!="string")throw new Error(`records[${c}].id is required and must be a string`);return{id:p.id,fields_value:Ui(p.fields_value,`records[${c}].fields_value`)}});return await Se(o,"wps_dbsheet_update_records",async l=>{let c=await l.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records/update`,body:{records:d}});return c.data??c})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_list_records",description:"List records with cursor pagination (\u5217\u4E3E\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records`. Returns records with optional filter and cursor-based pagination (page_token). Use `page_token` from previous response to fetch next page. For page-number pagination use `wps_dbsheet_list_records_by_page`. Requires delegated OAuth (`kso.dbsheet.read`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer)."},fields:{type:"array",items:{type:"string"},description:"Optional. Field names to include. Omit to return all fields."},filter:{type:"object",additionalProperties:!0,description:"Optional filter. Structure: { mode: 'AND'|'OR', criteria: [{ field: string, operator: string, values: string[] }] }. operator: Equals|NotEqu|Greater|GreaterEqu|Less|LessEqu|GreaterEquAndLessEqu|LessOrGreater|BeginWith|EndWith|Contains|NotContains|Intersected|Empty|NotEmpty."},max_records:{type:"integer",description:"Optional. Max records to return."},page_size:{type:"integer",description:"Optional. Records per page, default 100, max 1000."},page_token:{type:"string",description:"Optional. Cursor from previous response."},view_id:{type:"string",description:"Optional. View ID to apply view visibility."},text_value:{type:"string",enum:["original","text","compound"],description:"Optional. Return value format. Default: original."},show_fields_info:{type:"boolean",description:"Optional. Include field schema in response."},show_record_extra_info:{type:"boolean",description:"Optional. Include creator/creation time/last-modifier metadata."}},required:["wps_user_id","file_id","sheet_id"]},async execute(r,n){try{let o=T(n,"wps_user_id"),i=T(n,"file_id"),s=Me(n),a={},d=Je(n,"fields");d&&(a.fields=d),n.filter!==void 0&&n.filter!==null&&(a.filter=n.filter);let l=V(n,"max_records");l!==void 0&&(a.max_records=l);let c=V(n,"page_size");c!==void 0&&(a.page_size=c);let p=X(n,"page_token");p!==void 0&&p!==""&&(a.page_token=p);let u=X(n,"view_id");u!==void 0&&u!==""&&(a.view_id=u);let _=X(n,"text_value");_!==void 0&&(a.text_value=_);let f=re(n,"show_fields_info");f!==void 0&&(a.show_fields_info=f);let y=re(n,"show_record_extra_info");return y!==void 0&&(a.show_record_extra_info=y),await Se(o,"wps_dbsheet_list_records",async h=>{let m=await h.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records`,body:a});return m.data??m})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_list_records_by_page",description:"List records with page-number pagination (\u6309\u9875\u5217\u4E3E\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/list_by_page`. Uses page_num (starts from 1) / page_size. Also returns total count. For cursor-based pagination use `wps_dbsheet_list_records`. Requires delegated OAuth (`kso.dbsheet.read`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer)."},fields:{type:"array",items:{type:"string"},description:"Optional. Field names to include."},filter:{type:"object",additionalProperties:!0,description:"Optional filter. Structure: { mode: 'AND'|'OR', criteria: [{ field, operator, values[] }] }."},max_records:{type:"integer",description:"Optional. Max records to return."},page_num:{type:"integer",description:"Optional. Page number starting from 1."},page_size:{type:"integer",description:"Optional. Records per page, default 100, max 1000."},view_id:{type:"string",description:"Optional. View ID."},text_value:{type:"string",enum:["original","text","compound"],description:"Optional. Return value format."},show_fields_info:{type:"boolean",description:"Optional. Include field schema."},show_record_extra_info:{type:"boolean",description:"Optional. Include metadata."}},required:["wps_user_id","file_id","sheet_id"]},async execute(r,n){try{let o=T(n,"wps_user_id"),i=T(n,"file_id"),s=Me(n),a={},d=Je(n,"fields");d&&(a.fields=d),n.filter!==void 0&&n.filter!==null&&(a.filter=n.filter);let l=V(n,"max_records");l!==void 0&&(a.max_records=l);let c=V(n,"page_num");c!==void 0&&(a.page_num=c);let p=V(n,"page_size");p!==void 0&&(a.page_size=p);let u=X(n,"view_id");u!==void 0&&u!==""&&(a.view_id=u);let _=X(n,"text_value");_!==void 0&&(a.text_value=_);let f=re(n,"show_fields_info");f!==void 0&&(a.show_fields_info=f);let y=re(n,"show_record_extra_info");return y!==void 0&&(a.show_record_extra_info=y),await Se(o,"wps_dbsheet_list_records_by_page",async h=>{let m=await h.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records/list_by_page`,body:a});return m.data??m})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_get_records",description:"Get multiple records by ID (\u6309 ID \u6279\u91CF\u68C0\u7D22\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/search`. Retrieves specific records by their IDs. Use when you already know the record IDs. For filter-based listing use `wps_dbsheet_list_records` instead. Requires delegated OAuth (`kso.dbsheet.read`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer)."},records:{type:"array",items:{type:"string"},description:"Array of record IDs to retrieve."},text_value:{type:"string",enum:["original","text","compound"],description:"Optional. Return value format."},show_fields_info:{type:"boolean",description:"Optional. Include field schema."},show_record_extra_info:{type:"boolean",description:"Optional. Include metadata."}},required:["wps_user_id","file_id","sheet_id","records"]},async execute(r,n){try{let o=T(n,"wps_user_id"),i=T(n,"file_id"),s=Me(n),a=Je(n,"records");if(!a||a.length===0)throw new Error("records must be a non-empty array of record IDs");let d={records:a},l=X(n,"text_value");l!==void 0&&(d.text_value=l);let c=re(n,"show_fields_info");c!==void 0&&(d.show_fields_info=c);let p=re(n,"show_record_extra_info");return p!==void 0&&(d.show_record_extra_info=p),await Se(o,"wps_dbsheet_get_records",async u=>{let _=await u.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records/search`,body:d});return _.data??_})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_get_record",description:"Get a single record (\u68C0\u7D22\u5355\u6761\u8BB0\u5F55): GET `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/{record_id}`. Retrieves a single record by its ID. Requires delegated OAuth (`kso.dbsheet.read`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer)."},record_id:{type:"string",description:"Record ID to retrieve."},text_value:{type:"string",enum:["original","text","compound"],description:"Optional. Return value format."},show_fields_info:{type:"boolean",description:"Optional. Include field schema."},show_record_extra_info:{type:"boolean",description:"Optional. Include metadata."}},required:["wps_user_id","file_id","sheet_id","record_id"]},async execute(r,n){try{let o=T(n,"wps_user_id"),i=T(n,"file_id"),s=Me(n),a=T(n,"record_id"),d={},l=X(n,"text_value");l!==void 0&&(d.text_value=l);let c=re(n,"show_fields_info");c!==void 0&&(d.show_fields_info=c);let p=re(n,"show_record_extra_info");return p!==void 0&&(d.show_record_extra_info=p),await Se(o,"wps_dbsheet_get_record",async u=>{let _=await u.request({method:"GET",path:`${Pe(i)}/sheets/${s}/records/${encodeURIComponent(a)}`,query:Object.keys(d).length>0?d:void 0});return _.data??_})}catch(o){return ie(o)}}}),t({name:"wps_dbsheet_delete_records",description:"Delete records (\u6279\u91CF\u5220\u9664\u8BB0\u5F55): POST `/v7/coop/dbsheet/{file_id}/sheets/{sheet_id}/records/batch_delete`. Deletes one or more records by their IDs. This operation is irreversible. Requires delegated OAuth (`kso.dbsheet.readwrite`). Use current SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (current SenderId)."},file_id:{type:"string",description:"DBSheet file ID."},sheet_id:{type:"string",description:"Sheet ID (integer)."},records:{type:"array",items:{type:"string"},description:"Array of record IDs to delete."}},required:["wps_user_id","file_id","sheet_id","records"]},async execute(r,n){try{let o=T(n,"wps_user_id"),i=T(n,"file_id"),s=Me(n),a=Je(n,"records");if(!a||a.length===0)throw new Error("records must be a non-empty array of record IDs");return await Se(o,"wps_dbsheet_delete_records",async d=>{let l=await d.request({method:"POST",path:`${Pe(i)}/sheets/${s}/records/batch_delete`,body:{records:a}});return l.data??l})}catch(o){return ie(o)}}})}it();import{createHash as ca}from"node:crypto";import{readFile as la,stat as pa}from"node:fs/promises";var ua="/v7/drives",_a="/v7/files/search",fa=50,ma=500,ha=50,ga=500,ya=50,wa=500,ji=["folder","file","shortcut"],cr=["fail","rename","overwrite","replace"],Ki=["kdc","plain","markdown"],Hi=["sync","async","auto"],ba=["para","table","component","textbox","all"],Mi=["file_name","content","all"],Wi=["folder","file","shortcut"],zi=["ctime","mtime","otime","stime"],Li=["desc","asc"],Bi=["ctime","mtime"],Fi=["desc","asc"],Gi=["ctime","mtime","dtime","fname","fsize"],Ia=["all","share_by_me","share_to_me","latest","personal_drive","group_drive","recycle","customize","latest_opened","latest_edited"];function ze(e){return{error:e instanceof Error?e.message:String(e)}}function D(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function $(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}function yt(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function oe(e,t){let r=e[t];if(r!=null){if(typeof r=="boolean")return r;if(r==="true"||r==="false")return r==="true";throw new Error(`${t} must be a boolean`)}}function G(e,t){let r=e[t];if(r==null)return;if(!Array.isArray(r))throw new Error(`${t} must be an array of strings`);let n=r.map(o=>String(o).trim()).filter(Boolean);return n.length>0?n:void 0}function We(e){let t=$(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let r=t.trim();if(r!=="internal"&&r!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":r}}function ka(e){let t={};for(let[r,n]of Object.entries(e.requestHeaders)){let o=r.trim();if(o==="")continue;let i=o.toLowerCase();i==="content-length"||i==="transfer-encoding"||i==="content-type"||(t[o]=n)}return t["Content-Type"]="application/octet-stream",t}function Sa(e){let t=e.trim();if(!t)throw new Error("url is required and must be a non-empty string");let r;try{r=new URL(t)}catch{throw new Error("url must be an absolute URL from step-1 data.store_request.url (e.g. https://...); relative paths are not supported")}if(r.protocol!=="https:"&&r.protocol!=="http:")throw new Error(`url must use http: or https: scheme, got: ${r.protocol}`)}function xa(e){let t={allotee_type:e.alloteeType,page_size:Math.max(1,Math.min(ma,Math.trunc(e.pageSize??fa)))};return e.alloteeId!==void 0&&e.alloteeId.trim()!==""&&(t.allotee_id=e.alloteeId.trim()),e.withExtAttrs!==void 0&&(t.with_ext_attrs=e.withExtAttrs),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),e.sources!==void 0&&e.sources.length>0&&(t.sources=[...e.sources]),t}function va(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/create`}function Ta(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/children`}function Ea(e){let t={page_size:Math.max(1,Math.min(wa,Math.trunc(e.pageSize??ya)))};return e.withPermission!==void 0&&(t.with_permission=e.withPermission),e.withExtAttrs!==void 0&&(t.with_ext_attrs=e.withExtAttrs),e.filterExts!==void 0&&e.filterExts.trim()!==""&&(t.filter_exts=e.filterExts.trim()),e.filterType!==void 0&&Object.keys(e.filterType).length>0&&(t.filter_type=JSON.stringify(e.filterType)),e.order!==void 0&&(t.order=e.order),e.orderBy!==void 0&&(t.order_by=e.orderBy),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),t}function Pa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/request_upload`}function Oa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/commit_upload`}function Aa(e){let t=e.name.trim();if(!t)throw new Error("name must be a non-empty string");let r={file_type:e.fileType,name:t};if(e.fileType==="shortcut"){if(!e.fileId||!e.fileId.trim())throw new Error("file_id is required when file_type is shortcut");r.file_id=e.fileId.trim()}else e.fileId!==void 0&&e.fileId.trim()!==""&&(r.file_id=e.fileId.trim());return e.onNameConflict!==void 0&&(r.on_name_conflict=e.onNameConflict),e.parentPath!==void 0&&e.parentPath.length>0&&(r.parent_path=[...e.parentPath]),r}function Ra(e){let t={size:Math.max(0,Math.trunc(e.size))};return e.fileId!==void 0&&e.fileId.trim()!==""&&(t.file_id=e.fileId.trim()),e.hashes!==void 0&&e.hashes.length>0&&(t.hashes=e.hashes.map(r=>({type:r.type,sum:r.sum.trim()}))),e.internal!==void 0&&(t.internal=e.internal),e.name!==void 0&&e.name.trim()!==""&&(t.name=e.name.trim()),e.onNameConflict!==void 0&&(t.on_name_conflict=e.onNameConflict),e.parentPath!==void 0&&e.parentPath.length>0&&(t.parent_path=[...e.parentPath]),e.storageBaseDomain!==void 0&&e.storageBaseDomain.trim()!==""&&(t.storage_base_domain=e.storageBaseDomain.trim()),e.uploadScene!==void 0&&e.uploadScene.trim()!==""&&(t.upload_scene=e.uploadScene.trim()),t}function $a(e){let t={};return e.id!==void 0&&e.id.trim()!==""&&(t.id=e.id.trim()),e.uploadId!==void 0&&e.uploadId.trim()!==""&&(t.upload_id=e.uploadId.trim()),t}function qa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/content`}function Ca(e){let t={};if(e.format!==void 0&&e.format.trim()!==""){let r=e.format.trim();if(!Ki.includes(r))throw new Error("format must be one of: kdc, plain, markdown");t.format=r}if(e.includeElements!==void 0&&e.includeElements.length>0){let r=e.includeElements.map(n=>n.trim()).filter(Boolean).filter((n,o,i)=>i.indexOf(n)===o);for(let n of r)if(!ba.includes(n))throw new Error("include_elements items must be one of: para, table, component, textbox, all");r.length>0&&(t.include_elements=r)}if(e.mode!==void 0&&e.mode.trim()!==""){let r=e.mode.trim();if(!Hi.includes(r))throw new Error("mode must be one of: sync, async, auto");t.mode=r}return e.taskId!==void 0&&e.taskId.trim()!==""&&(t.task_id=e.taskId.trim()),t}function Da(e){return`/v7/files/${encodeURIComponent(e.trim())}/meta`}function Na(e){let t={};return e.withPermission!==void 0&&(t.with_permission=e.withPermission),e.withExtAttrs!==void 0&&(t.with_ext_attrs=e.withExtAttrs),e.withDrive!==void 0&&(t.with_drive=e.withDrive),t}function Ua(e){let t={type:e.type,page_size:Math.max(1,Math.min(ga,Math.trunc(e.pageSize??ha)))};return e.keyword!==void 0&&e.keyword.trim()!==""&&(t.keyword=e.keyword.trim()),e.fileType!==void 0&&(t.file_type=e.fileType),e.fileExts!==void 0&&e.fileExts.length>0&&(t.file_exts=[...e.fileExts]),e.driveIds!==void 0&&e.driveIds.length>0&&(t.drive_ids=[...e.driveIds]),e.parentIds!==void 0&&e.parentIds.length>0&&(t.parent_ids=[...e.parentIds]),e.creatorIds!==void 0&&e.creatorIds.length>0&&(t.creator_ids=[...e.creatorIds]),e.modifierIds!==void 0&&e.modifierIds.length>0&&(t.modifier_ids=[...e.modifierIds]),e.sharerIds!==void 0&&e.sharerIds.length>0&&(t.sharer_ids=[...e.sharerIds]),e.receiverIds!==void 0&&e.receiverIds.length>0&&(t.receiver_ids=[...e.receiverIds]),e.timeType!==void 0&&(t.time_type=e.timeType),e.startTime!==void 0&&(t.start_time=Math.trunc(e.startTime)),e.endTime!==void 0&&(t.end_time=Math.trunc(e.endTime)),e.withPermission!==void 0&&(t.with_permission=e.withPermission),e.withLink!==void 0&&(t.with_link=e.withLink),e.withTotal!==void 0&&(t.with_total=e.withTotal),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),e.channels!==void 0&&e.channels.length>0&&(t.channels=[...e.channels]),e.deviceIds!==void 0&&e.deviceIds.length>0&&(t.device_ids=[...e.deviceIds]),e.excludeChannels!==void 0&&e.excludeChannels.length>0&&(t.exclude_channels=[...e.excludeChannels]),e.excludeFileExts!==void 0&&e.excludeFileExts.length>0&&(t.exclude_file_exts=[...e.excludeFileExts]),e.filterUserId!==void 0&&(t.filter_user_id=Math.trunc(e.filterUserId)),e.fileExtGroups!==void 0&&e.fileExtGroups.length>0&&(t.file_ext_groups=[...e.fileExtGroups]),e.withFolder!==void 0&&(t.with_folder=e.withFolder),e.withDrive!==void 0&&(t.with_drive=e.withDrive),e.order!==void 0&&(t.order=e.order),e.orderBy!==void 0&&(t.order_by=e.orderBy),e.scope!==void 0&&e.scope.length>0&&(t.scope=[...e.scope]),e.searchOperatorName!==void 0&&(t.search_operator_name=e.searchOperatorName),t}async function Ve(e,t,r,n){try{return await ce({wpsUserId:e,authCardOriginalMessage:t,needsAuthMessage:r,logTag:"drive",run:n})}catch(o){return ze(o)}}function wn(e,t){t({name:"wps_cloud_doc_list_drives",description:"List cloud drives (\u83B7\u53D6\u76D8\u5217\u8868): GET `/v7/drives`. Requires delegated OAuth (`kso.drive.readwrite`). Use SenderId as `wps_user_id`. Required query: `allotee_type` (`user` | `group` | `app`). Optional `allotee_id` can be supplied for user/group/app scopes. Optional: `with_ext_attrs`, `page_size` (default 50, max 500), `page_token`, `sources` (array). Optional `x_kso_id_type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},allotee_type:{type:"string",description:"Drive allocation type.",enum:["user","group","app"]},allotee_id:{type:"string",description:"Optional allocation id for user/group/app scope."},with_ext_attrs:{type:"boolean",description:"Optional. Include ext_attrs in response."},page_size:{type:"number",description:"Optional. Page size (default 50, max 500)."},page_token:{type:"string",description:"Optional pagination token."},sources:{type:"array",items:{type:"string"},description:"Optional source filters."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","allotee_type"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"allotee_type");if(i!=="user"&&i!=="group"&&i!=="app")throw new Error("allotee_type must be user, group, or app");let s=i,a=$(n,"allotee_id"),d=oe(n,"with_ext_attrs"),l=yt(n,"page_size"),c=$(n,"page_token"),p=G(n,"sources");return await Ve(o,"\u83B7\u53D6\u76D8\u5217\u8868","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u8BBF\u95EE\u4E91\u6587\u6863\u76D8\u5217\u8868\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async u=>{let _=xa({alloteeType:s,alloteeId:a,withExtAttrs:d,pageSize:l,pageToken:c,sources:p}),f=await u.request({method:"GET",path:ua,query:_,headers:We(n)});return f.data??f})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_list_children_files",description:"List child files under a parent folder (\u83B7\u53D6\u5B50\u6587\u4EF6\u5217\u8868): GET `/v7/drives/{drive_id}/files/{parent_id}/children`. Requires delegated OAuth (`kso.file.read`). Use SenderId as `wps_user_id`. Required: `drive_id`, `parent_id` (root parent_id is `0`). Optional query: `with_permission`, `with_ext_attrs`, `filter_exts`, `filter_type`, `order`, `order_by`, `page_size`, `page_token`. Optional `x_kso_id_type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId)."},drive_id:{type:"string",description:"Drive ID."},parent_id:{type:"string",description:"Parent folder id (root is `0`)."},with_permission:{type:"boolean",description:"Optional. Include operation permissions in response."},with_ext_attrs:{type:"boolean",description:"Optional. Include file ext_attrs in response."},filter_exts:{type:"string",description:"Optional. Extension filter string separated by semicolons, e.g. `docx;xlsx`."},filter_type:{type:"object",description:"Optional file type filter object (passed through to API query `filter_type`).",additionalProperties:!0},order:{type:"string",enum:[...Fi],description:"Optional order direction."},order_by:{type:"string",enum:[...Gi],description:"Optional order field."},page_size:{type:"number",description:"Optional page size (default 50, max 500)."},page_token:{type:"string",description:"Optional pagination token."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","drive_id","parent_id"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"drive_id"),s=D(n,"parent_id"),a=oe(n,"with_permission"),d=oe(n,"with_ext_attrs"),l=$(n,"filter_exts"),c=yt(n,"page_size"),p=$(n,"page_token"),u=$(n,"order");if(u!==void 0&&!Fi.includes(u))throw new Error("order must be one of: desc, asc");let _=u,f=$(n,"order_by");if(f!==void 0&&!Gi.includes(f))throw new Error("order_by must be one of: ctime, mtime, dtime, fname, fsize");let y=f,h=n.filter_type,m;if(h!=null){if(typeof h!="object"||Array.isArray(h))throw new Error("filter_type must be an object when provided");m=h}return await Ve(o,"\u83B7\u53D6\u5B50\u6587\u4EF6\u5217\u8868","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u83B7\u53D6\u5B50\u6587\u4EF6\u5217\u8868\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async g=>{let w=Ea({withPermission:a,withExtAttrs:d,filterExts:l,filterType:m,order:_,orderBy:y,pageSize:c,pageToken:p}),b=await g.request({method:"GET",path:Ta(i,s),query:w,headers:We(n)});return b.data??b})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_create_file",description:"Create file/folder/shortcut (\u65B0\u5EFA\u6587\u4EF6(\u5939)): POST `/v7/drives/{drive_id}/files/{parent_id}/create`. Requires delegated OAuth (`kso.file.readwrite`). Use SenderId as `wps_user_id`. Required: `drive_id`, `parent_id`, `file_type` (`folder` | `file` | `shortcut`), `name`. When `file_type` is `shortcut`, `file_id` is required. Optional: `on_name_conflict` (`fail` | `rename` | `overwrite` | `replace`), `parent_path` (string array). Optional `x_kso_id_type` header (`internal` | `external`).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},drive_id:{type:"string",description:"Drive ID."},parent_id:{type:"string",description:"Parent file/folder ID (root is 0)."},file_type:{type:"string",enum:[...ji],description:"Created resource type: folder, file, or shortcut."},name:{type:"string",description:"Name to create. Include extension for files when needed."},file_id:{type:"string",description:"Required only for file_type=shortcut (target file id)."},on_name_conflict:{type:"string",enum:[...cr],description:"Name conflict behavior."},parent_path:{type:"array",items:{type:"string"},description:"Optional relative nested path array under parent_id."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","drive_id","parent_id","file_type","name"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"drive_id"),s=D(n,"parent_id"),a=D(n,"file_type");if(!ji.includes(a))throw new Error("file_type must be one of: folder, file, shortcut");let d=a,l=D(n,"name"),c=$(n,"file_id"),p=$(n,"on_name_conflict");if(p!==void 0&&!cr.includes(p))throw new Error("on_name_conflict must be one of: fail, rename, overwrite, replace");let u=p,_=G(n,"parent_path");return await Ve(o,"\u65B0\u5EFA\u6587\u4EF6\uFF08\u5939\uFF09","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u65B0\u5EFA\u4E91\u6587\u6863\u6587\u4EF6\uFF08\u5939\uFF09\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async f=>{let y=Aa({fileType:d,name:l,fileId:c,onNameConflict:u,parentPath:_}),h=await f.request({method:"POST",path:va(i,s),body:y,headers:We(n)});return h.data??h})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_upload_file",description:"**THE ONLY tool for uploading files** (\u4E00\u4F53\u5316\u4E0A\u4F20). Combines step-1 request_upload, step-2 upload bytes, and step-3 commit_upload into a **single tool call**. Pass `file_path` (local file path, e.g. from prefetched attachment `localPath`); the plugin reads the file directly from disk. The plugin computes `size` and `sha256` hash from the actual file bytes \u2014 **no need for the caller to compute or pass `size` / `hashes`**. This avoids `ContentLengthInvalid` and `BadDigest` errors (no base64 encoding, no truncation risk). Requires delegated OAuth (`kso.file.readwrite`). Use SenderId as `wps_user_id`. Returns the final committed file object.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId)."},drive_id:{type:"string",description:"Drive ID."},parent_id:{type:"string",description:"Parent file/folder ID (root is 0)."},file_path:{type:"string",description:"Absolute path to the local file to upload (e.g. from prefetched attachment `localPath`). The plugin reads bytes directly from disk \u2014 no base64 encoding needed, no truncation risk."},name:{type:"string",description:"Filename for the uploaded file (e.g. 'report.doc'). If omitted, the filename is extracted from `file_path`."},on_name_conflict:{type:"string",enum:[...cr],description:"Optional name conflict behavior (default: server decides)."},file_id:{type:"string",description:"Optional target file id for update upload."},internal:{type:"boolean",description:"Optional internal endpoint preference."},upload_scene:{type:"string",description:"Optional upload scene."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","drive_id","parent_id","file_path"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"drive_id"),s=D(n,"parent_id"),a=D(n,"file_path"),d=$(n,"name"),l=$(n,"on_name_conflict");if(l!==void 0&&!cr.includes(l))throw new Error("on_name_conflict must be one of: fail, rename, overwrite, replace");let c=l,p=$(n,"file_id"),u=oe(n,"internal"),_=$(n,"upload_scene"),f=a.trim();try{if(!(await pa(f)).isFile())throw new Error("path is not a regular file")}catch(g){throw new Error(`file_path "${f}" is not accessible: ${g instanceof Error?g.message:String(g)}`)}let y=await la(f);if(!d){let g=Math.max(f.lastIndexOf("/"),f.lastIndexOf("\\")),b=(g>=0?f.substring(g+1):f).replace(/^[0-9a-f]{8}_/i,"");b&&(d=b)}if(y.byteLength===0)throw new Error("upload content is empty (file has zero bytes)");let h=y.byteLength,m=ca("sha256").update(y).digest("hex");return await Ve(o,"\u4E00\u4F53\u5316\u4E0A\u4F20\u6587\u4EF6","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u4E0A\u4F20\u4E91\u6587\u6863\u6587\u4EF6\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async g=>{let w=Ra({size:h,fileId:p??void 0,hashes:[{type:"sha256",sum:m}],internal:u??void 0,name:d??void 0,onNameConflict:c,uploadScene:_??void 0}),b=await g.request({method:"POST",path:Pa(i,s),body:w,headers:We(n)}),I=b.data??b,S=I.store_request;if(!S||typeof S.url!="string"||!S.url.trim())throw new Error(`step-1 response missing store_request.url \u2014 cannot proceed with upload. Response: ${JSON.stringify(I).substring(0,300)}`);let N=typeof S.method=="string"?S.method.toUpperCase():"PUT",K=S.url;Sa(K);let Q=S.headers??{},B=typeof I.upload_id=="string"?I.upload_id:void 0,ee=vt(o);if(!ee||!ee.trim())throw new Error("delegated access token missing after auth gate");let tt=ka({requestHeaders:Q}),ye={Authorization:`Bearer ${ee.trim()}`,...tt},le=new Uint8Array(y.buffer,y.byteOffset,y.byteLength),pe;try{pe=await fetch(K,{method:N,headers:ye,body:le})}catch(Re){let It=Re instanceof Error?Re.message:String(Re);throw new Error(`upload step-2 fetch failed: ${It}. Check outbound HTTPS/DNS/firewall from the gateway to the presigned URL.`)}if(!pe.ok){let Re=await pe.text().catch(()=>"");throw new Error(`upload step-2 failed: HTTP ${pe.status} ${Re.substring(0,300)} [diag: size=${h}, sha256=${m}]`)}if(!B)return{step1:I,step2_status:pe.status,etag:pe.headers.get("etag")??void 0,warning:"upload_id missing from step-1 \u2014 skipped commit_upload."};let bt=$a({uploadId:B}),ur=await g.request({method:"POST",path:Oa(i,s),body:bt,headers:We(n)});return ur.data??ur})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_extract_file_content",description:"Extract file content (\u6587\u6863\u5185\u5BB9\u62BD\u53D6): GET `/v7/drives/{drive_id}/files/{file_id}/content`. Requires delegated OAuth (`kso.file.read`). Use SenderId as `wps_user_id`. Required: `drive_id`, `file_id`. Optional query: `format` (`kdc` | `plain` | `markdown`), `include_elements` (`para` | `table` | `component` | `textbox` | `all`), `mode` (`sync` | `async` | `auto`), `task_id`. Returns upstream `data` as-is (for fields like `task_id`, `task_status`, `doc`, `markdown`, `plain`, etc.).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},drive_id:{type:"string",description:"Drive ID."},file_id:{type:"string",description:"File ID."},format:{type:"string",enum:[...Ki],description:"Optional output format."},include_elements:{type:"array",items:{type:"string"},description:"Optional extracted element types."},mode:{type:"string",enum:[...Hi],description:"Optional extraction mode."},task_id:{type:"string",description:"Optional task id for async/auto result polling."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","drive_id","file_id"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"drive_id"),s=D(n,"file_id"),a=$(n,"format"),d=G(n,"include_elements"),l=$(n,"mode"),c=$(n,"task_id");return await Ve(o,"\u6587\u6863\u5185\u5BB9\u62BD\u53D6","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u8FDB\u884C\u6587\u6863\u5185\u5BB9\u62BD\u53D6\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async p=>{let u=Ca({format:a,includeElements:d,mode:l,taskId:c}),_=await p.request({method:"GET",path:qa(i,s),query:Object.keys(u).length>0?u:void 0,headers:We(n)});return _.data??_})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_get_file_meta",description:"Get file metadata (\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F): GET `/v7/files/{file_id}/meta`. Requires delegated OAuth (`kso.file.read`). Use SenderId as `wps_user_id`. Required: `file_id`. Optional query: `with_permission`, `with_ext_attrs`, `with_drive` (boolean). Returns upstream `data` as-is (for fields like `drive`, `permission`, `ext_attrs`, etc.).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"File ID."},with_permission:{type:"boolean",description:"Optional. Include permission field in response."},with_ext_attrs:{type:"boolean",description:"Optional. Include ext_attrs field in response."},with_drive:{type:"boolean",description:"Optional. Include drive field in response."},x_kso_id_type:{type:"string",description:"Optional. Sent as X-Kso-Id-Type: internal or external.",enum:["internal","external"]}},required:["wps_user_id","file_id"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"file_id"),s=oe(n,"with_permission"),a=oe(n,"with_ext_attrs"),d=oe(n,"with_drive");return await Ve(o,"\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async l=>{let c=Na({withPermission:s,withExtAttrs:a,withDrive:d}),p=await l.request({method:"GET",path:Da(i),query:Object.keys(c).length>0?c:void 0,headers:We(n)});return p.data??p})}catch(o){return ze(o)}}}),t({name:"wps_cloud_doc_search_files",description:"Search files (\u6587\u4EF6\u641C\u7D22): GET `/v7/files/search`. Requires delegated OAuth (`kso.file.search`). Use SenderId as `wps_user_id`. Required query: `type` (`file_name` | `content` | `all`), `page_size` (default 50, max 500). Supports optional filters: keyword, file_type, file_exts, drive_ids, parent_ids, creator_ids, modifier_ids, sharer_ids, receiver_ids, time_type/start_time/end_time, with_permission/with_link/with_total, page_token, channels/device_ids/exclude_channels/exclude_file_exts, filter_user_id, file_ext_groups, with_folder, with_drive, order/order_by, scope, search_operator_name.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId)."},keyword:{type:"string",description:"Optional search keyword."},type:{type:"string",enum:[...Mi],description:"Search type."},file_type:{type:"string",enum:[...Wi],description:"Optional file type filter."},file_exts:{type:"array",items:{type:"string"},description:"Optional file extension filters."},drive_ids:{type:"array",items:{type:"string"},description:"Optional drive id filters."},parent_ids:{type:"array",items:{type:"string"},description:"Optional parent id filters."},creator_ids:{type:"array",items:{type:"string"},description:"Optional creator id filters."},modifier_ids:{type:"array",items:{type:"string"},description:"Optional modifier id filters."},sharer_ids:{type:"array",items:{type:"string"},description:"Optional sharer id filters."},receiver_ids:{type:"array",items:{type:"string"},description:"Optional receiver id filters."},time_type:{type:"string",enum:[...zi],description:"Optional time type."},start_time:{type:"number",description:"Optional start time (unix seconds)."},end_time:{type:"number",description:"Optional end time (unix seconds)."},with_permission:{type:"boolean",description:"Optional. Include permission fields."},with_link:{type:"boolean",description:"Optional. Include sharing link fields."},with_total:{type:"boolean",description:"Optional. Include total count in response."},page_size:{type:"number",description:"Optional. Default 50, max 500."},page_token:{type:"string",description:"Optional pagination token."},channels:{type:"array",items:{type:"string"},description:"Optional channel filters."},device_ids:{type:"array",items:{type:"string"},description:"Optional device filters."},exclude_channels:{type:"array",items:{type:"string"},description:"Optional excluded channel filters."},exclude_file_exts:{type:"array",items:{type:"string"},description:"Optional excluded file extension filters."},filter_user_id:{type:"number",description:"Optional filter user id."},file_ext_groups:{type:"array",items:{type:"string"},description:"Optional file extension groups."},with_folder:{type:"boolean",description:"Optional include folder results."},with_drive:{type:"boolean",description:"Optional include drive info."},order:{type:"string",enum:[...Li],description:"Optional order."},order_by:{type:"string",enum:[...Bi],description:"Optional order by field."},scope:{type:"array",items:{type:"string"},description:"Optional search scopes."},search_operator_name:{type:"boolean",description:"Optional search by operator name switch."},x_kso_id_type:{type:"string",enum:["internal","external"],description:"Optional. Sent as X-Kso-Id-Type."}},required:["wps_user_id","type"]},async execute(r,n){try{let o=D(n,"wps_user_id"),i=D(n,"type");if(!Mi.includes(i))throw new Error("type must be one of: file_name, content, all");let s=i,a=$(n,"file_type");if(a!==void 0&&!Wi.includes(a))throw new Error("file_type must be one of: folder, file, shortcut");let d=a,l=$(n,"time_type");if(l!==void 0&&!zi.includes(l))throw new Error("time_type must be one of: ctime, mtime, otime, stime");let c=l,p=$(n,"order");if(p!==void 0&&!Li.includes(p))throw new Error("order must be one of: desc, asc");let u=p,_=$(n,"order_by");if(_!==void 0&&!Bi.includes(_))throw new Error("order_by must be one of: ctime, mtime");let f=_,y=G(n,"scope");if(y!==void 0){for(let h of y)if(!Ia.includes(h))throw new Error("scope items must be one of: all, share_by_me, share_to_me, latest, personal_drive, group_drive, recycle, customize, latest_opened, latest_edited")}return await Ve(o,"\u6587\u4EF6\u641C\u7D22","\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u641C\u7D22\u4E91\u6587\u6863\u6587\u4EF6\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",async h=>{let m=Ua({keyword:$(n,"keyword"),type:s,fileType:d,fileExts:G(n,"file_exts"),driveIds:G(n,"drive_ids"),parentIds:G(n,"parent_ids"),creatorIds:G(n,"creator_ids"),modifierIds:G(n,"modifier_ids"),sharerIds:G(n,"sharer_ids"),receiverIds:G(n,"receiver_ids"),timeType:c,startTime:yt(n,"start_time"),endTime:yt(n,"end_time"),withPermission:oe(n,"with_permission"),withLink:oe(n,"with_link"),withTotal:oe(n,"with_total"),pageSize:yt(n,"page_size"),pageToken:$(n,"page_token"),channels:G(n,"channels"),deviceIds:G(n,"device_ids"),excludeChannels:G(n,"exclude_channels"),excludeFileExts:G(n,"exclude_file_exts"),filterUserId:yt(n,"filter_user_id"),fileExtGroups:G(n,"file_ext_groups"),withFolder:oe(n,"with_folder"),withDrive:oe(n,"with_drive"),order:u,orderBy:f,scope:y,searchOperatorName:oe(n,"search_operator_name")}),g=await h.request({method:"GET",path:_a,query:m,headers:We(n)});return g.data??g})}catch(o){return ze(o)}}})}var ja="/v7/airpage/files";function Ye(e,t){return`/v7/airpage/${encodeURIComponent(e.trim())}${t}`}function Qe(e){return{arg:Buffer.from(JSON.stringify(e),"utf8").toString("base64")}}function Ze(e,t){return e.length>36?`${t} (${e.slice(0,36)}...)`:`${t} (${e})`}function Xi(e,t){let r=e.operation,n=e.blockId;if(typeof r!="string"||!r.trim())throw new Error(`${t}.operation is required and must be a non-empty string`);if(typeof n!="string"||!n.trim())throw new Error(`${t}.blockId is required and must be a non-empty string`)}var bn=["rename","fail","overwrite"];function Oe(e){return{error:e instanceof Error?e.message:String(e)}}function q(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function Ji(e,t){let r=e[t];if(r==null)return;if(typeof r!="string")throw new Error(`${t} must be a string`);let n=r.trim();return n===""?void 0:n}function pr(e,t){let r=e[t];if(!Array.isArray(r))throw new Error(`${t} is required and must be an array`);return r}function Ma(e,t){let n=pr(e,t).map(o=>String(o).trim()).filter(Boolean);if(n.length===0)throw new Error(`${t} must contain at least one non-empty string`);return n}function Wa(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return Math.max(0,Math.trunc(r));if(typeof r=="string"&&r.trim()!==""){let n=Number(r.trim());if(Number.isFinite(n))return Math.max(0,Math.trunc(n))}throw new Error(`${t} must be a finite integer when provided`)}}function lr(e,t){let r=e[t];if(r==null)throw new Error(`${t} is required and must be a finite integer`);if(typeof r=="number"&&Number.isFinite(r))return Math.trunc(r);if(typeof r=="string"&&r.trim()!==""){let n=Number(r.trim());if(Number.isFinite(n))return Math.trunc(n)}throw new Error(`${t} must be a finite integer`)}function za(e){let t={blockId:e.blockId.trim(),content:e.content},r=e.index;return r!==void 0&&(t.index=r),Qe(t)}function La(e){let t={blockId:e.blockId.trim()};return Qe(t)}function Ba(e){let t={blockIds:e.blockIds.map(r=>r.trim()).filter(Boolean)};if(t.blockIds.length===0)throw new Error("blockIds must contain at least one non-empty id");return Qe(t)}function Fa(e){if(e.endIndex<=e.startIndex)throw new Error("endIndex must be greater than startIndex");let t={blockId:e.blockId.trim(),startIndex:Math.trunc(e.startIndex),endIndex:Math.trunc(e.endIndex)};if(!t.blockId)throw new Error("blockId must be non-empty");return Qe(t)}function Ga(e){if(!Array.isArray(e)||e.length===0)throw new Error("delete_items must contain at least one delete range");let t=e.map(r=>{let n=r.blockId.trim(),o=Math.trunc(r.startIndex),i=Math.trunc(r.endIndex);if(!n)throw new Error("delete_items.blockId must be non-empty");if(i<=o)throw new Error("delete_items.endIndex must be greater than delete_items.startIndex");return{blockId:n,startIndex:o,endIndex:i}});return Qe(t)}function Ka(e){return Xi(e,"operation"),Qe(e)}function Ha(e){if(!Array.isArray(e)||e.length===0)throw new Error("operations must contain at least one operation object");for(let[t,r]of e.entries()){if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`operations[${t}] must be an object`);Xi(r,`operations[${t}]`)}return Qe(e)}function Ja(e){let t=e.trim().toLowerCase();if(bn.includes(t))return t;throw new Error(`on_name_conflict must be one of: ${bn.join(", ")} (got: ${e})`)}function Xa(e){let t={drive_id:e.driveId,name:e.name,on_name_conflict:e.onNameConflict};return e.parentId!==void 0&&(t.parent_id=e.parentId),e.templateId!==void 0&&(t.template_id=e.templateId),t}async function Le(e,t,r){try{return await ce({wpsUserId:e,authCardOriginalMessage:t,needsAuthMessage:"\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u64CD\u4F5C\u667A\u80FD\u6587\u6863\uFF08Airpage\uFF09\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u7528\u6237\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5\u3002",logTag:"airpage",run:r})}catch(n){return Oe(n)}}function In(e,t){t({name:"wps_airpage_create_file",description:"Create a blank Smart Document (Airpage / \u667A\u80FD\u6587\u6863) via WPS OpenAPI: POST `/v7/airpage/files`. Requires user delegated OAuth with scope `kso.airpage.readwrite` (or equivalent). Use SenderId as `wps_user_id`. Required: `drive_id`, `name` (document title without file extension), `on_name_conflict` (`rename` | `fail` | `overwrite`). Optional: `parent_id` (parent folder id), `template_id` (create from template). Obtain `drive_id` via `wps_cloud_doc_list_drives`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},drive_id:{type:"string",description:"Target drive id (from wps_cloud_doc_list_drives)."},name:{type:"string",description:"Document name without extension (per API)."},on_name_conflict:{type:"string",enum:[...bn],description:"Strategy when the name already exists: rename, fail, or overwrite."},parent_id:{type:"string",description:"Optional parent folder id."},template_id:{type:"string",description:"Optional template id to create from."}},required:["wps_user_id","drive_id","name","on_name_conflict"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"drive_id"),s=q(n,"name"),a=q(n,"on_name_conflict"),d=Ja(a),l=Ji(n,"parent_id"),c=Ji(n,"template_id"),p=`\u521B\u5EFA\u667A\u80FD\u6587\u6863: ${s}`;return await Le(o,p,async u=>{let _=Xa({driveId:i,name:s,onNameConflict:d,parentId:l,templateId:c}),f=await u.request({method:"POST",path:ja,body:_});return f.data??f})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_create_block_content",description:'Insert block content into a Smart Document (Airpage): POST `/v7/airpage/{file_id}/blocks/create`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON). JSON fields: `blockId` (parent block; use literal `doc` for document root), optional `index` (insert position; omit for API default 0), required `content` (array of child block nodes). Requires delegated `kso.airpage.readwrite`. Use SenderId as `wps_user_id`.\n\n## Block node types (used in `content` array):\nEach node: `{ type, attrs?, content? }`. `content` is an array of child blocks or inline nodes.\n\n- **title**: Document title (unique, must be first child of doc). attrs: `align` (1=left,2=center,3=right). content: inline nodes.\n- **paragraph**: Paragraph (also used for lists). attrs: `indent` (0|1), `contentIndent` (>=0), `align` (1|2|3), `listAttrs` `{id,type(1=unordered,2=ordered,3=task),styleType(1-13),level,styleFormat(1-9)}`. content: inline nodes.\n- **heading**: Heading h1-h6. attrs: `level` (1-6), `indent`, `contentIndent`, `align`, `listAttrs` (same as paragraph). content: inline nodes.\n- **blockQuote**: Quote block. attrs: `indent`, `contentIndent`, `align`. content: block nodes (paragraph, heading, etc.). Inline `br` for line breaks inside.\n- **codeBlock**: Code block. attrs: `lang` (1=plaintext,2=css,3=go,4=python,5=shell,...19=javascript,12=typescript,17=json,43=yaml, etc.), `autoWrap` (bool), `theme` (1=light,2=dark). content: text nodes (may contain `\\n`).\n- **highLightBlock**: Highlight block. attrs: `emoji` (required), `style {fontColor(1-12),backgroundColor(1-6),borderColor}`. content: block nodes. Cannot contain title, table, column, highLightBlock, lockBlock.\n- **lockBlock**: Content protection area (only file creator can edit). No attrs. content: block nodes. Cannot contain title, lockBlock.\n- **table**: Table. attrs: `borderStyle` (1=none,2=solid). content: tableRow nodes.\n - **tableRow**: Table row. No attrs. content: tableCell nodes.\n - **tableCell**: Cell. attrs: `width`, `height`, `colspan` (>=1), `rowspan` (>=1), `verticalAlign` (1=top,2=middle,3=bottom). content: block nodes.\n- **column**: Column layout (1-10 columns). attrs: `backgroundColor` (1-12). content: columnItem nodes.\n - **columnItem**: Column item. attrs: `width` (percent string e.g. "50.00%"), `backgroundColor` (1-42). content: block nodes.\n- **pictureColumn**: Side-by-side images (2-5). attrs: `width` (percent), `align` (1|2|3). content: picture nodes.\n- **picture**: Image. attrs (required: sourceKey, width, height): `sourceKey` (image resource id from attachment upload), `width`, `height`, `renderWidth`, `caption`, `rotate` (0|-90|-180|-270), `borderType` (0|1), `align`. No content.\n- **blockAnchor**: Placeholder. attrs (required: id, aimType, width, height): `id`, `aimType` (\'picture\'|\'video\'|\'processon\'|\'spreadsheet\'), `width`, `height`. No content.\n- **hr**: Horizontal rule. No attrs, no content.\n- **video**: Video. attrs (required: sourceId, sourceKey, width, height): `sourceId`, `sourceKey` (cover image id), `width`, `height`, `title`, `align`.\n- **audio**: Audio. attrs (required: sourceId): `sourceId`, `title`.\n- **videoLink**: Video link. attrs (required: url): `url`, `platform` (1=bilibili), `align`.\n- **countdown**: Countdown. attrs (required: type): `type` (1=date,2=time), `duration` (ms, 0-86399999000).\n- **map**: Map (Amap). attrs (required: lng, lat, address, addressName): `lng`, `lat`, `address`, `addressName`, `platform` (1), `mapZoom`, `align`.\n- **thirdResource**: 3rd-party embed. attrs (required: url): `url`, `type` (1=mooc,2=modao,3=masterGo,4=netease,5=aliyun,6=survey,7=figma,8=pixso,9=xiaohuazhuo), `align`.\n- **dbsheet**: Multi-dim table. attrs (required: sourceId): `sourceId`, `width`, `height`.\n- **spreadsheet**: Spreadsheet. attrs (required: sourceId): `sourceId`, `sheetId`.\n- **groupCard**: Group card. attrs (required: id, name, masterName): `id`, `name`, `masterName`.\n- **appComponent**: App plugin. attrs: `type` (1=vote,2=video_channel,...8=canvas).\n- **processon**: Flowchart/mindmap. attrs (required: type, sourceId, sourceKey, width, height): `type` (1=flow,2=mind), `sourceId`, `sourceKey`, `caption`, `rotate`, `width`, `height`, `renderWidth`, `borderType`, `align`.\n\n## Inline node types (used in content of paragraph, heading, blockQuote, title, codeBlock):\n- **text**: Text. `content` field is a non-empty string (only in codeBlock may contain `\\n`). Common attrs: `bold`, `italic`, `underline`, `strike`, `sup`, `sub` (all bool); `fontSize {fontSize: 9|11|13|15|16|19|22}`; `color {fontColor,backgroundColor,fontGradientColor(1-6)}`.\n- **emoji**: Emoji. attrs (required: emoji): single emoji character.\n- **br**: Line break (used inside blockQuote). No attrs.\n- **latex**: Formula. attrs (required: width, height, latexStr): `width`, `height`, `latexStr`.\n- **linkView**: Hyperlink view. attrs (required: title, url, viewType, sourceKey, description): `title`, `url`, `viewType` (1=title,2=card \u2014 card requires paragraph parent with no siblings), `sourceKey` (icon id), `description`.\n- **schedule**: Schedule. attrs (required: id, name, startTime, endTime): `id` (taskId|sid|teamId), `name`, `startTime` (unix ms), `endTime` (unix ms), `actionType` (1=partial,2=allday).\n- **staticTime**: Date. attrs (required: time): `time` (unix ms), `timeType` (1=date,2=datetime).\n- **WPSUser**: @mention. attrs (required: userId, name): `userId`, `name`, `avatar`.\n- **WPSDocument**: Cloud doc / local file. attrs (required: wpsDocumentId, wpsDocumentName, wpsDocumentType): `wpsDocumentId`, `wpsDocumentName`, `wpsDocumentType`, `wpsDocumentLink` (required for cloud doc), `viewType` (1=title,2=preview,3=card,4=attachment \u2014 2/3/4 require paragraph parent with no siblings), `size` (bytes, required for local file), `width`, `height`, `align`.\n\n## Examples:\nParagraph: `{"type":"paragraph","content":[{"type":"text","content":"Hello"}]}`\nHeading h2: `{"type":"heading","attrs":{"level":2},"content":[{"type":"text","content":"Title"}]}`\nBold text: `{"type":"paragraph","content":[{"type":"text","attrs":{"bold":true},"content":"bold text"}]}`\nOrdered list: `{"type":"paragraph","attrs":{"listAttrs":{"type":2,"styleType":4,"level":0}},"content":[{"type":"text","content":"item 1"}]}`\nCode block: `{"type":"codeBlock","attrs":{"lang":19},"content":[{"type":"text","content":"console.log(\'hi\')"}]}`\nTable 2x2: `{"type":"table","attrs":{"borderStyle":2},"content":[{"type":"tableRow","content":[{"type":"tableCell","attrs":{"width":200,"height":40},"content":[{"type":"paragraph","content":[{"type":"text","content":"A1"}]}]},{"type":"tableCell","attrs":{"width":200,"height":40},"content":[{"type":"paragraph","content":[{"type":"text","content":"B1"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"width":200,"height":40},"content":[{"type":"paragraph","content":[{"type":"text","content":"A2"}]}]},{"type":"tableCell","attrs":{"width":200,"height":40},"content":[{"type":"paragraph","content":[{"type":"text","content":"B2"}]}]}]}]}`',parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/create)."},block_id:{type:"string",description:"Parent block id. Use the string `doc` to insert under the document root; otherwise use a block id from the query-document-blocks API."},index:{type:"integer",description:"Optional insert position (0-based, must be >= 0). 0 = insert before first child. To append at the end, use a large number (e.g. 9999) or omit this field. Negative values are NOT supported and will cause API errors."},content:{type:"array",description:"Required array of block nodes to insert. Each node has `type` (string), optional `attrs` (object), and optional `content` (child nodes or text string for text nodes). See description above for all supported block and inline types.",items:{type:"object",additionalProperties:!0}}},required:["wps_user_id","file_id","block_id","content"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),s=q(n,"block_id"),a=pr(n,"content"),d=Wa(n,"index"),l=za({blockId:s,content:a,index:d}),c=Ze(i,"\u667A\u80FD\u6587\u6863\u521B\u5EFA\u5757\u5185\u5BB9");return await Le(o,c,async p=>{let u=await p.request({method:"POST",path:Ye(i,"/blocks/create"),body:l});return u.data??u})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_query_document_blocks",description:"Query blocks from a Smart Document (Airpage): POST `/v7/airpage/{file_id}/blocks`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON). JSON fields: required `blockId` (use literal `doc` to query the whole document tree, or pass a specific block id to query its children). Requires delegated Airpage permission (`kso.airpage.read` or `kso.airpage.readwrite` depending on app grants). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks)."},block_id:{type:"string",description:"Target block id mapped to request JSON field blockId. Use doc to query entire document blocks."}},required:["wps_user_id","file_id","block_id"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),s=q(n,"block_id"),a=La({blockId:s}),d=Ze(i,"\u667A\u80FD\u6587\u6863\u67E5\u8BE2\u6587\u6863\u5757");return await Le(o,d,async l=>{let c=await l.request({method:"POST",path:Ye(i,"/blocks"),body:a});return c.data??c})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_batch_query_document_blocks",description:"Batch query blocks from a Smart Document (Airpage): POST `/v7/airpage/{file_id}/blocks/batch_get`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON), with JSON field `blockIds` (string array). Use this when querying multiple specific block ids in one request. Requires delegated Airpage permission (`kso.airpage.read` or `kso.airpage.readwrite`). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/batch_get)."},block_ids:{type:"array",description:"Required block id list mapped to JSON blockIds for batch query.",items:{type:"string"}}},required:["wps_user_id","file_id","block_ids"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),s=Ma(n,"block_ids"),a=Ba({blockIds:s}),d=Ze(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u67E5\u8BE2\u6587\u6863\u5757");return await Le(o,d,async l=>{let c=await l.request({method:"POST",path:Ye(i,"/blocks/batch_get"),body:a});return c.data??c})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_delete_block_content",description:"Delete block content from a Smart Document (Airpage): POST `/v7/airpage/{file_id}/blocks/delete`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON), with JSON fields: `blockId`, `startIndex`, `endIndex` (`endIndex` must be > `startIndex`). Use SenderId as `wps_user_id`. Requires delegated `kso.airpage.readwrite`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/delete)."},block_id:{type:"string",description:"Parent block id mapped to JSON field blockId. Commonly use doc for document root."},start_index:{type:"integer",description:"Required delete start position (mapped to JSON startIndex)."},end_index:{type:"integer",description:"Required delete end position (mapped to JSON endIndex), must be greater than start_index."}},required:["wps_user_id","file_id","block_id","start_index","end_index"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),s=q(n,"block_id"),a=lr(n,"start_index"),d=lr(n,"end_index"),l=Fa({blockId:s,startIndex:a,endIndex:d}),c=Ze(i,"\u667A\u80FD\u6587\u6863\u5220\u9664\u5757\u5185\u5BB9");return await Le(o,c,async p=>{let u=await p.request({method:"POST",path:Ye(i,"/blocks/delete"),body:l});return u.data??u})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_batch_delete_block_content",description:"Batch delete block content ranges from a Smart Document (Airpage): POST `/v7/airpage/{file_id}/blocks/batch_delete`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON), with JSON as an array of delete-range objects: `[{ blockId, startIndex, endIndex }]` and each item requires `endIndex > startIndex`. Use SenderId as `wps_user_id`. Requires delegated `kso.airpage.readwrite`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/batch_delete)."},delete_items:{type:"array",description:"Required delete range array. Each item: block_id, start_index, end_index (end_index > start_index).",items:{type:"object",properties:{block_id:{type:"string"},start_index:{type:"integer"},end_index:{type:"integer"}},required:["block_id","start_index","end_index"]}}},required:["wps_user_id","file_id","delete_items"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),a=pr(n,"delete_items").map((c,p)=>{if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`delete_items[${p}] must be an object`);let u=c,_=q(u,"block_id"),f=lr(u,"start_index"),y=lr(u,"end_index");return{blockId:_,startIndex:f,endIndex:y}}),d=Ga(a),l=Ze(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u5220\u9664\u5757\u5185\u5BB9");return await Le(o,l,async c=>{let p=await c.request({method:"POST",path:Ye(i,"/blocks/batch_delete"),body:d});return p.data??p})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_update_document_block",description:"Update Smart Document blocks via Airpage operation object: POST `/v7/airpage/{file_id}/blocks/update`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON) of ONE operation object (e.g. update_content, update_attrs, insert_table_rows, insert_table_columns, delete_table_rows, delete_table_columns, merge_table_cells, split_table_cell, replace_anchor, replace_feature). At minimum operation JSON should contain `operation` and `blockId`; other fields depend on operation type. Use SenderId as `wps_user_id`. Requires delegated `kso.airpage.readwrite`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/update)."},operation:{type:"object",description:"Required operation object that will be encoded as arg JSON. Must include operation + blockId. Example: {operation:'update_content', blockId:'xxx', content:[...]}",additionalProperties:!0}},required:["wps_user_id","file_id","operation"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),s=n.operation;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("operation is required and must be an object");let d=Ka(s),l=Ze(i,"\u667A\u80FD\u6587\u6863\u66F4\u65B0\u6587\u6863\u5757");return await Le(o,l,async c=>{let p=await c.request({method:"POST",path:Ye(i,"/blocks/update"),body:d});return p.data??p})}catch(o){return Oe(o)}}}),t({name:"wps_airpage_batch_update_document_blocks",description:"Batch update Smart Document blocks via Airpage operation array: POST `/v7/airpage/{file_id}/blocks/batch_update`. Body is `{ arg }` where `arg` is Base64(UTF-8 JSON) of an operation object array. Each operation object must include `operation` + `blockId`; other fields depend on operation type (update_content, update_attrs, insert_table_rows, insert_table_columns, delete_table_rows, delete_table_columns, merge_table_cells, split_table_cell, replace_anchor, replace_feature). Use SenderId as `wps_user_id`. Requires delegated `kso.airpage.readwrite`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},file_id:{type:"string",description:"Smart document file id (path segment in /v7/airpage/{file_id}/blocks/batch_update)."},operations:{type:"array",description:"Required operation object array. Each item must include operation + blockId; extra fields depend on operation type.",items:{type:"object",additionalProperties:!0}}},required:["wps_user_id","file_id","operations"]},async execute(r,n){try{let o=q(n,"wps_user_id"),i=q(n,"file_id"),a=pr(n,"operations").map((c,p)=>{if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`operations[${p}] must be an object`);return c}),d=Ha(a),l=Ze(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u66F4\u65B0\u6587\u6863\u5757");return await Le(o,l,async c=>{let p=await c.request({method:"POST",path:Ye(i,"/blocks/batch_update"),body:d});return p.data??p})}catch(o){return Oe(o)}}})}var Va="/v7/meeting_rooms",Ya="/v7/meeting_rooms/search",Za="/v7/meeting_room_bookings/batch_get",Qa=["success","failed"];var Zi=["success","failed","approving"];function Ut(e){return{error:e instanceof Error?e.message:String(e)}}function Ae(e,t){let r=e[t];if(typeof r!="string"||!r.trim())throw new Error(`${t} is required and must be a non-empty string`);return r.trim()}function wt(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`${t} must be a string`);return r}}function kn(e,t){let r=e[t];if(r!=null){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}}function Vi(e,t){let r=e[t];if(r==null)throw new Error(`${t} is required and must be a finite number`);if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}throw new Error(`${t} must be a finite number`)}function ed(e,t){let r=e[t];if(r!=null){if(typeof r=="boolean")return r;if(r==="true"||r==="false")return r==="true";throw new Error(`${t} must be a boolean`)}}function Qi(e,t){let r=e[t];if(r==null)return;if(!Array.isArray(r))throw new Error(`${t} must be an array`);let n=[];for(let o of r){if(typeof o!="string")throw new Error(`${t} entries must be strings`);let i=o.trim();i!==""&&n.push(i)}return n.length>0?n:void 0}function td(e,t){let r=Qi(e,t);if(r===void 0)return;let n=new Set(Zi),o=r.filter(i=>n.has(i));return o.length>0?o:void 0}function Yi(e){let t=wt(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let r=t.trim();if(r!=="internal"&&r!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":r}}function rd(e){let t=e.pageSize??20,n={page_size:Math.max(1,Math.min(500,Math.trunc(t)))};return e.roomLevelId!==void 0&&e.roomLevelId.trim()!==""&&(n.room_level_id=e.roomLevelId.trim()),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(n.page_token=e.pageToken.trim()),n}function nd(e){let t=e.trim();if(!t)throw new Error("room_id must be a non-empty string");return`/v7/meeting_rooms/${encodeURIComponent(t)}`}function id(e){let t=e.keyword.trim();if(!t)throw new Error("keyword is required and must be a non-empty string");let r=e.pageSize??20,n=Math.max(1,Math.min(100,Math.trunc(r))),o={keyword:t,page_size:n};return e.pageToken!==void 0&&e.pageToken.trim()!==""&&(o.page_token=e.pageToken.trim()),o}function od(e){let t=Math.trunc(Number(e.startTimeSec)),r=Math.trunc(Number(e.endTimeSec));if(!Number.isFinite(t)||!Number.isFinite(r))throw new Error("start_time and end_time must be finite Unix timestamps in seconds");if(r<t)throw new Error("end_time must be >= start_time (Unix seconds)");let n=e.roomLevelId?.trim()??"",o=n!=="",i=e.roomIds?.filter(c=>c.trim()!=="").map(c=>c.trim())??[],s=i.length>0;if(o&&s)throw new Error("Provide either room_ids or room_level_id, not both");if(!o&&!s)throw new Error("Provide exactly one of room_ids (non-empty array) or room_level_id");let a=e.pageSize??20,d=Math.max(1,Math.min(500,Math.trunc(Number(a))));if(!Number.isFinite(d))throw new Error("page_size must be finite");let l={start_time:t,end_time:r,page_size:d};return o&&(l.room_level_id=n),s&&(l.room_ids=i),e.includeDeleted===!0&&(l.include_deleted=!0),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(l.page_token=e.pageToken.trim()),e.results!==void 0&&e.results.length>0&&(l.results=[...e.results]),l}function sd(e){let t=e.trim();if(!t)throw new Error("booking_id must be a non-empty string");return`/v7/meeting_room_bookings/${encodeURIComponent(t)}/update_status`}function ad(e){let t=e.trim();if(t!=="success"&&t!=="failed")throw new Error("status must be success or failed");return{status:t}}function Sn(e,t){t({name:"wps_meeting_rooms_list",description:"List meeting rooms (\u67E5\u8BE2\u4F1A\u8BAE\u5BA4\u5217\u8868): GET `/v7/meeting_rooms`. Uses **application** access_token (client_credentials); requires app scopes **`kso.meeting_rooms.read`** or **`kso.meeting_rooms.readwrite`** on the Open Platform (often **app-only**, not user OAuth). Still pass SenderId as `wps_user_id` for session context (not sent as HTTP user identity). Optional: `room_level_id` (\u4F1A\u8BAE\u5BA4\u5C42\u7EA7 id), `page_size` (default 20, max 500), `page_token` (omit on first page). Response `data` typically includes `items[]` (id, name, capacity, level_id, disable, remark, device_list, tag_list) and `next_page_token`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},room_level_id:{type:"string",description:"Optional. Meeting room level id (\u4F1A\u8BAE\u5BA4\u5C42\u7EA7 id)."},page_size:{type:"number",description:"Optional. Items per page (default 20 per API, max 500 client cap)."},page_token:{type:"string",description:"Optional. Pagination token from data.next_page_token; omit for first request."}},required:["wps_user_id"]},async execute(r,n){try{Ae(n,"wps_user_id");let o=wt(n,"room_level_id"),i=kn(n,"page_size"),s=wt(n,"page_token"),a=rd({roomLevelId:o,pageSize:i,pageToken:s}),d=await e.request({method:"GET",path:Va,query:a});return d.data??d}catch(o){return Ut(o)}}}),t({name:"wps_meeting_rooms_get",description:"Get meeting room details (\u67E5\u8BE2\u4F1A\u8BAE\u5BA4\u8BE6\u60C5): GET `/v7/meeting_rooms/{room_id}`. Uses **application** access_token; requires app **`kso.meeting_rooms.read`** or **`kso.meeting_rooms.readwrite`**. Pass SenderId as `wps_user_id` for context only. Required: `room_id` from `wps_meeting_rooms_list` items[]. Response `data` is a single room object (id, name, capacity, level_id, disable, remark, device_list, tag_list).",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},room_id:{type:"string",description:"Meeting room id from the meeting room list (\u4F1A\u8BAE\u5BA4 id\uFF0C\u53EF\u901A\u8FC7\u4F1A\u8BAE\u5BA4\u5217\u8868\u67E5\u8BE2)."}},required:["wps_user_id","room_id"]},async execute(r,n){try{Ae(n,"wps_user_id");let o=Ae(n,"room_id"),i=await e.request({method:"GET",path:nd(o)});return i.data??i}catch(o){return Ut(o)}}}),t({name:"wps_meeting_rooms_search",description:"Search meeting rooms by keyword (\u641C\u7D22\u4F1A\u8BAE\u5BA4): POST `/v7/meeting_rooms/search`. Uses **application** access_token; requires app **`kso.meeting_rooms.read`** or **`kso.meeting_rooms.readwrite`**. Pass SenderId as `wps_user_id` for context only. Required body: `keyword` (meeting room name search). Optional: `page_size` (default 20, max 100 per API), `page_token` (omit on first page; use data.next_page_token). Response `data` typically includes `items[]` and `next_page_token`.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},keyword:{type:"string",description:"Search keyword; supports meeting room name (\u641C\u7D22\u5173\u952E\u8BCD\uFF0C\u652F\u6301\u4F1A\u8BAE\u5BA4\u540D\u79F0\u641C\u7D22)."},page_size:{type:"number",description:"Optional. Items per page (default 20 per API, max 100)."},page_token:{type:"string",description:"Optional. Pagination token from data.next_page_token; omit for first request."}},required:["wps_user_id","keyword"]},async execute(r,n){try{Ae(n,"wps_user_id");let o=Ae(n,"keyword"),i=kn(n,"page_size"),s=wt(n,"page_token"),a=id({keyword:o,pageSize:i,pageToken:s}),d=await e.request({method:"POST",path:Ya,body:a});return d.data??d}catch(o){return Ut(o)}}}),t({name:"wps_meeting_room_bookings_batch_get",description:"Batch query meeting room bookings (\u6279\u91CF\u67E5\u8BE2\u4F1A\u8BAE\u5BA4\u9884\u7EA6): POST `/v7/meeting_room_bookings/batch_get`. Uses **application** access_token; requires app **`kso.meeting_rooms.read`** or **`kso.meeting_rooms.readwrite`**. Pass SenderId as `wps_user_id` for context only. Required JSON body params: `start_time`, `end_time` (**Unix timestamps in seconds**). Exactly one of: non-empty **`room_ids`** (string[]) **or** **`room_level_id`** (string)\u2014not both, not neither. Optional: `include_deleted` (boolean, default false), `page_size` (default 20, max 500), `page_token`, `results` filter array (`success`|`failed`|`approving`). Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},start_time:{type:"number",description:"Query window start (**Unix timestamp in seconds**, \u5FC5\u586B)."},end_time:{type:"number",description:"Query window end (**Unix timestamp in seconds**, \u5FC5\u586B)."},room_ids:{type:"array",items:{type:"string"},description:"Meeting room id list. Mutually exclusive with room_level_id."},room_level_id:{type:"string",description:"Meeting room level id. Mutually exclusive with room_ids."},include_deleted:{type:"boolean",description:"Whether to include deleted bookings (\u9ED8\u8BA4 false)."},page_size:{type:"number",description:"Page size (default 20 per API, max 500 client cap)."},page_token:{type:"string",description:"Pagination token; omit on first page when unused."},results:{type:"array",items:{type:"string",enum:[...Zi]},description:"Optional filter by reservation result: success, failed, approving."},x_kso_id_type:{type:"string",enum:["internal","external"],description:"Optional. Maps to HTTP header X-Kso-Id-Type."}},required:["wps_user_id","start_time","end_time"]},async execute(r,n){try{Ae(n,"wps_user_id");let o=Vi(n,"start_time"),i=Vi(n,"end_time"),s=Qi(n,"room_ids"),a=wt(n,"room_level_id"),d=ed(n,"include_deleted"),l=kn(n,"page_size"),c=wt(n,"page_token"),p=td(n,"results"),u=od({startTimeSec:o,endTimeSec:i,roomIds:s,roomLevelId:a,includeDeleted:d,pageSize:l,pageToken:c,results:p??void 0}),_=await e.request({method:"POST",path:Za,body:u,headers:Yi(n)});return _.data??_}catch(o){return Ut(o)}}}),t({name:"wps_meeting_room_bookings_update_status",description:"Update meeting room booking status (\u66F4\u65B0\u4F1A\u8BAE\u5BA4\u9884\u7EA6\u72B6\u6001): POST `/v7/meeting_room_bookings/{booking_id}/update_status`. Uses **application** access_token; requires app **`kso.meeting_rooms.readwrite`** (per API). Pass SenderId as `wps_user_id` for context only. Path: **`booking_id`** from booking list / batch query (`items[].id`). JSON body: **`status`** enum **`success`** (\u9884\u7EA6\u6210\u529F) or **`failed`** (\u9884\u7EA6\u5931\u8D25). Optional `x_kso_id_type` \u2192 `X-Kso-Id-Type` header.",parameters:{type:"object",properties:{wps_user_id:{type:"string",description:"WPS user ID (SenderId). Do NOT call wps_user_search for this."},booking_id:{type:"string",description:"Meeting room booking id (\u4F1A\u8BAE\u5BA4\u9884\u7EA6 id\uFF0C\u53EF\u4ECE\u6279\u91CF\u67E5\u8BE2\u9884\u7EA6\u7B49\u63A5\u53E3 items[].id \u53D6\u5F97)."},status:{type:"string",enum:[...Qa],description:"Updated reservation outcome: success or failed."},x_kso_id_type:{type:"string",enum:["internal","external"],description:"Optional. Maps to HTTP header X-Kso-Id-Type."}},required:["wps_user_id","booking_id","status"]},async execute(r,n){try{Ae(n,"wps_user_id");let o=Ae(n,"booking_id"),i=Ae(n,"status"),s=ad(i),a=await e.request({method:"POST",path:sd(o),body:s,headers:Yi(n)});return a.data??a}catch(o){return Ut(o)}}})}var he={type:"string",description:"WPS user ID (current SenderId). Do NOT call wps_user_search for this."},xe={type:"string",description:"Smart Sheet file ID."},et={type:["integer","string"],description:"Worksheet ID (integer). From wps_airsheet_list_worksheets."};async function dd(e,t,r){return ce({wpsUserId:e,authCardOriginalMessage:"",needsAuthMessage:"\u9700\u8981\u7528\u6237\u6388\u6743\u624D\u80FD\u64CD\u4F5C\u667A\u80FD\u8868\u683C\u3002\u5DF2\u53D1\u9001\u6388\u6743\u5361\u7247\uFF0C\u8BF7\u70B9\u51FB\u300C\u524D\u5F80\u6388\u6743\u300D\u540E\u91CD\u8BD5\u3002",logTag:t,run:r})}function ge(e,t){return async(r,n)=>{try{let o=T(n,"wps_user_id");return await dd(o,e,i=>t(n,i))}catch(o){return ie(o)}}}function xn(e,t){t({name:"wps_airsheet_create_file",description:"Create a Smart Sheet (\u667A\u80FD\u8868\u683C / AirSheet): POST `/v7/airsheet/files`. Creates a new smart sheet file in the specified drive. Required: `drive_id` (from `wps_cloud_doc_list_drives`), `name` (file name, may omit extension; if extension is provided it must be `ksheet`). Optional: `on_name_conflict` (`rename` (default) | `fail`), `parent_id` (folder id, empty = root), `parent_path` (string array of folder names as relative path; auto-created if not exists). Requires delegated OAuth with scope `kso.airsheet.readwrite`. Use SenderId as `wps_user_id`. Response includes `id`, `link_id`, `link_url`, `name`, `parent_id`.",parameters:{type:"object",properties:{wps_user_id:he,drive_id:{type:"string",description:"Target drive id (from wps_cloud_doc_list_drives)."},name:{type:"string",description:"File name. May omit extension; if extension is provided it must be ksheet."},on_name_conflict:{type:"string",enum:["rename","fail"],description:"Optional. Strategy when name conflicts: rename (default) or fail."},parent_id:{type:"string",description:"Optional. Parent folder id. Empty means root directory."},parent_path:{type:"array",items:{type:"string"},description:"Optional. Relative path as array of folder names (not ids). If the path does not exist, the system will auto-create it."}},required:["wps_user_id","drive_id","name"]},execute:ge("wps_airsheet_create_file",async(r,n)=>{let o=T(r,"drive_id"),i=T(r,"name"),s=X(r,"on_name_conflict"),a=X(r,"parent_id"),d=Je(r,"parent_path");if(s&&s!=="rename"&&s!=="fail")throw new Error("on_name_conflict must be 'rename' or 'fail'");let l={drive_id:o,name:i};s&&(l.on_name_conflict=s),a!==void 0&&(l.parent_id=a),d&&d.length>0&&(l.parent_path=d);let c=await n.request({method:"POST",path:"/v7/airsheet/files",body:l});return c.data??c})}),t({name:"wps_airsheet_create_worksheet",description:"Create a worksheet in a Smart Sheet (\u521B\u5EFA\u5DE5\u4F5C\u8868): POST `/v7/airsheet/{file_id}/worksheets`. Creates a new worksheet (tab) inside an existing smart sheet file. Required: `file_id`, `position` (object \u2014 at least one of `after_sheet_id`, `before_sheet_id`, or `end` must be set). Optional: `name` (worksheet name), `col_width` (default column width in pixels). Position rules: set `end: true` to append at the end; or use `after_sheet_id`/`before_sheet_id` (integer) to place relative to an existing sheet. Requires delegated OAuth with scope `kso.airsheet.readwrite`. Use SenderId as `wps_user_id`. Response includes `data.sheet_id` (integer).",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,name:{type:"string",description:"Optional. Worksheet name."},col_width:{type:"number",description:"Optional. Default column width in pixels."},position:{type:"object",description:"Insertion position. Must provide at least one of: after_sheet_id (integer), before_sheet_id (integer), end (boolean, true = append).",properties:{after_sheet_id:{type:"integer",description:"Insert after this sheet id."},before_sheet_id:{type:"integer",description:"Insert before this sheet id."},end:{type:"boolean",description:"If true, append at the end."}}}},required:["wps_user_id","file_id","position"]},execute:ge("wps_airsheet_create_worksheet",async(r,n)=>{let o=T(r,"file_id"),i=X(r,"name"),s=V(r,"col_width"),a=r.position;if(!a||typeof a!="object")throw new Error("position is required and must be an object");let d=a,l={},c=V(d,"after_sheet_id");c!==void 0&&(l.after_sheet_id=c);let p=V(d,"before_sheet_id");p!==void 0&&(l.before_sheet_id=p);let u=re(d,"end");u!==void 0&&(l.end=u);let _={position:l};i!==void 0&&(_.name=i),s!==void 0&&(_.col_width=s);let f=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets`,body:_});return f.data??f})}),t({name:"wps_airsheet_list_worksheets",description:"List worksheets in a Smart Sheet (\u83B7\u53D6 Sheet \u5217\u8868\u4FE1\u606F): GET `/v7/airsheet/{file_id}/worksheets`. Returns all worksheets (tabs) in the specified smart sheet file. Each sheet includes: `sheet_id` (integer), `name`, `index`, `hidden`, `empty`, `max_row`, `max_col`, `resource_type` (et = normal spreadsheet), and `active_area` (col_from, col_to, row_from, row_to \u2014 the editing region). Use this to discover `sheet_id` before reading/writing data. Requires delegated OAuth (`kso.airsheet.read` or `kso.airsheet.readwrite`). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe},required:["wps_user_id","file_id"]},execute:ge("wps_airsheet_list_worksheets",async(r,n)=>{let o=T(r,"file_id"),i=await n.request({method:"GET",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets`});return i.data??i})}),t({name:"wps_airsheet_copy_worksheet",description:"Copy a worksheet (\u590D\u5236\u5DE5\u4F5C\u8868): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/copy`. Duplicates an existing worksheet within the same smart sheet file. Required: `file_id`, `worksheet_id` (integer, from `wps_airsheet_list_worksheets`). Optional: `copy_first_sheet` (boolean \u2014 if true, copies the first sheet regardless of `worksheet_id`). Requires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`. Response includes `data.sheet_id` (integer) \u2014 the new copied sheet's id.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:et,copy_first_sheet:{type:"boolean",description:"Optional. If true, copies the first sheet."}},required:["wps_user_id","file_id","worksheet_id"]},execute:ge("wps_airsheet_copy_worksheet",async(r,n)=>{let o=T(r,"file_id"),i=De(r,"worksheet_id"),s=re(r,"copy_first_sheet"),a={};s!==void 0&&(a.copy_first_sheet=s);let d=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/copy`,body:a});return d.data??d})}),t({name:"wps_airsheet_update_worksheet",description:"Update a worksheet (\u66F4\u65B0\u5DE5\u4F5C\u8868): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/update`. Renames or moves a worksheet within the same smart sheet file. Required: `file_id`, `worksheet_id` (integer). Optional: `name` (new worksheet name), `move_sheet_id` (integer \u2014 reference sheet id for move), `move_type` (`sheet_move_type_before` | `sheet_move_type_after` \u2014 move before/after the reference sheet). Requires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`. Response: `{ code, msg }`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:et,name:{type:"string",description:"Optional. New worksheet name."},move_sheet_id:{type:["integer","string"],description:"Optional. Reference sheet id for repositioning."},move_type:{type:"string",enum:["sheet_move_type_before","sheet_move_type_after"],description:"Optional. Move before or after the reference sheet."}},required:["wps_user_id","file_id","worksheet_id"]},execute:ge("wps_airsheet_update_worksheet",async(r,n)=>{let o=T(r,"file_id"),i=De(r,"worksheet_id"),s=X(r,"name"),a=V(r,"move_sheet_id"),d=X(r,"move_type");if(d&&d!=="sheet_move_type_before"&&d!=="sheet_move_type_after")throw new Error("move_type must be 'sheet_move_type_before' or 'sheet_move_type_after'");let l={};s!==void 0&&(l.name=s),a!==void 0&&(l.move_sheet_id=a),d!==void 0&&(l.move_type=d);let c=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/update`,body:l});return c.data??c})}),t({name:"wps_airsheet_delete_worksheets",description:"Delete worksheets (\u5220\u9664\u5DE5\u4F5C\u8868): POST `/v7/airsheet/{file_id}/worksheets/batch_delete`. Batch-deletes one or more worksheets by their IDs. **This operation is irreversible.** Required: `file_id`, `worksheet_ids` (array of integers \u2014 sheet IDs from `wps_airsheet_list_worksheets`). Requires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`. Response: `{ code, msg }`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_ids:{type:"array",items:{type:"integer"},description:"Array of worksheet IDs (integers) to delete."}},required:["wps_user_id","file_id","worksheet_ids"]},execute:ge("wps_airsheet_delete_worksheets",async(r,n)=>{let o=T(r,"file_id"),i=r.worksheet_ids;if(!Array.isArray(i)||i.length===0)throw new Error("worksheet_ids must be a non-empty array of integers");let s=i.map((d,l)=>{let c=typeof d=="number"?d:parseInt(String(d),10);if(!Number.isFinite(c)||c<0)throw new Error(`worksheet_ids[${l}] must be a non-negative integer`);return c}),a=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/batch_delete`,body:{worksheet_ids:s}});return a.data??a})}),t({name:"wps_airsheet_create_rows",description:"Create rows in a worksheet (\u521B\u5EFA\u884C): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/rows`. Inserts one or more rows with cell data into the specified worksheet. Required: `file_id`, `worksheet_id` (integer). Optional: `range_data` (array of cell objects). Each cell object can include: `col` (integer, 0-based column index), `formula` (string, cell formula or plain value), `op_type` (string, e.g. `cell_operation_type_formula`), `cell_pic_info` (object for image cells: `{ height, width, pic_content, tag }` where tag = `sheet_pic_type_local`). If `range_data` is omitted, an empty row is appended. Requires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`. Response: `{ code, msg }`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:et,range_data:{type:"array",description:"Optional. Array of cell data objects. Each: { col: integer (0-based), formula?: string, op_type?: string, cell_pic_info?: { height: number, width: number, pic_content: string, tag: string } }.",items:{type:"object",properties:{col:{type:"integer",description:"0-based column index."},formula:{type:"string",description:"Cell formula or plain text value."},op_type:{type:"string",description:"Operation type, e.g. cell_operation_type_formula."},cell_pic_info:{type:"object",description:"Image cell info: { height, width, pic_content, tag }.",properties:{height:{type:"number"},width:{type:"number"},pic_content:{type:"string"},tag:{type:"string",description:"e.g. sheet_pic_type_local"}}}}}}},required:["wps_user_id","file_id","worksheet_id"]},execute:ge("wps_airsheet_create_rows",async(r,n)=>{let o=T(r,"file_id"),i=De(r,"worksheet_id"),s={},a=r.range_data;if(a!=null){if(!Array.isArray(a))throw new Error("range_data must be an array");s.range_data=a}let d=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/rows`,body:s});return d.data??d})}),t({name:"wps_airsheet_get_range_data",description:"Get cell range data (\u83B7\u53D6\u5355\u5143\u683C\u9009\u533A\u6570\u636E): GET `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/range_data`. Reads cell values from a rectangular region defined by row/col indices (0-based). Required: `file_id`, `worksheet_id` (integer), `row_from`, `row_to`, `col_from`, `col_to` (all integers). Use `wps_airsheet_list_worksheets` first to get `sheet_id` and `active_area` for valid ranges. Response: `data.range_data` array of cell objects, each with: `cell_text` (display value), `col_from`, `col_to`, `row_from`, `row_to`, `is_cell_pic` (boolean), `num_format`, `original_cell_value` (formula bar value), `pic_content`, `pic_data` (image id for online files), `sha1` (image hash for local images), `tag`. Requires delegated OAuth (`kso.airsheet.read` or `kso.airsheet.readwrite`). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:et,row_from:{type:"integer",description:"Start row index (0-based, inclusive)."},row_to:{type:"integer",description:"End row index (0-based, inclusive)."},col_from:{type:"integer",description:"Start column index (0-based, inclusive)."},col_to:{type:"integer",description:"End column index (0-based, inclusive)."}},required:["wps_user_id","file_id","worksheet_id","row_from","row_to","col_from","col_to"]},execute:ge("wps_airsheet_get_range_data",async(r,n)=>{let o=T(r,"file_id"),i=De(r,"worksheet_id"),s=V(r,"row_from"),a=V(r,"row_to"),d=V(r,"col_from"),l=V(r,"col_to");if(s===void 0||a===void 0||d===void 0||l===void 0)throw new Error("row_from, row_to, col_from, col_to are all required");let c=await n.request({method:"GET",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/range_data`,query:{row_from:s,row_to:a,col_from:d,col_to:l}});return c.data??c})}),t({name:"wps_airsheet_find_cells",description:"Find cells in a worksheet (\u67E5\u627E\u5355\u5143\u683C): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/range_data/find`. Searches cells within a specified range using filter conditions, with optional pagination and deduplication. Required: `file_id`, `worksheet_id`, `filter` (object), `range` (object with row_from/row_to/col_from/col_to). Optional: `ignore_hidden_cell` (boolean, default false \u2014 skip hidden cells), `option_cols` (array of integers \u2014 column indices to get option/dropdown values for), `page` (object: { page: integer (min 1), page_size: integer (default 100) }), `show_total` (boolean, default false \u2014 include total count in response). \n\n**filter structure**: `{ condition: [{ col: integer, info: [{ value: string }], mode: 'filter_mode_and' | 'filter_mode_or' }], duplicates: { col: [integer] }, search: [{ col: integer, value: [string] }] }`. All sub-fields in filter are optional. \n\nResponse: `data.range_data` (matched cells), `data.merge_range_data` (merged cell data), `data.option_col` (option column results with texts/count), `data.result_type` (0=fail, 1=success), `data.total`. Requires delegated OAuth (`kso.airsheet.read` or `kso.airsheet.readwrite`). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:et,filter:{type:"object",description:"Filter conditions. Structure: { condition?: [{ col: int, info: [{ value: string }], mode: 'filter_mode_and'|'filter_mode_or' }], duplicates?: { col: [int] }, search?: [{ col: int, value: [string] }] }."},range:{type:"object",description:"Search range (required). { row_from: int, row_to: int, col_from: int, col_to: int }.",properties:{row_from:{type:"integer",description:"Start row index (0-based)."},row_to:{type:"integer",description:"End row index (0-based)."},col_from:{type:"integer",description:"Start column index (0-based)."},col_to:{type:"integer",description:"End column index (0-based)."}},required:["row_from","row_to","col_from","col_to"]},ignore_hidden_cell:{type:"boolean",description:"Optional. If true, skip hidden cells. Default false."},option_cols:{type:"array",items:{type:"integer"},description:"Optional. Column indices to retrieve option/dropdown values for (relative to range)."},page:{type:"object",description:"Optional pagination. { page: integer (min 1), page_size: integer (default 100) }.",properties:{page:{type:"integer",description:"Page number, min 1."},page_size:{type:"integer",description:"Page size, default 100."}}},show_total:{type:"boolean",description:"Optional. If true, include total count in response. Default false."}},required:["wps_user_id","file_id","worksheet_id","filter","range"]},execute:ge("wps_airsheet_find_cells",async(r,n)=>{let o=T(r,"file_id"),i=De(r,"worksheet_id"),s=r.filter;if(!s||typeof s!="object")throw new Error("filter is required and must be an object");let a=r.range;if(!a||typeof a!="object")throw new Error("range is required and must be an object");let d={filter:s,range:a},l=re(r,"ignore_hidden_cell");l!==void 0&&(d.ignore_hidden_cell=l);let c=r.option_cols;if(c!=null){if(!Array.isArray(c))throw new Error("option_cols must be an array of integers");d.option_cols=c.map((f,y)=>{let h=typeof f=="number"?f:parseInt(String(f),10);if(!Number.isFinite(h)||h<0)throw new Error(`option_cols[${y}] must be a non-negative integer`);return h})}let p=r.page;if(p!=null){if(typeof p!="object")throw new Error("page must be an object");d.page=p}let u=re(r,"show_total");u!==void 0&&(d.show_total=u);let _=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/range_data/find`,body:d});return _.data??_})}),t({name:"wps_airsheet_batch_update_cells",description:"Batch update cell range data (\u66F4\u65B0\u5355\u5143\u683C\u9009\u533A\u6570\u636E): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/range_data/batch_update`. Updates one or more cells in a worksheet. Each cell in `range_data` specifies its position (row_from, row_to, col_from, col_to) and operation type (`op_type`). \n\n**op_type values**: `cell_operation_type_formula` \u2014 set cell value/formula (use `formula` field), `cell_operation_type_picture` \u2014 set cell image (use `cell_pic_info` with height/width/pic_content/tag), `cell_operation_type_format` \u2014 set cell formatting (use `xf` field for styles), `cell_operation_type_merge` \u2014 merge cells (use `merge_type`: merge_type_center / merge_type_content / merge_type_same / merge_type_columns). \n\n**cell_pic_info.tag values**: `sheet_pic_type_local`, `sheet_pic_type_attachment`, `sheet_pic_type_url`. \n\n**xf (format) object** includes: `alc_h` (horizontal align), `alc_v` (vertical align), border colors (`clr_bottom/clr_top/clr_left/clr_right/clr_diag_down/clr_diag_up/clr_inside_horz/clr_inside_vert` \u2014 each `{tint,type,value}`), border styles (`dg_bottom/dg_top/dg_left/dg_right/dg_diag_down/dg_diag_up/dg_inside_horz/dg_inside_vert`), `fill` ({back:{tint,type,value}, fore:{tint,type,value}, type}), `font` ({bls,char_set,color:{tint,type,value},dy_height,italic,name,sss,strikeout,theme_font,uls}), `hidden`, `indent`, `locked`, `mask_cats`, `mask_cats_font`, `numfmt`, `reading_order`, `shrink_to_fit`, `trot`, `wrap`. \n\nRequires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`. Response: `{ code, msg }`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:et,range_data:{type:"array",description:"Array of cell update objects. Each must include: row_from (int), row_to (int), col_from (int), col_to (int), op_type (string). Depending on op_type, also include: formula (string), cell_pic_info (object), merge_type (string), xf (format object).",items:{type:"object",properties:{row_from:{type:"integer",description:"Start row (0-based)."},row_to:{type:"integer",description:"End row (0-based)."},col_from:{type:"integer",description:"Start column (0-based)."},col_to:{type:"integer",description:"End column (0-based)."},op_type:{type:"string",enum:["cell_operation_type_formula","cell_operation_type_picture","cell_operation_type_format","cell_operation_type_merge"],description:"Cell operation type."},formula:{type:"string",description:"Cell value or formula (for op_type=formula)."},cell_pic_info:{type:"object",description:"Image info (for op_type=picture): { height, width, pic_content, tag }."},merge_type:{type:"string",enum:["merge_type_center","merge_type_content","merge_type_same","merge_type_columns"],description:"Merge type (for op_type=merge)."},xf:{type:"object",description:"Format/style object (for op_type=format). See tool description for full structure."}},required:["row_from","row_to","col_from","col_to","op_type"]}}},required:["wps_user_id","file_id","worksheet_id","range_data"]},execute:ge("wps_airsheet_batch_update_cells",async(r,n)=>{let o=T(r,"file_id"),i=De(r,"worksheet_id"),s=r.range_data;if(!Array.isArray(s)||s.length===0)throw new Error("range_data must be a non-empty array");let a=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/range_data/batch_update`,body:{range_data:s}});return a.data??a})}),t({name:"wps_airsheet_batch_delete_cells",description:"Batch delete cell range data (\u5220\u9664\u5355\u5143\u683C\u9009\u533A\u6570\u636E): POST `/v7/airsheet/{file_id}/worksheets/{worksheet_id}/range_data/batch_delete`. Deletes data in specified cell ranges. Caller must ensure row/col indices are within the worksheet's max row/col limits (obtainable via getSheetInfo). \n\nRequired: `file_id`, `worksheet_id`, `range_data` (array of range objects, each with `col_from`, `col_to`, `row_from`, `row_to` \u2014 all integers, required). \n\nOptional: `shift_type` \u2014 how remaining cells shift after deletion. Values: `shift_up` (default, shift up) or `shift_left` (shift left). \n\nResponse: `{ code, msg }`. Requires delegated OAuth (`kso.airsheet.readwrite`). Use SenderId as `wps_user_id`.",parameters:{type:"object",properties:{wps_user_id:he,file_id:xe,worksheet_id:et,range_data:{type:"array",description:"Array of range objects to delete. Each must include col_from, col_to, row_from, row_to (all integers).",items:{type:"object",properties:{col_from:{type:"integer",description:"Start column index (0-based)."},col_to:{type:"integer",description:"End column index (0-based)."},row_from:{type:"integer",description:"Start row index (0-based)."},row_to:{type:"integer",description:"End row index (0-based)."}},required:["col_from","col_to","row_from","row_to"]}},shift_type:{type:"string",enum:["shift_up","shift_left"],description:"Optional. How remaining cells shift after deletion. Default: shift_up."}},required:["wps_user_id","file_id","worksheet_id","range_data"]},execute:ge("wps_airsheet_batch_delete_cells",async(r,n)=>{let o=T(r,"file_id"),i=De(r,"worksheet_id"),s=r.range_data;if(!Array.isArray(s)||s.length===0)throw new Error("range_data must be a non-empty array");let a={range_data:s},d=X(r,"shift_type");d!==void 0&&(a.shift_type=d);let l=await n.request({method:"POST",path:`/v7/airsheet/${encodeURIComponent(o)}/worksheets/${i}/range_data/batch_delete`,body:a});return l.data??l})})}function cd(){return new Proxy({},{get(e,t,r){let n=Kr(),o=Reflect.get(n,t,r);return typeof o=="function"?o.bind(n):o}})}function eo(e){let t=[],r=o=>{e(()=>({name:o.name,label:o.name,description:o.description,parameters:o.parameters,async execute(s,a){let d=await o.execute(s,a);if(d&&typeof d=="object"&&"error"in d)throw new Error(d.error);return{content:[{type:"text",text:JSON.stringify(d,null,2)}],details:d}}}),{name:o.name}),t.push(o.name)},n=cd();return cn(n,r),ln(n,r),_n(n,r),rn(n,r),hn(n,r),gn(n,r),wn(n,r),yn(n,r),In(n,r),Sn(n,r),xn(n,r),console.log(`[wps-xiezuo] OAPI tools registered: ${t.length} tools`),t.length}var ld={id:be,name:"WPS Xiezuo",description:"WPS365 Open Platform channel plugin for OpenClaw",configSchema:Mn(),register(e){ki(e.runtime);let t=e.logger??{info:()=>{},warn:()=>{},error:()=>{}};if(e.registerChannel({plugin:an}),typeof e.registerTool=="function"){t.info(`[${be}] registerTool is available (type: ${typeof e.registerTool})`);try{let r=eo(e.registerTool);t.info(`[${be}] registered ${r} WPS OAPI tool factories`)}catch(r){t.error(`[${be}] tool registration failed: ${r}`)}}else t.warn(`[${be}] registerTool not available (type: ${typeof e.registerTool})`);typeof e.on=="function"?(e.on("before_prompt_build",async(r,n)=>{let o=n;if(o.channelId==="wps-xiezuo"||o.messageProvider==="wps-xiezuo")return{appendSystemContext:["","## WPS \u6D88\u606F\u8DEF\u7531","- \u53D1\u6587\u672C\u5230\u7FA4\u804A/\u7528\u6237\uFF1A`wps_message_send(receiver_type, receiver_id, msg_type='text', content=...)`","- \u6309\u540D\u5B57\u627E\u7FA4\uFF1A\u5148 `wps_chat_find_by_name(keyword=<\u540D\u79F0>)` \u62FF chat_id","- \u56DE\u5F53\u524D\u4F1A\u8BDD\uFF1Areceiver_id \u7528 RawBody \u7684 `chatId`\uFF08\u7FA4\u804A\uFF09\u6216 `SenderId`\uFF08\u5355\u804A\uFF09","","## WPS365 \u65E5\u7A0B / \u65E5\u5386","\u610F\u56FE\u2192\u5DE5\u5177\u3001\u53C2\u6570\u4E0E\u793A\u4F8B\u4EE5 **`skills/wps-calendar/SKILL.md`** \u4E3A\u51C6\uFF08\u968F\u63D2\u4EF6\u52A0\u8F7D\uFF09\u3002\u4EC5\u5141\u8BB8\u901A\u8FC7 **`wps_calendar_*`** \u8C03\u7528\u5F00\u653E\u5E73\u53F0\u7528\u6237\u65E5\u5386\uFF1B\u67D0\u6761\u65E5\u7A0B\u4E0A\u4F1A\u8BAE\u5BA4**\u5217\u8868**/\u6279\u91CF**\u6DFB\u52A0**/\u6279\u91CF**\u5220\u9664**\u5206\u522B\u7528 **`wps_calendar_list_event_meeting_rooms`** / **`wps_calendar_event_meeting_rooms_batch_create`** / **`wps_calendar_event_meeting_rooms_batch_delete`**\uFF1B**\u7981\u6B62**\u7528 .ics\u3001\u672C\u5730\u811A\u672C\u6216\u5176\u5B83\u6377\u5F84\u5192\u5145\u5DF2\u521B\u5EFA/\u5DF2\u67E5\u8BE2\u3002","## WPS365 \u65E5\u7A0B\u4F1A\u8BAE\u5BA4","\u4EE5 **`skills/wps-meeting-room/SKILL.md`** \u4E3A\u51C6\uFF1A\u5217\u8868 **`wps_meeting_rooms_list`**\uFF1B\u641C\u7D22 **`wps_meeting_rooms_search`**\uFF1B\u8BE6\u60C5 **`wps_meeting_rooms_get`**\uFF1B\u6279\u91CF\u9884\u7EA6 **`wps_meeting_room_bookings_batch_get`**\uFF08Unix \u79D2\u65F6\u95F4\u7A97\uFF0C`room_ids`/`room_level_id` \u4E8C\u9009\u4E00\uFF09\uFF1B\u66F4\u65B0\u9884\u7EA6\u72B6\u6001 **`wps_meeting_room_bookings_update_status`**\uFF08`booking_id`\uFF0C`status`=`success`|`failed`\uFF0C\u987B **readwrite**\uFF09\u3002`wps_user_id` \u4F7F\u7528 **SenderId**\uFF1B\u53EF\u9009 **`x_kso_id_type`**\uFF1B\u672A\u6388\u6743\u65F6\u8FD4\u56DE `needsAuth`\u3002","## WPS365 \u4E2A\u4EBA\u5F85\u529E","\u610F\u56FE\u4E0E\u53C2\u6570\u4EE5 **`skills/wps-todo/SKILL.md`** \u4E3A\u51C6\u3002\u521B\u5EFA **`wps_todo_create_personal_task`**\uFF0C\u5217\u4E3E **`wps_todo_list_personal_tasks`**\uFF0C\u8BE6\u60C5 **`wps_todo_get_personal_task`**\uFF0C\u66F4\u65B0 **`wps_todo_update_personal_task`**\uFF0C\u72B6\u6001\u66F4\u65B0 **`wps_todo_update_personal_task_status`**\uFF1B`wps_user_id` \u4F7F\u7528 **SenderId**\uFF0C\u672A\u6388\u6743\u65F6\u540C\u6837\u8FD4\u56DE `needsAuth`\u3002","## WPS365 \u667A\u80FD\u6587\u6863\uFF08Airpage\uFF09","\u4EE5 **`skills/wps-airpage/SKILL.md`** \u4E3A\u51C6\u3002\u65B0\u5EFA\u6587\u6863\uFF1A**`wps_airpage_create_file`**\uFF08`POST /v7/airpage/files`\uFF09\uFF1B\u5411\u6587\u6863\u63D2\u5165\u5757\uFF1A**`wps_airpage_create_block_content`**\uFF08`POST /v7/airpage/{file_id}/blocks/create`\uFF09\uFF1B\u67E5\u8BE2\u6587\u6863\u5757\uFF1A**`wps_airpage_query_document_blocks`**\uFF08`POST /v7/airpage/{file_id}/blocks`\uFF09\uFF1B\u6279\u91CF\u67E5\u8BE2\uFF1A**`wps_airpage_batch_query_document_blocks`**\uFF08`POST /v7/airpage/{file_id}/blocks/batch_get`\uFF09\uFF1B\u5220\u9664\u5757\u5185\u5BB9\uFF1A**`wps_airpage_delete_block_content`**\uFF08`POST /v7/airpage/{file_id}/blocks/delete`\uFF09\uFF1B\u6279\u91CF\u5220\u9664\uFF1A**`wps_airpage_batch_delete_block_content`**\uFF08`POST /v7/airpage/{file_id}/blocks/batch_delete`\uFF09\uFF1B\u66F4\u65B0\u6587\u6863\u5757\uFF1A**`wps_airpage_update_document_block`**\uFF08`POST /v7/airpage/{file_id}/blocks/update`\uFF09\uFF1B\u6279\u91CF\u66F4\u65B0\uFF1A**`wps_airpage_batch_update_document_blocks`**\uFF08`POST /v7/airpage/{file_id}/blocks/batch_update`\uFF09\u3002\u5757\u76F8\u5173\u63A5\u53E3 Body \u5185 **`arg`** \u5747\u4E3A Base64(JSON)\uFF0C\u542B **`blockId`** / **`blockIds`** / `startIndex` / `endIndex` / operation \u6216 operation \u6570\u7EC4\u7ED3\u6784\u3002\u9700 Airpage delegated \u6743\u9650\uFF08\u8BFB\u5199\u6216\u53EA\u8BFB\uFF09\uFF1B\u65B0\u5EFA\u524D\u7528 **`wps_cloud_doc_list_drives`** \u53D6 **`drive_id`**\u3002`wps_user_id` \u4F7F\u7528 **SenderId**\uFF1B\u672A\u6388\u6743\u65F6\u8FD4\u56DE `needsAuth`\u3002","## WPS365 \u4E91\u6587\u6863","\u4E91\u6587\u6863\u53C2\u6570\u4E0E\u7EA6\u675F\u4EE5 **`skills/wps-cloud-doc/SKILL.md`** \u4E3A\u51C6\u3002\u83B7\u53D6\u76D8\u5217\u8868\u7528 **`wps_cloud_doc_list_drives`**\uFF08\u53C2\u6570\u540D `allotee_type/allotee_id`\uFF09\uFF1B\u83B7\u53D6\u5B50\u6587\u4EF6\u5217\u8868\u7528 **`wps_cloud_doc_list_children_files`**\uFF08`drive_id`\u3001`parent_id`\uFF09\uFF1B\u65B0\u5EFA\u6587\u4EF6\uFF08\u5939\uFF09\u7528 **`wps_cloud_doc_create_file`**\uFF1B\u6587\u6863\u5185\u5BB9\u62BD\u53D6\u7528 **`wps_cloud_doc_extract_file_content`**\uFF1B\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F\u7528 **`wps_cloud_doc_get_file_meta`**\uFF1B\u6587\u4EF6\u641C\u7D22\u7528 **`wps_cloud_doc_search_files`**\u3002`wps_user_id` \u5FC5\u987B\u4F7F\u7528 **SenderId**\uFF0C\u672A\u6388\u6743\u65F6\u5DE5\u5177\u8FD4\u56DE `needsAuth` \u5E76\u81EA\u52A8\u4E0B\u53D1\u6388\u6743\u5361\u7247\u3002","`wps_user_id` \u4F7F\u7528\u5165\u7AD9\u4E0A\u4E0B\u6587\u7684 **SenderId**\uFF1B\u4E0D\u8981\u4E3A\u6B64\u8C03\u7528 `wps_user_search`\u3002\u672A\u6388\u6743\u65F6\u5DE5\u5177\u8FD4\u56DE `needsAuth` \u5E76\u5DF2\u53D1\u6388\u6743\u5361\u7247\uFF0C\u5F15\u5BFC\u7528\u6237\u5B8C\u6210\u6388\u6743\u540E\u518D\u8BD5\u3002","","## \u53D1\u56FE\u7247/\u6587\u4EF6\uFF08\u672C\u5730\u5DF2\u4E0B\u8F7D\u8DEF\u5F84\uFF09","\u5F53 Body \u4E2D\u51FA\u73B0 `[\u5DF2\u4E0B\u8F7D\u56FE\u7247: ...]` \u6216 `[\u5DF2\u4E0B\u8F7D\u6587\u4EF6: ...]` \u6216\u5F15\u7528\u9644\u4EF6\u56DE\u53D1\u6307\u4EE4\u4E2D\u7ED9\u51FA\u4E86\u8DEF\u5F84\uFF0C\u8981\u53D1\u56DE\u7ED9\u7528\u6237\u65F6\uFF1A","\u7528 `message` \u5DE5\u5177\uFF08\u53C2\u6570\u540D\u662F `to` \u548C `message`\uFF0C\u4E0D\u662F receiver_id \u548C content\uFF09\uFF1A",' message(action="send", to="user:<SenderId>", message="\u4E3A\u60A8\u53D1\u56DE\u56FE\u7247", media="<\u8DEF\u5F84>")',"\u26A0\uFE0F `to` \u53C2\u6570\u662F**\u5FC5\u586B**\u7684\uFF01\u7EDD\u5BF9\u4E0D\u80FD\u7701\u7565 `to`\uFF0C\u5426\u5219\u4F1A\u5BFC\u81F4 deMixValue \u9519\u8BEF\u3002","\u26A0\uFE0F `to` \u7684\u503C\u5FC5\u987B\u662F `user:<\u7528\u6237ID>` \u6216 `chat:<\u7FA4ID>`\uFF0C\u4E14 `<...>` \u5185\u53EA\u80FD\u662F **\u88F8 id**\uFF08\u4E0E RawBody \u7684 `chatId` / `SenderId` \u4E00\u81F4\uFF09\u3002","\u26A0\uFE0F \u7981\u6B62\u5199\u6210 `chat:wps:...` \u6216 `user:wps:...`\uFF1A\u4E0D\u8981\u628A `OriginatingFrom` \u91CC\u7684 `wps:` \u524D\u7F00\u62FC\u8FDB id\uFF08\u63D2\u4EF6\u4F1A\u5C3D\u91CF\u7EA0\u6B63\uFF0C\u4F46\u8BEF\u7528 SessionKey \u91CC `:bot:` \u540E\u7684 AK\u2026 \u4ECD\u4F1A\u5931\u8D25\uFF09\u3002","\u63D2\u4EF6\u4F1A\u81EA\u52A8\u5B8C\u6210\u4E0A\u4F20\u548C\u53D1\u9001\uFF0C\u4E0D\u9700\u8981\u4F60\u624B\u52A8\u8C03\u7528 upload\u3002","","## \u6536\u5230\u56FE\u7247/\u6587\u4EF6\u65F6\u7684\u884C\u4E3A\u51C6\u5219","- \u7528\u6237\u76F4\u63A5\u53D1\u9001\u56FE\u7247\u6216\u6587\u4EF6\u65F6\uFF08\u6CA1\u6709\u9644\u52A0\u6587\u5B57\u6307\u4EE4\uFF09\uFF0C**\u4E0D\u8981\u81EA\u52A8\u53D1\u56DE**\uFF0C\u5E94\u8BE2\u95EE\u7528\u6237\u9700\u8981\u4EC0\u4E48\u64CD\u4F5C\u3002","- \u53EA\u6709\u5F53\u7528\u6237\u660E\u786E\u8981\u6C42\u300C\u53D1\u56DE\u6765\u300D\u300C\u8F6C\u53D1\u300D\u300C\u53D1\u7ED9\u6211\u300D\u7B49\u64CD\u4F5C\u65F6\uFF0C\u624D\u4F7F\u7528 message \u5DE5\u5177\u53D1\u56DE\u3002","","## \u4E91\u6587\u4EF6\uFF08cloud file\uFF09","\u5F53 Body \u4E2D\u51FA\u73B0 `[\u5F15\u7528\u4E91\u6587\u4EF6: ...]` \u6216 `[\u4E91\u6587\u4EF6\u94FE\u63A5: ...]` \u65F6\uFF0C\u8FD9\u662F WPS \u4E91\u6587\u4EF6\uFF08\u65E0\u672C\u5730\u8DEF\u5F84\uFF09\u3002","\u5F53 Body \u4E2D\u51FA\u73B0\u77E5\u8BC6\u5E93\u94FE\u63A5\uFF08\u5982 `www.kdocs.cn/wiki/l/0lxxxx` \u6216 `{\u4F01\u4E1A\u57DF\u540D}.kdocs.cn/wiki/l/0lxxxx`\uFF09\u65F6\uFF0C\u8DEF\u5F84\u4E2D **`0l` \u4E4B\u540E\u7684 xxxx** \u4E3A link_id\uFF0C\u53EF\u4F5C\u4E3A file_id \u4F7F\u7528\u3002","\u7981\u6B62\u4F7F\u7528 wps_message_send \u4EE5 msg_type='file' + cloud \u7ED3\u6784\u8F6C\u53D1\u4E91\u6587\u4EF6\uFF08\u5E94\u7528 token \u4E0D\u652F\u6301\uFF0C\u4F1A\u8FD4\u56DE 400 InvalidMessage\uFF09\u3002","\u5982\u9700\u8BFB\u53D6\u4E91\u6587\u4EF6\u5185\u5BB9\uFF0C\u8C03\u7528 wps_cloud_doc_get_file_meta(file_id, with_drive=true) \u83B7\u53D6 drive_id\uFF0C\u518D\u8C03\u7528 wps_cloud_doc_extract_file_content(drive_id, file_id) \u62BD\u53D6\u6B63\u6587\u3002","\u5982\u9700\u5411\u7528\u6237\u5206\u4EAB\u4E91\u6587\u4EF6\uFF0C\u7528 wps_message_send \u53D1\u9001\u4E00\u6761\u5305\u542B link_url \u7684\u6587\u672C\u6D88\u606F\u5373\u53EF\uFF08\u53EA\u53D1\u4E00\u6761\uFF0C\u4E0D\u8981\u91CD\u590D\u53D1\u9001\uFF09\u3002","","\u26A0\uFE0F \u7981\u6B62\u4F7F\u7528 sessions_send \u5411 WPS \u4F1A\u8BDD\u53D1\u6D88\u606F\uFF08sessions_send \u4EC5\u7528\u4E8E OpenClaw \u5185\u90E8\u4F1A\u8BDD\u95F4\u901A\u4FE1\uFF0C\u65E0\u6CD5\u6295\u9012\u5230 WPS \u5BA2\u6237\u7AEF\uFF09\u3002\u7981\u6B62\u628A\u672C\u5730\u6587\u4EF6\u8DEF\u5F84\u5F53\u7EAF\u6587\u672C\u56DE\u590D\u3002","\u26A0\uFE0F \u7981\u6B62\u544A\u8BC9\u7528\u6237\u53BB WPS \u754C\u9762\u624B\u52A8\u53D1\u9001\uFF1B\u6709 **`wps_message_send`** / **`message`** \u80FD\u529B\u65F6\u5FC5\u987B\u76F4\u63A5\u6267\u884C\u3002"].join(`
36
+ `)}}),t.info(`[${be}] before_prompt_build hook registered`)):t.warn(`[${be}] api.on not available, cannot register prompt hook`),t.info(`[${be}] plugin registered`)}},rp=ld;export{rp as default};
37
37
  //# sourceMappingURL=__bundle.tmp.js.map