@wps365/openclaw-wpsxiezuo 1.8.1 → 1.8.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.mjs CHANGED
File without changes
package/dist/index.js CHANGED
@@ -32,6 +32,6 @@ ${(t?e.slice(0,Ft):e).join(`
32
32
 
33
33
  For multi-account channels, approve with:
34
34
  openclaw pairing approve --channel ${v} --account ${i} ${B}`;await nt(c,E,$t)}}}return}if(!k){let O=a?.groupPolicy??"allowlist",B=a?.groups??{};if(O==="allowlist"&&!B[y]&&!B["*"]){n(`Group ${y} blocked by groupPolicy=allowlist`);return}}if(Ke.trim()==="/wpsxiezuo auth"){let{sendAuthCard:O}=await Promise.resolve().then(()=>(Bt(),zn)),{getLazyWpsCfg:B}=await Promise.resolve().then(()=>(tt(),ei));try{let G=y?"chat":"user",Ue=y||_;await O({creds:c,wpsCfg:B(),wpsUserId:_,receiverType:G,receiverId:Ue})||await nt(c,E,"\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(G){r("WPS /wpsxiezuo auth failed:",G),await nt(c,E,`\u6388\u6743\u5361\u7247\u53D1\u9001\u5931\u8D25\uFF1A${String(G)}`)}return}if(Ke.trim()==="/wps-id"||Ke.trim().startsWith("/wps-id ")){let O={sender:{id:p.id??"",type:p.type??"",name:p.name??""},chat:{id:u?.id??"",type:u?.type??""},message:{id:d.id??"",type:d.type??""},isDirect:k};await nt(c,E,`WPS id debug:
35
- ${JSON.stringify(O,null,2)}`);return}if(!s){n("WPS: channelRuntime not available \u2014 skipping AI dispatch");return}let A=s.reply,Te=s.routing,Ee="main",Y="",U=i;if(Te?.resolveAgentRoute){let O=Te.resolveAgentRoute({cfg:o,channel:v,accountId:i,peer:{kind:k?"direct":"group",id:h.session_key}});Ee=O.agentId,Y=O.sessionKey?.trim()??"",O.accountId&&(U=O.accountId,n(`WPS route account override: ${i} -> ${O.accountId}`))}let z=Y||h.session_key,hr=U;n(`WPS route: agentId=${Ee}, inboundSessionKey=${z}, accountId=${hr}`);let yr={Body:we,BodyForAgent:we,...oe.length>0?{MediaPath:oe[0],MediaType:ge[0],MediaPaths:oe,MediaTypes:ge}:{},RawBody:JSON.stringify({session:h,chatId:y,messageId:w,messageType:b.kind,plainText:b.plainText,attachments:b.attachments,...ie?{prefetchedMedia:ie}:{}}),CommandBody:we,From:J,To:k?`user:${_}`:`chat:${y}`,SessionKey:z,Label:z,ConversationLabel:z,DisplayName:z,SessionLabel:z,AccountId:hr,ChatType:k?"direct":"group",GroupId:void 0,SenderName:p.name??void 0,SenderId:_,Provider:v,Surface:"wps",Channel:v,Timestamp:l.send_time??Date.now(),OriginatingChannel:v,OriginatingFrom:`wps:${_}`,OriginatingTo:`wps:${c.clientId}`},gr=A.finalizeInboundContext?A.finalizeInboundContext(yr):yr,_t=null;if(y&&w)try{await yn(c,y,w),_t={kind:"reaction",chatId:y,messageId:w},n(`WPS thinking reaction added: chatId=${y}, messageId=${w}`)}catch(O){n(`WPS thinking reaction failed, falling back to text: ${String(O)}`);try{await nt(c,E,"\u6B63\u5728\u601D\u8003\u4E2D..."),_t={kind:"text-fallback"}}catch(B){n(`WPS thinking fallback text failed: ${String(B)}`)}}let wr=()=>async(O,B)=>{let G=O.text??"";if(!G)return;let Ue=G.trim();if(/Message:.*[\\/]openclaw-media[\\/].*failed/i.test(Ue)){n(`WPS deliver: suppressed media-failed noise: ${Ue.substring(0,80)}`);return}n(`WPS deliver: text length=${G.length}, preview=${G.substring(0,80)}`),!k&&y&&w?await Fo(c,y,w,G):await nt(c,E,G)};try{if(A.dispatchReplyWithBufferedBlockDispatcher)await A.dispatchReplyWithBufferedBlockDispatcher({ctx:gr,cfg:o,dispatcherOptions:{deliver:wr(),responsePrefix:"",humanDelay:A.resolveHumanDelayConfig?A.resolveHumanDelayConfig(o,Ee):void 0,onError:(O,B)=>{r(`WPS ${B.kind} reply error: ${String(O)}`)}}}),n("WPS: agent dispatch completed");else if(A.dispatchReplyFromConfig&&A.createReplyDispatcherWithTyping){let O=A.resolveHumanDelayConfig?A.resolveHumanDelayConfig(o,Ee):void 0,{dispatcher:B,replyOptions:G,markDispatchIdle:Ue}=A.createReplyDispatcherWithTyping({responsePrefix:"",humanDelay:O,deliver:wr(),onError:($t,zi)=>{r(`WPS ${zi.kind} reply error: ${String($t)}`)}});try{await A.dispatchReplyFromConfig({ctx:gr,cfg:o,dispatcher:B,replyOptions:G})}finally{Ue()}n("WPS: agent dispatch completed (fallback path)")}else n("WPS: channelRuntime.reply dispatch APIs not found, skipping agent dispatch")}finally{_t?.kind==="reaction"&&(await gn(c,_t.chatId,_t.messageId,t),n("WPS thinking reaction removed"))}}catch(P){r("WPS async inbound error:",P)}}tt();Ve();wt();import{createHash as Bo}from"node:crypto";function Go(e){return Bo("sha256").update(e).digest("hex")}var di=20*1024*1024;function Hn(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 Ho(e,t){let n={};for(let[o,i]of Object.entries(e)){if(typeof i!="string")continue;let s=o.trim();if(!s)continue;let a=s.toLowerCase();a==="content-length"||a==="transfer-encoding"||(n[s]=i)}return Object.keys(n).some(o=>o.trim().toLowerCase()==="content-type")||(n["Content-Type"]=t),n}async function Kn(e,t,n,r,o){let i=o?.info??console.log,s=o?.error??console.error,a=r.byteLength;if(a===0)throw new Error("upload content is empty");if(a>di)throw new Error(`file too large: ${a} bytes (max ${di})`);let c=Go(r);i(`[upload] phase1 start: fileName=${t} fileType=${n} size=${a} checksum=${c.substring(0,16)}\u2026`);let l=await e.request({method:"POST",path:"/v7/chats/resources/upload",body:{file_name:t,file_size:a,file_type:n,checksum:c}}),d=l.data??l;if(!d||typeof d!="object")throw new Error(`upload phase 1 returned no data: ${JSON.stringify(l).substring(0,300)}`);let p=d.data,u=p&&typeof p=="object"?p:d;i(`[upload] phase1 response keys: source=[${Object.keys(u)}] hasNested=${!!p}`);let f=u.upload_entry;f&&i(`[upload] upload_entry keys: [${Object.keys(f)}]`);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():f&&typeof f.url=="string"&&f.url.trim()?f.url.trim():null,h=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(d).substring(0,300)}`);if(!h)throw new Error(`upload phase 1 did not return a storage_key: keys=${JSON.stringify(Object.keys(u))}`);i(`[upload] phase1 ok: storageKey=${h.substring(0,20)}\u2026 uploadUrl=${m.substring(0,80)}\u2026`);let g=f&&typeof f.headers=="object"&&f.headers&&Object.keys(f.headers).length>0,_=Ho(g?f.headers:{},n);i(`[upload] phase2 PUT headers: ${JSON.stringify(_)}`);let y=await fetch(m,{method:"PUT",headers:_,body:r});if(!y.ok){let w=await y.text().catch(()=>"");throw s(`[upload] phase2 PUT failed: HTTP ${y.status} body=${w.substring(0,300)}`),new Error(`upload phase 2 PUT failed: HTTP ${y.status} ${w.substring(0,200)}`)}return i(`[upload] phase2 PUT ok: HTTP ${y.status} storageKey=${h.substring(0,20)}\u2026`),{storage_key:h,file_name:t,file_size:a}}function Gn(e){return e.data??null}function Gt(e){return{error:e instanceof Error?e.message:String(e)}}function te(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function Ko(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} is required and must be a finite number`)}function Jo(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number when provided`)}}function Jn(e,t,n){let r=n?.info??(()=>{}),o=n?.error??(()=>{});t({name:"wps_media_download",description:"Obtain a pre-signed download URL for a message attachment or resource (GET /v7/chats/{chat_id}/messages/{message_id}/resources/{storage_key}/download). Use storage_key from inbound message attachments (WPS cloud). Do NOT use the generic read() tool with the attachment display filename \u2014 that file is not on the OpenClaw workspace disk. The returned data typically includes a short-lived URL for HTTP GET.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"Chat id containing the message."},message_id:{type:"string",description:"Message id that owns the resource."},storage_key:{type:"string",description:"Resource storage key from the message."}},required:["chat_id","message_id","storage_key"]},async execute(i,s){try{let a=encodeURIComponent(te(s,"chat_id")),c=encodeURIComponent(te(s,"message_id")),l=encodeURIComponent(te(s,"storage_key")),d=await e.request({method:"GET",path:`/v7/chats/${a}/messages/${c}/resources/${l}/download`});return Gn(d)}catch(a){return Gt(a)}}}),t({name:"wps_media_fetch_base64",description:"Fetch attachment bytes from WPS and return base64 (no shell/exec required). It internally calls the WPS media download endpoint, follows the pre-signed URL, and returns `{ mime_type, size, base64 }`. Use this when you need OCR or image understanding in-tool; do NOT call exec/curl manually.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"Chat id containing the message."},message_id:{type:"string",description:"Message id that owns the resource."},storage_key:{type:"string",description:"Resource storage key from the message."},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=encodeURIComponent(te(s,"chat_id")),c=encodeURIComponent(te(s,"message_id")),l=encodeURIComponent(te(s,"storage_key")),d=Jo(s,"max_bytes")??5*1024*1024;if(d<=0)throw new Error("max_bytes must be positive");r(`[tool:wps_media_fetch_base64] start: chatId=${decodeURIComponent(a)} msgId=${decodeURIComponent(c)} sk=${decodeURIComponent(l).substring(0,20)}\u2026`);let p=await e.request({method:"GET",path:`/v7/chats/${a}/messages/${c}/resources/${l}/download`}),u=Gn(p),f=mn(u),m=await fetch(f);if(!m.ok)throw new Error(`download url request failed: HTTP ${m.status}`);let h=Number(m.headers.get("content-length")??"0");if(Number.isFinite(h)&&h>d)throw new Error(`attachment too large: ${h} bytes > max_bytes=${d}`);let g=m.headers.get("content-type")??"application/octet-stream",_=new Uint8Array(await m.arrayBuffer());if(_.byteLength>d)throw new Error(`attachment too large after download: ${_.byteLength} bytes > max_bytes=${d}`);return r(`[tool:wps_media_fetch_base64] ok: ${g} ${_.byteLength}B`),{chat_id:decodeURIComponent(a),message_id:decodeURIComponent(c),storage_key:decodeURIComponent(l),mime_type:g,size:_.byteLength,base64:Buffer.from(_).toString("base64")}}catch(a){return o("[tool:wps_media_fetch_base64] error:",a),Gt(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=te(s,"file_name"),c=Ko(s,"file_size"),l=te(s,"file_type"),d=te(s,"checksum");if(c<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:c,file_type:l,checksum:d}});return Gn(p)}catch(a){return Gt(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=te(s,"file_name"),c=te(s,"file_type"),l=te(s,"base64"),d=Buffer.from(l,"base64");r(`[tool:wps_media_upload_base64] start: ${a} ${c} ${d.byteLength}B`);let{storage_key:p,file_name:u,file_size:f}=await Kn(e,a,c,d);return r(`[tool:wps_media_upload_base64] ok: storage_key=${p.substring(0,20)}\u2026 ${u} ${f}B`),{storage_key:p,file_name:u,file_size:f}}catch(a){return o("[tool:wps_media_upload_base64] error:",a),Gt(a)}}})}wt();var ts={Debug:0,Info:1,Warn:2,Error:3},rt=null;function li(e){rt=e}function ns(){if(!rt)throw new Error("WPS plugin runtime not initialized");return rt}var Kt="wps",ci={id:v,label:"WPS",selectionLabel:"WPS365 (Open Platform)",docsPath:"/channels/wps-xiezuo",docsLabel:"WPS",blurb:"WPS365 Open Platform bot integration.",aliases:[v,Kt,"wps365"],order:70};function Jt(e){let t=e.channels;if(t)return t[v]??t[Kt]}function Oe(e){return ln(Jt(e))}function rs(){let e=Ht.join(Zo(),".openclaw","openclaw.json");if(!Xo(e))return null;try{let t=Vo(e,"utf8");return t.trim()?JSON.parse(t):null}catch{return null}}function Xn(e){let t=e&&typeof e=="object"?e:null;if(t&&Object.keys(Oe(t)).length>0)return t;let n=rt?.config&&typeof rt.config=="object"?rt.config:null;if(n&&Object.keys(Oe(n)).length>0)return n;let r=rs();return r&&Object.keys(Oe(r)).length>0?r:t??n??r??{}}function V(e){return cn(Jt(e))}function ne(e,t){let n=Oe(e);return n[t]??n[V(e)]??n[Pe]}function is(e,t=Pe){let n=ne(e,t);return{accountId:t,enabled:n?.enabled!==!1,configured:!!de(n),config:n??{enabled:!1}}}function Vn(e){return e.trim().replace(/^wps-xiezuo:/i,"").replace(/^wps:/i,"")}function os(e){return e.trim().length>0}function pi(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 n=e.match(/:p2p:([^:]+)/);if(n)return{type:"user",id:n[1]};let r=e.split(":");if(r.length===2)return{type:"user",id:r[1]};let o=r[2]??r[1],i=r[3]??r[2];return{type:o==="group"?"chat":"user",id:i??r[r.length-1]??e}}return{type:"user",id:e}}async function Yn(e,t,n){let r=N(e),o=M(e.baseUrl,r),i=pi(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:n,type:"markdown"}}}})).data?.message_id??""}}var Zn={id:v,meta:{...ci,aliases:[...ci.aliases]},capabilities:{chatTypes:["direct","group"],media:!0,threads:!0,nativeCommands:!1,blockStreaming:!0},reload:{configPrefixes:[`channels.${v}`,`channels.${Kt}`]},configSchema:Rr(dn),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=Xn(e),n=Object.keys(Oe(t));return n.length>0?n:[Pe]},resolveAccount:e=>{let t=Xn(e);return is(t,V(t))},defaultAccountId:e=>{let t=Xn(e);return V(t)},setAccountEnabled:({cfg:e,enabled:t})=>({...e,channels:{...e.channels,[v]:{...Jt(e),accounts:{...Oe(e),[V(e)]:{...ne(e,V(e))??{},enabled:t}}}}}),deleteAccount:({cfg:e})=>{let t={...e},n={...t.channels},r=Jt(e);if(r){let o=V(e),i={...Oe(e)};delete i[o],n[v]={...r,accounts:i}}else delete n[v],delete n[Kt];return t.channels=Object.keys(n).length>0?n:void 0,t},isConfigured:(e,t)=>!!de(ne(t,e.accountId)),describeAccount:e=>({accountId:e.accountId,enabled:e.enabled,configured:e.configured}),resolveAllowFrom:({cfg:e})=>{let t=e;return ne(t,V(t))?.allowFrom??[]},formatAllowFrom:({allowFrom:e})=>e.map(t=>Vn(String(t)))},security:{resolveDmPolicy:({cfg:e})=>{let t=e,n=V(t),r=ne(t,n);return{policy:r?.dmPolicy??"pairing",allowFrom:r?.allowFrom??[],policyPath:`channels.${v}.accounts.${n}.dmPolicy`,allowFromPath:`channels.${v}.accounts.${n}.allowFrom`,approveHint:Cr(v),normalizeEntry:Vn}},collectWarnings:({cfg:e})=>{let t=[],n=Oe(e);for(let[r,o]of Object.entries(n))o.dmPolicy==="open"&&t.push(`- WPS account '${r}' DMs are open to anyone. Set channels.${v}.accounts.${r}.dmPolicy="pairing" or "allowlist" for security.`),(o.groupPolicy??"allowlist")==="open"&&t.push(`- WPS account '${r}' groups: groupPolicy="open" allows any group to trigger. Set channels.${v}.accounts.${r}.groupPolicy="allowlist".`);return t}},pairing:{idLabel:"wpsUserId",normalizeAllowEntry:Vn,notifyApproval:async({cfg:e,id:t})=>{let n=e,r=ne(n,V(n)),o=de(r);if(!o)throw new Error("WPS credentials not configured");await Yn(o,`user:${t}`,"Your pairing request has been approved. You can now chat with this bot.")}},groups:{resolveRequireMention:({cfg:e,groupId:t})=>{let n=e,r=ne(n,V(n));return!r?.groups||!t?!0:(r.groups[t]??r.groups["*"])?.requireMention??!0},resolveToolPolicy:()=>{}},outbound:{deliveryMode:"direct",textChunkLimit:5e3,chunker:(e,t)=>ns().channel.text.chunkMarkdownText(e,t),chunkerMode:"markdown",resolveTarget:({to:e,allowFrom:t})=>{let n=e?.trim()??"";if(n&&os(n))return{ok:!0,to:n};let r=t?.[0];return r?{ok:!0,to:String(r).trim()}:{ok:!1,error:new Error("WPS target is required (user_id or chat_id)")}},sendText:async({cfg:e,to:t,text:n})=>{let r=e,o=ne(r,V(r)),i=de(o);if(!i)throw new Error("WPS credentials not configured");return Yn(i,t,n)},sendMedia:async({cfg:e,to:t,mediaUrl:n,mimeType:r})=>{let o=e,i=ne(o,V(o)),s=de(i);if(!s)throw new Error("WPS credentials not configured");let a=N(s),c=M(s.baseUrl,a),l=pi(t),d=(n??"").trim();if(!d)throw new Error("WPS sendMedia requires mediaUrl");let p,u,f=(r??"").trim()||"application/octet-stream",m=null;if(Hn(d)){let _=await Yo(d),y=Ht.basename(d)||"attachment";if(p=/^[0-9a-f]{8}_/.test(y)?y.substring(9):y,!(r??"").trim()){let b=Ht.extname(p).toLowerCase();f={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"}[b]??"application/octet-stream"}f.startsWith("image/")&&(m=Ar(_),console.log(`[${v}] sendMedia: parsed dimensions ${m?`${m.width}x${m.height}`:"(null)"} for ${p}`)),u=_.byteLength,d=(await Kn(c,p,f,_)).storage_key}let g=f.startsWith("image/")?{type:"image",receiver:{type:l.type,receiver_id:l.id},content:{image:{storage_key:d,...f.startsWith("image/")?{type:f}:{},...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:d,...p?{name:p}:{},...u!==void 0?{size:u}:{}}}}};return c.request({method:"POST",path:"/v7/messages/create",body:g})}},status:{defaultRuntime:{accountId:Pe,running:!1,lastStartAt:null,lastStopAt:null,lastError:null},collectStatusIssues:e=>e.flatMap(t=>{let n=[];return t.enabled&&!t.configured&&n.push({channel:v,accountId:t.accountId,kind:"config",message:"WPS credentials not configured (appId and appSecret required).",fix:`Set channels.${v}.accounts.${t.accountId}.appId and channels.${v}.accounts.${t.accountId}.appSecret.`}),n}),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=de(e.config);if(!t)return{ok:!1,error:"Not configured"};try{return{ok:!0,token:(await N(t).getToken()).substring(0,8)+"..."}}catch(n){return{ok:!1,error:String(n)}}},buildAccountSnapshot:({account:e,runtime:t,probe:n})=>({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:n})},gateway:{startAccount:async e=>{let t=ne(e.cfg,e.accountId);if(!t?.enabled){e.log?.info?.(`[${e.accountId}] WPS provider disabled`);return}let n=de(t);if(!n){e.log?.error?.(`[${e.accountId}] WPS credentials not configured`);return}let r=async()=>{},o=a=>{Bn({cfg:e.cfg,accountId:e.accountId,channelRuntime:e.channelRuntime??void 0,wpsCfg:t,creds:n,eventPayload:a,log:e.log}).catch(c=>e.log?.error?.("WPS inbound handler error:",c))},i=!1;if(t.sdk?.enabled)try{let a=Qo,c=es,l=ts,p={debug:l.Debug,warn:l.Warn,error:l.Error}[t.sdk.logLevel??"info"]??l.Info,u=new c().onV7AppChatMessageCreate(async g=>{try{let _=g.parsedData;e.log?.info?.(`[WPS SDK][${e.accountId}/${n.clientId}] message: chat_id=${_.chat.id}, message_id=${_.message.id}`);let y=Lr(_);o(y)}catch(_){e.log?.error?.("WPS SDK message handler error:",_)}}).onV7AppGroupChatMemberRobotCreate(async g=>{let _=g.parsedData;if(e.log?.info?.(`[WPS SDK] robot joined group: chat_id=${_.chat_id}`),t.robotJoinGroupMessage!==void 0){let y=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=N(n);await M(n.baseUrl,w).request({method:"POST",path:"/v7/messages/create",body:{type:"text",receiver:{type:"chat",receiver_id:_.chat_id},content:{text:{content:y,type:"markdown"}}}})}catch(w){e.log?.error?.("WPS welcome message failed:",w)}}}).onV7AppGroupChatMemberRobotDelete(async g=>{e.log?.info?.(`[WPS SDK] robot left group: chat_id=${g.parsedData.chat_id}`)}).registerFallbackFunc(g=>{let _=null;if(g.parsedData&&typeof g.parsedData=="object")_=g.parsedData;else if(typeof g.data=="string"&&g.data)try{_=JSON.parse(g.data)}catch{}let y=_?Object.keys(_).join(","):"N/A";if(e.log?.info?.(`[WPS SDK] unhandled event: ${g.eventCode}, keys=${y}`),_&&e.log?.info?.(`[WPS SDK] event payload: ${JSON.stringify(_).slice(0,500)}`),_){let w=typeof _.code=="string"?_.code:typeof _.authorization_code=="string"?_.authorization_code:void 0,b=typeof _.state=="string"?_.state:void 0;if(w){let k=typeof _.user_id=="string"?_.user_id:void 0;e.log?.info?.(`[WPS SDK] Auth code detected: eventCode=${g.eventCode}, code=${w.slice(0,8)}..., state=${b??"(none)"}, userId=${k??"(none)"}`),(async()=>{try{let{handleAuthEvent:E}=await Promise.resolve().then(()=>(Bt(),zn));await E({code:w,state:b??"",creds:n,wpsCfg:t,log:e.log,userId:k})}catch(E){e.log?.error?.(`[WPS SDK] Auth event handling failed: ${String(E)}`)}})()}}}),f=new a(Fr({appId:n.clientId,appSecret:n.clientSecret,dispatcher:u,logLevel:p,endpoint:t.sdk.endpoint},t.sdk));f.start().catch(g=>{e.log?.error?.("WPS SDK client.run ended:",g)});let m=t.sdk.connectTimeoutMs??2e4,h=Date.now()+m;for(;Date.now()<h&&!f.isConnected();)await new Promise(g=>setTimeout(g,150));if(f.isConnected()){i=!0,e.log?.info?.("[WPS SDK] long connection established");let g=()=>f.stop();e.abortSignal.addEventListener("abort",g),r=async()=>{e.abortSignal.removeEventListener("abort",g),f.stop()}}else f.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"),c=(a.default||a)();c.use(a.json());let l=t.webhook?.port??3e3,d=t.webhook?.path??"/wps/webhook",p=t.enableEncryption!==!1;c.post(d,(f,m)=>{let h=zr(f.body,{appId:n.clientId,appSecret:n.clientSecret},p,e.log);if("challenge"in h){m.status(200).json({challenge:h.challenge});return}if(!h.ok){let g=h.status??200;g===200?m.status(200).json({code:0,msg:"ok"}):m.status(g).json({code:-1,msg:h.error});return}m.status(200).json({code:0,msg:"ok"}),o(h.payload)});let u=c.listen(l,()=>{e.log?.info?.(`[${e.accountId}] WPS webhook listening on :${l}${d}`)});r=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=N(n),c=M(n.baseUrl,a);Nn(c,e.log,t,n),pn({appId:n.clientId,appSecret:n.clientSecret,baseUrl:n.baseUrl}),e.log?.info?.(`[${e.accountId}] WPS client initialized for OAPI tools`);try{let d=((await c.request({method:"GET",path:`/v7/developer/apps/${encodeURIComponent(n.clientId)}`})).data?.scopes??[]).filter(p=>p.auth_types?.includes("delegated")).map(p=>({name:p.name??"",description:p.description??""})).filter(p=>p.name);zt(d),e.log?.info?.(`[${e.accountId}] Delegated scopes: ${d.map(p=>p.name).join(", ")||"(none)"}`)}catch(l){zt([]);let d=String(l);d.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: ${d}`)}}catch(a){e.log?.error?.(`[${e.accountId}] WPS client init failed:`,a)}return qr(e.abortSignal,r)}},onboarding:{channel:v,getStatus:async({cfg:e})=>{let t=e,n=ne(t,V(t)),r=!!de(n);return{channel:v,configured:r,statusLines:[`WPS: ${r?"configured":"needs appId and appSecret"}`],selectionHint:r?"configured":"needs credentials",quickstartScore:r?2:1}},configure:async({cfg:e})=>({cfg:e})},agentPrompt:{messageToolHints:e=>["- 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>`)."]},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,n=e.params.message??e.params.text??e.params.content,r=e.params.media,o=e.cfg,i=ne(o,V(o)),s=de(i);if(!s)throw new Error("WPS credentials not configured");let a=t&&typeof t=="string"&&t.trim()?t.trim():"";if(r&&typeof r=="string"&&r.trim()){let l=r.trim();if(Hn(l)){if(!a)throw new Error("WPS send with media requires 'to' (e.g. 'user:<id>' or 'chat:<id>')");return await Zn.outbound.sendMedia({cfg:e.cfg,to:a,mediaUrl:l,mimeType:void 0}),{text:`Media sent (${Ht.basename(l)||"attachment"})`}}}if(!a)throw new Error("WPS send requires 'to' (e.g. 'user:<id>' or 'chat:<id>')");if(!n||typeof n!="string"||!n.trim())throw new Error("WPS send requires 'message' or 'text'");return{text:`Message sent (id: ${(await Yn(s,a,n.trim())).messageId})`}}}};tt();function Xt(e){return e.data??null}function Vt(e){return{error:e instanceof Error?e.message:String(e)}}function le(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function Qn(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function ss(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function ui(e){try{return JSON.parse(e)}catch{throw new Error("content must be valid JSON matching the WPS message content structure")}}function as(e,t){if(e==="text"){try{let r=JSON.parse(t);if(r&&typeof r=="object"&&"text"in r)return{type:"text",content:r}}catch{}return{type:"text",content:{text:{content:t,type:"markdown"}}}}let n=ui(t);if(typeof n!="object"||n===null)throw new Error(`content for ${e} must be a JSON object (message content subtree)`);return e==="rich_text"?{type:"rich_text",content:n}:{type:"image",content:n}}function er(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:{}}},required:["receiver_type","receiver_id","msg_type","content"]},async execute(n,r){try{let o=le(r,"receiver_type");if(o!=="user"&&o!=="chat")throw new Error("receiver_type must be 'user' or 'chat'");let i=le(r,"receiver_id"),s=le(r,"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=le(r,"content");if(a.length>5e3)throw new Error("content JSON string exceeds 5000 characters");let c=ui(a);if(typeof c!="object"||c===null)throw new Error("parsed content must be a JSON object");let l={type:s,receiver:{type:o,receiver_id:i},content:c},d=r.mentions;if(d!==void 0){if(!Array.isArray(d))throw new Error("mentions must be an array when provided");l.mentions=d}let p=await e.request({method:"POST",path:"/v7/messages/create",body:l});return Xt(p)}catch(o){return Vt(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:"Chat session id."},message_id:{type:"string",description:"Message id to reply to."},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(n,r){try{let o=encodeURIComponent(le(r,"chat_id")),i=encodeURIComponent(le(r,"message_id")),s=le(r,"msg_type");if(s!=="text"&&s!=="rich_text"&&s!=="image")throw new Error("msg_type must be text, rich_text, or image");let a=le(r,"content"),c=as(s,a),l=await e.request({method:"POST",path:`/v7/chats/${o}/messages/${i}/reply`,body:c});return Xt(l)}catch(o){return Vt(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:"Chat session id."},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(n,r){try{let o=encodeURIComponent(le(r,"chat_id")),i=Qn(r,"start_time"),s=Qn(r,"end_time"),a=Qn(r,"page_size")??50,c=ss(r,"page_token"),l={page_size:a};c!==void 0&&(l.page_token=c),i!==void 0&&(l.start_time=Math.trunc(i*1e3)),s!==void 0&&(l.end_time=Math.trunc(s*1e3));let d=await e.request({method:"GET",path:`/v7/chats/${o}/messages`,query:l});return Xt(d)}catch(o){return Vt(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:"Chat session id."},message_id:{type:"string",description:"Message id."}},required:["chat_id","message_id"]},async execute(n,r){try{let o=encodeURIComponent(le(r,"chat_id")),i=encodeURIComponent(le(r,"message_id")),s=await e.request({method:"GET",path:`/v7/chats/${o}/messages/${i}`});return Xt(s)}catch(o){return Vt(o)}}})}function _i(e){return e.data??null}function fi(e){return{error:e instanceof Error?e.message:String(e)}}function ds(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function cs(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function ls(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}var ps=["active"],us=["user_name","email","phone"],_s=["company_user"],fs=50;function tr(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(n,r){try{let o=await e.request({method:"GET",path:"/v7/users/current"});return _i(o)}catch(o){return fi(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(n,r){try{let o=ds(r,"keyword"),i=cs(r,"page_size")??fs,s=ls(r,"page_token"),a={keyword:o,status:[...ps],search_field:[...us],search_source:[..._s],page_size:i};s!==void 0&&(a.page_token=s);let c=await e.request({method:"GET",path:"/v7/users/search",query:a});return _i(c)}catch(o){return fi(o)}}})}function Tt(e){return e.data??null}function it(e){return{error:e instanceof Error?e.message:String(e)}}function Et(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function mi(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function nr(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}var hi=50;function ms(e,t){let n=e[t];if(!Array.isArray(n)||n.length===0)throw new Error(`${t} must be a non-empty array of user id strings`);let r=[];for(let o=0;o<n.length;o++){let i=n[o];if(typeof i!="string"||!i.trim())throw new Error(`${t}[${o}] must be a non-empty string`);r.push(i.trim())}return r}function rr(e,t="user"){return{id:e,type:t}}var Yt=null;async function hs(e){if(Yt)return Yt;let n=(await e.request({method:"GET",path:"/v7/users/current"})).data;if(!n||typeof n.id!="string"||!n.id.trim())throw new Error("Cannot retrieve current operator identity from /v7/users/current. Ensure the app has kso.user_base.read permission.");return Yt={id:n.id.trim(),type:"user"},Yt}function ir(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(n,r){try{let o=Et(r,"type");if(o!=="p2p"&&o!=="group")throw new Error("type must be 'p2p' or 'group'");let i=ms(r,"member_ids"),s,a={type:o};if(o==="group"){let l=await hs(e),d=new Set;s=[],d.add(l.id),s.push(rr(l.id));for(let u of i)d.has(u)||(s.push(rr(u)),d.add(u));a.owner_id=l.id;let p=nr(r,"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(d=>rr(d))}a.account_id_list=s;let c=await e.request({method:"POST",path:"/v7/chats/create",body:a});return Tt(c)}catch(o){return it(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(n,r){try{let o=mi(r,"page_size")??hi,i=nr(r,"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 Tt(a)}catch(o){return it(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:"Chat session id."}},required:["chat_id"]},async execute(n,r){try{let o=encodeURIComponent(Et(r,"chat_id")),i=await e.request({method:"GET",path:`/v7/chats/${o}`});return Tt(i)}catch(o){return it(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(n,r){try{let o=encodeURIComponent(Et(r,"chat_id")),i=mi(r,"page_size")??hi,s=nr(r,"page_token"),a={page_size:i};s!==void 0&&(a.page_token=s);let c=await e.request({method:"GET",path:`/v7/chats/${o}/members`,query:a});return Tt(c)}catch(o){return it(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(n,r){try{let o=encodeURIComponent(Et(r,"chat_id")),i=await e.request({method:"GET",path:`/v7/chats/${o}/members/is_in_chat`});return Tt(i)}catch(o){return it(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(n,r){try{let o=Et(r,"keyword").toLowerCase(),i=[],s,a=!1;for(let l=0;l<10;l++){let d={page_size:100};s&&(d.page_token=s);let p=await e.request({method:"GET",path:"/v7/chats",query:d});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 c={};return a&&(c.warning="Results may be incomplete: pagination was truncated due to missing page_token."),i.length===0?{...c,found:!1,message:`No chats found matching "${o}"`}:i.length===1?{...c,found:!0,match:i[0]}:{...c,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 it(o)}}})}Ve();tt();jt();Bt();async function me(e){let t=ht(e.wpsUserId);if(t){let i=Lt(),s=fn(i.baseUrl,t);return await e.run(s)}let n=Mn(),r=Lt(),o=et();try{await Ln({creds:r,wpsCfg:n,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 yi=31*24*60*60*1e3,ys=100,gi=200,wi=50,bi=100;function L(e){return{error:e instanceof Error?e.message:String(e)}}function T(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function x(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function ot(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function st(e,t){let n=e[t];if(n!=null){if(typeof n=="boolean")return n;if(n==="true"||n==="false")return n==="true";throw new Error(`${t} must be a boolean`)}}function gs(e,t){let n=e[t];if(n==null)throw new Error(`${t} is required and must be a finite number`);if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}function Zt(e,t){let n=new Date(t.trim());if(Number.isNaN(n.getTime()))throw new Error(`${e} must be a valid RFC3339 / ISO 8601 datetime string`);return n}function at(e){return e.toISOString()}function or(e){let t=e.now??new Date,n,r,o=!!e.startRfc?.trim(),i=!!e.endRfc?.trim();if(o&&i?(n=Zt("start_time",e.startRfc),r=Zt("end_time",e.endRfc)):o?(n=Zt("start_time",e.startRfc),r=new Date(n.getTime()+14*86400*1e3)):i?(r=Zt("end_time",e.endRfc),n=new Date(r.getTime()-14*86400*1e3)):(n=new Date(t.getTime()-86400*1e3),r=new Date(t.getTime()+14*86400*1e3)),r.getTime()<n.getTime())throw new Error("end_time must be >= start_time (RFC3339 range)");return r.getTime()-n.getTime()>yi&&(r=new Date(n.getTime()+yi)),{start:n,end:r}}function ws(e){let{start:t,end:n}=or({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now}),r={start_time:at(t),end_time:at(n)},o=e.pageSize??30;return r.page_size=Math.max(1,Math.min(500,Math.trunc(o))),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(r.page_token=e.pageToken.trim()),r}function bs(e){let{start:t,end:n}=or({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now});return{start_time:at(t),end_time:at(n)}}function Is(e){let t={},n=e.pageSize??30;if(t.page_size=Math.max(1,Math.min(500,Math.trunc(n))),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:r,end:o}=or({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now});return t.start_time=at(r),t.end_time=at(o),t}function Ss(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 Ie(e,t){return`/v7/calendars/${encodeURIComponent(e)}/events/${encodeURIComponent(t)}`}function xs(e,t){return`${Ie(e,t)}/respond`}function sr(e,t){return`${Ie(e,t)}/attendees`}function ks(e,t){return`${sr(e,t)}/batch_create`}function vs(e,t){return`${sr(e,t)}/batch_delete`}function Ts(e,t){return`${Ie(e,t)}/meeting_rooms`}function Es(e,t){return`${Ie(e,t)}/meeting_rooms/batch_create`}function Ps(e,t){return`${Ie(e,t)}/meeting_rooms/batch_delete`}function Ii(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((n,r)=>{if(typeof n!="string")throw new Error(`room_ids[${r}] must be a string`);let o=n.trim();if(!o)throw new Error(`room_ids[${r}] must be non-empty`);return o});if(t.length>bi)throw new Error(`room_ids length must be <= ${bi}`);return{room_ids:t}}function Os(e){let t=e.pageSize??30,r={page_size:Math.max(1,Math.min(ys,Math.trunc(t)))};return e.pageToken!==void 0&&e.pageToken.trim()!==""&&(r.page_token=e.pageToken.trim()),r}function Ae(e){let t=x(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let n=t.trim();if(n!=="internal"&&n!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":n}}async function H(e,t,n){try{return await me({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:n})}catch(r){return L(r)}}function ar(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=T(i,"summary"),a=T(i,"start_time"),c=x(i,"end_time"),l=c&&c.trim()!==""?c.trim():Ss(a),d=x(i,"description"),p=x(i,"location"),u=x(i,"wps_user_id")??"";return u?await H(u,s,async f=>{let m={summary:s,start_time:{datetime:a},end_time:{datetime:l}};d&&(m.description=d),p&&(m.locations=[{name:p}]);let h=await f.request({method:"POST",path:"/v7/calendars/primary/events/create",body:m});return h.data??h}):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=T(i,"wps_user_id"),a=x(i,"start_time"),c=x(i,"end_time"),l=ot(i,"page_size"),d=x(i,"page_token"),p=st(i,"with_cancelled"),u=x(i,"sync_token"),f=x(i,"anchor_time");return await H(s,"\u67E5\u8BE2\u4E3B\u65E5\u5386\u65E5\u7A0B\u5217\u8868",async m=>{let h=Is({startRfc:a,endRfc:c,pageSize:l,pageToken:d,withCancelled:p,syncToken:u,anchorTime:f}),g=await m.request({method:"GET",path:"/v7/calendars/primary/events",query:h});return g.data??g})}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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary";return await H(s,"\u67E5\u8BE2\u65E5\u7A0B\u8BE6\u60C5",async l=>{let d=await l.request({method:"GET",path:Ie(c,a),headers:Ae(i)});return d.data??d})}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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary",l=ot(i,"page_size"),d=x(i,"page_token");return await H(s,"\u83B7\u53D6\u65E5\u7A0B\u53C2\u4E0E\u8005\u5217\u8868",async p=>{let u=Os({pageSize:l,pageToken:d}),f=await p.request({method:"GET",path:sr(c,a),query:u,headers:Ae(i)});return f.data??f})}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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary",l=st(i,"is_notification"),d=i.attendees;if(!Array.isArray(d)||d.length===0)throw new Error("attendees is required and must be a non-empty array");if(d.length>gi)throw new Error(`attendees length must be <= ${gi}`);let p=d.map((u,f)=>{if(typeof u!="object"||u===null||Array.isArray(u))throw new Error(`attendees[${f}] must be an object`);let m=u,h={};if(m.type!==void 0){if(typeof m.type!="string"||!m.type.trim())throw new Error(`attendees[${f}].type must be a non-empty string when provided`);h.type=m.type.trim()}if(m.user_id!==void 0){if(typeof m.user_id!="string"||!m.user_id.trim())throw new Error(`attendees[${f}].user_id must be a non-empty string when provided`);h.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[${f}].third_party_email must be a non-empty string when provided`);h.third_party_email=m.third_party_email.trim()}if(m.is_optional!==void 0){if(typeof m.is_optional!="boolean")throw new Error(`attendees[${f}].is_optional must be a boolean when provided`);h.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[${f}].response_status must be a non-empty string when provided`);h.response_status=m.response_status.trim()}if(Object.keys(h).length===0)throw new Error(`attendees[${f}] must contain at least one valid field`);return h});return await H(s,"\u6DFB\u52A0\u65E5\u7A0B\u53C2\u4E0E\u8005",async u=>{let f={attendees:p};l!==void 0&&(f.is_notification=l);let m=await u.request({method:"POST",path:ks(c,a),body:f,headers:Ae(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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary";return await H(s,"\u83B7\u53D6\u65E5\u7A0B\u4F1A\u8BAE\u5BA4\u5217\u8868",async l=>{let d=await l.request({method:"GET",path:Ts(c,a),headers:Ae(i)});return d.data??d})}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=T(i,"wps_user_id"),a=T(i,"event_id"),c=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 d=Ii(l);return await H(s,"\u6279\u91CF\u6DFB\u52A0\u65E5\u7A0B\u4F1A\u8BAE\u5BA4",async p=>{let u=await p.request({method:"POST",path:Es(c,a),body:d,headers:Ae(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=T(i,"wps_user_id"),a=T(i,"event_id"),c=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 d=Ii(l);return await H(s,"\u6279\u91CF\u5220\u9664\u65E5\u7A0B\u4F1A\u8BAE\u5BA4",async p=>{let u=await p.request({method:"POST",path:Ps(c,a),body:d,headers:Ae(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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary",l=st(i,"is_notification"),d=i.attendee_ids,p;if(d!==void 0){if(!Array.isArray(d))throw new Error("attendee_ids must be an array of strings when provided");p=d.map((h,g)=>{if(typeof h!="string"||!h.trim())throw new Error(`attendee_ids[${g}] must be a non-empty string`);return h.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 f=u.map((h,g)=>{if(typeof h!="object"||h===null||Array.isArray(h))throw new Error(`attendees[${g}] must be an object`);let _=h,y={};if(_.type!==void 0){if(typeof _.type!="string"||!_.type.trim())throw new Error(`attendees[${g}].type must be a non-empty string when provided`);y.type=_.type.trim()}if(_.user_id!==void 0){if(typeof _.user_id!="string"||!_.user_id.trim())throw new Error(`attendees[${g}].user_id must be a non-empty string when provided`);y.user_id=_.user_id.trim()}if(_.third_party_email!==void 0){if(typeof _.third_party_email!="string"||!_.third_party_email.trim())throw new Error(`attendees[${g}].third_party_email must be a non-empty string when provided`);y.third_party_email=_.third_party_email.trim()}if(Object.keys(y).length===0)throw new Error(`attendees[${g}] must contain at least one valid field`);return y});if((p?.length??0)+f.length>wi)throw new Error(`attendee_ids.length + attendees.length must be <= ${wi}`);return await H(s,"\u5220\u9664\u65E5\u7A0B\u53C2\u4E0E\u8005",async h=>{let g={attendees:f};p&&p.length>0&&(g.attendee_ids=p),l!==void 0&&(g.is_notification=l);let _=await h.request({method:"POST",path:vs(c,a),body:g,headers:Ae(i)});return _.data??_})}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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary",l=T(i,"mod_type");if(l!=="normal"&&l!=="one"&&l!=="all")throw new Error("mod_type must be normal, one, or all");let d=T(i,"response_status");if(d!=="accepted"&&d!=="declined"&&d!=="tentative")throw new Error("response_status must be accepted, declined, or tentative");let p=Math.trunc(gs(i,"which_day_time"));return await H(s,"\u7B54\u590D\u65E5\u7A0B\u9080\u8BF7",async u=>{let f=await u.request({method:"POST",path:xs(c,a),body:{mod_type:l,response_status:d,which_day_time:p}});return f.data??f})}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=T(i,"wps_user_id"),a=x(i,"calendar_id")??"primary",c=x(i,"start_time"),l=x(i,"end_time"),d=ot(i,"page_size"),p=x(i,"page_token");return await H(s,"\u67E5\u8BE2\u65E5\u5386\u65E5\u7A0B\u5B9E\u4F8B\u5217\u8868",async u=>{let f=ws({startRfc:c,endRfc:l,pageSize:d,pageToken:p}),m=await u.request({method:"GET",path:`/v7/calendars/${encodeURIComponent(a)}/event_instances`,query:f});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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary",l=x(i,"start_time"),d=x(i,"end_time");return await H(s,"\u67E5\u8BE2\u5355\u6761\u65E5\u7A0B\u5B9E\u4F8B",async p=>{let u=bs({startRfc:l,endRfc:d}),f=await p.request({method:"GET",path:`${Ie(c,a)}/event_instances`,query:u});return f.data??f})}catch(s){return L(s)}}});let n=100,r=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=T(i,"wps_user_id"),a=T(i,"keyword");if(a.length>n)throw new Error(`keyword must be at most ${n} characters`);let c=x(i,"calendar_id")??"primary",l=ot(i,"page_size"),d=x(i,"page_token");return await H(s,"\u641C\u7D22\u65E5\u7A0B",async p=>{let u={keyword:a},f=l??200;u.page_size=Math.max(1,Math.min(r,Math.trunc(f))),d!==void 0&&d.trim()!==""&&(u.page_token=d.trim());let m=await p.request({method:"POST",path:`/v7/calendars/${encodeURIComponent(c)}/events/search`,body:u,headers:Ae(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=T(i,"wps_user_id"),a=T(i,"event_id"),c=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 d=ot(i,"which_day_time");if(l==="one"&&d==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 f=x(i,"attendee_ability");if(f!==void 0&&f!=="can_see_others"&&f!=="can_invite_others")throw new Error("attendee_ability must be can_see_others or can_invite_others");return await H(s,"\u4FEE\u6539\u65E5\u7A0B",async m=>{let h={},g=x(i,"summary");g!==void 0&&(h.summary=g);let _=x(i,"description");_!==void 0&&(h.description=_);let y=x(i,"start_time");y!==void 0&&(h.start_time={datetime:y});let w=x(i,"end_time");w!==void 0&&(h.end_time={datetime:w});let b=x(i,"location");b!==void 0&&(h.locations=[{name:b}]),p!==void 0&&(h.free_busy_status=p),u!==void 0&&(h.visibility=u),f!==void 0&&(h.attendee_ability=f),l!==void 0&&(h.mod_type=l),d!==void 0&&(h.which_day_time=Math.trunc(d));let k=st(i,"is_notification");k!==void 0&&(h.is_notification=k);let E=st(i,"is_reinvition");E!==void 0&&(h.is_reinvition=E);let J=i.reminders;Array.isArray(J)&&(h.reminders=J.slice(0,10).map(ie=>{let oe=ie;return{minutes:typeof oe.minutes=="number"?Math.trunc(oe.minutes):0}}));let re=await m.request({method:"POST",path:`${Ie(c,a)}/update`,body:h});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=T(i,"wps_user_id"),a=T(i,"event_id"),c=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 d=ot(i,"which_day_time");if(l==="one"&&d===void 0)throw new Error("which_day_time (ms) is required when mod_type is one");let p=st(i,"is_notification");return await H(s,"\u5220\u9664\u65E5\u7A0B",async u=>{let f={};p!==void 0&&(f.is_notification=p),l!==void 0&&(f.mod_type=l),d!==void 0&&(f.which_day_time=Math.trunc(d));let m=await u.request({method:"POST",path:`${Ie(c,a)}/delete`,body:f});return m.data??m})}catch(s){return L(s)}}})}var As="/v7/todo/personal_tasks",$s="/v7/todo/personal_tasks/batch_get";function Qt(e){return`/v7/todo/personal_tasks/${encodeURIComponent(e.trim())}`}function Rs(e){return`${Qt(e.trim())}/update`}function Cs(e){return`${Qt(e.trim())}/update_status`}var Si=100,qs=20,Ds=50;function ct(e){return{error:e instanceof Error?e.message:String(e)}}function Se(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function K(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function We(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function Us(e,t){let n=e[t];if(n==null)return;if(!Array.isArray(n))throw new Error(`${t} must be an array of strings`);let r=n.map(o=>String(o).trim()).filter(Boolean);return r.length>0?r:void 0}function Ns(e,t){let n=e[t];if(n==null)return;if(!Array.isArray(n))throw new Error(`${t} must be an array of objects with name and value`);let r=[];for(let o of n){if(typeof o!="object"||o===null)continue;let i=o;typeof i.name!="string"||typeof i.value!="string"||r.push({name:i.name.trim(),value:i.value})}return r.length>0?r:void 0}function js(e,t){let n=K(e,t);if(!(n===void 0||n.trim()===""))try{let r=JSON.parse(n);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`${t} must be a JSON object`);return r}catch(r){throw r instanceof SyntaxError?new Error(`${t} must be valid JSON`):r}}function dt(e){let t=K(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let n=t.trim();if(n!=="internal"&&n!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":n}}function Ms(e){let t=e.titleSubject.trim();if(!t)throw new Error("title_subject must be non-empty");let n={subject:t};e.titlePrefix!==void 0&&e.titlePrefix.trim()!==""&&(n.prefix=e.titlePrefix.trim());let r={title:n};if(e.description!==void 0&&e.description.trim()!==""&&(r.description=e.description.trim()),e.dueTimeMs!==void 0){if(!Number.isFinite(e.dueTimeMs))throw new Error("due_time_ms must be a finite number");r.due_time=Math.trunc(e.dueTimeMs)}if((e.status==="todo"||e.status==="finish")&&(r.status=e.status),e.executors!==void 0&&e.executors.length>0){if(e.executors.length>Si)throw new Error(`executors must have at most ${Si} entries`);r.executors=[...e.executors]}return r}function Ws(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 n=e.pageSize;t.page_size=Math.max(1,Math.min(Ds,Math.trunc(n)))}else t.page_size=qs;if(e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),e.createdTimeStartMs!==void 0||e.createdTimeEndMs!==void 0){let n={};e.createdTimeStartMs!==void 0&&Number.isFinite(e.createdTimeStartMs)&&(n.start_time=Math.trunc(e.createdTimeStartMs)),e.createdTimeEndMs!==void 0&&Number.isFinite(e.createdTimeEndMs)&&(n.end_time=Math.trunc(e.createdTimeEndMs)),Object.keys(n).length>0&&(t.created_time=n)}if(e.dueTimeStartMs!==void 0||e.dueTimeEndMs!==void 0){let n={};e.dueTimeStartMs!==void 0&&Number.isFinite(e.dueTimeStartMs)&&(n.start_time=Math.trunc(e.dueTimeStartMs)),e.dueTimeEndMs!==void 0&&Number.isFinite(e.dueTimeEndMs)&&(n.end_time=Math.trunc(e.dueTimeEndMs)),Object.keys(n).length>0&&(t.due_time=n)}return t}function Ls(e){let t={},n=e.titleSubject?.trim()??"",r=e.titlePrefix?.trim()??"";if(n!==""||r!==""){let o={};n!==""&&(o.subject=n),r!==""&&(o.prefix=r),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 zs=new Set(["finish","unfinish","finish_all","unfinish_all"]);function Fs(e){return zs.has(e)}function xi(e){let t=e.trim();if(!Fs(t))throw new Error("action must be exactly one of: finish, unfinish, finish_all, unfinish_all");return t}function Bs(e){return{action:xi(e.action)}}function Gs(e){if(e==null||typeof e!="object")return null;let t=e,n=["creator_id","creator_user_id","create_user_id","owner_id"];for(let o of n){let i=t[o];if(typeof i=="string"&&i.trim())return i.trim()}let r=t.creator;if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r;for(let i of["id","user_id","userId"]){let s=o[i];if(typeof s=="string"&&s.trim())return s.trim()}}return null}function Hs(e,t){let n=e.trim(),r=t.trim();return n===r?!0:n.toLowerCase()===r.toLowerCase()}function Ks(e){let{hasCompletion:t,completionRaw:n,markScopeRaw:r,actionParam:o,isCreator:i,taskId:s,creatorId:a}=e,c=r?.trim()??"";if(t){if(n!=="complete"&&n!=="incomplete")throw new Error("completion must be complete or incomplete");let d=n==="complete";if(i){if(!c||c==="none")return{kind:"needs_confirmation",taskId:s,completion:n,creatorId:a};if(c!=="self"&&c!=="all")throw new Error("mark_scope must be none, self, or all when provided");return{kind:"post",action:c==="all"?d?"finish_all":"unfinish_all":d?"finish":"unfinish"}}return{kind:"post",action:d?"finish":"unfinish"}}let l=xi(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 Pt(e,t,n){try{return await me({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:n})}catch(r){return ct(r)}}function dr(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(n,r){try{let o=Se(r,"wps_user_id"),i=Se(r,"title_subject"),s=K(r,"title_prefix"),a=K(r,"description"),c=We(r,"due_time_ms"),l=K(r,"status"),d=Us(r,"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=Ms({titleSubject:i,titlePrefix:s,description:a,dueTimeMs:c,status:p,executors:d});return await Pt(o,"\u521B\u5EFA\u4E2A\u4EBA\u5F85\u529E",async f=>{let m=await f.request({method:"POST",path:As,body:u,headers:dt(r)});return m.data??m})}catch(o){return ct(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(n,r){try{let o=Se(r,"wps_user_id"),i=K(r,"keyword"),s=K(r,"executor"),a=K(r,"status"),c=We(r,"page_size"),l=K(r,"page_token"),d=We(r,"created_time_start_ms"),p=We(r,"created_time_end_ms"),u=We(r,"due_time_start_ms"),f=We(r,"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 h=Ws({keyword:i,executor:s,status:m,pageSize:c,pageToken:l,createdTimeStartMs:d,createdTimeEndMs:p,dueTimeStartMs:u,dueTimeEndMs:f});return await Pt(o,"\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u5217\u8868",async g=>{let _=await g.request({method:"POST",path:$s,body:h,headers:dt(r)});return _.data??_})}catch(o){return ct(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(n,r){try{let o=Se(r,"wps_user_id"),i=Se(r,"task_id");return await Pt(o,"\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u8BE6\u60C5",async s=>{let a=await s.request({method:"GET",path:Qt(i),headers:dt(r)});return a.data??a})}catch(o){return ct(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(n,r){try{let o=Se(r,"wps_user_id"),i=Se(r,"task_id"),s=K(r,"completion"),a=K(r,"mark_scope"),c=K(r,"action"),l=s!==void 0,d=c!==void 0&&c!=="";if(l===d)throw!l&&!d?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 Pt(o,"\u66F4\u65B0\u4E2A\u4EBA\u5F85\u529E\u72B6\u6001",async p=>{let u=await p.request({method:"GET",path:Qt(i),headers:dt(r)}),f=u.data??u,m=Gs(f),h=m!==null&&Hs(o,m),g=Ks({hasCompletion:l,completionRaw:s,markScopeRaw:a,actionParam:c,isCreator:h,taskId:i,creatorId:m});if(g.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:g.taskId,completion:g.completion,creator_id:g.creatorId,...g.requested_action!==void 0?{requested_action:g.requested_action}:{}};let _=Bs({action:g.action}),y=await p.request({method:"POST",path:Cs(i),body:_,headers:dt(r)});return y.data??y})}catch(o){return ct(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(n,r){try{let o=Se(r,"wps_user_id"),i=Se(r,"task_id"),s=K(r,"title_subject"),a=K(r,"title_prefix"),c=K(r,"description"),l=We(r,"due_time_ms"),d=Ns(r,"ext_attrs"),p=js(r,"notify_config_json"),u=Ls({titleSubject:s,titlePrefix:a,description:c,dueTimeMs:l,extAttrs:d,notifyConfig:p});return await Pt(o,"\u66F4\u65B0\u4E2A\u4EBA\u5F85\u529E",async f=>{let m=await f.request({method:"POST",path:Rs(i),body:u,headers:dt(r)});return m.data??m})}catch(o){return ct(o)}}})}function xe(e){return`/v7/coop/dbsheet/${encodeURIComponent(e)}`}function Js(e){return`/v7/dbsheet/${encodeURIComponent(e)}`}function he(e){return{error:e instanceof Error?e.message:String(e)}}function $(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function $e(e){let t=e.sheet_id;if(t==null)throw new Error("sheet_id is required");let n=typeof t=="number"?t:parseInt(String(t),10);if(!Number.isFinite(n)||n<=0)throw new Error("sheet_id must be a positive integer");return n}function Le(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function Ot(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function Re(e,t){let n=e[t];if(n!=null){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1;throw new Error(`${t} must be a boolean`)}}function en(e,t){let n=e[t];if(n!=null){if(!Array.isArray(n))throw new Error(`${t} must be an array`);return n.map(r=>String(r))}}function ki(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 ye(e,t,n){return me({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:n})}function cr(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id");return await ye(o,"wps_dbsheet_get_schema",async s=>{let a=await s.request({method:"GET",path:`${xe(i)}/schema`});return a.data??a})}catch(o){return he(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"}},position:{type:"object"}},required:["name"]}}},required:["wps_user_id","file_id","sheets"]},async execute(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=r.sheets;if(!Array.isArray(s)||s.length===0)throw new Error("sheets must be a non-empty array");return await ye(o,"wps_dbsheet_batch_create_sheets",async a=>{let c=await a.request({method:"POST",path:`${Js(i)}/sheets/batch_create`,body:{sheets:s}});return c.data??c})}catch(o){return he(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:["integer","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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=$(r,"name");return await ye(o,"wps_dbsheet_update_sheet",async c=>{let l=await c.request({method:"POST",path:`${xe(i)}/sheets/${s}/update`,body:{name:a}});return l.data??l})}catch(o){return he(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:["integer","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:{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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=r.records;if(!Array.isArray(a)||a.length===0)throw new Error("records must be a non-empty array");let c=a.map((l,d)=>{if(!l||typeof l!="object")throw new Error(`records[${d}] must be an object`);return{fields_value:ki(l.fields_value,`records[${d}].fields_value`)}});return await ye(o,"wps_dbsheet_create_records",async l=>{let d=await l.request({method:"POST",path:`${xe(i)}/sheets/${s}/records/create`,body:{records:c}});return d.data??d})}catch(o){return he(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:["integer","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:{description:"Field values as JSON string or object."}},required:["id","fields_value"]}}},required:["wps_user_id","file_id","sheet_id","records"]},async execute(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=r.records;if(!Array.isArray(a)||a.length===0)throw new Error("records must be a non-empty array");let c=a.map((l,d)=>{if(!l||typeof l!="object")throw new Error(`records[${d}] must be an object`);let p=l;if(!p.id||typeof p.id!="string")throw new Error(`records[${d}].id is required and must be a string`);return{id:p.id,fields_value:ki(p.fields_value,`records[${d}].fields_value`)}});return await ye(o,"wps_dbsheet_update_records",async l=>{let d=await l.request({method:"POST",path:`${xe(i)}/sheets/${s}/records/update`,body:{records:c}});return d.data??d})}catch(o){return he(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:["integer","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",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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a={},c=en(r,"fields");c&&(a.fields=c),r.filter!==void 0&&r.filter!==null&&(a.filter=r.filter);let l=Ot(r,"max_records");l!==void 0&&(a.max_records=l);let d=Ot(r,"page_size");d!==void 0&&(a.page_size=d);let p=Le(r,"page_token");p!==void 0&&p!==""&&(a.page_token=p);let u=Le(r,"view_id");u!==void 0&&u!==""&&(a.view_id=u);let f=Le(r,"text_value");f!==void 0&&(a.text_value=f);let m=Re(r,"show_fields_info");m!==void 0&&(a.show_fields_info=m);let h=Re(r,"show_record_extra_info");return h!==void 0&&(a.show_record_extra_info=h),await ye(o,"wps_dbsheet_list_records",async g=>{let _=await g.request({method:"POST",path:`${xe(i)}/sheets/${s}/records`,body:a});return _.data??_})}catch(o){return he(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:["integer","string"],description:"Sheet ID (integer)."},fields:{type:"array",items:{type:"string"},description:"Optional. Field names to include."},filter:{type:"object",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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a={},c=en(r,"fields");c&&(a.fields=c),r.filter!==void 0&&r.filter!==null&&(a.filter=r.filter);let l=Ot(r,"max_records");l!==void 0&&(a.max_records=l);let d=Ot(r,"page_num");d!==void 0&&(a.page_num=d);let p=Ot(r,"page_size");p!==void 0&&(a.page_size=p);let u=Le(r,"view_id");u!==void 0&&u!==""&&(a.view_id=u);let f=Le(r,"text_value");f!==void 0&&(a.text_value=f);let m=Re(r,"show_fields_info");m!==void 0&&(a.show_fields_info=m);let h=Re(r,"show_record_extra_info");return h!==void 0&&(a.show_record_extra_info=h),await ye(o,"wps_dbsheet_list_records_by_page",async g=>{let _=await g.request({method:"POST",path:`${xe(i)}/sheets/${s}/records/list_by_page`,body:a});return _.data??_})}catch(o){return he(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:["integer","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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=en(r,"records");if(!a||a.length===0)throw new Error("records must be a non-empty array of record IDs");let c={records:a},l=Le(r,"text_value");l!==void 0&&(c.text_value=l);let d=Re(r,"show_fields_info");d!==void 0&&(c.show_fields_info=d);let p=Re(r,"show_record_extra_info");return p!==void 0&&(c.show_record_extra_info=p),await ye(o,"wps_dbsheet_get_records",async u=>{let f=await u.request({method:"POST",path:`${xe(i)}/sheets/${s}/records/search`,body:c});return f.data??f})}catch(o){return he(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:["integer","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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=$(r,"record_id"),c={},l=Le(r,"text_value");l!==void 0&&(c.text_value=l);let d=Re(r,"show_fields_info");d!==void 0&&(c.show_fields_info=d);let p=Re(r,"show_record_extra_info");return p!==void 0&&(c.show_record_extra_info=p),await ye(o,"wps_dbsheet_get_record",async u=>{let f=await u.request({method:"GET",path:`${xe(i)}/sheets/${s}/records/${encodeURIComponent(a)}`,query:Object.keys(c).length>0?c:void 0});return f.data??f})}catch(o){return he(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:["integer","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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=en(r,"records");if(!a||a.length===0)throw new Error("records must be a non-empty array of record IDs");return await ye(o,"wps_dbsheet_delete_records",async c=>{let l=await c.request({method:"POST",path:`${xe(i)}/sheets/${s}/records/batch_delete`,body:{records:a}});return l.data??l})}catch(o){return he(o)}}})}Ve();import{createHash as Xs}from"node:crypto";import{readFile as Vs,stat as Ys}from"node:fs/promises";var Zs="/v7/drives",Qs="/v7/files/search",ea=50,ta=500,na=50,ra=500,ia=50,oa=500,vi=["folder","file","shortcut"],tn=["fail","rename","overwrite","replace"],Ci=["kdc","plain","markdown"],qi=["sync","async","auto"],sa=["para","table","component","textbox","all"],Ti=["file_name","content","all"],Ei=["folder","file","shortcut"],Pi=["ctime","mtime","otime","stime"],Oi=["desc","asc"],Ai=["ctime","mtime"],$i=["desc","asc"],Ri=["ctime","mtime","dtime","fname","fsize"],aa=["all","share_by_me","share_to_me","latest","personal_drive","group_drive","recycle","customize","latest_opened","latest_edited"];function qe(e){return{error:e instanceof Error?e.message:String(e)}}function D(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function R(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function lt(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function Z(e,t){let n=e[t];if(n!=null){if(typeof n=="boolean")return n;if(n==="true"||n==="false")return n==="true";throw new Error(`${t} must be a boolean`)}}function F(e,t){let n=e[t];if(n==null)return;if(!Array.isArray(n))throw new Error(`${t} must be an array of strings`);let r=n.map(o=>String(o).trim()).filter(Boolean);return r.length>0?r:void 0}function Ce(e){let t=R(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let n=t.trim();if(n!=="internal"&&n!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":n}}function da(e){let t={};for(let[n,r]of Object.entries(e.requestHeaders)){let o=n.trim();if(o==="")continue;let i=o.toLowerCase();i==="content-length"||i==="transfer-encoding"||i==="content-type"||(t[o]=r)}return t["Content-Type"]="application/octet-stream",t}function ca(e){let t=e.trim();if(!t)throw new Error("url is required and must be a non-empty string");let n;try{n=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(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`url must use http: or https: scheme, got: ${n.protocol}`)}function la(e){let t={allotee_type:e.alloteeType,page_size:Math.max(1,Math.min(ta,Math.trunc(e.pageSize??ea)))};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 pa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/create`}function ua(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/children`}function _a(e){let t={page_size:Math.max(1,Math.min(oa,Math.trunc(e.pageSize??ia)))};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 fa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/request_upload`}function ma(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/commit_upload`}function ha(e){let t=e.name.trim();if(!t)throw new Error("name must be a non-empty string");let n={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");n.file_id=e.fileId.trim()}else e.fileId!==void 0&&e.fileId.trim()!==""&&(n.file_id=e.fileId.trim());return e.onNameConflict!==void 0&&(n.on_name_conflict=e.onNameConflict),e.parentPath!==void 0&&e.parentPath.length>0&&(n.parent_path=[...e.parentPath]),n}function ya(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(n=>({type:n.type,sum:n.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 ga(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 wa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/content`}function ba(e){let t={};if(e.format!==void 0&&e.format.trim()!==""){let n=e.format.trim();if(!Ci.includes(n))throw new Error("format must be one of: kdc, plain, markdown");t.format=n}if(e.includeElements!==void 0&&e.includeElements.length>0){let n=e.includeElements.map(r=>r.trim()).filter(Boolean).filter((r,o,i)=>i.indexOf(r)===o);for(let r of n)if(!sa.includes(r))throw new Error("include_elements items must be one of: para, table, component, textbox, all");n.length>0&&(t.include_elements=n)}if(e.mode!==void 0&&e.mode.trim()!==""){let n=e.mode.trim();if(!qi.includes(n))throw new Error("mode must be one of: sync, async, auto");t.mode=n}return e.taskId!==void 0&&e.taskId.trim()!==""&&(t.task_id=e.taskId.trim()),t}function Ia(e){return`/v7/files/${encodeURIComponent(e.trim())}/meta`}function Sa(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 xa(e){let t={type:e.type,page_size:Math.max(1,Math.min(ra,Math.trunc(e.pageSize??na)))};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 ze(e,t,n,r){try{return await me({wpsUserId:e,authCardOriginalMessage:t,needsAuthMessage:n,logTag:"drive",run:r})}catch(o){return qe(o)}}function lr(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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"allotee_type");if(i!=="user"&&i!=="group"&&i!=="app")throw new Error("allotee_type must be user, group, or app");let s=i,a=R(r,"allotee_id"),c=Z(r,"with_ext_attrs"),l=lt(r,"page_size"),d=R(r,"page_token"),p=F(r,"sources");return await ze(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 f=la({alloteeType:s,alloteeId:a,withExtAttrs:c,pageSize:l,pageToken:d,sources:p}),m=await u.request({method:"GET",path:Zs,query:f,headers:Ce(r)});return m.data??m})}catch(o){return qe(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:[...$i],description:"Optional order direction."},order_by:{type:"string",enum:[...Ri],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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"drive_id"),s=D(r,"parent_id"),a=Z(r,"with_permission"),c=Z(r,"with_ext_attrs"),l=R(r,"filter_exts"),d=lt(r,"page_size"),p=R(r,"page_token"),u=R(r,"order");if(u!==void 0&&!$i.includes(u))throw new Error("order must be one of: desc, asc");let f=u,m=R(r,"order_by");if(m!==void 0&&!Ri.includes(m))throw new Error("order_by must be one of: ctime, mtime, dtime, fname, fsize");let h=m,g=r.filter_type,_;if(g!=null){if(typeof g!="object"||Array.isArray(g))throw new Error("filter_type must be an object when provided");_=g}return await ze(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 y=>{let w=_a({withPermission:a,withExtAttrs:c,filterExts:l,filterType:_,order:f,orderBy:h,pageSize:d,pageToken:p}),b=await y.request({method:"GET",path:ua(i,s),query:w,headers:Ce(r)});return b.data??b})}catch(o){return qe(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:[...vi],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:[...tn],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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"drive_id"),s=D(r,"parent_id"),a=D(r,"file_type");if(!vi.includes(a))throw new Error("file_type must be one of: folder, file, shortcut");let c=a,l=D(r,"name"),d=R(r,"file_id"),p=R(r,"on_name_conflict");if(p!==void 0&&!tn.includes(p))throw new Error("on_name_conflict must be one of: fail, rename, overwrite, replace");let u=p,f=F(r,"parent_path");return await ze(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 h=ha({fileType:c,name:l,fileId:d,onNameConflict:u,parentPath:f}),g=await m.request({method:"POST",path:pa(i,s),body:h,headers:Ce(r)});return g.data??g})}catch(o){return qe(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:[...tn],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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"drive_id"),s=D(r,"parent_id"),a=D(r,"file_path"),c=R(r,"name"),l=R(r,"on_name_conflict");if(l!==void 0&&!tn.includes(l))throw new Error("on_name_conflict must be one of: fail, rename, overwrite, replace");let d=l,p=R(r,"file_id"),u=Z(r,"internal"),f=R(r,"upload_scene"),m=a.trim();try{if(!(await Ys(m)).isFile())throw new Error("path is not a regular file")}catch(y){throw new Error(`file_path "${m}" is not accessible: ${y instanceof Error?y.message:String(y)}`)}let h=await Vs(m);if(!c){let y=Math.max(m.lastIndexOf("/"),m.lastIndexOf("\\")),b=(y>=0?m.substring(y+1):m).replace(/^[0-9a-f]{8}_/i,"");b&&(c=b)}if(h.byteLength===0)throw new Error("upload content is empty (file has zero bytes)");let g=h.byteLength,_=Xs("sha256").update(h).digest("hex");return await ze(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 y=>{let w=ya({size:g,fileId:p??void 0,hashes:[{type:"sha256",sum:_}],internal:u??void 0,name:c??void 0,onNameConflict:d,uploadScene:f??void 0}),b=await y.request({method:"POST",path:fa(i,s),body:w,headers:Ce(r)}),k=b.data??b,E=k.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(k).substring(0,300)}`);let J=typeof E.method=="string"?E.method.toUpperCase():"PUT",re=E.url;ca(re);let ie=E.headers??{},oe=typeof k.upload_id=="string"?k.upload_id:void 0,ge=ht(o);if(!ge||!ge.trim())throw new Error("delegated access token missing after auth gate");let se=da({requestHeaders:ie}),ae={Authorization:`Bearer ${ge.trim()}`,...se},He=new Uint8Array(h.buffer,h.byteOffset,h.byteLength),pe;try{pe=await fetch(re,{method:J,headers:ae,body:He})}catch(we){let Ke=we instanceof Error?we.message:String(we);throw new Error(`upload step-2 fetch failed: ${Ke}. Check outbound HTTPS/DNS/firewall from the gateway to the presigned URL.`)}if(!pe.ok){let we=await pe.text().catch(()=>"");throw new Error(`upload step-2 failed: HTTP ${pe.status} ${we.substring(0,300)} [diag: size=${g}, sha256=${_}]`)}if(!oe)return{step1:k,step2_status:pe.status,etag:pe.headers.get("etag")??void 0,warning:"upload_id missing from step-1 \u2014 skipped commit_upload."};let mr=ga({uploadId:oe}),ut=await y.request({method:"POST",path:ma(i,s),body:mr,headers:Ce(r)});return ut.data??ut})}catch(o){return qe(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:[...Ci],description:"Optional output format."},include_elements:{type:"array",items:{type:"string"},description:"Optional extracted element types."},mode:{type:"string",enum:[...qi],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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"drive_id"),s=D(r,"file_id"),a=R(r,"format"),c=F(r,"include_elements"),l=R(r,"mode"),d=R(r,"task_id");return await ze(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=ba({format:a,includeElements:c,mode:l,taskId:d}),f=await p.request({method:"GET",path:wa(i,s),query:Object.keys(u).length>0?u:void 0,headers:Ce(r)});return f.data??f})}catch(o){return qe(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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"file_id"),s=Z(r,"with_permission"),a=Z(r,"with_ext_attrs"),c=Z(r,"with_drive");return await ze(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 d=Sa({withPermission:s,withExtAttrs:a,withDrive:c}),p=await l.request({method:"GET",path:Ia(i),query:Object.keys(d).length>0?d:void 0,headers:Ce(r)});return p.data??p})}catch(o){return qe(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:[...Ti],description:"Search type."},file_type:{type:"string",enum:[...Ei],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:[...Pi],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:[...Oi],description:"Optional order."},order_by:{type:"string",enum:[...Ai],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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"type");if(!Ti.includes(i))throw new Error("type must be one of: file_name, content, all");let s=i,a=R(r,"file_type");if(a!==void 0&&!Ei.includes(a))throw new Error("file_type must be one of: folder, file, shortcut");let c=a,l=R(r,"time_type");if(l!==void 0&&!Pi.includes(l))throw new Error("time_type must be one of: ctime, mtime, otime, stime");let d=l,p=R(r,"order");if(p!==void 0&&!Oi.includes(p))throw new Error("order must be one of: desc, asc");let u=p,f=R(r,"order_by");if(f!==void 0&&!Ai.includes(f))throw new Error("order_by must be one of: ctime, mtime");let m=f,h=F(r,"scope");if(h!==void 0){for(let g of h)if(!aa.includes(g))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 ze(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 g=>{let _=xa({keyword:R(r,"keyword"),type:s,fileType:c,fileExts:F(r,"file_exts"),driveIds:F(r,"drive_ids"),parentIds:F(r,"parent_ids"),creatorIds:F(r,"creator_ids"),modifierIds:F(r,"modifier_ids"),sharerIds:F(r,"sharer_ids"),receiverIds:F(r,"receiver_ids"),timeType:d,startTime:lt(r,"start_time"),endTime:lt(r,"end_time"),withPermission:Z(r,"with_permission"),withLink:Z(r,"with_link"),withTotal:Z(r,"with_total"),pageSize:lt(r,"page_size"),pageToken:R(r,"page_token"),channels:F(r,"channels"),deviceIds:F(r,"device_ids"),excludeChannels:F(r,"exclude_channels"),excludeFileExts:F(r,"exclude_file_exts"),filterUserId:lt(r,"filter_user_id"),fileExtGroups:F(r,"file_ext_groups"),withFolder:Z(r,"with_folder"),withDrive:Z(r,"with_drive"),order:u,orderBy:m,scope:h,searchOperatorName:Z(r,"search_operator_name")}),y=await g.request({method:"GET",path:Qs,query:_,headers:Ce(r)});return y.data??y})}catch(o){return qe(o)}}})}var ka="/v7/airpage/files";function Fe(e,t){return`/v7/airpage/${encodeURIComponent(e.trim())}${t}`}function Ge(e){return{arg:Buffer.from(JSON.stringify(e),"utf8").toString("base64")}}function Be(e,t){return e.length>36?`${t} (${e.slice(0,36)}...)`:`${t} (${e})`}function Ui(e,t){let n=e.operation,r=e.blockId;if(typeof n!="string"||!n.trim())throw new Error(`${t}.operation is required and must be a non-empty string`);if(typeof r!="string"||!r.trim())throw new Error(`${t}.blockId is required and must be a non-empty string`)}var pr=["rename","fail","overwrite"];function ke(e){return{error:e instanceof Error?e.message:String(e)}}function C(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function Di(e,t){let n=e[t];if(n==null)return;if(typeof n!="string")throw new Error(`${t} must be a string`);let r=n.trim();return r===""?void 0:r}function rn(e,t){let n=e[t];if(!Array.isArray(n))throw new Error(`${t} is required and must be an array`);return n}function va(e,t){let r=rn(e,t).map(o=>String(o).trim()).filter(Boolean);if(r.length===0)throw new Error(`${t} must contain at least one non-empty string`);return r}function Ta(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return Math.trunc(n);if(typeof n=="string"&&n.trim()!==""){let r=Number(n.trim());if(Number.isFinite(r))return Math.trunc(r)}throw new Error(`${t} must be a finite integer when provided`)}}function nn(e,t){let n=e[t];if(n==null)throw new Error(`${t} is required and must be a finite integer`);if(typeof n=="number"&&Number.isFinite(n))return Math.trunc(n);if(typeof n=="string"&&n.trim()!==""){let r=Number(n.trim());if(Number.isFinite(r))return Math.trunc(r)}throw new Error(`${t} must be a finite integer`)}function Ea(e){let t={blockId:e.blockId.trim(),content:e.content},n=e.index;return n!==void 0&&(t.index=n),Ge(t)}function Pa(e){let t={blockId:e.blockId.trim()};return Ge(t)}function Oa(e){let t={blockIds:e.blockIds.map(n=>n.trim()).filter(Boolean)};if(t.blockIds.length===0)throw new Error("blockIds must contain at least one non-empty id");return Ge(t)}function Aa(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 Ge(t)}function $a(e){if(!Array.isArray(e)||e.length===0)throw new Error("delete_items must contain at least one delete range");let t=e.map(n=>{let r=n.blockId.trim(),o=Math.trunc(n.startIndex),i=Math.trunc(n.endIndex);if(!r)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:r,startIndex:o,endIndex:i}});return Ge(t)}function Ra(e){return Ui(e,"operation"),Ge(e)}function Ca(e){if(!Array.isArray(e)||e.length===0)throw new Error("operations must contain at least one operation object");for(let[t,n]of e.entries()){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`operations[${t}] must be an object`);Ui(n,`operations[${t}]`)}return Ge(e)}function qa(e){let t=e.trim().toLowerCase();if(pr.includes(t))return t;throw new Error(`on_name_conflict must be one of: ${pr.join(", ")} (got: ${e})`)}function Da(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 De(e,t,n){try{return await me({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:n})}catch(r){return ke(r)}}function ur(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:[...pr],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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"drive_id"),s=C(r,"name"),a=C(r,"on_name_conflict"),c=qa(a),l=Di(r,"parent_id"),d=Di(r,"template_id"),p=`\u521B\u5EFA\u667A\u80FD\u6587\u6863: ${s}`;return await De(o,p,async u=>{let f=Da({driveId:i,name:s,onNameConflict:c,parentId:l,templateId:d}),m=await u.request({method:"POST",path:ka,body:f});return m.data??m})}catch(o){return ke(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) per API. JSON fields: `blockId` (parent block; use literal doc for document root), optional `index` (insert position; omit to let API default, typically 0), required `content` (array of child block nodes). Example paragraph: `{ "type":"paragraph","content":[{"type":"text","content":"hello"}] }`. Requires delegated `kso.airpage.readwrite`. Use SenderId as `wps_user_id`. `file_id` is the smart document id (e.g. from create file response `id` / `link_id` per your product convention).',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 = end). Omit to use API default."},content:{type:"array",description:"Required array of block nodes to insert (e.g. paragraph with nested text blocks per Open Platform docs).",items:{type:"object"}}},required:["wps_user_id","file_id","block_id","content"]},async execute(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),s=C(r,"block_id"),a=rn(r,"content"),c=Ta(r,"index"),l=Ea({blockId:s,content:a,index:c}),d=Be(i,"\u667A\u80FD\u6587\u6863\u521B\u5EFA\u5757\u5185\u5BB9");return await De(o,d,async p=>{let u=await p.request({method:"POST",path:Fe(i,"/blocks/create"),body:l});return u.data??u})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),s=C(r,"block_id"),a=Pa({blockId:s}),c=Be(i,"\u667A\u80FD\u6587\u6863\u67E5\u8BE2\u6587\u6863\u5757");return await De(o,c,async l=>{let d=await l.request({method:"POST",path:Fe(i,"/blocks"),body:a});return d.data??d})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),s=va(r,"block_ids"),a=Oa({blockIds:s}),c=Be(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u67E5\u8BE2\u6587\u6863\u5757");return await De(o,c,async l=>{let d=await l.request({method:"POST",path:Fe(i,"/blocks/batch_get"),body:a});return d.data??d})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),s=C(r,"block_id"),a=nn(r,"start_index"),c=nn(r,"end_index"),l=Aa({blockId:s,startIndex:a,endIndex:c}),d=Be(i,"\u667A\u80FD\u6587\u6863\u5220\u9664\u5757\u5185\u5BB9");return await De(o,d,async p=>{let u=await p.request({method:"POST",path:Fe(i,"/blocks/delete"),body:l});return u.data??u})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),a=rn(r,"delete_items").map((d,p)=>{if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`delete_items[${p}] must be an object`);let u=d,f=C(u,"block_id"),m=nn(u,"start_index"),h=nn(u,"end_index");return{blockId:f,startIndex:m,endIndex:h}}),c=$a(a),l=Be(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u5220\u9664\u5757\u5185\u5BB9");return await De(o,l,async d=>{let p=await d.request({method:"POST",path:Fe(i,"/blocks/batch_delete"),body:c});return p.data??p})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),s=r.operation;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("operation is required and must be an object");let c=Ra(s),l=Be(i,"\u667A\u80FD\u6587\u6863\u66F4\u65B0\u6587\u6863\u5757");return await De(o,l,async d=>{let p=await d.request({method:"POST",path:Fe(i,"/blocks/update"),body:c});return p.data??p})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),a=rn(r,"operations").map((d,p)=>{if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`operations[${p}] must be an object`);return d}),c=Ca(a),l=Be(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u66F4\u65B0\u6587\u6863\u5757");return await De(o,l,async d=>{let p=await d.request({method:"POST",path:Fe(i,"/blocks/batch_update"),body:c});return p.data??p})}catch(o){return ke(o)}}})}var Ua="/v7/meeting_rooms",Na="/v7/meeting_rooms/search",ja="/v7/meeting_room_bookings/batch_get",Ma=["success","failed"];var Mi=["success","failed","approving"];function At(e){return{error:e instanceof Error?e.message:String(e)}}function ve(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function pt(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function _r(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function Ni(e,t){let n=e[t];if(n==null)throw new Error(`${t} is required and must be a finite number`);if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}function Wa(e,t){let n=e[t];if(n!=null){if(typeof n=="boolean")return n;if(n==="true"||n==="false")return n==="true";throw new Error(`${t} must be a boolean`)}}function Wi(e,t){let n=e[t];if(n==null)return;if(!Array.isArray(n))throw new Error(`${t} must be an array`);let r=[];for(let o of n){if(typeof o!="string")throw new Error(`${t} entries must be strings`);let i=o.trim();i!==""&&r.push(i)}return r.length>0?r:void 0}function La(e,t){let n=Wi(e,t);if(n===void 0)return;let r=new Set(Mi),o=n.filter(i=>r.has(i));return o.length>0?o:void 0}function ji(e){let t=pt(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let n=t.trim();if(n!=="internal"&&n!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":n}}function za(e){let t=e.pageSize??20,r={page_size:Math.max(1,Math.min(500,Math.trunc(t)))};return e.roomLevelId!==void 0&&e.roomLevelId.trim()!==""&&(r.room_level_id=e.roomLevelId.trim()),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(r.page_token=e.pageToken.trim()),r}function Fa(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 Ba(e){let t=e.keyword.trim();if(!t)throw new Error("keyword is required and must be a non-empty string");let n=e.pageSize??20,r=Math.max(1,Math.min(100,Math.trunc(n))),o={keyword:t,page_size:r};return e.pageToken!==void 0&&e.pageToken.trim()!==""&&(o.page_token=e.pageToken.trim()),o}function Ga(e){let t=Math.trunc(Number(e.startTimeSec)),n=Math.trunc(Number(e.endTimeSec));if(!Number.isFinite(t)||!Number.isFinite(n))throw new Error("start_time and end_time must be finite Unix timestamps in seconds");if(n<t)throw new Error("end_time must be >= start_time (Unix seconds)");let r=e.roomLevelId?.trim()??"",o=r!=="",i=e.roomIds?.filter(d=>d.trim()!=="").map(d=>d.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,c=Math.max(1,Math.min(500,Math.trunc(Number(a))));if(!Number.isFinite(c))throw new Error("page_size must be finite");let l={start_time:t,end_time:n,page_size:c};return o&&(l.room_level_id=r),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 Ha(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 Ka(e){let t=e.trim();if(t!=="success"&&t!=="failed")throw new Error("status must be success or failed");return{status:t}}function fr(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(n,r){try{ve(r,"wps_user_id");let o=pt(r,"room_level_id"),i=_r(r,"page_size"),s=pt(r,"page_token"),a=za({roomLevelId:o,pageSize:i,pageToken:s}),c=await e.request({method:"GET",path:Ua,query:a});return c.data??c}catch(o){return At(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(n,r){try{ve(r,"wps_user_id");let o=ve(r,"room_id"),i=await e.request({method:"GET",path:Fa(o)});return i.data??i}catch(o){return At(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(n,r){try{ve(r,"wps_user_id");let o=ve(r,"keyword"),i=_r(r,"page_size"),s=pt(r,"page_token"),a=Ba({keyword:o,pageSize:i,pageToken:s}),c=await e.request({method:"POST",path:Na,body:a});return c.data??c}catch(o){return At(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:[...Mi]},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(n,r){try{ve(r,"wps_user_id");let o=Ni(r,"start_time"),i=Ni(r,"end_time"),s=Wi(r,"room_ids"),a=pt(r,"room_level_id"),c=Wa(r,"include_deleted"),l=_r(r,"page_size"),d=pt(r,"page_token"),p=La(r,"results"),u=Ga({startTimeSec:o,endTimeSec:i,roomIds:s,roomLevelId:a,includeDeleted:c,pageSize:l,pageToken:d,results:p??void 0}),f=await e.request({method:"POST",path:ja,body:u,headers:ji(r)});return f.data??f}catch(o){return At(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:[...Ma],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(n,r){try{ve(r,"wps_user_id");let o=ve(r,"booking_id"),i=ve(r,"status"),s=Ka(i),a=await e.request({method:"POST",path:Ha(o),body:s,headers:ji(r)});return a.data??a}catch(o){return At(o)}}})}function Ja(){return new Proxy({},{get(e,t,n){let r=jn(),o=Reflect.get(r,t,n);return typeof o=="function"?o.bind(r):o}})}function Li(e){let t=[],n=o=>{e(()=>({name:o.name,label:o.name,description:o.description,parameters:o.parameters,async execute(s,a){let c=await o.execute(s,a);if(c&&typeof c=="object"&&"error"in c)throw new Error(c.error);return{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:c}}}),{name:o.name}),t.push(o.name)},r=Ja();return er(r,n),tr(r,n),ir(r,n),Jn(r,n),ar(r,n),dr(r,n),lr(r,n),cr(r,n),ur(r,n),fr(r,n),console.log(`[wps-xiezuo] OAPI tools registered: ${t.length} tools`),t.length}var Xa={id:_e,name:"WPS Xiezuo",description:"WPS365 Open Platform channel plugin for OpenClaw",configSchema:$r(),register(e){li(e.runtime);let t=e.logger??{info:()=>{},warn:()=>{},error:()=>{}};if(e.registerChannel({plugin:Zn}),typeof e.registerTool=="function"){t.info(`[${_e}] registerTool is available (type: ${typeof e.registerTool})`);try{let n=Li(e.registerTool);t.info(`[${_e}] registered ${n} WPS OAPI tool factories`)}catch(n){t.error(`[${_e}] tool registration failed: ${n}`)}}else t.warn(`[${_e}] registerTool not available (type: ${typeof e.registerTool})`);typeof e.on=="function"?(e.on("before_prompt_build",async(n,r)=>{let o=r;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: <\u8DEF\u5F84>]` \u6216 `[\u5DF2\u4E0B\u8F7D\u6587\u4EF6: <\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(`
35
+ ${JSON.stringify(O,null,2)}`);return}if(!s){n("WPS: channelRuntime not available \u2014 skipping AI dispatch");return}let A=s.reply,Te=s.routing,Ee="main",Y="",U=i;if(Te?.resolveAgentRoute){let O=Te.resolveAgentRoute({cfg:o,channel:v,accountId:i,peer:{kind:k?"direct":"group",id:h.session_key}});Ee=O.agentId,Y=O.sessionKey?.trim()??"",O.accountId&&(U=O.accountId,n(`WPS route account override: ${i} -> ${O.accountId}`))}let z=Y||h.session_key,hr=U;n(`WPS route: agentId=${Ee}, inboundSessionKey=${z}, accountId=${hr}`);let yr={Body:we,BodyForAgent:we,...oe.length>0?{MediaPath:oe[0],MediaType:ge[0],MediaPaths:oe,MediaTypes:ge}:{},RawBody:JSON.stringify({session:h,chatId:y,messageId:w,messageType:b.kind,plainText:b.plainText,attachments:b.attachments,...ie?{prefetchedMedia:ie}:{}}),CommandBody:we,From:J,To:k?`user:${_}`:`chat:${y}`,SessionKey:z,Label:z,ConversationLabel:z,DisplayName:z,SessionLabel:z,AccountId:hr,ChatType:k?"direct":"group",GroupId:void 0,SenderName:p.name??void 0,SenderId:_,Provider:v,Surface:"wps",Channel:v,Timestamp:l.send_time??Date.now(),OriginatingChannel:v,OriginatingFrom:`wps:${_}`,OriginatingTo:`wps:${c.clientId}`},gr=A.finalizeInboundContext?A.finalizeInboundContext(yr):yr,_t=null;if(y&&w)try{await yn(c,y,w),_t={kind:"reaction",chatId:y,messageId:w},n(`WPS thinking reaction added: chatId=${y}, messageId=${w}`)}catch(O){n(`WPS thinking reaction failed, falling back to text: ${String(O)}`);try{await nt(c,E,"\u6B63\u5728\u601D\u8003\u4E2D..."),_t={kind:"text-fallback"}}catch(B){n(`WPS thinking fallback text failed: ${String(B)}`)}}let wr=()=>async(O,B)=>{let G=O.text??"";if(!G)return;let Ue=G.trim();if(/Message:.*[\\/]openclaw-media[\\/].*failed/i.test(Ue)){n(`WPS deliver: suppressed media-failed noise: ${Ue.substring(0,80)}`);return}n(`WPS deliver: text length=${G.length}, preview=${G.substring(0,80)}`),!k&&y&&w?await Fo(c,y,w,G):await nt(c,E,G)};try{if(A.dispatchReplyWithBufferedBlockDispatcher)await A.dispatchReplyWithBufferedBlockDispatcher({ctx:gr,cfg:o,dispatcherOptions:{deliver:wr(),responsePrefix:"",humanDelay:A.resolveHumanDelayConfig?A.resolveHumanDelayConfig(o,Ee):void 0,onError:(O,B)=>{r(`WPS ${B.kind} reply error: ${String(O)}`)}}}),n("WPS: agent dispatch completed");else if(A.dispatchReplyFromConfig&&A.createReplyDispatcherWithTyping){let O=A.resolveHumanDelayConfig?A.resolveHumanDelayConfig(o,Ee):void 0,{dispatcher:B,replyOptions:G,markDispatchIdle:Ue}=A.createReplyDispatcherWithTyping({responsePrefix:"",humanDelay:O,deliver:wr(),onError:($t,zi)=>{r(`WPS ${zi.kind} reply error: ${String($t)}`)}});try{await A.dispatchReplyFromConfig({ctx:gr,cfg:o,dispatcher:B,replyOptions:G})}finally{Ue()}n("WPS: agent dispatch completed (fallback path)")}else n("WPS: channelRuntime.reply dispatch APIs not found, skipping agent dispatch")}finally{_t?.kind==="reaction"&&(await gn(c,_t.chatId,_t.messageId,t),n("WPS thinking reaction removed"))}}catch(P){r("WPS async inbound error:",P)}}tt();Ve();wt();import{createHash as Bo}from"node:crypto";function Go(e){return Bo("sha256").update(e).digest("hex")}var di=20*1024*1024;function Hn(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 Ho(e,t){let n={};for(let[o,i]of Object.entries(e)){if(typeof i!="string")continue;let s=o.trim();if(!s)continue;let a=s.toLowerCase();a==="content-length"||a==="transfer-encoding"||(n[s]=i)}return Object.keys(n).some(o=>o.trim().toLowerCase()==="content-type")||(n["Content-Type"]=t),n}async function Kn(e,t,n,r,o){let i=o?.info??console.log,s=o?.error??console.error,a=r.byteLength;if(a===0)throw new Error("upload content is empty");if(a>di)throw new Error(`file too large: ${a} bytes (max ${di})`);let c=Go(r);i(`[upload] phase1 start: fileName=${t} fileType=${n} size=${a} checksum=${c.substring(0,16)}\u2026`);let l=await e.request({method:"POST",path:"/v7/chats/resources/upload",body:{file_name:t,file_size:a,file_type:n,checksum:c}}),d=l.data??l;if(!d||typeof d!="object")throw new Error(`upload phase 1 returned no data: ${JSON.stringify(l).substring(0,300)}`);let p=d.data,u=p&&typeof p=="object"?p:d;i(`[upload] phase1 response keys: source=[${Object.keys(u)}] hasNested=${!!p}`);let f=u.upload_entry;f&&i(`[upload] upload_entry keys: [${Object.keys(f)}]`);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():f&&typeof f.url=="string"&&f.url.trim()?f.url.trim():null,h=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(d).substring(0,300)}`);if(!h)throw new Error(`upload phase 1 did not return a storage_key: keys=${JSON.stringify(Object.keys(u))}`);i(`[upload] phase1 ok: storageKey=${h.substring(0,20)}\u2026 uploadUrl=${m.substring(0,80)}\u2026`);let g=f&&typeof f.headers=="object"&&f.headers&&Object.keys(f.headers).length>0,_=Ho(g?f.headers:{},n);i(`[upload] phase2 PUT headers: ${JSON.stringify(_)}`);let y=await fetch(m,{method:"PUT",headers:_,body:r});if(!y.ok){let w=await y.text().catch(()=>"");throw s(`[upload] phase2 PUT failed: HTTP ${y.status} body=${w.substring(0,300)}`),new Error(`upload phase 2 PUT failed: HTTP ${y.status} ${w.substring(0,200)}`)}return i(`[upload] phase2 PUT ok: HTTP ${y.status} storageKey=${h.substring(0,20)}\u2026`),{storage_key:h,file_name:t,file_size:a}}function Gn(e){return e.data??null}function Gt(e){return{error:e instanceof Error?e.message:String(e)}}function te(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function Ko(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} is required and must be a finite number`)}function Jo(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number when provided`)}}function Jn(e,t,n){let r=n?.info??(()=>{}),o=n?.error??(()=>{});t({name:"wps_media_download",description:"Obtain a pre-signed download URL for a message attachment or resource (GET /v7/chats/{chat_id}/messages/{message_id}/resources/{storage_key}/download). Use storage_key from inbound message attachments (WPS cloud). Do NOT use the generic read() tool with the attachment display filename \u2014 that file is not on the OpenClaw workspace disk. The returned data typically includes a short-lived URL for HTTP GET.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"Chat id containing the message."},message_id:{type:"string",description:"Message id that owns the resource."},storage_key:{type:"string",description:"Resource storage key from the message."}},required:["chat_id","message_id","storage_key"]},async execute(i,s){try{let a=encodeURIComponent(te(s,"chat_id")),c=encodeURIComponent(te(s,"message_id")),l=encodeURIComponent(te(s,"storage_key")),d=await e.request({method:"GET",path:`/v7/chats/${a}/messages/${c}/resources/${l}/download`});return Gn(d)}catch(a){return Gt(a)}}}),t({name:"wps_media_fetch_base64",description:"Fetch attachment bytes from WPS and return base64 (no shell/exec required). It internally calls the WPS media download endpoint, follows the pre-signed URL, and returns `{ mime_type, size, base64 }`. Use this when you need OCR or image understanding in-tool; do NOT call exec/curl manually.",parameters:{type:"object",properties:{chat_id:{type:"string",description:"Chat id containing the message."},message_id:{type:"string",description:"Message id that owns the resource."},storage_key:{type:"string",description:"Resource storage key from the message."},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=encodeURIComponent(te(s,"chat_id")),c=encodeURIComponent(te(s,"message_id")),l=encodeURIComponent(te(s,"storage_key")),d=Jo(s,"max_bytes")??5*1024*1024;if(d<=0)throw new Error("max_bytes must be positive");r(`[tool:wps_media_fetch_base64] start: chatId=${decodeURIComponent(a)} msgId=${decodeURIComponent(c)} sk=${decodeURIComponent(l).substring(0,20)}\u2026`);let p=await e.request({method:"GET",path:`/v7/chats/${a}/messages/${c}/resources/${l}/download`}),u=Gn(p),f=mn(u),m=await fetch(f);if(!m.ok)throw new Error(`download url request failed: HTTP ${m.status}`);let h=Number(m.headers.get("content-length")??"0");if(Number.isFinite(h)&&h>d)throw new Error(`attachment too large: ${h} bytes > max_bytes=${d}`);let g=m.headers.get("content-type")??"application/octet-stream",_=new Uint8Array(await m.arrayBuffer());if(_.byteLength>d)throw new Error(`attachment too large after download: ${_.byteLength} bytes > max_bytes=${d}`);return r(`[tool:wps_media_fetch_base64] ok: ${g} ${_.byteLength}B`),{chat_id:decodeURIComponent(a),message_id:decodeURIComponent(c),storage_key:decodeURIComponent(l),mime_type:g,size:_.byteLength,base64:Buffer.from(_).toString("base64")}}catch(a){return o("[tool:wps_media_fetch_base64] error:",a),Gt(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=te(s,"file_name"),c=Ko(s,"file_size"),l=te(s,"file_type"),d=te(s,"checksum");if(c<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:c,file_type:l,checksum:d}});return Gn(p)}catch(a){return Gt(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=te(s,"file_name"),c=te(s,"file_type"),l=te(s,"base64"),d=Buffer.from(l,"base64");r(`[tool:wps_media_upload_base64] start: ${a} ${c} ${d.byteLength}B`);let{storage_key:p,file_name:u,file_size:f}=await Kn(e,a,c,d);return r(`[tool:wps_media_upload_base64] ok: storage_key=${p.substring(0,20)}\u2026 ${u} ${f}B`),{storage_key:p,file_name:u,file_size:f}}catch(a){return o("[tool:wps_media_upload_base64] error:",a),Gt(a)}}})}wt();var ts={Debug:0,Info:1,Warn:2,Error:3},rt=null;function li(e){rt=e}function ns(){if(!rt)throw new Error("WPS plugin runtime not initialized");return rt}var Kt="wps",ci={id:v,label:"WPS",selectionLabel:"WPS365 (Open Platform)",docsPath:"/channels/wps-xiezuo",docsLabel:"WPS",blurb:"WPS365 Open Platform bot integration.",aliases:[v,Kt,"wps365"],order:70};function Jt(e){let t=e.channels;if(t)return t[v]??t[Kt]}function Oe(e){return ln(Jt(e))}function rs(){let e=Ht.join(Zo(),".openclaw","openclaw.json");if(!Xo(e))return null;try{let t=Vo(e,"utf8");return t.trim()?JSON.parse(t):null}catch{return null}}function Xn(e){let t=e&&typeof e=="object"?e:null;if(t&&Object.keys(Oe(t)).length>0)return t;let n=rt?.config&&typeof rt.config=="object"?rt.config:null;if(n&&Object.keys(Oe(n)).length>0)return n;let r=rs();return r&&Object.keys(Oe(r)).length>0?r:t??n??r??{}}function V(e){return cn(Jt(e))}function ne(e,t){let n=Oe(e);return n[t]??n[V(e)]??n[Pe]}function is(e,t=Pe){let n=ne(e,t);return{accountId:t,enabled:n?.enabled!==!1,configured:!!de(n),config:n??{enabled:!1}}}function Vn(e){return e.trim().replace(/^wps-xiezuo:/i,"").replace(/^wps:/i,"")}function os(e){return e.trim().length>0}function pi(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 n=e.match(/:p2p:([^:]+)/);if(n)return{type:"user",id:n[1]};let r=e.split(":");if(r.length===2)return{type:"user",id:r[1]};let o=r[2]??r[1],i=r[3]??r[2];return{type:o==="group"?"chat":"user",id:i??r[r.length-1]??e}}return{type:"user",id:e}}async function Yn(e,t,n){let r=N(e),o=M(e.baseUrl,r),i=pi(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:n,type:"markdown"}}}})).data?.message_id??""}}var Zn={id:v,meta:{...ci,aliases:[...ci.aliases]},capabilities:{chatTypes:["direct","group"],media:!0,threads:!0,nativeCommands:!1,blockStreaming:!0},reload:{configPrefixes:[`channels.${v}`,`channels.${Kt}`]},configSchema:Rr(dn),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=Xn(e),n=Object.keys(Oe(t));return n.length>0?n:[Pe]},resolveAccount:e=>{let t=Xn(e);return is(t,V(t))},defaultAccountId:e=>{let t=Xn(e);return V(t)},setAccountEnabled:({cfg:e,enabled:t})=>({...e,channels:{...e.channels,[v]:{...Jt(e),accounts:{...Oe(e),[V(e)]:{...ne(e,V(e))??{},enabled:t}}}}}),deleteAccount:({cfg:e})=>{let t={...e},n={...t.channels},r=Jt(e);if(r){let o=V(e),i={...Oe(e)};delete i[o],n[v]={...r,accounts:i}}else delete n[v],delete n[Kt];return t.channels=Object.keys(n).length>0?n:void 0,t},isConfigured:(e,t)=>!!de(ne(t,e.accountId)),describeAccount:e=>({accountId:e.accountId,enabled:e.enabled,configured:e.configured}),resolveAllowFrom:({cfg:e})=>{let t=e;return ne(t,V(t))?.allowFrom??[]},formatAllowFrom:({allowFrom:e})=>e.map(t=>Vn(String(t)))},security:{resolveDmPolicy:({cfg:e})=>{let t=e,n=V(t),r=ne(t,n);return{policy:r?.dmPolicy??"pairing",allowFrom:r?.allowFrom??[],policyPath:`channels.${v}.accounts.${n}.dmPolicy`,allowFromPath:`channels.${v}.accounts.${n}.allowFrom`,approveHint:Cr(v),normalizeEntry:Vn}},collectWarnings:({cfg:e})=>{let t=[],n=Oe(e);for(let[r,o]of Object.entries(n))o.dmPolicy==="open"&&t.push(`- WPS account '${r}' DMs are open to anyone. Set channels.${v}.accounts.${r}.dmPolicy="pairing" or "allowlist" for security.`),(o.groupPolicy??"allowlist")==="open"&&t.push(`- WPS account '${r}' groups: groupPolicy="open" allows any group to trigger. Set channels.${v}.accounts.${r}.groupPolicy="allowlist".`);return t}},pairing:{idLabel:"wpsUserId",normalizeAllowEntry:Vn,notifyApproval:async({cfg:e,id:t})=>{let n=e,r=ne(n,V(n)),o=de(r);if(!o)throw new Error("WPS credentials not configured");await Yn(o,`user:${t}`,"Your pairing request has been approved. You can now chat with this bot.")}},groups:{resolveRequireMention:({cfg:e,groupId:t})=>{let n=e,r=ne(n,V(n));return!r?.groups||!t?!0:(r.groups[t]??r.groups["*"])?.requireMention??!0},resolveToolPolicy:()=>{}},outbound:{deliveryMode:"direct",textChunkLimit:5e3,chunker:(e,t)=>ns().channel.text.chunkMarkdownText(e,t),chunkerMode:"markdown",resolveTarget:({to:e,allowFrom:t})=>{let n=e?.trim()??"";if(n&&os(n))return{ok:!0,to:n};let r=t?.[0];return r?{ok:!0,to:String(r).trim()}:{ok:!1,error:new Error("WPS target is required (user_id or chat_id)")}},sendText:async({cfg:e,to:t,text:n})=>{let r=e,o=ne(r,V(r)),i=de(o);if(!i)throw new Error("WPS credentials not configured");return Yn(i,t,n)},sendMedia:async({cfg:e,to:t,mediaUrl:n,mimeType:r})=>{let o=e,i=ne(o,V(o)),s=de(i);if(!s)throw new Error("WPS credentials not configured");let a=N(s),c=M(s.baseUrl,a),l=pi(t),d=(n??"").trim();if(!d)throw new Error("WPS sendMedia requires mediaUrl");let p,u,f=(r??"").trim()||"application/octet-stream",m=null;if(Hn(d)){let _=await Yo(d),y=Ht.basename(d)||"attachment";if(p=/^[0-9a-f]{8}_/.test(y)?y.substring(9):y,!(r??"").trim()){let b=Ht.extname(p).toLowerCase();f={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"}[b]??"application/octet-stream"}f.startsWith("image/")&&(m=Ar(_),console.log(`[${v}] sendMedia: parsed dimensions ${m?`${m.width}x${m.height}`:"(null)"} for ${p}`)),u=_.byteLength,d=(await Kn(c,p,f,_)).storage_key}let g=f.startsWith("image/")?{type:"image",receiver:{type:l.type,receiver_id:l.id},content:{image:{storage_key:d,...f.startsWith("image/")?{type:f}:{},...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:d,...p?{name:p}:{},...u!==void 0?{size:u}:{}}}}};return c.request({method:"POST",path:"/v7/messages/create",body:g})}},status:{defaultRuntime:{accountId:Pe,running:!1,lastStartAt:null,lastStopAt:null,lastError:null},collectStatusIssues:e=>e.flatMap(t=>{let n=[];return t.enabled&&!t.configured&&n.push({channel:v,accountId:t.accountId,kind:"config",message:"WPS credentials not configured (appId and appSecret required).",fix:`Set channels.${v}.accounts.${t.accountId}.appId and channels.${v}.accounts.${t.accountId}.appSecret.`}),n}),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=de(e.config);if(!t)return{ok:!1,error:"Not configured"};try{return{ok:!0,token:(await N(t).getToken()).substring(0,8)+"..."}}catch(n){return{ok:!1,error:String(n)}}},buildAccountSnapshot:({account:e,runtime:t,probe:n})=>({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:n})},gateway:{startAccount:async e=>{let t=ne(e.cfg,e.accountId);if(!t?.enabled){e.log?.info?.(`[${e.accountId}] WPS provider disabled`);return}let n=de(t);if(!n){e.log?.error?.(`[${e.accountId}] WPS credentials not configured`);return}let r=async()=>{},o=a=>{Bn({cfg:e.cfg,accountId:e.accountId,channelRuntime:e.channelRuntime??void 0,wpsCfg:t,creds:n,eventPayload:a,log:e.log}).catch(c=>e.log?.error?.("WPS inbound handler error:",c))},i=!1;if(t.sdk?.enabled)try{let a=Qo,c=es,l=ts,p={debug:l.Debug,warn:l.Warn,error:l.Error}[t.sdk.logLevel??"info"]??l.Info,u=new c().onV7AppChatMessageCreate(async g=>{try{let _=g.parsedData;e.log?.info?.(`[WPS SDK][${e.accountId}/${n.clientId}] message: chat_id=${_.chat.id}, message_id=${_.message.id}`);let y=Lr(_);o(y)}catch(_){e.log?.error?.("WPS SDK message handler error:",_)}}).onV7AppGroupChatMemberRobotCreate(async g=>{let _=g.parsedData;if(e.log?.info?.(`[WPS SDK] robot joined group: chat_id=${_.chat_id}`),t.robotJoinGroupMessage!==void 0){let y=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=N(n);await M(n.baseUrl,w).request({method:"POST",path:"/v7/messages/create",body:{type:"text",receiver:{type:"chat",receiver_id:_.chat_id},content:{text:{content:y,type:"markdown"}}}})}catch(w){e.log?.error?.("WPS welcome message failed:",w)}}}).onV7AppGroupChatMemberRobotDelete(async g=>{e.log?.info?.(`[WPS SDK] robot left group: chat_id=${g.parsedData.chat_id}`)}).registerFallbackFunc(g=>{let _=null;if(g.parsedData&&typeof g.parsedData=="object")_=g.parsedData;else if(typeof g.data=="string"&&g.data)try{_=JSON.parse(g.data)}catch{}let y=_?Object.keys(_).join(","):"N/A";if(e.log?.info?.(`[WPS SDK] unhandled event: ${g.eventCode}, keys=${y}`),_&&e.log?.info?.(`[WPS SDK] event payload: ${JSON.stringify(_).slice(0,500)}`),_){let w=typeof _.code=="string"?_.code:typeof _.authorization_code=="string"?_.authorization_code:void 0,b=typeof _.state=="string"?_.state:void 0;if(w){let k=typeof _.user_id=="string"?_.user_id:void 0;e.log?.info?.(`[WPS SDK] Auth code detected: eventCode=${g.eventCode}, code=${w.slice(0,8)}..., state=${b??"(none)"}, userId=${k??"(none)"}`),(async()=>{try{let{handleAuthEvent:E}=await Promise.resolve().then(()=>(Bt(),zn));await E({code:w,state:b??"",creds:n,wpsCfg:t,log:e.log,userId:k})}catch(E){e.log?.error?.(`[WPS SDK] Auth event handling failed: ${String(E)}`)}})()}}}),f=new a(Fr({appId:n.clientId,appSecret:n.clientSecret,dispatcher:u,logLevel:p,endpoint:t.sdk.endpoint},t.sdk));f.start().catch(g=>{e.log?.error?.("WPS SDK client.run ended:",g)});let m=t.sdk.connectTimeoutMs??2e4,h=Date.now()+m;for(;Date.now()<h&&!f.isConnected();)await new Promise(g=>setTimeout(g,150));if(f.isConnected()){i=!0,e.log?.info?.("[WPS SDK] long connection established");let g=()=>f.stop();e.abortSignal.addEventListener("abort",g),r=async()=>{e.abortSignal.removeEventListener("abort",g),f.stop()}}else f.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"),c=(a.default||a)();c.use(a.json());let l=t.webhook?.port??3e3,d=t.webhook?.path??"/wps/webhook",p=t.enableEncryption!==!1;c.post(d,(f,m)=>{let h=zr(f.body,{appId:n.clientId,appSecret:n.clientSecret},p,e.log);if("challenge"in h){m.status(200).json({challenge:h.challenge});return}if(!h.ok){let g=h.status??200;g===200?m.status(200).json({code:0,msg:"ok"}):m.status(g).json({code:-1,msg:h.error});return}m.status(200).json({code:0,msg:"ok"}),o(h.payload)});let u=c.listen(l,()=>{e.log?.info?.(`[${e.accountId}] WPS webhook listening on :${l}${d}`)});r=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=N(n),c=M(n.baseUrl,a);Nn(c,e.log,t,n),pn({appId:n.clientId,appSecret:n.clientSecret,baseUrl:n.baseUrl}),e.log?.info?.(`[${e.accountId}] WPS client initialized for OAPI tools`);try{let d=((await c.request({method:"GET",path:`/v7/developer/apps/${encodeURIComponent(n.clientId)}`})).data?.scopes??[]).filter(p=>p.auth_types?.includes("delegated")).map(p=>({name:p.name??"",description:p.description??""})).filter(p=>p.name);zt(d),e.log?.info?.(`[${e.accountId}] Delegated scopes: ${d.map(p=>p.name).join(", ")||"(none)"}`)}catch(l){zt([]);let d=String(l);d.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: ${d}`)}}catch(a){e.log?.error?.(`[${e.accountId}] WPS client init failed:`,a)}return qr(e.abortSignal,r)}},onboarding:{channel:v,getStatus:async({cfg:e})=>{let t=e,n=ne(t,V(t)),r=!!de(n);return{channel:v,configured:r,statusLines:[`WPS: ${r?"configured":"needs appId and appSecret"}`],selectionHint:r?"configured":"needs credentials",quickstartScore:r?2:1}},configure:async({cfg:e})=>({cfg:e})},agentPrompt:{messageToolHints:e=>["- 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>`)."]},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,n=e.params.message??e.params.text??e.params.content,r=e.params.media,o=e.cfg,i=ne(o,V(o)),s=de(i);if(!s)throw new Error("WPS credentials not configured");let a=t&&typeof t=="string"&&t.trim()?t.trim():"";if(r&&typeof r=="string"&&r.trim()){let l=r.trim();if(Hn(l)){if(!a)throw new Error("WPS send with media requires 'to' (e.g. 'user:<id>' or 'chat:<id>')");return await Zn.outbound.sendMedia({cfg:e.cfg,to:a,mediaUrl:l,mimeType:void 0}),{text:`Media sent (${Ht.basename(l)||"attachment"})`}}}if(!a)throw new Error("WPS send requires 'to' (e.g. 'user:<id>' or 'chat:<id>')");if(!n||typeof n!="string"||!n.trim())throw new Error("WPS send requires 'message' or 'text'");return{text:`Message sent (id: ${(await Yn(s,a,n.trim())).messageId})`}}}};tt();function Xt(e){return e.data??null}function Vt(e){return{error:e instanceof Error?e.message:String(e)}}function le(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function Qn(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function ss(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function ui(e){try{return JSON.parse(e)}catch{throw new Error("content must be valid JSON matching the WPS message content structure")}}function as(e,t){if(e==="text"){try{let r=JSON.parse(t);if(r&&typeof r=="object"&&"text"in r)return{type:"text",content:r}}catch{}return{type:"text",content:{text:{content:t,type:"markdown"}}}}let n=ui(t);if(typeof n!="object"||n===null)throw new Error(`content for ${e} must be a JSON object (message content subtree)`);return e==="rich_text"?{type:"rich_text",content:n}:{type:"image",content:n}}function er(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(n,r){try{let o=le(r,"receiver_type");if(o!=="user"&&o!=="chat")throw new Error("receiver_type must be 'user' or 'chat'");let i=le(r,"receiver_id"),s=le(r,"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=le(r,"content");if(a.length>5e3)throw new Error("content JSON string exceeds 5000 characters");let c=ui(a);if(typeof c!="object"||c===null)throw new Error("parsed content must be a JSON object");let l={type:s,receiver:{type:o,receiver_id:i},content:c},d=r.mentions;if(d!==void 0){if(!Array.isArray(d))throw new Error("mentions must be an array when provided");l.mentions=d}let p=await e.request({method:"POST",path:"/v7/messages/create",body:l});return Xt(p)}catch(o){return Vt(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:"Chat session id."},message_id:{type:"string",description:"Message id to reply to."},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(n,r){try{let o=encodeURIComponent(le(r,"chat_id")),i=encodeURIComponent(le(r,"message_id")),s=le(r,"msg_type");if(s!=="text"&&s!=="rich_text"&&s!=="image")throw new Error("msg_type must be text, rich_text, or image");let a=le(r,"content"),c=as(s,a),l=await e.request({method:"POST",path:`/v7/chats/${o}/messages/${i}/reply`,body:c});return Xt(l)}catch(o){return Vt(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:"Chat session id."},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(n,r){try{let o=encodeURIComponent(le(r,"chat_id")),i=Qn(r,"start_time"),s=Qn(r,"end_time"),a=Qn(r,"page_size")??50,c=ss(r,"page_token"),l={page_size:a};c!==void 0&&(l.page_token=c),i!==void 0&&(l.start_time=Math.trunc(i*1e3)),s!==void 0&&(l.end_time=Math.trunc(s*1e3));let d=await e.request({method:"GET",path:`/v7/chats/${o}/messages`,query:l});return Xt(d)}catch(o){return Vt(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:"Chat session id."},message_id:{type:"string",description:"Message id."}},required:["chat_id","message_id"]},async execute(n,r){try{let o=encodeURIComponent(le(r,"chat_id")),i=encodeURIComponent(le(r,"message_id")),s=await e.request({method:"GET",path:`/v7/chats/${o}/messages/${i}`});return Xt(s)}catch(o){return Vt(o)}}})}function _i(e){return e.data??null}function fi(e){return{error:e instanceof Error?e.message:String(e)}}function ds(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function cs(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function ls(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}var ps=["active"],us=["user_name","email","phone"],_s=["company_user"],fs=50;function tr(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(n,r){try{let o=await e.request({method:"GET",path:"/v7/users/current"});return _i(o)}catch(o){return fi(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(n,r){try{let o=ds(r,"keyword"),i=cs(r,"page_size")??fs,s=ls(r,"page_token"),a={keyword:o,status:[...ps],search_field:[...us],search_source:[..._s],page_size:i};s!==void 0&&(a.page_token=s);let c=await e.request({method:"GET",path:"/v7/users/search",query:a});return _i(c)}catch(o){return fi(o)}}})}function Tt(e){return e.data??null}function it(e){return{error:e instanceof Error?e.message:String(e)}}function Et(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function mi(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function nr(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}var hi=50;function ms(e,t){let n=e[t];if(!Array.isArray(n)||n.length===0)throw new Error(`${t} must be a non-empty array of user id strings`);let r=[];for(let o=0;o<n.length;o++){let i=n[o];if(typeof i!="string"||!i.trim())throw new Error(`${t}[${o}] must be a non-empty string`);r.push(i.trim())}return r}function rr(e,t="user"){return{id:e,type:t}}var Yt=null;async function hs(e){if(Yt)return Yt;let n=(await e.request({method:"GET",path:"/v7/users/current"})).data;if(!n||typeof n.id!="string"||!n.id.trim())throw new Error("Cannot retrieve current operator identity from /v7/users/current. Ensure the app has kso.user_base.read permission.");return Yt={id:n.id.trim(),type:"user"},Yt}function ir(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(n,r){try{let o=Et(r,"type");if(o!=="p2p"&&o!=="group")throw new Error("type must be 'p2p' or 'group'");let i=ms(r,"member_ids"),s,a={type:o};if(o==="group"){let l=await hs(e),d=new Set;s=[],d.add(l.id),s.push(rr(l.id));for(let u of i)d.has(u)||(s.push(rr(u)),d.add(u));a.owner_id=l.id;let p=nr(r,"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(d=>rr(d))}a.account_id_list=s;let c=await e.request({method:"POST",path:"/v7/chats/create",body:a});return Tt(c)}catch(o){return it(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(n,r){try{let o=mi(r,"page_size")??hi,i=nr(r,"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 Tt(a)}catch(o){return it(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:"Chat session id."}},required:["chat_id"]},async execute(n,r){try{let o=encodeURIComponent(Et(r,"chat_id")),i=await e.request({method:"GET",path:`/v7/chats/${o}`});return Tt(i)}catch(o){return it(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(n,r){try{let o=encodeURIComponent(Et(r,"chat_id")),i=mi(r,"page_size")??hi,s=nr(r,"page_token"),a={page_size:i};s!==void 0&&(a.page_token=s);let c=await e.request({method:"GET",path:`/v7/chats/${o}/members`,query:a});return Tt(c)}catch(o){return it(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(n,r){try{let o=encodeURIComponent(Et(r,"chat_id")),i=await e.request({method:"GET",path:`/v7/chats/${o}/members/is_in_chat`});return Tt(i)}catch(o){return it(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(n,r){try{let o=Et(r,"keyword").toLowerCase(),i=[],s,a=!1;for(let l=0;l<10;l++){let d={page_size:100};s&&(d.page_token=s);let p=await e.request({method:"GET",path:"/v7/chats",query:d});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 c={};return a&&(c.warning="Results may be incomplete: pagination was truncated due to missing page_token."),i.length===0?{...c,found:!1,message:`No chats found matching "${o}"`}:i.length===1?{...c,found:!0,match:i[0]}:{...c,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 it(o)}}})}Ve();tt();jt();Bt();async function me(e){let t=ht(e.wpsUserId);if(t){let i=Lt(),s=fn(i.baseUrl,t);return await e.run(s)}let n=Mn(),r=Lt(),o=et();try{await Ln({creds:r,wpsCfg:n,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 yi=31*24*60*60*1e3,ys=100,gi=200,wi=50,bi=100;function L(e){return{error:e instanceof Error?e.message:String(e)}}function T(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function x(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function ot(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function st(e,t){let n=e[t];if(n!=null){if(typeof n=="boolean")return n;if(n==="true"||n==="false")return n==="true";throw new Error(`${t} must be a boolean`)}}function gs(e,t){let n=e[t];if(n==null)throw new Error(`${t} is required and must be a finite number`);if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}function Zt(e,t){let n=new Date(t.trim());if(Number.isNaN(n.getTime()))throw new Error(`${e} must be a valid RFC3339 / ISO 8601 datetime string`);return n}function at(e){return e.toISOString()}function or(e){let t=e.now??new Date,n,r,o=!!e.startRfc?.trim(),i=!!e.endRfc?.trim();if(o&&i?(n=Zt("start_time",e.startRfc),r=Zt("end_time",e.endRfc)):o?(n=Zt("start_time",e.startRfc),r=new Date(n.getTime()+14*86400*1e3)):i?(r=Zt("end_time",e.endRfc),n=new Date(r.getTime()-14*86400*1e3)):(n=new Date(t.getTime()-86400*1e3),r=new Date(t.getTime()+14*86400*1e3)),r.getTime()<n.getTime())throw new Error("end_time must be >= start_time (RFC3339 range)");return r.getTime()-n.getTime()>yi&&(r=new Date(n.getTime()+yi)),{start:n,end:r}}function ws(e){let{start:t,end:n}=or({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now}),r={start_time:at(t),end_time:at(n)},o=e.pageSize??30;return r.page_size=Math.max(1,Math.min(500,Math.trunc(o))),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(r.page_token=e.pageToken.trim()),r}function bs(e){let{start:t,end:n}=or({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now});return{start_time:at(t),end_time:at(n)}}function Is(e){let t={},n=e.pageSize??30;if(t.page_size=Math.max(1,Math.min(500,Math.trunc(n))),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:r,end:o}=or({startRfc:e.startRfc,endRfc:e.endRfc,now:e.now});return t.start_time=at(r),t.end_time=at(o),t}function Ss(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 Ie(e,t){return`/v7/calendars/${encodeURIComponent(e)}/events/${encodeURIComponent(t)}`}function xs(e,t){return`${Ie(e,t)}/respond`}function sr(e,t){return`${Ie(e,t)}/attendees`}function ks(e,t){return`${sr(e,t)}/batch_create`}function vs(e,t){return`${sr(e,t)}/batch_delete`}function Ts(e,t){return`${Ie(e,t)}/meeting_rooms`}function Es(e,t){return`${Ie(e,t)}/meeting_rooms/batch_create`}function Ps(e,t){return`${Ie(e,t)}/meeting_rooms/batch_delete`}function Ii(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((n,r)=>{if(typeof n!="string")throw new Error(`room_ids[${r}] must be a string`);let o=n.trim();if(!o)throw new Error(`room_ids[${r}] must be non-empty`);return o});if(t.length>bi)throw new Error(`room_ids length must be <= ${bi}`);return{room_ids:t}}function Os(e){let t=e.pageSize??30,r={page_size:Math.max(1,Math.min(ys,Math.trunc(t)))};return e.pageToken!==void 0&&e.pageToken.trim()!==""&&(r.page_token=e.pageToken.trim()),r}function Ae(e){let t=x(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let n=t.trim();if(n!=="internal"&&n!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":n}}async function H(e,t,n){try{return await me({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:n})}catch(r){return L(r)}}function ar(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=T(i,"summary"),a=T(i,"start_time"),c=x(i,"end_time"),l=c&&c.trim()!==""?c.trim():Ss(a),d=x(i,"description"),p=x(i,"location"),u=x(i,"wps_user_id")??"";return u?await H(u,s,async f=>{let m={summary:s,start_time:{datetime:a},end_time:{datetime:l}};d&&(m.description=d),p&&(m.locations=[{name:p}]);let h=await f.request({method:"POST",path:"/v7/calendars/primary/events/create",body:m});return h.data??h}):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=T(i,"wps_user_id"),a=x(i,"start_time"),c=x(i,"end_time"),l=ot(i,"page_size"),d=x(i,"page_token"),p=st(i,"with_cancelled"),u=x(i,"sync_token"),f=x(i,"anchor_time");return await H(s,"\u67E5\u8BE2\u4E3B\u65E5\u5386\u65E5\u7A0B\u5217\u8868",async m=>{let h=Is({startRfc:a,endRfc:c,pageSize:l,pageToken:d,withCancelled:p,syncToken:u,anchorTime:f}),g=await m.request({method:"GET",path:"/v7/calendars/primary/events",query:h});return g.data??g})}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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary";return await H(s,"\u67E5\u8BE2\u65E5\u7A0B\u8BE6\u60C5",async l=>{let d=await l.request({method:"GET",path:Ie(c,a),headers:Ae(i)});return d.data??d})}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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary",l=ot(i,"page_size"),d=x(i,"page_token");return await H(s,"\u83B7\u53D6\u65E5\u7A0B\u53C2\u4E0E\u8005\u5217\u8868",async p=>{let u=Os({pageSize:l,pageToken:d}),f=await p.request({method:"GET",path:sr(c,a),query:u,headers:Ae(i)});return f.data??f})}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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary",l=st(i,"is_notification"),d=i.attendees;if(!Array.isArray(d)||d.length===0)throw new Error("attendees is required and must be a non-empty array");if(d.length>gi)throw new Error(`attendees length must be <= ${gi}`);let p=d.map((u,f)=>{if(typeof u!="object"||u===null||Array.isArray(u))throw new Error(`attendees[${f}] must be an object`);let m=u,h={};if(m.type!==void 0){if(typeof m.type!="string"||!m.type.trim())throw new Error(`attendees[${f}].type must be a non-empty string when provided`);h.type=m.type.trim()}if(m.user_id!==void 0){if(typeof m.user_id!="string"||!m.user_id.trim())throw new Error(`attendees[${f}].user_id must be a non-empty string when provided`);h.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[${f}].third_party_email must be a non-empty string when provided`);h.third_party_email=m.third_party_email.trim()}if(m.is_optional!==void 0){if(typeof m.is_optional!="boolean")throw new Error(`attendees[${f}].is_optional must be a boolean when provided`);h.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[${f}].response_status must be a non-empty string when provided`);h.response_status=m.response_status.trim()}if(Object.keys(h).length===0)throw new Error(`attendees[${f}] must contain at least one valid field`);return h});return await H(s,"\u6DFB\u52A0\u65E5\u7A0B\u53C2\u4E0E\u8005",async u=>{let f={attendees:p};l!==void 0&&(f.is_notification=l);let m=await u.request({method:"POST",path:ks(c,a),body:f,headers:Ae(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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary";return await H(s,"\u83B7\u53D6\u65E5\u7A0B\u4F1A\u8BAE\u5BA4\u5217\u8868",async l=>{let d=await l.request({method:"GET",path:Ts(c,a),headers:Ae(i)});return d.data??d})}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=T(i,"wps_user_id"),a=T(i,"event_id"),c=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 d=Ii(l);return await H(s,"\u6279\u91CF\u6DFB\u52A0\u65E5\u7A0B\u4F1A\u8BAE\u5BA4",async p=>{let u=await p.request({method:"POST",path:Es(c,a),body:d,headers:Ae(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=T(i,"wps_user_id"),a=T(i,"event_id"),c=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 d=Ii(l);return await H(s,"\u6279\u91CF\u5220\u9664\u65E5\u7A0B\u4F1A\u8BAE\u5BA4",async p=>{let u=await p.request({method:"POST",path:Ps(c,a),body:d,headers:Ae(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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary",l=st(i,"is_notification"),d=i.attendee_ids,p;if(d!==void 0){if(!Array.isArray(d))throw new Error("attendee_ids must be an array of strings when provided");p=d.map((h,g)=>{if(typeof h!="string"||!h.trim())throw new Error(`attendee_ids[${g}] must be a non-empty string`);return h.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 f=u.map((h,g)=>{if(typeof h!="object"||h===null||Array.isArray(h))throw new Error(`attendees[${g}] must be an object`);let _=h,y={};if(_.type!==void 0){if(typeof _.type!="string"||!_.type.trim())throw new Error(`attendees[${g}].type must be a non-empty string when provided`);y.type=_.type.trim()}if(_.user_id!==void 0){if(typeof _.user_id!="string"||!_.user_id.trim())throw new Error(`attendees[${g}].user_id must be a non-empty string when provided`);y.user_id=_.user_id.trim()}if(_.third_party_email!==void 0){if(typeof _.third_party_email!="string"||!_.third_party_email.trim())throw new Error(`attendees[${g}].third_party_email must be a non-empty string when provided`);y.third_party_email=_.third_party_email.trim()}if(Object.keys(y).length===0)throw new Error(`attendees[${g}] must contain at least one valid field`);return y});if((p?.length??0)+f.length>wi)throw new Error(`attendee_ids.length + attendees.length must be <= ${wi}`);return await H(s,"\u5220\u9664\u65E5\u7A0B\u53C2\u4E0E\u8005",async h=>{let g={attendees:f};p&&p.length>0&&(g.attendee_ids=p),l!==void 0&&(g.is_notification=l);let _=await h.request({method:"POST",path:vs(c,a),body:g,headers:Ae(i)});return _.data??_})}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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary",l=T(i,"mod_type");if(l!=="normal"&&l!=="one"&&l!=="all")throw new Error("mod_type must be normal, one, or all");let d=T(i,"response_status");if(d!=="accepted"&&d!=="declined"&&d!=="tentative")throw new Error("response_status must be accepted, declined, or tentative");let p=Math.trunc(gs(i,"which_day_time"));return await H(s,"\u7B54\u590D\u65E5\u7A0B\u9080\u8BF7",async u=>{let f=await u.request({method:"POST",path:xs(c,a),body:{mod_type:l,response_status:d,which_day_time:p}});return f.data??f})}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=T(i,"wps_user_id"),a=x(i,"calendar_id")??"primary",c=x(i,"start_time"),l=x(i,"end_time"),d=ot(i,"page_size"),p=x(i,"page_token");return await H(s,"\u67E5\u8BE2\u65E5\u5386\u65E5\u7A0B\u5B9E\u4F8B\u5217\u8868",async u=>{let f=ws({startRfc:c,endRfc:l,pageSize:d,pageToken:p}),m=await u.request({method:"GET",path:`/v7/calendars/${encodeURIComponent(a)}/event_instances`,query:f});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=T(i,"wps_user_id"),a=T(i,"event_id"),c=x(i,"calendar_id")??"primary",l=x(i,"start_time"),d=x(i,"end_time");return await H(s,"\u67E5\u8BE2\u5355\u6761\u65E5\u7A0B\u5B9E\u4F8B",async p=>{let u=bs({startRfc:l,endRfc:d}),f=await p.request({method:"GET",path:`${Ie(c,a)}/event_instances`,query:u});return f.data??f})}catch(s){return L(s)}}});let n=100,r=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=T(i,"wps_user_id"),a=T(i,"keyword");if(a.length>n)throw new Error(`keyword must be at most ${n} characters`);let c=x(i,"calendar_id")??"primary",l=ot(i,"page_size"),d=x(i,"page_token");return await H(s,"\u641C\u7D22\u65E5\u7A0B",async p=>{let u={keyword:a},f=l??200;u.page_size=Math.max(1,Math.min(r,Math.trunc(f))),d!==void 0&&d.trim()!==""&&(u.page_token=d.trim());let m=await p.request({method:"POST",path:`/v7/calendars/${encodeURIComponent(c)}/events/search`,body:u,headers:Ae(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=T(i,"wps_user_id"),a=T(i,"event_id"),c=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 d=ot(i,"which_day_time");if(l==="one"&&d==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 f=x(i,"attendee_ability");if(f!==void 0&&f!=="can_see_others"&&f!=="can_invite_others")throw new Error("attendee_ability must be can_see_others or can_invite_others");return await H(s,"\u4FEE\u6539\u65E5\u7A0B",async m=>{let h={},g=x(i,"summary");g!==void 0&&(h.summary=g);let _=x(i,"description");_!==void 0&&(h.description=_);let y=x(i,"start_time");y!==void 0&&(h.start_time={datetime:y});let w=x(i,"end_time");w!==void 0&&(h.end_time={datetime:w});let b=x(i,"location");b!==void 0&&(h.locations=[{name:b}]),p!==void 0&&(h.free_busy_status=p),u!==void 0&&(h.visibility=u),f!==void 0&&(h.attendee_ability=f),l!==void 0&&(h.mod_type=l),d!==void 0&&(h.which_day_time=Math.trunc(d));let k=st(i,"is_notification");k!==void 0&&(h.is_notification=k);let E=st(i,"is_reinvition");E!==void 0&&(h.is_reinvition=E);let J=i.reminders;Array.isArray(J)&&(h.reminders=J.slice(0,10).map(ie=>{let oe=ie;return{minutes:typeof oe.minutes=="number"?Math.trunc(oe.minutes):0}}));let re=await m.request({method:"POST",path:`${Ie(c,a)}/update`,body:h});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=T(i,"wps_user_id"),a=T(i,"event_id"),c=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 d=ot(i,"which_day_time");if(l==="one"&&d===void 0)throw new Error("which_day_time (ms) is required when mod_type is one");let p=st(i,"is_notification");return await H(s,"\u5220\u9664\u65E5\u7A0B",async u=>{let f={};p!==void 0&&(f.is_notification=p),l!==void 0&&(f.mod_type=l),d!==void 0&&(f.which_day_time=Math.trunc(d));let m=await u.request({method:"POST",path:`${Ie(c,a)}/delete`,body:f});return m.data??m})}catch(s){return L(s)}}})}var As="/v7/todo/personal_tasks",$s="/v7/todo/personal_tasks/batch_get";function Qt(e){return`/v7/todo/personal_tasks/${encodeURIComponent(e.trim())}`}function Rs(e){return`${Qt(e.trim())}/update`}function Cs(e){return`${Qt(e.trim())}/update_status`}var Si=100,qs=20,Ds=50;function ct(e){return{error:e instanceof Error?e.message:String(e)}}function Se(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function K(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function We(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function Us(e,t){let n=e[t];if(n==null)return;if(!Array.isArray(n))throw new Error(`${t} must be an array of strings`);let r=n.map(o=>String(o).trim()).filter(Boolean);return r.length>0?r:void 0}function Ns(e,t){let n=e[t];if(n==null)return;if(!Array.isArray(n))throw new Error(`${t} must be an array of objects with name and value`);let r=[];for(let o of n){if(typeof o!="object"||o===null)continue;let i=o;typeof i.name!="string"||typeof i.value!="string"||r.push({name:i.name.trim(),value:i.value})}return r.length>0?r:void 0}function js(e,t){let n=K(e,t);if(!(n===void 0||n.trim()===""))try{let r=JSON.parse(n);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`${t} must be a JSON object`);return r}catch(r){throw r instanceof SyntaxError?new Error(`${t} must be valid JSON`):r}}function dt(e){let t=K(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let n=t.trim();if(n!=="internal"&&n!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":n}}function Ms(e){let t=e.titleSubject.trim();if(!t)throw new Error("title_subject must be non-empty");let n={subject:t};e.titlePrefix!==void 0&&e.titlePrefix.trim()!==""&&(n.prefix=e.titlePrefix.trim());let r={title:n};if(e.description!==void 0&&e.description.trim()!==""&&(r.description=e.description.trim()),e.dueTimeMs!==void 0){if(!Number.isFinite(e.dueTimeMs))throw new Error("due_time_ms must be a finite number");r.due_time=Math.trunc(e.dueTimeMs)}if((e.status==="todo"||e.status==="finish")&&(r.status=e.status),e.executors!==void 0&&e.executors.length>0){if(e.executors.length>Si)throw new Error(`executors must have at most ${Si} entries`);r.executors=[...e.executors]}return r}function Ws(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 n=e.pageSize;t.page_size=Math.max(1,Math.min(Ds,Math.trunc(n)))}else t.page_size=qs;if(e.pageToken!==void 0&&e.pageToken.trim()!==""&&(t.page_token=e.pageToken.trim()),e.createdTimeStartMs!==void 0||e.createdTimeEndMs!==void 0){let n={};e.createdTimeStartMs!==void 0&&Number.isFinite(e.createdTimeStartMs)&&(n.start_time=Math.trunc(e.createdTimeStartMs)),e.createdTimeEndMs!==void 0&&Number.isFinite(e.createdTimeEndMs)&&(n.end_time=Math.trunc(e.createdTimeEndMs)),Object.keys(n).length>0&&(t.created_time=n)}if(e.dueTimeStartMs!==void 0||e.dueTimeEndMs!==void 0){let n={};e.dueTimeStartMs!==void 0&&Number.isFinite(e.dueTimeStartMs)&&(n.start_time=Math.trunc(e.dueTimeStartMs)),e.dueTimeEndMs!==void 0&&Number.isFinite(e.dueTimeEndMs)&&(n.end_time=Math.trunc(e.dueTimeEndMs)),Object.keys(n).length>0&&(t.due_time=n)}return t}function Ls(e){let t={},n=e.titleSubject?.trim()??"",r=e.titlePrefix?.trim()??"";if(n!==""||r!==""){let o={};n!==""&&(o.subject=n),r!==""&&(o.prefix=r),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 zs=new Set(["finish","unfinish","finish_all","unfinish_all"]);function Fs(e){return zs.has(e)}function xi(e){let t=e.trim();if(!Fs(t))throw new Error("action must be exactly one of: finish, unfinish, finish_all, unfinish_all");return t}function Bs(e){return{action:xi(e.action)}}function Gs(e){if(e==null||typeof e!="object")return null;let t=e,n=["creator_id","creator_user_id","create_user_id","owner_id"];for(let o of n){let i=t[o];if(typeof i=="string"&&i.trim())return i.trim()}let r=t.creator;if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r;for(let i of["id","user_id","userId"]){let s=o[i];if(typeof s=="string"&&s.trim())return s.trim()}}return null}function Hs(e,t){let n=e.trim(),r=t.trim();return n===r?!0:n.toLowerCase()===r.toLowerCase()}function Ks(e){let{hasCompletion:t,completionRaw:n,markScopeRaw:r,actionParam:o,isCreator:i,taskId:s,creatorId:a}=e,c=r?.trim()??"";if(t){if(n!=="complete"&&n!=="incomplete")throw new Error("completion must be complete or incomplete");let d=n==="complete";if(i){if(!c||c==="none")return{kind:"needs_confirmation",taskId:s,completion:n,creatorId:a};if(c!=="self"&&c!=="all")throw new Error("mark_scope must be none, self, or all when provided");return{kind:"post",action:c==="all"?d?"finish_all":"unfinish_all":d?"finish":"unfinish"}}return{kind:"post",action:d?"finish":"unfinish"}}let l=xi(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 Pt(e,t,n){try{return await me({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:n})}catch(r){return ct(r)}}function dr(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(n,r){try{let o=Se(r,"wps_user_id"),i=Se(r,"title_subject"),s=K(r,"title_prefix"),a=K(r,"description"),c=We(r,"due_time_ms"),l=K(r,"status"),d=Us(r,"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=Ms({titleSubject:i,titlePrefix:s,description:a,dueTimeMs:c,status:p,executors:d});return await Pt(o,"\u521B\u5EFA\u4E2A\u4EBA\u5F85\u529E",async f=>{let m=await f.request({method:"POST",path:As,body:u,headers:dt(r)});return m.data??m})}catch(o){return ct(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(n,r){try{let o=Se(r,"wps_user_id"),i=K(r,"keyword"),s=K(r,"executor"),a=K(r,"status"),c=We(r,"page_size"),l=K(r,"page_token"),d=We(r,"created_time_start_ms"),p=We(r,"created_time_end_ms"),u=We(r,"due_time_start_ms"),f=We(r,"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 h=Ws({keyword:i,executor:s,status:m,pageSize:c,pageToken:l,createdTimeStartMs:d,createdTimeEndMs:p,dueTimeStartMs:u,dueTimeEndMs:f});return await Pt(o,"\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u5217\u8868",async g=>{let _=await g.request({method:"POST",path:$s,body:h,headers:dt(r)});return _.data??_})}catch(o){return ct(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(n,r){try{let o=Se(r,"wps_user_id"),i=Se(r,"task_id");return await Pt(o,"\u83B7\u53D6\u4E2A\u4EBA\u5F85\u529E\u8BE6\u60C5",async s=>{let a=await s.request({method:"GET",path:Qt(i),headers:dt(r)});return a.data??a})}catch(o){return ct(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(n,r){try{let o=Se(r,"wps_user_id"),i=Se(r,"task_id"),s=K(r,"completion"),a=K(r,"mark_scope"),c=K(r,"action"),l=s!==void 0,d=c!==void 0&&c!=="";if(l===d)throw!l&&!d?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 Pt(o,"\u66F4\u65B0\u4E2A\u4EBA\u5F85\u529E\u72B6\u6001",async p=>{let u=await p.request({method:"GET",path:Qt(i),headers:dt(r)}),f=u.data??u,m=Gs(f),h=m!==null&&Hs(o,m),g=Ks({hasCompletion:l,completionRaw:s,markScopeRaw:a,actionParam:c,isCreator:h,taskId:i,creatorId:m});if(g.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:g.taskId,completion:g.completion,creator_id:g.creatorId,...g.requested_action!==void 0?{requested_action:g.requested_action}:{}};let _=Bs({action:g.action}),y=await p.request({method:"POST",path:Cs(i),body:_,headers:dt(r)});return y.data??y})}catch(o){return ct(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(n,r){try{let o=Se(r,"wps_user_id"),i=Se(r,"task_id"),s=K(r,"title_subject"),a=K(r,"title_prefix"),c=K(r,"description"),l=We(r,"due_time_ms"),d=Ns(r,"ext_attrs"),p=js(r,"notify_config_json"),u=Ls({titleSubject:s,titlePrefix:a,description:c,dueTimeMs:l,extAttrs:d,notifyConfig:p});return await Pt(o,"\u66F4\u65B0\u4E2A\u4EBA\u5F85\u529E",async f=>{let m=await f.request({method:"POST",path:Rs(i),body:u,headers:dt(r)});return m.data??m})}catch(o){return ct(o)}}})}function xe(e){return`/v7/coop/dbsheet/${encodeURIComponent(e)}`}function Js(e){return`/v7/dbsheet/${encodeURIComponent(e)}`}function he(e){return{error:e instanceof Error?e.message:String(e)}}function $(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function $e(e){let t=e.sheet_id;if(t==null)throw new Error("sheet_id is required");let n=typeof t=="number"?t:parseInt(String(t),10);if(!Number.isFinite(n)||n<=0)throw new Error("sheet_id must be a positive integer");return n}function Le(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function Ot(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function Re(e,t){let n=e[t];if(n!=null){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1;throw new Error(`${t} must be a boolean`)}}function en(e,t){let n=e[t];if(n!=null){if(!Array.isArray(n))throw new Error(`${t} must be an array`);return n.map(r=>String(r))}}function ki(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 ye(e,t,n){return me({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:n})}function cr(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id");return await ye(o,"wps_dbsheet_get_schema",async s=>{let a=await s.request({method:"GET",path:`${xe(i)}/schema`});return a.data??a})}catch(o){return he(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=r.sheets;if(!Array.isArray(s)||s.length===0)throw new Error("sheets must be a non-empty array");return await ye(o,"wps_dbsheet_batch_create_sheets",async a=>{let c=await a.request({method:"POST",path:`${Js(i)}/sheets/batch_create`,body:{sheets:s}});return c.data??c})}catch(o){return he(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=$(r,"name");return await ye(o,"wps_dbsheet_update_sheet",async c=>{let l=await c.request({method:"POST",path:`${xe(i)}/sheets/${s}/update`,body:{name:a}});return l.data??l})}catch(o){return he(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=r.records;if(!Array.isArray(a)||a.length===0)throw new Error("records must be a non-empty array");let c=a.map((l,d)=>{if(!l||typeof l!="object")throw new Error(`records[${d}] must be an object`);return{fields_value:ki(l.fields_value,`records[${d}].fields_value`)}});return await ye(o,"wps_dbsheet_create_records",async l=>{let d=await l.request({method:"POST",path:`${xe(i)}/sheets/${s}/records/create`,body:{records:c}});return d.data??d})}catch(o){return he(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=r.records;if(!Array.isArray(a)||a.length===0)throw new Error("records must be a non-empty array");let c=a.map((l,d)=>{if(!l||typeof l!="object")throw new Error(`records[${d}] must be an object`);let p=l;if(!p.id||typeof p.id!="string")throw new Error(`records[${d}].id is required and must be a string`);return{id:p.id,fields_value:ki(p.fields_value,`records[${d}].fields_value`)}});return await ye(o,"wps_dbsheet_update_records",async l=>{let d=await l.request({method:"POST",path:`${xe(i)}/sheets/${s}/records/update`,body:{records:c}});return d.data??d})}catch(o){return he(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a={},c=en(r,"fields");c&&(a.fields=c),r.filter!==void 0&&r.filter!==null&&(a.filter=r.filter);let l=Ot(r,"max_records");l!==void 0&&(a.max_records=l);let d=Ot(r,"page_size");d!==void 0&&(a.page_size=d);let p=Le(r,"page_token");p!==void 0&&p!==""&&(a.page_token=p);let u=Le(r,"view_id");u!==void 0&&u!==""&&(a.view_id=u);let f=Le(r,"text_value");f!==void 0&&(a.text_value=f);let m=Re(r,"show_fields_info");m!==void 0&&(a.show_fields_info=m);let h=Re(r,"show_record_extra_info");return h!==void 0&&(a.show_record_extra_info=h),await ye(o,"wps_dbsheet_list_records",async g=>{let _=await g.request({method:"POST",path:`${xe(i)}/sheets/${s}/records`,body:a});return _.data??_})}catch(o){return he(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a={},c=en(r,"fields");c&&(a.fields=c),r.filter!==void 0&&r.filter!==null&&(a.filter=r.filter);let l=Ot(r,"max_records");l!==void 0&&(a.max_records=l);let d=Ot(r,"page_num");d!==void 0&&(a.page_num=d);let p=Ot(r,"page_size");p!==void 0&&(a.page_size=p);let u=Le(r,"view_id");u!==void 0&&u!==""&&(a.view_id=u);let f=Le(r,"text_value");f!==void 0&&(a.text_value=f);let m=Re(r,"show_fields_info");m!==void 0&&(a.show_fields_info=m);let h=Re(r,"show_record_extra_info");return h!==void 0&&(a.show_record_extra_info=h),await ye(o,"wps_dbsheet_list_records_by_page",async g=>{let _=await g.request({method:"POST",path:`${xe(i)}/sheets/${s}/records/list_by_page`,body:a});return _.data??_})}catch(o){return he(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=en(r,"records");if(!a||a.length===0)throw new Error("records must be a non-empty array of record IDs");let c={records:a},l=Le(r,"text_value");l!==void 0&&(c.text_value=l);let d=Re(r,"show_fields_info");d!==void 0&&(c.show_fields_info=d);let p=Re(r,"show_record_extra_info");return p!==void 0&&(c.show_record_extra_info=p),await ye(o,"wps_dbsheet_get_records",async u=>{let f=await u.request({method:"POST",path:`${xe(i)}/sheets/${s}/records/search`,body:c});return f.data??f})}catch(o){return he(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=$(r,"record_id"),c={},l=Le(r,"text_value");l!==void 0&&(c.text_value=l);let d=Re(r,"show_fields_info");d!==void 0&&(c.show_fields_info=d);let p=Re(r,"show_record_extra_info");return p!==void 0&&(c.show_record_extra_info=p),await ye(o,"wps_dbsheet_get_record",async u=>{let f=await u.request({method:"GET",path:`${xe(i)}/sheets/${s}/records/${encodeURIComponent(a)}`,query:Object.keys(c).length>0?c:void 0});return f.data??f})}catch(o){return he(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(n,r){try{let o=$(r,"wps_user_id"),i=$(r,"file_id"),s=$e(r),a=en(r,"records");if(!a||a.length===0)throw new Error("records must be a non-empty array of record IDs");return await ye(o,"wps_dbsheet_delete_records",async c=>{let l=await c.request({method:"POST",path:`${xe(i)}/sheets/${s}/records/batch_delete`,body:{records:a}});return l.data??l})}catch(o){return he(o)}}})}Ve();import{createHash as Xs}from"node:crypto";import{readFile as Vs,stat as Ys}from"node:fs/promises";var Zs="/v7/drives",Qs="/v7/files/search",ea=50,ta=500,na=50,ra=500,ia=50,oa=500,vi=["folder","file","shortcut"],tn=["fail","rename","overwrite","replace"],Ci=["kdc","plain","markdown"],qi=["sync","async","auto"],sa=["para","table","component","textbox","all"],Ti=["file_name","content","all"],Ei=["folder","file","shortcut"],Pi=["ctime","mtime","otime","stime"],Oi=["desc","asc"],Ai=["ctime","mtime"],$i=["desc","asc"],Ri=["ctime","mtime","dtime","fname","fsize"],aa=["all","share_by_me","share_to_me","latest","personal_drive","group_drive","recycle","customize","latest_opened","latest_edited"];function qe(e){return{error:e instanceof Error?e.message:String(e)}}function D(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function R(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function lt(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function Z(e,t){let n=e[t];if(n!=null){if(typeof n=="boolean")return n;if(n==="true"||n==="false")return n==="true";throw new Error(`${t} must be a boolean`)}}function F(e,t){let n=e[t];if(n==null)return;if(!Array.isArray(n))throw new Error(`${t} must be an array of strings`);let r=n.map(o=>String(o).trim()).filter(Boolean);return r.length>0?r:void 0}function Ce(e){let t=R(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let n=t.trim();if(n!=="internal"&&n!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":n}}function da(e){let t={};for(let[n,r]of Object.entries(e.requestHeaders)){let o=n.trim();if(o==="")continue;let i=o.toLowerCase();i==="content-length"||i==="transfer-encoding"||i==="content-type"||(t[o]=r)}return t["Content-Type"]="application/octet-stream",t}function ca(e){let t=e.trim();if(!t)throw new Error("url is required and must be a non-empty string");let n;try{n=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(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`url must use http: or https: scheme, got: ${n.protocol}`)}function la(e){let t={allotee_type:e.alloteeType,page_size:Math.max(1,Math.min(ta,Math.trunc(e.pageSize??ea)))};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 pa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/create`}function ua(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/children`}function _a(e){let t={page_size:Math.max(1,Math.min(oa,Math.trunc(e.pageSize??ia)))};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 fa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/request_upload`}function ma(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/commit_upload`}function ha(e){let t=e.name.trim();if(!t)throw new Error("name must be a non-empty string");let n={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");n.file_id=e.fileId.trim()}else e.fileId!==void 0&&e.fileId.trim()!==""&&(n.file_id=e.fileId.trim());return e.onNameConflict!==void 0&&(n.on_name_conflict=e.onNameConflict),e.parentPath!==void 0&&e.parentPath.length>0&&(n.parent_path=[...e.parentPath]),n}function ya(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(n=>({type:n.type,sum:n.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 ga(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 wa(e,t){return`/v7/drives/${encodeURIComponent(e.trim())}/files/${encodeURIComponent(t.trim())}/content`}function ba(e){let t={};if(e.format!==void 0&&e.format.trim()!==""){let n=e.format.trim();if(!Ci.includes(n))throw new Error("format must be one of: kdc, plain, markdown");t.format=n}if(e.includeElements!==void 0&&e.includeElements.length>0){let n=e.includeElements.map(r=>r.trim()).filter(Boolean).filter((r,o,i)=>i.indexOf(r)===o);for(let r of n)if(!sa.includes(r))throw new Error("include_elements items must be one of: para, table, component, textbox, all");n.length>0&&(t.include_elements=n)}if(e.mode!==void 0&&e.mode.trim()!==""){let n=e.mode.trim();if(!qi.includes(n))throw new Error("mode must be one of: sync, async, auto");t.mode=n}return e.taskId!==void 0&&e.taskId.trim()!==""&&(t.task_id=e.taskId.trim()),t}function Ia(e){return`/v7/files/${encodeURIComponent(e.trim())}/meta`}function Sa(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 xa(e){let t={type:e.type,page_size:Math.max(1,Math.min(ra,Math.trunc(e.pageSize??na)))};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 ze(e,t,n,r){try{return await me({wpsUserId:e,authCardOriginalMessage:t,needsAuthMessage:n,logTag:"drive",run:r})}catch(o){return qe(o)}}function lr(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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"allotee_type");if(i!=="user"&&i!=="group"&&i!=="app")throw new Error("allotee_type must be user, group, or app");let s=i,a=R(r,"allotee_id"),c=Z(r,"with_ext_attrs"),l=lt(r,"page_size"),d=R(r,"page_token"),p=F(r,"sources");return await ze(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 f=la({alloteeType:s,alloteeId:a,withExtAttrs:c,pageSize:l,pageToken:d,sources:p}),m=await u.request({method:"GET",path:Zs,query:f,headers:Ce(r)});return m.data??m})}catch(o){return qe(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:[...$i],description:"Optional order direction."},order_by:{type:"string",enum:[...Ri],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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"drive_id"),s=D(r,"parent_id"),a=Z(r,"with_permission"),c=Z(r,"with_ext_attrs"),l=R(r,"filter_exts"),d=lt(r,"page_size"),p=R(r,"page_token"),u=R(r,"order");if(u!==void 0&&!$i.includes(u))throw new Error("order must be one of: desc, asc");let f=u,m=R(r,"order_by");if(m!==void 0&&!Ri.includes(m))throw new Error("order_by must be one of: ctime, mtime, dtime, fname, fsize");let h=m,g=r.filter_type,_;if(g!=null){if(typeof g!="object"||Array.isArray(g))throw new Error("filter_type must be an object when provided");_=g}return await ze(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 y=>{let w=_a({withPermission:a,withExtAttrs:c,filterExts:l,filterType:_,order:f,orderBy:h,pageSize:d,pageToken:p}),b=await y.request({method:"GET",path:ua(i,s),query:w,headers:Ce(r)});return b.data??b})}catch(o){return qe(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:[...vi],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:[...tn],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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"drive_id"),s=D(r,"parent_id"),a=D(r,"file_type");if(!vi.includes(a))throw new Error("file_type must be one of: folder, file, shortcut");let c=a,l=D(r,"name"),d=R(r,"file_id"),p=R(r,"on_name_conflict");if(p!==void 0&&!tn.includes(p))throw new Error("on_name_conflict must be one of: fail, rename, overwrite, replace");let u=p,f=F(r,"parent_path");return await ze(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 h=ha({fileType:c,name:l,fileId:d,onNameConflict:u,parentPath:f}),g=await m.request({method:"POST",path:pa(i,s),body:h,headers:Ce(r)});return g.data??g})}catch(o){return qe(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:[...tn],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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"drive_id"),s=D(r,"parent_id"),a=D(r,"file_path"),c=R(r,"name"),l=R(r,"on_name_conflict");if(l!==void 0&&!tn.includes(l))throw new Error("on_name_conflict must be one of: fail, rename, overwrite, replace");let d=l,p=R(r,"file_id"),u=Z(r,"internal"),f=R(r,"upload_scene"),m=a.trim();try{if(!(await Ys(m)).isFile())throw new Error("path is not a regular file")}catch(y){throw new Error(`file_path "${m}" is not accessible: ${y instanceof Error?y.message:String(y)}`)}let h=await Vs(m);if(!c){let y=Math.max(m.lastIndexOf("/"),m.lastIndexOf("\\")),b=(y>=0?m.substring(y+1):m).replace(/^[0-9a-f]{8}_/i,"");b&&(c=b)}if(h.byteLength===0)throw new Error("upload content is empty (file has zero bytes)");let g=h.byteLength,_=Xs("sha256").update(h).digest("hex");return await ze(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 y=>{let w=ya({size:g,fileId:p??void 0,hashes:[{type:"sha256",sum:_}],internal:u??void 0,name:c??void 0,onNameConflict:d,uploadScene:f??void 0}),b=await y.request({method:"POST",path:fa(i,s),body:w,headers:Ce(r)}),k=b.data??b,E=k.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(k).substring(0,300)}`);let J=typeof E.method=="string"?E.method.toUpperCase():"PUT",re=E.url;ca(re);let ie=E.headers??{},oe=typeof k.upload_id=="string"?k.upload_id:void 0,ge=ht(o);if(!ge||!ge.trim())throw new Error("delegated access token missing after auth gate");let se=da({requestHeaders:ie}),ae={Authorization:`Bearer ${ge.trim()}`,...se},He=new Uint8Array(h.buffer,h.byteOffset,h.byteLength),pe;try{pe=await fetch(re,{method:J,headers:ae,body:He})}catch(we){let Ke=we instanceof Error?we.message:String(we);throw new Error(`upload step-2 fetch failed: ${Ke}. Check outbound HTTPS/DNS/firewall from the gateway to the presigned URL.`)}if(!pe.ok){let we=await pe.text().catch(()=>"");throw new Error(`upload step-2 failed: HTTP ${pe.status} ${we.substring(0,300)} [diag: size=${g}, sha256=${_}]`)}if(!oe)return{step1:k,step2_status:pe.status,etag:pe.headers.get("etag")??void 0,warning:"upload_id missing from step-1 \u2014 skipped commit_upload."};let mr=ga({uploadId:oe}),ut=await y.request({method:"POST",path:ma(i,s),body:mr,headers:Ce(r)});return ut.data??ut})}catch(o){return qe(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:[...Ci],description:"Optional output format."},include_elements:{type:"array",items:{type:"string"},description:"Optional extracted element types."},mode:{type:"string",enum:[...qi],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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"drive_id"),s=D(r,"file_id"),a=R(r,"format"),c=F(r,"include_elements"),l=R(r,"mode"),d=R(r,"task_id");return await ze(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=ba({format:a,includeElements:c,mode:l,taskId:d}),f=await p.request({method:"GET",path:wa(i,s),query:Object.keys(u).length>0?u:void 0,headers:Ce(r)});return f.data??f})}catch(o){return qe(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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"file_id"),s=Z(r,"with_permission"),a=Z(r,"with_ext_attrs"),c=Z(r,"with_drive");return await ze(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 d=Sa({withPermission:s,withExtAttrs:a,withDrive:c}),p=await l.request({method:"GET",path:Ia(i),query:Object.keys(d).length>0?d:void 0,headers:Ce(r)});return p.data??p})}catch(o){return qe(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:[...Ti],description:"Search type."},file_type:{type:"string",enum:[...Ei],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:[...Pi],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:[...Oi],description:"Optional order."},order_by:{type:"string",enum:[...Ai],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(n,r){try{let o=D(r,"wps_user_id"),i=D(r,"type");if(!Ti.includes(i))throw new Error("type must be one of: file_name, content, all");let s=i,a=R(r,"file_type");if(a!==void 0&&!Ei.includes(a))throw new Error("file_type must be one of: folder, file, shortcut");let c=a,l=R(r,"time_type");if(l!==void 0&&!Pi.includes(l))throw new Error("time_type must be one of: ctime, mtime, otime, stime");let d=l,p=R(r,"order");if(p!==void 0&&!Oi.includes(p))throw new Error("order must be one of: desc, asc");let u=p,f=R(r,"order_by");if(f!==void 0&&!Ai.includes(f))throw new Error("order_by must be one of: ctime, mtime");let m=f,h=F(r,"scope");if(h!==void 0){for(let g of h)if(!aa.includes(g))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 ze(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 g=>{let _=xa({keyword:R(r,"keyword"),type:s,fileType:c,fileExts:F(r,"file_exts"),driveIds:F(r,"drive_ids"),parentIds:F(r,"parent_ids"),creatorIds:F(r,"creator_ids"),modifierIds:F(r,"modifier_ids"),sharerIds:F(r,"sharer_ids"),receiverIds:F(r,"receiver_ids"),timeType:d,startTime:lt(r,"start_time"),endTime:lt(r,"end_time"),withPermission:Z(r,"with_permission"),withLink:Z(r,"with_link"),withTotal:Z(r,"with_total"),pageSize:lt(r,"page_size"),pageToken:R(r,"page_token"),channels:F(r,"channels"),deviceIds:F(r,"device_ids"),excludeChannels:F(r,"exclude_channels"),excludeFileExts:F(r,"exclude_file_exts"),filterUserId:lt(r,"filter_user_id"),fileExtGroups:F(r,"file_ext_groups"),withFolder:Z(r,"with_folder"),withDrive:Z(r,"with_drive"),order:u,orderBy:m,scope:h,searchOperatorName:Z(r,"search_operator_name")}),y=await g.request({method:"GET",path:Qs,query:_,headers:Ce(r)});return y.data??y})}catch(o){return qe(o)}}})}var ka="/v7/airpage/files";function Fe(e,t){return`/v7/airpage/${encodeURIComponent(e.trim())}${t}`}function Ge(e){return{arg:Buffer.from(JSON.stringify(e),"utf8").toString("base64")}}function Be(e,t){return e.length>36?`${t} (${e.slice(0,36)}...)`:`${t} (${e})`}function Ui(e,t){let n=e.operation,r=e.blockId;if(typeof n!="string"||!n.trim())throw new Error(`${t}.operation is required and must be a non-empty string`);if(typeof r!="string"||!r.trim())throw new Error(`${t}.blockId is required and must be a non-empty string`)}var pr=["rename","fail","overwrite"];function ke(e){return{error:e instanceof Error?e.message:String(e)}}function C(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function Di(e,t){let n=e[t];if(n==null)return;if(typeof n!="string")throw new Error(`${t} must be a string`);let r=n.trim();return r===""?void 0:r}function rn(e,t){let n=e[t];if(!Array.isArray(n))throw new Error(`${t} is required and must be an array`);return n}function va(e,t){let r=rn(e,t).map(o=>String(o).trim()).filter(Boolean);if(r.length===0)throw new Error(`${t} must contain at least one non-empty string`);return r}function Ta(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return Math.trunc(n);if(typeof n=="string"&&n.trim()!==""){let r=Number(n.trim());if(Number.isFinite(r))return Math.trunc(r)}throw new Error(`${t} must be a finite integer when provided`)}}function nn(e,t){let n=e[t];if(n==null)throw new Error(`${t} is required and must be a finite integer`);if(typeof n=="number"&&Number.isFinite(n))return Math.trunc(n);if(typeof n=="string"&&n.trim()!==""){let r=Number(n.trim());if(Number.isFinite(r))return Math.trunc(r)}throw new Error(`${t} must be a finite integer`)}function Ea(e){let t={blockId:e.blockId.trim(),content:e.content},n=e.index;return n!==void 0&&(t.index=n),Ge(t)}function Pa(e){let t={blockId:e.blockId.trim()};return Ge(t)}function Oa(e){let t={blockIds:e.blockIds.map(n=>n.trim()).filter(Boolean)};if(t.blockIds.length===0)throw new Error("blockIds must contain at least one non-empty id");return Ge(t)}function Aa(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 Ge(t)}function $a(e){if(!Array.isArray(e)||e.length===0)throw new Error("delete_items must contain at least one delete range");let t=e.map(n=>{let r=n.blockId.trim(),o=Math.trunc(n.startIndex),i=Math.trunc(n.endIndex);if(!r)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:r,startIndex:o,endIndex:i}});return Ge(t)}function Ra(e){return Ui(e,"operation"),Ge(e)}function Ca(e){if(!Array.isArray(e)||e.length===0)throw new Error("operations must contain at least one operation object");for(let[t,n]of e.entries()){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`operations[${t}] must be an object`);Ui(n,`operations[${t}]`)}return Ge(e)}function qa(e){let t=e.trim().toLowerCase();if(pr.includes(t))return t;throw new Error(`on_name_conflict must be one of: ${pr.join(", ")} (got: ${e})`)}function Da(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 De(e,t,n){try{return await me({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:n})}catch(r){return ke(r)}}function ur(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:[...pr],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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"drive_id"),s=C(r,"name"),a=C(r,"on_name_conflict"),c=qa(a),l=Di(r,"parent_id"),d=Di(r,"template_id"),p=`\u521B\u5EFA\u667A\u80FD\u6587\u6863: ${s}`;return await De(o,p,async u=>{let f=Da({driveId:i,name:s,onNameConflict:c,parentId:l,templateId:d}),m=await u.request({method:"POST",path:ka,body:f});return m.data??m})}catch(o){return ke(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) per API. JSON fields: `blockId` (parent block; use literal doc for document root), optional `index` (insert position; omit to let API default, typically 0), required `content` (array of child block nodes). Example paragraph: `{ "type":"paragraph","content":[{"type":"text","content":"hello"}] }`. Requires delegated `kso.airpage.readwrite`. Use SenderId as `wps_user_id`. `file_id` is the smart document id (e.g. from create file response `id` / `link_id` per your product convention).',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 = end). Omit to use API default."},content:{type:"array",description:"Required array of block nodes to insert (e.g. paragraph with nested text blocks per Open Platform docs).",items:{type:"object",additionalProperties:!0}}},required:["wps_user_id","file_id","block_id","content"]},async execute(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),s=C(r,"block_id"),a=rn(r,"content"),c=Ta(r,"index"),l=Ea({blockId:s,content:a,index:c}),d=Be(i,"\u667A\u80FD\u6587\u6863\u521B\u5EFA\u5757\u5185\u5BB9");return await De(o,d,async p=>{let u=await p.request({method:"POST",path:Fe(i,"/blocks/create"),body:l});return u.data??u})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),s=C(r,"block_id"),a=Pa({blockId:s}),c=Be(i,"\u667A\u80FD\u6587\u6863\u67E5\u8BE2\u6587\u6863\u5757");return await De(o,c,async l=>{let d=await l.request({method:"POST",path:Fe(i,"/blocks"),body:a});return d.data??d})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),s=va(r,"block_ids"),a=Oa({blockIds:s}),c=Be(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u67E5\u8BE2\u6587\u6863\u5757");return await De(o,c,async l=>{let d=await l.request({method:"POST",path:Fe(i,"/blocks/batch_get"),body:a});return d.data??d})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),s=C(r,"block_id"),a=nn(r,"start_index"),c=nn(r,"end_index"),l=Aa({blockId:s,startIndex:a,endIndex:c}),d=Be(i,"\u667A\u80FD\u6587\u6863\u5220\u9664\u5757\u5185\u5BB9");return await De(o,d,async p=>{let u=await p.request({method:"POST",path:Fe(i,"/blocks/delete"),body:l});return u.data??u})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),a=rn(r,"delete_items").map((d,p)=>{if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`delete_items[${p}] must be an object`);let u=d,f=C(u,"block_id"),m=nn(u,"start_index"),h=nn(u,"end_index");return{blockId:f,startIndex:m,endIndex:h}}),c=$a(a),l=Be(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u5220\u9664\u5757\u5185\u5BB9");return await De(o,l,async d=>{let p=await d.request({method:"POST",path:Fe(i,"/blocks/batch_delete"),body:c});return p.data??p})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),s=r.operation;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("operation is required and must be an object");let c=Ra(s),l=Be(i,"\u667A\u80FD\u6587\u6863\u66F4\u65B0\u6587\u6863\u5757");return await De(o,l,async d=>{let p=await d.request({method:"POST",path:Fe(i,"/blocks/update"),body:c});return p.data??p})}catch(o){return ke(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(n,r){try{let o=C(r,"wps_user_id"),i=C(r,"file_id"),a=rn(r,"operations").map((d,p)=>{if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`operations[${p}] must be an object`);return d}),c=Ca(a),l=Be(i,"\u667A\u80FD\u6587\u6863\u6279\u91CF\u66F4\u65B0\u6587\u6863\u5757");return await De(o,l,async d=>{let p=await d.request({method:"POST",path:Fe(i,"/blocks/batch_update"),body:c});return p.data??p})}catch(o){return ke(o)}}})}var Ua="/v7/meeting_rooms",Na="/v7/meeting_rooms/search",ja="/v7/meeting_room_bookings/batch_get",Ma=["success","failed"];var Mi=["success","failed","approving"];function At(e){return{error:e instanceof Error?e.message:String(e)}}function ve(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`${t} is required and must be a non-empty string`);return n.trim()}function pt(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}function _r(e,t){let n=e[t];if(n!=null){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}}function Ni(e,t){let n=e[t];if(n==null)throw new Error(`${t} is required and must be a finite number`);if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){let r=Number(n);if(Number.isFinite(r))return r}throw new Error(`${t} must be a finite number`)}function Wa(e,t){let n=e[t];if(n!=null){if(typeof n=="boolean")return n;if(n==="true"||n==="false")return n==="true";throw new Error(`${t} must be a boolean`)}}function Wi(e,t){let n=e[t];if(n==null)return;if(!Array.isArray(n))throw new Error(`${t} must be an array`);let r=[];for(let o of n){if(typeof o!="string")throw new Error(`${t} entries must be strings`);let i=o.trim();i!==""&&r.push(i)}return r.length>0?r:void 0}function La(e,t){let n=Wi(e,t);if(n===void 0)return;let r=new Set(Mi),o=n.filter(i=>r.has(i));return o.length>0?o:void 0}function ji(e){let t=pt(e,"x_kso_id_type");if(t===void 0||t.trim()==="")return;let n=t.trim();if(n!=="internal"&&n!=="external")throw new Error("x_kso_id_type must be internal or external when provided");return{"X-Kso-Id-Type":n}}function za(e){let t=e.pageSize??20,r={page_size:Math.max(1,Math.min(500,Math.trunc(t)))};return e.roomLevelId!==void 0&&e.roomLevelId.trim()!==""&&(r.room_level_id=e.roomLevelId.trim()),e.pageToken!==void 0&&e.pageToken.trim()!==""&&(r.page_token=e.pageToken.trim()),r}function Fa(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 Ba(e){let t=e.keyword.trim();if(!t)throw new Error("keyword is required and must be a non-empty string");let n=e.pageSize??20,r=Math.max(1,Math.min(100,Math.trunc(n))),o={keyword:t,page_size:r};return e.pageToken!==void 0&&e.pageToken.trim()!==""&&(o.page_token=e.pageToken.trim()),o}function Ga(e){let t=Math.trunc(Number(e.startTimeSec)),n=Math.trunc(Number(e.endTimeSec));if(!Number.isFinite(t)||!Number.isFinite(n))throw new Error("start_time and end_time must be finite Unix timestamps in seconds");if(n<t)throw new Error("end_time must be >= start_time (Unix seconds)");let r=e.roomLevelId?.trim()??"",o=r!=="",i=e.roomIds?.filter(d=>d.trim()!=="").map(d=>d.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,c=Math.max(1,Math.min(500,Math.trunc(Number(a))));if(!Number.isFinite(c))throw new Error("page_size must be finite");let l={start_time:t,end_time:n,page_size:c};return o&&(l.room_level_id=r),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 Ha(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 Ka(e){let t=e.trim();if(t!=="success"&&t!=="failed")throw new Error("status must be success or failed");return{status:t}}function fr(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(n,r){try{ve(r,"wps_user_id");let o=pt(r,"room_level_id"),i=_r(r,"page_size"),s=pt(r,"page_token"),a=za({roomLevelId:o,pageSize:i,pageToken:s}),c=await e.request({method:"GET",path:Ua,query:a});return c.data??c}catch(o){return At(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(n,r){try{ve(r,"wps_user_id");let o=ve(r,"room_id"),i=await e.request({method:"GET",path:Fa(o)});return i.data??i}catch(o){return At(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(n,r){try{ve(r,"wps_user_id");let o=ve(r,"keyword"),i=_r(r,"page_size"),s=pt(r,"page_token"),a=Ba({keyword:o,pageSize:i,pageToken:s}),c=await e.request({method:"POST",path:Na,body:a});return c.data??c}catch(o){return At(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:[...Mi]},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(n,r){try{ve(r,"wps_user_id");let o=Ni(r,"start_time"),i=Ni(r,"end_time"),s=Wi(r,"room_ids"),a=pt(r,"room_level_id"),c=Wa(r,"include_deleted"),l=_r(r,"page_size"),d=pt(r,"page_token"),p=La(r,"results"),u=Ga({startTimeSec:o,endTimeSec:i,roomIds:s,roomLevelId:a,includeDeleted:c,pageSize:l,pageToken:d,results:p??void 0}),f=await e.request({method:"POST",path:ja,body:u,headers:ji(r)});return f.data??f}catch(o){return At(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:[...Ma],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(n,r){try{ve(r,"wps_user_id");let o=ve(r,"booking_id"),i=ve(r,"status"),s=Ka(i),a=await e.request({method:"POST",path:Ha(o),body:s,headers:ji(r)});return a.data??a}catch(o){return At(o)}}})}function Ja(){return new Proxy({},{get(e,t,n){let r=jn(),o=Reflect.get(r,t,n);return typeof o=="function"?o.bind(r):o}})}function Li(e){let t=[],n=o=>{e(()=>({name:o.name,label:o.name,description:o.description,parameters:o.parameters,async execute(s,a){let c=await o.execute(s,a);if(c&&typeof c=="object"&&"error"in c)throw new Error(c.error);return{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:c}}}),{name:o.name}),t.push(o.name)},r=Ja();return er(r,n),tr(r,n),ir(r,n),Jn(r,n),ar(r,n),dr(r,n),lr(r,n),cr(r,n),ur(r,n),fr(r,n),console.log(`[wps-xiezuo] OAPI tools registered: ${t.length} tools`),t.length}var Xa={id:_e,name:"WPS Xiezuo",description:"WPS365 Open Platform channel plugin for OpenClaw",configSchema:$r(),register(e){li(e.runtime);let t=e.logger??{info:()=>{},warn:()=>{},error:()=>{}};if(e.registerChannel({plugin:Zn}),typeof e.registerTool=="function"){t.info(`[${_e}] registerTool is available (type: ${typeof e.registerTool})`);try{let n=Li(e.registerTool);t.info(`[${_e}] registered ${n} WPS OAPI tool factories`)}catch(n){t.error(`[${_e}] tool registration failed: ${n}`)}}else t.warn(`[${_e}] registerTool not available (type: ${typeof e.registerTool})`);typeof e.on=="function"?(e.on("before_prompt_build",async(n,r)=>{let o=r;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: <\u8DEF\u5F84>]` \u6216 `[\u5DF2\u4E0B\u8F7D\u6587\u4EF6: <\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
36
  `)}}),t.info(`[${_e}] before_prompt_build hook registered`)):t.warn(`[${_e}] api.on not available, cannot register prompt hook`),t.info(`[${_e}] plugin registered`)}},Al=Xa;export{Al as default};
37
37
  //# sourceMappingURL=__bundle.tmp.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wps365/openclaw-wpsxiezuo",
3
- "version": "1.8.1",
3
+ "version": "1.8.2-beta.1",
4
4
  "description": "WPS Xiezuo OpenClaw plugin - connect OpenClaw Agent to the WPS Open Platform enterprise robot",
5
5
  "keywords": [
6
6
  "openclaw",
@@ -8,7 +8,6 @@
8
8
  ],
9
9
  "license": "MIT",
10
10
  "author": "WPS Xiezuo Team",
11
- "packageManager": "pnpm@10.33.0",
12
11
  "type": "module",
13
12
  "main": "dist/index.js",
14
13
  "types": "dist/index.d.ts",
@@ -34,19 +33,6 @@
34
33
  "engines": {
35
34
  "node": ">=22.0.0"
36
35
  },
37
- "scripts": {
38
- "build": "tsc -p tsconfig.json",
39
- "build:release": "rm -rf dist && tsc -p tsconfig.json && node scripts/minify.mjs",
40
- "typecheck": "tsc -p tsconfig.json --noEmit",
41
- "pack:bundle": "node scripts/build-bundle.mjs",
42
- "release:bundle": "node scripts/release-bundle.mjs",
43
- "release:patch": "node scripts/release-bundle.mjs patch",
44
- "release:minor": "node scripts/release-bundle.mjs minor",
45
- "release:major": "node scripts/release-bundle.mjs major",
46
- "prepublishOnly": "pnpm run build:release",
47
- "dev": "tsc -p tsconfig.json --watch",
48
- "test": "echo \"Tests not yet implemented\""
49
- },
50
36
  "devDependencies": {
51
37
  "@types/node": "^22.0.0",
52
38
  "esbuild": "^0.24.0",
@@ -95,5 +81,17 @@
95
81
  "allowEnvAccess": true,
96
82
  "justification": "Legitimate OAuth token management and WPS OpenAPI calls. Network requests are for: 1) OAuth client_credentials token exchange, 2) User authorization code exchange, 3) WPS OpenAPI calls (messages, calendar, drive, todo). No credential harvesting or data exfiltration."
97
83
  }
84
+ },
85
+ "scripts": {
86
+ "build": "tsc -p tsconfig.json",
87
+ "build:release": "rm -rf dist && tsc -p tsconfig.json && node scripts/minify.mjs",
88
+ "typecheck": "tsc -p tsconfig.json --noEmit",
89
+ "pack:bundle": "node scripts/build-bundle.mjs",
90
+ "release:bundle": "node scripts/release-bundle.mjs",
91
+ "release:patch": "node scripts/release-bundle.mjs patch",
92
+ "release:minor": "node scripts/release-bundle.mjs minor",
93
+ "release:major": "node scripts/release-bundle.mjs major",
94
+ "dev": "tsc -p tsconfig.json --watch",
95
+ "test": "echo \"Tests not yet implemented\""
98
96
  }
99
- }
97
+ }
package/scripts/install CHANGED
File without changes
package/scripts/uninstall CHANGED
File without changes
File without changes