@coze/cli 0.1.7-alpha.4f8149 → 0.1.7-alpha.a2b4dc
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/lib/cli.js +2 -2
- package/package.json +1 -1
package/lib/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";const e=require("./fetch-client-CWYDGe9Z.js"),t=require("./index-DVDXYPSZ.js"),i=require("chalk"),o=require("node:child_process"),s=require("./task-worker-B0N97176.js"),n=require("node:http"),r=require("node:https"),a=require("node:buffer"),c=require("node:path"),d=require("node:os"),l=require("node:fs"),p=require("undici"),u=require("node:fs/promises"),_=require("path"),h=require("fs/promises"),m=require("fs"),g=require("form-data"),f=require("omelette"),y=require("lodash"),v=require("child_process"),w=require("ws"),b=require("commander");function S(e,t){return null!=e?e:t()}require("crypto"),require("url"),require("http"),require("https"),require("http2"),require("util"),require("stream"),require("assert"),require("tty"),require("os"),require("zlib"),require("events"),require("mitt"),require("process");class P{format(e){const t=JSON.stringify(e,null,2);return t.endsWith("\n")?t:`${t}\n`}formatError(e){const t={code:e.code,errorName:S(e.errorName,(()=>"UNKNOWN_ERROR")),desc:S(e.desc,(()=>e.message)),trigger:S(e.trigger,(()=>null)),fix:S(e.fix,(()=>null)),example:S(e.example,(()=>null))},i=JSON.stringify(t,null,2);return i.endsWith("\n")?i:`${i}\n`}}function C(e,t){return null!=e?e:t()}function T(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}function E(e){return e.replace(/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"")}function k(e){return e>=4352&&e<=4447||(9001===e||9002===e||(e>=11904&&e<=12350||(e>=12352&&e<=42191||(e>=44032&&e<=55203||(e>=63744&&e<=64255||(e>=65040&&e<=65049||(e>=65072&&e<=65135||(e>=65280&&e<=65376||(e>=65504&&e<=65510||(e>=127744&&e<=129695||e>=131072&&e<=262141))))))))))}function I(e){const t=E(e);if(!t)return 0;const i=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/u;let o=0;const s=Array.from(t);for(let e=0;e<s.length;e+=1){const t=C(s[e],(()=>""));if(i.test(t))continue;const n=t.codePointAt(0);void 0!==n&&(o+=k(n)?2:1)}return o}function A(e,t){const i=I(e);return i>=t?e:`${e}${" ".repeat(t-i)}`}function j(e,t){if(t<=0)return"";if(I(e)<=t)return e;if(1===t)return"…";const i=E(e),o=Array.from(i),s=Math.max(0,t-I("…"));let n="",r=0;for(let e=0;e<o.length;e+=1){const t=C(o[e],(()=>"")),i=I(t);if(r+i>s)break;n+=t,r+=i}return`${n}…`}function R(e,t={}){if(0===e.length)return"";const i=function(e,t){if(0===e.length)return[];const i=new Set,o=[],s=C(e[0],(()=>({})));for(const e of Object.keys(s))i.has(e)||(i.add(e),o.push(e));for(const t of e)for(const e of Object.keys(t))i.has(e)||(i.add(e),o.push(e));const n=[];for(const t of o){let i=I(t);for(const o of e){const e=o[t],s=void 0===e?"":String(e);i=Math.max(i,I(s))}n.push({key:t,width:i})}const r=C(t.columnGap,(()=>2)),a=C(C(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),c=Math.max(1,Math.floor((a+r)/(6+r))),d=Math.min(C(t.maxColumns,(()=>c)),c);n.length>d&&n.splice(d);const l=Math.max(0,a-r*Math.max(0,n.length-1));for(;n.reduce(((e,t)=>e+t.width),0)>l;){let e=-1,t=-1;for(let i=0;i<n.length;i+=1){const o=C(T([n,"access",e=>e[i],"optionalAccess",e=>e.width]),(()=>0));o>t&&(t=o,e=i)}if(-1===e)break;const i=C(T([n,"access",t=>t[e],"optionalAccess",e=>e.width]),(()=>0));if(i<=6)break;n[e]={...n[e],width:i-1}}for(let e=0;e<n.length;e+=1){const t=n[e];t&&(n[e]={...t,width:Math.max(6,t.width)})}return n}(e,t);if(0===i.length)return"";const o=C(t.columnGap,(()=>2)),s=" ".repeat(o),n=i.map((e=>A(j(e.key,e.width),e.width))).join(s),r=i.map((e=>"-".repeat(e.width))).join(s),a=[];for(const t of e){const e=i.map((e=>{const i=t[e.key];return A(j(void 0===i?"":String(i),e.width),e.width)}));a.push(e.join(s))}return`${[n,r,...a].join("\n")}\n`}function z(e,t={}){const i=Object.entries(e);if(0===i.length)return"";let o=0;for(const[e]of i)o=Math.max(o,I(e));const s=C(C(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),n=C(t.columnGap,(()=>2)),r=C(t.minValueWidth,(()=>12));let a=Math.min(o,C(t.keyMaxWidth,(()=>32)));const c=Math.max(6,s-n-r);a=Math.min(a,c);const d=Math.max(0,s-a-n),l=" ".repeat(n);return`${i.map((([e,t])=>{const i=A(j(e,a),a),o=(void 0===t?"undefined":null===t?"null":String(t)).replace(/\s*\n\s*/g," "),s=d>0?j(o,d):"";return`${i}${l}${s}`})).join("\n")}\n`}function U(e,t="",i=0){const o={};if(null==e)return o;if("object"!=typeof(s=e)||null===s||Array.isArray(s))return o;var s;for(const[s,n]of Object.entries(e)){const e=t?`${t}.${s}`:s;if(null!=n)if(Array.isArray(n))i>=5?o[e]="[Array]":0===n.length?o[e]="[]":n.every((e=>"object"!=typeof e||null===e))?o[e]=n.map((e=>{return String((i=()=>"null",null!=(t=e)?t:i()));var t,i})).join(", "):o[e]="[Array]";else if("object"!=typeof n)o[e]=n;else if(i>=5)o[e]="[Object]";else{const t=U(n,e,i+1);Object.assign(o,t)}else o[e]=n}return o}function L(e,t){return null!=e?e:t()}function O(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class x{format(e){if(null===e)return"null\n";if(void 0===e)return"undefined\n";if(Array.isArray(e)){if(0===e.length)return"\n";if(t=e,Array.isArray(t)&&t.length>0&&t.every(O)){return R(e.map((e=>U(e))))}return function(e){return Array.isArray(e)&&e.length>0&&e.every((e=>null==e||"object"!=typeof e))}(e)?`${e.map((e=>String(L(e,(()=>"null"))))).join("\n")}\n`:"[Array]\n"}var t;if(O(e)){const t=U(e);return 0===Object.keys(t).length?"{}\n":z(t)}return`${String(e)}\n`}formatError(e){const t=[],i=L(e.errorName,(()=>"UNKNOWN_ERROR")),o=L(e.desc,(()=>e.message));return t.push(`ERROR [${e.code}] ${i}: ${o}`),e.trigger&&t.push(` Trigger: ${e.trigger}`),e.fix&&t.push(` Fix: ${e.fix}`),e.example&&t.push(` Example: ${e.example}`),e.details&&(t.push(" Error Details:"),t.push(`${function(e,t){if(null==e)return"";if("string"==typeof e)return`${t}${e}\n`;if(Array.isArray(e))return 0===e.length?"":`${e.map((e=>"object"==typeof e&&null!==e?z(U(e)):String(e))).map((e=>`${t}- ${e.trim()}`)).join("\n")}\n`;if(O(e)){const i=U(e);return 0===Object.keys(i).length?"":`${z(i).split("\n").filter((e=>e.trim())).map((e=>`${t}${e}`)).join("\n")}\n`}return`${t}${String(e)}\n`}(e.details," ")}`)),`${t.join("\n")}\n`}}function B(e,t){return null!=e?e:t()}function q(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}function D(e,t){if(null==e)return;const i=String(e).replace(/\s*\n\s*/g," ").replace(/\s+/g," ").trim();return i?i.length<=t?i:`${i.slice(0,Math.max(0,t-3))}...`:void 0}function M(e){const t=q([e,"optionalAccess",e=>e.help,"optionalAccess",e=>e.errors]);if(t&&t.length>0)return t;const i=q([e,"optionalAccess",e=>e.errors]);return Array.isArray(i)?i:void 0}function N(t,i){const o=B(t.trigger,(()=>function(e){if(!e||0===e.length)return;return D(("coze"===e[0]?e:["coze",...e]).join(" "),150)}(q([i,"optionalAccess",e=>e.argv])))),s=q([M,"call",e=>e(q([i,"optionalAccess",e=>e.commandConfig])),"optionalAccess",e=>e.find,"call",e=>e((e=>e.code===t.code))]),n=B(q([s,"optionalAccess",e=>e.name]),(()=>e.ErrorNameByCode[t.code])),r=B(D(n,80),(()=>"UNKNOWN_ERROR"));let a=n;t.isMessageExplicit&&t.message.trim()?a=t.message:q([s,"optionalAccess",e=>e.desc])&&(a=s.desc);const c=B(D(a,200),(()=>"An unexpected error occurred")),d=B(D(t.fix,150),(()=>D(q([s,"optionalAccess",e=>e.fix]),150))),l=B(D(t.example,150),(()=>D(q([s,"optionalAccess",e=>e.example]),150)));return{code:t.code,errorName:r,desc:c,trigger:o,fix:d,example:l}}function G(e,t){const i=N(e,t);return e.errorName=i.errorName,e.desc=i.desc,e.message=i.desc,e.trigger=i.trigger,e.fix=i.fix,e.example=i.example,e}function $(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}var F;!function(e){e[e.NOT_LOGIN=700012006]="NOT_LOGIN"}(F||(F={}));const V=(i,o)=>{const s=G(function(i){if(i instanceof e.CozeError)return i;if(i instanceof t.ChatCoreError){const{ext:t}=i;let o=e.ErrorCode.E5000;"number"==typeof t.code&&(t.code===F.NOT_LOGIN?o=e.ErrorCode.E2001:t.code>=500&&(o=e.ErrorCode.E5002));const{message:s}=i;return new e.CozeError(o,s,t)}if(e.isHttpError(i)){const t=i.toJSON();let o=e.ErrorCode.E5000;const s=$([i,"access",e=>e.response,"optionalAccess",e=>e.status]);i.code===F.NOT_LOGIN||401===s?o=e.ErrorCode.E2001:"ECONNREFUSED"===i.code||"ETIMEDOUT"===i.code?o=e.ErrorCode.E5001:403===s?o=e.ErrorCode.E2003:404===s?o=e.ErrorCode.E3000:429===s?o=e.ErrorCode.E4001:s&&s>=500&&(o=e.ErrorCode.E5002);const n=$([i,"access",e=>e.response,"optionalAccess",e=>e.headers,"optionalAccess",e=>e["x-tt-logid"]]),{message:r}=i;return new e.CozeError(o,r,{logId:n,...t})}return i instanceof Error?new e.CozeError(e.ErrorCode.E5000,i.message,i.stack):"string"==typeof i?new e.CozeError(e.ErrorCode.E5000,i):new e.CozeError(e.ErrorCode.E5000,"An unexpected error occurred")}(i),o?{argv:o.argv,commandConfig:o.commandConfig}:void 0);var n,r;if(s.code===e.ErrorCode.E2001&&process.stdout.write(`${n=s.desc,r=()=>s.message,null!=n?n:r()}\n`),o)o.response.eprint(s);else{const e=new x;process.stderr.write(e.formatError(s))}process.exit(e.exitCodeForError(s.code))};const W="0.1.7-alpha.4f8149",H="@coze/cli";function J(){return W}function K(e,t){const i=e=>{const t=e.replace(/^v/,"").split(".");return{major:parseInt(t[0]||"0",10),minor:parseInt(t[1]||"0",10),patch:parseInt(t[2]||"0",10)}},o=i(e),s=i(t);return s.major!==o.major?s.major>o.major:s.minor!==o.minor?s.minor>o.minor:s.patch>o.patch}async function Q(t,i=!1,n="latest"){const r=J(),{config:a}=t;if(!i&&a.latestVersion&&a.lastCheckTime&&Date.now()-a.lastCheckTime<864e5)return{currentVersion:r,latestVersion:a.latestVersion,hasUpdate:K(r,a.latestVersion)};const c=function(){try{return o.execSync("npm config get registry",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim().replace(/\/+$/,"")}catch(e){return"https://registry.npmjs.org"}}(),d=await async function(t,i="latest"){const o=`${t}/${H}/${i}`,s=await e.customFetch.fetch(o,{headers:{accept:"application/json"}});if(!s.ok)throw new Error(`Failed to fetch latest version: ${s.status} ${s.statusText}`);return(await s.json()).version}(c,n);return await s.saveConfig({latestVersion:d,lastCheckTime:Date.now()},a.configScope),{currentVersion:r,latestVersion:d,hasUpdate:K(r,d)}}async function Y(e,t){if(await t(),!0===e.config.autoCheckUpdate)try{const t=await Q(e);if(t.hasUpdate){const o=`\nUpdate available: ${i.gray(t.currentVersion)} → ${i.green(t.latestVersion)}\nRun ${i.cyan("coze upgrade")} to update\n`;e.ui.info(o)}}catch(e){}}var Z=e.requireSrc();const X=e.getDefaultExportFromCjs(Z);function ee(e){var t,i,o=e.transport,s=e.endpoint,n=e.size,r=void 0===n?10:n,a=e.wait,c=void 0===a?1e3:a,d=[],l=0;function p(){if(d.length){var e=this.getBatchData();o.post({url:s,data:e,fail:function(i){t&&t(i,e)},success:function(){i&&i(e)}}),d=[]}}return{getSize:function(){return r},getWait:function(){return c},setSize:function(e){r=e},setWait:function(e){c=e},getEndpoint:function(){return s},setEndpoint:function(e){s=e},send:function(e){d.push(e),d.length>=r&&p.call(this),clearTimeout(l),l=setTimeout(p.bind(this),c)},flush:function(){clearTimeout(l),p.call(this)},getBatchData:function(){return d.length?(e=d,JSON.stringify({ev_type:"batch",list:e})):"";var e},clear:function(){clearTimeout(l),d=[]},fail:function(e){t=e},success:function(e){i=e}}}
|
|
2
|
+
"use strict";const e=require("./fetch-client-CWYDGe9Z.js"),t=require("./index-DVDXYPSZ.js"),i=require("chalk"),o=require("node:child_process"),s=require("./task-worker-B0N97176.js"),n=require("node:http"),r=require("node:https"),a=require("node:buffer"),c=require("node:path"),d=require("node:os"),l=require("node:fs"),p=require("undici"),u=require("node:fs/promises"),_=require("path"),h=require("fs/promises"),m=require("fs"),g=require("form-data"),f=require("omelette"),y=require("lodash"),v=require("child_process"),w=require("ws"),b=require("commander");function S(e,t){return null!=e?e:t()}require("crypto"),require("url"),require("http"),require("https"),require("http2"),require("util"),require("stream"),require("assert"),require("tty"),require("os"),require("zlib"),require("events"),require("mitt"),require("process");class P{format(e){const t=JSON.stringify(e,null,2);return t.endsWith("\n")?t:`${t}\n`}formatError(e){const t={code:e.code,errorName:S(e.errorName,(()=>"UNKNOWN_ERROR")),desc:S(e.desc,(()=>e.message)),trigger:S(e.trigger,(()=>null)),fix:S(e.fix,(()=>null)),example:S(e.example,(()=>null))},i=JSON.stringify(t,null,2);return i.endsWith("\n")?i:`${i}\n`}}function C(e,t){return null!=e?e:t()}function T(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}function E(e){return e.replace(/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"")}function k(e){return e>=4352&&e<=4447||(9001===e||9002===e||(e>=11904&&e<=12350||(e>=12352&&e<=42191||(e>=44032&&e<=55203||(e>=63744&&e<=64255||(e>=65040&&e<=65049||(e>=65072&&e<=65135||(e>=65280&&e<=65376||(e>=65504&&e<=65510||(e>=127744&&e<=129695||e>=131072&&e<=262141))))))))))}function I(e){const t=E(e);if(!t)return 0;const i=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/u;let o=0;const s=Array.from(t);for(let e=0;e<s.length;e+=1){const t=C(s[e],(()=>""));if(i.test(t))continue;const n=t.codePointAt(0);void 0!==n&&(o+=k(n)?2:1)}return o}function A(e,t){const i=I(e);return i>=t?e:`${e}${" ".repeat(t-i)}`}function j(e,t){if(t<=0)return"";if(I(e)<=t)return e;if(1===t)return"…";const i=E(e),o=Array.from(i),s=Math.max(0,t-I("…"));let n="",r=0;for(let e=0;e<o.length;e+=1){const t=C(o[e],(()=>"")),i=I(t);if(r+i>s)break;n+=t,r+=i}return`${n}…`}function R(e,t={}){if(0===e.length)return"";const i=function(e,t){if(0===e.length)return[];const i=new Set,o=[],s=C(e[0],(()=>({})));for(const e of Object.keys(s))i.has(e)||(i.add(e),o.push(e));for(const t of e)for(const e of Object.keys(t))i.has(e)||(i.add(e),o.push(e));const n=[];for(const t of o){let i=I(t);for(const o of e){const e=o[t],s=void 0===e?"":String(e);i=Math.max(i,I(s))}n.push({key:t,width:i})}const r=C(t.columnGap,(()=>2)),a=C(C(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),c=Math.max(1,Math.floor((a+r)/(6+r))),d=Math.min(C(t.maxColumns,(()=>c)),c);n.length>d&&n.splice(d);const l=Math.max(0,a-r*Math.max(0,n.length-1));for(;n.reduce(((e,t)=>e+t.width),0)>l;){let e=-1,t=-1;for(let i=0;i<n.length;i+=1){const o=C(T([n,"access",e=>e[i],"optionalAccess",e=>e.width]),(()=>0));o>t&&(t=o,e=i)}if(-1===e)break;const i=C(T([n,"access",t=>t[e],"optionalAccess",e=>e.width]),(()=>0));if(i<=6)break;n[e]={...n[e],width:i-1}}for(let e=0;e<n.length;e+=1){const t=n[e];t&&(n[e]={...t,width:Math.max(6,t.width)})}return n}(e,t);if(0===i.length)return"";const o=C(t.columnGap,(()=>2)),s=" ".repeat(o),n=i.map((e=>A(j(e.key,e.width),e.width))).join(s),r=i.map((e=>"-".repeat(e.width))).join(s),a=[];for(const t of e){const e=i.map((e=>{const i=t[e.key];return A(j(void 0===i?"":String(i),e.width),e.width)}));a.push(e.join(s))}return`${[n,r,...a].join("\n")}\n`}function z(e,t={}){const i=Object.entries(e);if(0===i.length)return"";let o=0;for(const[e]of i)o=Math.max(o,I(e));const s=C(C(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),n=C(t.columnGap,(()=>2)),r=C(t.minValueWidth,(()=>12));let a=Math.min(o,C(t.keyMaxWidth,(()=>32)));const c=Math.max(6,s-n-r);a=Math.min(a,c);const d=Math.max(0,s-a-n),l=" ".repeat(n);return`${i.map((([e,t])=>{const i=A(j(e,a),a),o=(void 0===t?"undefined":null===t?"null":String(t)).replace(/\s*\n\s*/g," "),s=d>0?j(o,d):"";return`${i}${l}${s}`})).join("\n")}\n`}function U(e,t="",i=0){const o={};if(null==e)return o;if("object"!=typeof(s=e)||null===s||Array.isArray(s))return o;var s;for(const[s,n]of Object.entries(e)){const e=t?`${t}.${s}`:s;if(null!=n)if(Array.isArray(n))i>=5?o[e]="[Array]":0===n.length?o[e]="[]":n.every((e=>"object"!=typeof e||null===e))?o[e]=n.map((e=>{return String((i=()=>"null",null!=(t=e)?t:i()));var t,i})).join(", "):o[e]="[Array]";else if("object"!=typeof n)o[e]=n;else if(i>=5)o[e]="[Object]";else{const t=U(n,e,i+1);Object.assign(o,t)}else o[e]=n}return o}function L(e,t){return null!=e?e:t()}function O(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class x{format(e){if(null===e)return"null\n";if(void 0===e)return"undefined\n";if(Array.isArray(e)){if(0===e.length)return"\n";if(t=e,Array.isArray(t)&&t.length>0&&t.every(O)){return R(e.map((e=>U(e))))}return function(e){return Array.isArray(e)&&e.length>0&&e.every((e=>null==e||"object"!=typeof e))}(e)?`${e.map((e=>String(L(e,(()=>"null"))))).join("\n")}\n`:"[Array]\n"}var t;if(O(e)){const t=U(e);return 0===Object.keys(t).length?"{}\n":z(t)}return`${String(e)}\n`}formatError(e){const t=[],i=L(e.errorName,(()=>"UNKNOWN_ERROR")),o=L(e.desc,(()=>e.message));return t.push(`ERROR [${e.code}] ${i}: ${o}`),e.trigger&&t.push(` Trigger: ${e.trigger}`),e.fix&&t.push(` Fix: ${e.fix}`),e.example&&t.push(` Example: ${e.example}`),e.details&&(t.push(" Error Details:"),t.push(`${function(e,t){if(null==e)return"";if("string"==typeof e)return`${t}${e}\n`;if(Array.isArray(e))return 0===e.length?"":`${e.map((e=>"object"==typeof e&&null!==e?z(U(e)):String(e))).map((e=>`${t}- ${e.trim()}`)).join("\n")}\n`;if(O(e)){const i=U(e);return 0===Object.keys(i).length?"":`${z(i).split("\n").filter((e=>e.trim())).map((e=>`${t}${e}`)).join("\n")}\n`}return`${t}${String(e)}\n`}(e.details," ")}`)),`${t.join("\n")}\n`}}function B(e,t){return null!=e?e:t()}function q(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}function D(e,t){if(null==e)return;const i=String(e).replace(/\s*\n\s*/g," ").replace(/\s+/g," ").trim();return i?i.length<=t?i:`${i.slice(0,Math.max(0,t-3))}...`:void 0}function M(e){const t=q([e,"optionalAccess",e=>e.help,"optionalAccess",e=>e.errors]);if(t&&t.length>0)return t;const i=q([e,"optionalAccess",e=>e.errors]);return Array.isArray(i)?i:void 0}function N(t,i){const o=B(t.trigger,(()=>function(e){if(!e||0===e.length)return;return D(("coze"===e[0]?e:["coze",...e]).join(" "),150)}(q([i,"optionalAccess",e=>e.argv])))),s=q([M,"call",e=>e(q([i,"optionalAccess",e=>e.commandConfig])),"optionalAccess",e=>e.find,"call",e=>e((e=>e.code===t.code))]),n=B(q([s,"optionalAccess",e=>e.name]),(()=>e.ErrorNameByCode[t.code])),r=B(D(n,80),(()=>"UNKNOWN_ERROR"));let a=n;t.isMessageExplicit&&t.message.trim()?a=t.message:q([s,"optionalAccess",e=>e.desc])&&(a=s.desc);const c=B(D(a,200),(()=>"An unexpected error occurred")),d=B(D(t.fix,150),(()=>D(q([s,"optionalAccess",e=>e.fix]),150))),l=B(D(t.example,150),(()=>D(q([s,"optionalAccess",e=>e.example]),150)));return{code:t.code,errorName:r,desc:c,trigger:o,fix:d,example:l}}function G(e,t){const i=N(e,t);return e.errorName=i.errorName,e.desc=i.desc,e.message=i.desc,e.trigger=i.trigger,e.fix=i.fix,e.example=i.example,e}function $(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}var F;!function(e){e[e.NOT_LOGIN=700012006]="NOT_LOGIN"}(F||(F={}));const V=(i,o)=>{const s=G(function(i){if(i instanceof e.CozeError)return i;if(i instanceof t.ChatCoreError){const{ext:t}=i;let o=e.ErrorCode.E5000;"number"==typeof t.code&&(t.code===F.NOT_LOGIN?o=e.ErrorCode.E2001:t.code>=500&&(o=e.ErrorCode.E5002));const{message:s}=i;return new e.CozeError(o,s,t)}if(e.isHttpError(i)){const t=i.toJSON();let o=e.ErrorCode.E5000;const s=$([i,"access",e=>e.response,"optionalAccess",e=>e.status]);i.code===F.NOT_LOGIN||401===s?o=e.ErrorCode.E2001:"ECONNREFUSED"===i.code||"ETIMEDOUT"===i.code?o=e.ErrorCode.E5001:403===s?o=e.ErrorCode.E2003:404===s?o=e.ErrorCode.E3000:429===s?o=e.ErrorCode.E4001:s&&s>=500&&(o=e.ErrorCode.E5002);const n=$([i,"access",e=>e.response,"optionalAccess",e=>e.headers,"optionalAccess",e=>e["x-tt-logid"]]),{message:r}=i;return new e.CozeError(o,r,{logId:n,...t})}return i instanceof Error?new e.CozeError(e.ErrorCode.E5000,i.message,i.stack):"string"==typeof i?new e.CozeError(e.ErrorCode.E5000,i):new e.CozeError(e.ErrorCode.E5000,"An unexpected error occurred")}(i),o?{argv:o.argv,commandConfig:o.commandConfig}:void 0);var n,r;if(s.code===e.ErrorCode.E2001&&process.stdout.write(`${n=s.desc,r=()=>s.message,null!=n?n:r()}\n`),o)o.response.eprint(s);else{const e=new x;process.stderr.write(e.formatError(s))}process.exit(e.exitCodeForError(s.code))};const W="0.1.7-alpha.a2b4dc",H="@coze/cli";function J(){return W}function K(e,t){const i=e=>{const t=e.replace(/^v/,"").split(".");return{major:parseInt(t[0]||"0",10),minor:parseInt(t[1]||"0",10),patch:parseInt(t[2]||"0",10)}},o=i(e),s=i(t);return s.major!==o.major?s.major>o.major:s.minor!==o.minor?s.minor>o.minor:s.patch>o.patch}async function Q(t,i=!1,n="latest"){const r=J(),{config:a}=t;if(!i&&a.latestVersion&&a.lastCheckTime&&Date.now()-a.lastCheckTime<864e5)return{currentVersion:r,latestVersion:a.latestVersion,hasUpdate:K(r,a.latestVersion)};const c=function(){try{return o.execSync("npm config get registry",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim().replace(/\/+$/,"")}catch(e){return"https://registry.npmjs.org"}}(),d=await async function(t,i="latest"){const o=`${t}/${H}/${i}`,s=await e.customFetch.fetch(o,{headers:{accept:"application/json"}});if(!s.ok)throw new Error(`Failed to fetch latest version: ${s.status} ${s.statusText}`);return(await s.json()).version}(c,n);return await s.saveConfig({latestVersion:d,lastCheckTime:Date.now()},a.configScope),{currentVersion:r,latestVersion:d,hasUpdate:K(r,d)}}async function Y(e,t){if(await t(),!0===e.config.autoCheckUpdate)try{const t=await Q(e);if(t.hasUpdate){const o=`\nUpdate available: ${i.gray(t.currentVersion)} → ${i.green(t.latestVersion)}\nRun ${i.cyan("coze upgrade")} to update\n`;e.ui.info(o)}}catch(e){}}var Z=e.requireSrc();const X=e.getDefaultExportFromCjs(Z);function ee(e){var t,i,o=e.transport,s=e.endpoint,n=e.size,r=void 0===n?10:n,a=e.wait,c=void 0===a?1e3:a,d=[],l=0;function p(){if(d.length){var e=this.getBatchData();o.post({url:s,data:e,fail:function(i){t&&t(i,e)},success:function(){i&&i(e)}}),d=[]}}return{getSize:function(){return r},getWait:function(){return c},setSize:function(e){r=e},setWait:function(e){c=e},getEndpoint:function(){return s},setEndpoint:function(e){s=e},send:function(e){d.push(e),d.length>=r&&p.call(this),clearTimeout(l),l=setTimeout(p.bind(this),c)},flush:function(){clearTimeout(l),p.call(this)},getBatchData:function(){return d.length?(e=d,JSON.stringify({ev_type:"batch",list:e})):"";var e},clear:function(){clearTimeout(l),d=[]},fail:function(e){t=e},success:function(e){i=e}}}
|
|
3
3
|
/*! *****************************************************************************
|
|
4
4
|
Copyright (c) Microsoft Corporation.
|
|
5
5
|
|
|
@@ -28,4 +28,4 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
|
28
28
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
29
29
|
PERFORMANCE OF THIS SOFTWARE.
|
|
30
30
|
***************************************************************************** */
|
|
31
|
-
function n_(e,t,i,o){return new(i||(i=Promise))((function(t,s){function n(e){try{a(o.next(e))}catch(e){s(e)}}function r(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var o;e.done?t(e.value):(o=e.value,o instanceof i?o:new i((function(e){e(o)}))).then(n,r)}a((o=o.apply(e,[])).next())}))}let r_="";function a_(e=""){const t=`${Date.now()}`,i=r_||(r_=function(e){const t=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(e),i=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(e);return t?function(e){const t=e.split(/\./).map((e=>{return t=e,(Array(8).join("0")+parseInt(t,10).toString(2)).slice(-8);var t})),i=[];i[0]=d_(t[0]+t[1]),i[1]=d_(t[2]+t[3]);const o=["0000","0000","0000","0000","0000","ffff",i[0],i[1]];return o.join("")}(e):i?function(e){let t="";const i=[];let o=0,s=0,n=!0;const r="0000";if(e.indexOf("::")>-1){const a=e.split("::");for(let e=0;e<a.length;e++){const t=a[e];if(t.indexOf(":")>0){const e=t.split(":");n&&(o=e.length),s+=e.length;for(let t=0;t<e.length;t++)if(4!==e[t].length){const o=r.substring(0,4-e[t].length).concat(e[t]);i.push(o)}else i.push(e[t]);n=!1}else{if(4!==t.length){const e=r.substring(0,4-t.length).concat(t);i.push(e)}else i.push(t);n&&(o+=1),s+=1,n=!1}}let c="";for(let e=0;e<8-s;e++)c=c.concat(r);for(let e=0;e<i.length;e++)e===o?(t=t.concat(c),t=t.concat(i[e])):t=t.concat(i[e]);return t}{const i=e.split(":");for(let e=0;e<i.length;e++){const o=i[e];if(4!==i[e].length){const s=r.substring(0,4-i[e].length).concat(o);t=t.concat(s)}else t=t.concat(o)}return t}}(e):"00000000000000000000000000000000"}(e));return"02"+t+i+Math.random().toString(16).slice(-6)}function c_(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function d_(e){return(Array(4).join("0")+parseInt(e,2).toString(16)).slice(-4)}function l_(e,t){const i=e.key;void 0!==i&&(R_(t,10),E_(t,i));const o=e.value;void 0!==o&&(R_(t,18),E_(t,o))}function p_(e){const t={};e:for(;!b_(e);){const i=j_(e);switch(i>>>3){case 0:break e;case 1:t.key=T_(e,j_(e));break;case 2:t.value=T_(e,j_(e));break;default:m_(e,7&i)}}if(void 0===t.key)throw new Error("Missing required field: key");if(void 0===t.value)throw new Error("Missing required field: value");return t}function u_(e){const t=y_();return function(e,t){const i=e.SeqID;void 0!==i&&(R_(t,8),U_(t,i));const o=e.LogID;void 0!==o&&(R_(t,16),U_(t,o));const s=e.service;void 0!==s&&(R_(t,24),U_(t,g_(s)));const n=e.method;void 0!==n&&(R_(t,32),U_(t,g_(n)));const r=e.headers;if(void 0!==r)for(const e of r){R_(t,42);const i=y_();l_(e,i),R_(t,i.limit),k_(t,i),v_(i)}const a=e.payloadEncoding;void 0!==a&&(R_(t,50),E_(t,a));const c=e.payloadType;void 0!==c&&(R_(t,58),E_(t,c));const d=e.payload;void 0!==d&&(R_(t,66),R_(t,d.length),function(e,t){const i=S_(e,t.length);e.bytes.set(t,i)}(t,d));const l=e.LogIDNew;void 0!==l&&(R_(t,74),E_(t,l));const p=e.serverTiming;void 0!==p&&(R_(t,82),E_(t,p));const u=e.msgID;void 0!==u&&(R_(t,90),E_(t,u));const _=e.frameType;void 0!==_&&(R_(t,96),U_(t,g_(_)))}(e,t),function(e){const t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function __(e){return function(e){const t={};e:for(;!b_(e);){const i=j_(e);switch(i>>>3){case 0:break e;case 1:t.SeqID=z_(e,!0);break;case 2:t.LogID=z_(e,!0);break;case 3:t.service=j_(e);break;case 4:t.method=j_(e);break;case 5:{const i=h_(e);(t.headers||(t.headers=[])).push(p_(e)),e.limit=i;break}case 6:t.payloadEncoding=T_(e,j_(e));break;case 7:t.payloadType=T_(e,j_(e));break;case 8:t.payload=C_(e,j_(e));break;case 9:t.LogIDNew=T_(e,j_(e));break;case 10:t.serverTiming=T_(e,j_(e));break;case 11:t.msgID=T_(e,j_(e));break;case 12:t.frameType=j_(e);break;default:m_(e,7&i)}}if(void 0===t.SeqID)throw new Error("Missing required field: SeqID");if(void 0===t.LogID)throw new Error("Missing required field: LogID");if(void 0===t.service)throw new Error("Missing required field: service");if(void 0===t.method)throw new Error("Missing required field: method");return t}({bytes:t=e,offset:0,limit:t.length});var t}function h_(e){const t=j_(e),i=e.limit;return e.limit=e.offset+t,i}function m_(e,t){switch(t){case 0:for(;128&I_(e););break;case 2:w_(e,j_(e));break;case 5:w_(e,4);break;case 1:w_(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function g_(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}const f_=[];function y_(){const e=f_.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function v_(e){f_.push(e)}function w_(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function b_(e){return e.offset>=e.limit}function S_(e,t){const i=e.bytes,o=e.offset,s=e.limit,n=o+t;if(n>i.length){const t=new Uint8Array(2*n);t.set(i),e.bytes=t}return e.offset=n,n>s&&(e.limit=n),o}function P_(e,t){const i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function C_(e,t){const i=P_(e,t);return e.bytes.subarray(i,i+t)}function T_(e,t){const i=P_(e,t),o=String.fromCharCode,s=e.bytes,n="�";let r="";for(let e=0;e<t;e++){const a=s[e+i];let c,d,l,p;128&a?192==(224&a)?e+1>=t?r+=n:(c=s[e+i+1],128!=(192&c)?r+=n:(p=(31&a)<<6|63&c,p<128?r+=n:(r+=o(p),e++))):224==(240&a)?e+2>=t?r+=n:(c=s[e+i+1],d=s[e+i+2],32896!=(49344&(c|d<<8))?r+=n:(p=(15&a)<<12|(63&c)<<6|63&d,p<2048||p>=55296&&p<=57343?r+=n:(r+=o(p),e+=2))):240==(248&a)?e+3>=t?r+=n:(c=s[e+i+1],d=s[e+i+2],l=s[e+i+3],8421504!=(12632256&(c|d<<8|l<<16))?r+=n:(p=(7&a)<<18|(63&c)<<12|(63&d)<<6|63&l,p<65536||p>1114111?r+=n:(p-=65536,r+=o(55296+(p>>10),56320+(1023&p)),e+=3))):r+=n:r+=o(a)}return r}function E_(e,t){const i=t.length;let o=0;for(let e=0;e<i;e++){let s=t.charCodeAt(e);s>=55296&&s<=56319&&e+1<i&&(s=(s<<10)+t.charCodeAt(++e)-56613888),o+=s<128?1:s<2048?2:s<65536?3:4}R_(e,o);let s=S_(e,o);const n=e.bytes;for(let e=0;e<i;e++){let o=t.charCodeAt(e);o>=55296&&o<=56319&&e+1<i&&(o=(o<<10)+t.charCodeAt(++e)-56613888),o<128?n[s++]=o:(o<2048?n[s++]=o>>6&31|192:(o<65536?n[s++]=o>>12&15|224:(n[s++]=o>>18&7|240,n[s++]=o>>12&63|128),n[s++]=o>>6&63|128),n[s++]=63&o|128)}}function k_(e,t){const i=S_(e,t.limit),o=e.bytes,s=t.bytes;for(let e=0,n=t.limit;e<n;e++)o[e+i]=s[e]}function I_(e){return e.bytes[P_(e,1)]}function A_(e,t){const i=S_(e,1);e.bytes[i]=t}function j_(e){let t,i=0,o=0;do{t=I_(e),i<32&&(o|=(127&t)<<i),i+=7}while(128&t);return o}function R_(e,t){for(t>>>=0;t>=128;)A_(e,127&t|128),t>>>=7;A_(e,t)}function z_(e,t){let i,o=0,s=0,n=0;return i=I_(e),o=127&i,128&i&&(i=I_(e),o|=(127&i)<<7,128&i&&(i=I_(e),o|=(127&i)<<14,128&i&&(i=I_(e),o|=(127&i)<<21,128&i&&(i=I_(e),s=127&i,128&i&&(i=I_(e),s|=(127&i)<<7,128&i&&(i=I_(e),s|=(127&i)<<14,128&i&&(i=I_(e),s|=(127&i)<<21,128&i&&(i=I_(e),n=127&i,128&i&&(i=I_(e),n|=(127&i)<<7))))))))),{low:o|s<<28,high:s>>>4|n<<24,unsigned:t}}function U_(e,t){const i=t.low>>>0,o=(t.low>>>28|t.high<<4)>>>0,s=t.high>>>24,n=0===s?0===o?i<16384?i<128?1:2:i<1<<21?3:4:o<16384?o<128?5:6:o<1<<21?7:8:s<128?9:10,r=S_(e,n),a=e.bytes;switch(n){case 10:a[r+9]=s>>>7&1;case 9:a[r+8]=9!==n?128|s:127&s;case 8:a[r+7]=8!==n?o>>>21|128:o>>>21&127;case 7:a[r+6]=7!==n?o>>>14|128:o>>>14&127;case 6:a[r+5]=6!==n?o>>>7|128:o>>>7&127;case 5:a[r+4]=5!==n?128|o:127&o;case 4:a[r+3]=4!==n?i>>>21|128:i>>>21&127;case 3:a[r+2]=3!==n?i>>>14|128:i>>>14&127;case 2:a[r+1]=2!==n?i>>>7|128:i>>>7&127;case 1:a[r]=1!==n?128|i:127&i}}function L_(e){return u_(e)}const O_=4294967296,x_=0x10000000000000000,B_=x_/2,q_=String.prototype.charCodeAt;class D_{constructor(e,t,i){this.isLong=!0,this.low=0|e,this.high=0|t,this.unsigned=!!i}static isLong(e){return e&&!0===e.isLong}static fromBits(e,t,i){return new D_(e,t,i)}static fromBytes(e,t,i){return i?D_.fromBytesLE(e,t):D_.fromBytesBE(e,t)}static fromBytesLE(e,t){return new D_(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)}static fromBytesBE(e,t){return new D_(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}static fromHash(e){return"\0\0\0\0\0\0\0\0"===e?M_:new D_((q_.call(e,0)|q_.call(e,1)<<8|q_.call(e,2)<<16|q_.call(e,3)<<24)>>>0,(q_.call(e,4)|q_.call(e,5)<<8|q_.call(e,6)<<16|q_.call(e,7)<<24)>>>0,!0)}toHash(){return String.fromCharCode(255&this.low,this.low>>>8&255,this.low>>>16&255,this.low>>>24,255&this.high,this.high>>>8&255,this.high>>>16&255,this.high>>>24)}static fromNumber(e,t=!0){if(isNaN(e))return t?N_:M_;if(t){if(e>=x_)return $_}else{if(e<=-B_)return F_;if(e+1>=B_)return G_}return D_.fromBits(e%O_|0,e/O_|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*O_+(this.low>>>0):this.high*O_+(this.low>>>0)}isZero(){return 0===this.high&&0===this.low}add(e){D_.isLong(e)||(e=D_.fromNumber(e));const t=this.high>>>16,i=65535&this.high,o=this.low>>>16,s=65535&this.low,n=e.high>>>16,r=65535&e.high,a=e.low>>>16;let c=0,d=0,l=0,p=0;return p+=s+(65535&e.low),l+=p>>>16,p&=65535,l+=o+a,d+=l>>>16,l&=65535,d+=i+r,c+=d>>>16,d&=65535,c+=t+n,c&=65535,D_.fromBits(l<<16|p,c<<16|d,this.unsigned)}equals(e){return D_.isLong(e)||(e=D_.fromNumber(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)}addOne(){return-1===this.low&&-1===this.high?D_.fromBits(0,0,this.unsigned):-1===this.low?D_.fromBits(0,this.high+1,this.unsigned):D_.fromBits(this.low+1,this.high,this.unsigned)}toBytes(e){return e?this.toBytesLE():this.toBytesBE()}toBytesLE(){const e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}toBytesBE(){const e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]}}const M_=new D_(0,0,!1),N_=new D_(0,0,!0),G_=D_.fromBits(-1,2147483647,!1),$_=D_.fromBits(-1,-1,!0),F_=D_.fromBits(0,-2147483648,!1);var V_;!function(e){e[e.NATIVE_ERROR=5001]="NATIVE_ERROR",e[e.CONNECTING_ERROR=5002]="CONNECTING_ERROR",e[e.MAX_RETRIES_ERROR=5003]="MAX_RETRIES_ERROR",e[e.MESSAGE_ERROR=5004]="MESSAGE_ERROR",e[e.OPEN_ERROR=5005]="OPEN_ERROR"}(V_||(V_={}));class W_{constructor(e){this.type=e,this.target=null}}class H_ extends W_{constructor(e,t){super(e),this.message=t&&t.message||null}}class J_ extends W_{constructor(e,t){super(e),this.error=t&&t.error||null,this.colno=t&&t.colno||0,this.filename=t&&t.filename||"",this.lineno=t&&t.lineno||0,this.message=t&&t.message||"",this.code=t&&t.code||V_.NATIVE_ERROR}}class K_ extends W_{constructor(e,t){super(e),this.code=t&&t.code||0,this.reason=t&&t.reason||"",this.wasClean=t&&t.wasClean||!1,this.willReconnect=t&&t.willReconnect||!1}}class Q_ extends W_{constructor(e,t){super(e),this.data=t&&t.data||null}}class Y_ extends Q_{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}}class Z_ extends W_{constructor(e,t){super(e),this.data=t&&t.data||null}}function X_(e,{message:t,code:i,error:o}){return new J_(e,{message:t,code:i,error:o})}function eh(e,{code:t,reason:i,wasClean:o,willReconnect:s}){return new K_(e,{code:t,reason:i,wasClean:o,willReconnect:s})}function th(e,{message:t}){return new H_(e,{message:t})}class ih{constructor(e,t){this.endpoints=e,this.maxRetries=t,this.currentIndex=0,this.currentEndpointTriesCount=0}resetEndpointConfig(){this.currentIndex=0,this.currentEndpointTriesCount=0}resetTries(){this.currentEndpointTriesCount=0}getCurrentEndpoint(){return this.endpoints[this.currentIndex]}getCurrentEndpointTriesCount(){return this.currentEndpointTriesCount}checkReachMaxTries(){return this.currentIndex>=this.endpoints.length||this.currentIndex===this.endpoints.length-1&&this.currentEndpointTriesCount===this.maxRetries}checkCurrentEndpointReachedMaxRetries(){return this.currentIndex==this.endpoints.length||this.currentEndpointTriesCount>this.maxRetries}replaceBackupEndpointAndUpdateCount(){return this.currentEndpointTriesCount=1,this.currentIndex++,this.endpoints[this.currentIndex]}getCurrentEndpointAndUpdateCount(){return this.currentEndpointTriesCount++,this.getCurrentEndpoint()}}const oh=("undefined"!=typeof globalThis&&"Window"===globalThis.constructor.name||"undefined"!=typeof window&&"Window"===window.constructor.name)&&"undefined"!=typeof document,sh="undefined"!=typeof globalThis&&("Object"===globalThis.constructor.name||"DedicatedWorkerGlobalScope"===globalThis.constructor.name)&&"undefined"!=typeof tt,nh=("undefined"!=typeof globalThis&&"Object"===globalThis.constructor.name||"undefined"==typeof globalThis||"undefined"!=typeof globalThis&&!!globalThis.WeixinJSBridge)&&"undefined"!=typeof wx,rh="undefined"!=typeof globalThis&&("DedicatedWorkerGlobalScope"===globalThis.constructor.name||"SharedWorkerGlobalScope"===globalThis.constructor.name||"ServiceWorkerGlobalScope"===globalThis.constructor.name)&&"undefined"!=typeof self,ah="undefined"!=typeof globalThis&&"Object"===globalThis.constructor.name&&"undefined"!=typeof global&&"Object"===global.constructor.name&&"undefined"!=typeof process&&!!process.version;class ch{constructor(){this._listeners={}}emit(e,...t){const i=this._listeners[e];if(i)i.slice().forEach((e=>e.fn.apply(e.ctx,t)));else if("error"===e&&!this.onerror){const e=t.length&&t[0];if(e instanceof Error)throw e;throw new Error("Unhandled error."+(e?" ("+e.message+")":"")).context=e,e}return this}off(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=null;else{const i=this._listeners[e];if(i)for(let e=0;e<i.length;)i[e].fn===t?i.splice(e,1):++e}return this}on(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this}}class dh extends ch{constructor(e,t,i){super(),this._socket=null,nh&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:i,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),sh&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:t,header:i,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then((()=>{this._addWsListeners()}))}_createSocketFailHandler(e){Promise.resolve().then((()=>{const t=X_("error",{message:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)});this.emit("error",t);const i=eh("close",{reason:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)});this.emit("close",i)}))}_addWsListeners(){this._socket.onOpen((e=>{this.emit("open",function(e,{data:t}){return new Z_(e,{data:t})}("open",Object.assign(Object.assign({},e),{data:e.errMsg||""})))})),this._socket.onClose((e=>{this.emit("close",eh("close",Object.assign({},e)))})),this._socket.onMessage((e=>{this.emit("message",function(e,{data:t,message:i}){return new Y_(e,{data:t,message:i})}("message",Object.assign({},e)))})),this._socket.onError((e=>{this.emit("error",X_("error",Object.assign(Object.assign({},e),{message:e.errMsg||""})))}))}send(e){if(e instanceof Uint8Array){const t=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);this._socket&&this._socket.send({data:t,fail:e=>{this.emit("error",X_("error",{message:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)}))}})}else this._socket&&this._socket.send({data:e,fail:e=>{this.emit("error",X_("error",{message:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)}))}})}close(e,t){this._socket&&this._socket.close({code:e,reason:t})}addEventListener(e,t){this.on(e,t)}removeEventListener(e,t){this.off(e,t)}get readyState(){return this._socket.readyState}get binaryType(){return this._socket.binaryType}set binaryType(e){}get url(){return this._socket.url}get protocol(){return this._socket.protocol}get extensions(){return this._socket.extensions}get bufferedAmount(){return 0}}function lh(e,t,i){let o=-1;!function s(n){return n_(this,0,void 0,(function*(){if(n<=o)return Promise.reject(new Error("next() called multiple times in process"));if(o=n,n===i.length)return Promise.resolve();return i[n].bind(e)(t,s.bind(null,n+1))}))}(0)}function ph(e){let t=0,i=0;for(let o=0;o<e.length;++o)i=e.charCodeAt(o),i<128?t+=1:i<2048?t+=2:55296==(64512&i)&&56320==(64512&e.charCodeAt(o+1))?(++o,t+=4):t+=3;return t}function uh(e,t,i){if(i-t<1)return"";let o="";for(let s=t;s<i;){const t=e[s++];if(t<=127)o+=String.fromCharCode(t);else if(t>=192&&t<224)o+=String.fromCharCode((31&t)<<6|63&e[s++]);else if(t>=224&&t<240)o+=String.fromCharCode((15&t)<<12|(63&e[s++])<<6|63&e[s++]);else if(t>=240){const i=((7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;o+=String.fromCharCode(55296+(i>>10)),o+=String.fromCharCode(56320+(1023&i))}}return o}function _h(e,t,i){const o=i;let s,n;for(let o=0;o<e.length;++o)s=e.charCodeAt(o),s<128?t[i++]=s:s<2048?(t[i++]=s>>6|192,t[i++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(o+1)))?(s=65536+((1023&s)<<10)+(1023&n),++o,t[i++]=s>>18|240,t[i++]=s>>12&63|128,t[i++]=s>>6&63|128,t[i++]=63&s|128):(t[i++]=s>>12|224,t[i++]=s>>6&63|128,t[i++]=63&s|128);return i-o}function hh(e){return n_(this,0,void 0,(function*(){if("string"==typeof e){const t=new Uint8Array(ph(e));return _h(e,t,0),t}return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}))}class mh{constructor(e){this.maxLossCount=e,this.count=0}addCount(){this.count++}checkReachMaxCount(){return this.count>=this.maxLossCount}resetCounter(e=0){this.maxLossCount=e,this.count=0}}function gh(e,t,i){return!!(null==e?void 0:e.find((e=>e.key===t&&e.value===i)))}function fh(e,t){var i;return null===(i=null==e?void 0:e.find((e=>e.key===t)))||void 0===i?void 0:i.value}function yh(e,t){return n_(this,0,void 0,(function*(){const{enableAutoAck:i}=this._options,o=gh(e.message.headers,"need_ack","1"),s=gh(e.message.headers,"is_ack","1"),n=gh(e.message.headers,"x_frontier_qos_ack","1");if(i&&o){const{SeqID:t,LogID:i,service:o,LogIDNew:s,method:n}=e.message;this._sendAck({SeqID:t,LogID:i,LogIDNew:s,service:o,method:n,headers:[{key:"is_ack",value:"1"},{key:"ack_id",value:s||""},{key:"ack_code",value:"0"}]})}s&&!n&&this._dispatchAckMessageEvent(e),t()}))}function vh(e,t){return n_(this,0,void 0,(function*(){this._debug("received",e.message),t()}))}function wh(e,t){return n_(this,0,void 0,(function*(){const i=__(yield hh(e.data));try{if(i.payload instanceof Uint8Array){const e=this._options.payloadEncoding instanceof Object?{force:!!this._options.payloadEncoding.force,encoding:this._options.payloadEncoding.encoding?this._options.payloadEncoding.encoding.replace(/\s/g,"").toLowerCase():""}:{force:!1,encoding:this._options.payloadEncoding?this._options.payloadEncoding.replace(/\s/g,"").toLowerCase():""},t=i.payloadEncoding?i.payloadEncoding.replace(/\s/g,"").toLowerCase():"",o=this._options.payloadType instanceof Object?{force:!!this._options.payloadType.force,type:this._options.payloadType.type?this._options.payloadType.type.replace(/\s/g,"").toLowerCase():""}:{force:!1,type:this._options.payloadType?this._options.payloadType.replace(/\s/g,"").toLowerCase():""},s=i.payloadType?i.payloadType.replace(/\s/g,"").toLowerCase():"",n=o.force?o.type:s||o.type,r=e.force?e.encoding:t||e.encoding,a=["text/plain;charset=utf-8","application/json","application/json;charset=utf-8","string"],c=["none_none","binary"];this._options.enableTransformTextPayload&&a.includes(n)&&(!r||c.includes(r))?i.textPayload=uh(i.payload,0,i.payload.byteLength):i.textPayload=""}else i.textPayload=""}catch(e){i.textPayload="",console.log(e)}e.message=i,t()}))}let bh,Sh;const Ph=new WeakMap,Ch=new WeakMap,Th=new WeakMap,Eh=new WeakMap,kh=new WeakMap;let Ih={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return Ch.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Th.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return Rh(e[t])},set:(e,t,i)=>(e[t]=i,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Ah(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Sh||(Sh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(zh(this),t),Rh(Ph.get(this))}:function(...t){return Rh(e.apply(zh(this),t))}:function(t,...i){const o=e.call(zh(this),t,...i);return Th.set(o,t.sort?t.sort():[t]),Rh(o)}}function jh(e){return"function"==typeof e?Ah(e):(e instanceof IDBTransaction&&function(e){if(Ch.has(e))return;const t=new Promise(((t,i)=>{const o=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",n),e.removeEventListener("abort",n)},s=()=>{t(),o()},n=()=>{i(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",s),e.addEventListener("error",n),e.addEventListener("abort",n)}));Ch.set(e,t)}(e),t=e,(bh||(bh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some((e=>t instanceof e))?new Proxy(e,Ih):e);var t}function Rh(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,i)=>{const o=()=>{e.removeEventListener("success",s),e.removeEventListener("error",n)},s=()=>{t(Rh(e.result)),o()},n=()=>{i(e.error),o()};e.addEventListener("success",s),e.addEventListener("error",n)}));return t.then((t=>{t instanceof IDBCursor&&Ph.set(t,e)})).catch((()=>{})),kh.set(t,e),t}(e);if(Eh.has(e))return Eh.get(e);const t=jh(e);return t!==e&&(Eh.set(e,t),kh.set(t,e)),t}const zh=e=>kh.get(e);const Uh=["get","getKey","getAll","getAllKeys","count"],Lh=["put","add","delete","clear"],Oh=new Map;function xh(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Oh.get(t))return Oh.get(t);const i=t.replace(/FromIndex$/,""),o=t!==i,s=Lh.includes(i);if(!(i in(o?IDBIndex:IDBObjectStore).prototype)||!s&&!Uh.includes(i))return;const n=async function(e,...t){const n=this.transaction(e,s?"readwrite":"readonly");let r=n.store;return o&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),s&&n.done]))[0]};return Oh.set(t,n),n}Ih=(e=>({...e,get:(t,i,o)=>xh(t,i)||e.get(t,i,o),has:(t,i)=>!!xh(t,i)||e.has(t,i)}))(Ih);class Bh extends ch{constructor(e,t){super(),this._dbName=e,this._keyPath=t,this._qosDB=void 0,this._init()}openDB(){return n_(this,0,void 0,(function*(){yield this._init()}))}_init(){return n_(this,0,void 0,(function*(){try{const e=this._dbName,t=this._keyPath;return new Promise((i=>{this._qosDB?i(this):(function(e,t,{blocked:i,upgrade:o,blocking:s,terminated:n}={}){const r=indexedDB.open(e,t),a=Rh(r);return o&&r.addEventListener("upgradeneeded",(e=>{o(Rh(r.result),e.oldVersion,e.newVersion,Rh(r.transaction))})),i&&r.addEventListener("blocked",(()=>i())),a.then((e=>{n&&e.addEventListener("close",(()=>n())),s&&e.addEventListener("versionchange",(()=>s()))})).catch((()=>{})),a}(`frontier_${e}`,1,{upgrade(i){i.createObjectStore(e,{keyPath:t})}}).then((e=>{this._qosDB=e,this.emit("ready")})),this.on("ready",(()=>{i(this),this.off()})))}))}catch(e){console.log(e)}}))}get(e){var t;return n_(this,0,void 0,(function*(){try{return null===(t=this._qosDB)||void 0===t?void 0:t.get(this._dbName,e)}catch(e){console.log(e)}}))}set(e,t){var i;return n_(this,0,void 0,(function*(){return null===(i=this._qosDB)||void 0===i?void 0:i.put(this._dbName,e)}))}del(e){var t;return n_(this,0,void 0,(function*(){try{return null===(t=this._qosDB)||void 0===t?void 0:t.delete(this._dbName,e)}catch(e){console.log(e)}}))}clear(){var e;return n_(this,0,void 0,(function*(){try{return null===(e=this._qosDB)||void 0===e?void 0:e.clear(this._dbName)}catch(e){console.log(e)}}))}keys(){var e;return n_(this,0,void 0,(function*(){return null===(e=this._qosDB)||void 0===e?void 0:e.getAllKeys(this._dbName)}))}getAll(){var e;return n_(this,0,void 0,(function*(){return null===(e=this._qosDB)||void 0===e?void 0:e.getAll(this._dbName)}))}closeDB(){var e;return n_(this,0,void 0,(function*(){try{null===(e=this._qosDB)||void 0===e||e.close(),this._qosDB=void 0}catch(e){console.log(e)}}))}get isReady(){try{return!!this._qosDB}catch(e){return console.log(e),!1}}}class qh{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=localStorage}openDB(){return n_(this,0,void 0,(function*(){}))}get _prefix(){return`frontier_${this._DBName}`}get(e){return n_(this,0,void 0,(function*(){const t=this._qosDB.getItem(this._prefix);return JSON.parse(t||"{}")[e]}))}set(e,t){return n_(this,0,void 0,(function*(){const i=this._qosDB.getItem(this._prefix),o=JSON.parse(i||"{}");return o[t||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(o)),t||e[this._pathKey]}))}del(e){return n_(this,0,void 0,(function*(){const t=this._qosDB.getItem(this._prefix),i=JSON.parse(t||"{}");return i[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(i))}))}clear(){return n_(this,0,void 0,(function*(){return this._qosDB.clear()}))}keys(){return n_(this,0,void 0,(function*(){const e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}))}getAll(){return n_(this,0,void 0,(function*(){const e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}))}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}}class Dh{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=sh?tt:nh?wx:null}openDB(){return n_(this,0,void 0,(function*(){}))}get _prefix(){return`frontier_${this._DBName}`}get(e){return n_(this,0,void 0,(function*(){const t=this._qosDB.getStorageSync(this._prefix);return JSON.parse(t||"{}")[e]}))}set(e,t){return n_(this,0,void 0,(function*(){const i=this._qosDB.getStorageSync(this._prefix),o=JSON.parse(i||"{}");return o[t||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(o)),t||e[this._pathKey]}))}del(e){return n_(this,0,void 0,(function*(){const t=this._qosDB.getStorageSync(this._prefix),i=JSON.parse(t||"{}");return i[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(i))}))}clear(){return n_(this,0,void 0,(function*(){return this._qosDB.clearStorageSync()}))}keys(){return n_(this,0,void 0,(function*(){const e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}))}getAll(){return n_(this,0,void 0,(function*(){const e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}))}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}}function Mh(e,t){if(sh||sh)return new Dh(e,t);if((oh||rh)&&void 0!==typeof indexedDB)return new Bh(e,t);if((oh||rh)&&void 0!==typeof localStorage)return new qh(e,t);throw new Error("init QoSDB failed")}class Nh{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=Mh("qos","message_id")}_intervalFlush(){return n_(this,0,void 0,(function*(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval((()=>{this.flushExpired()}),this._interval)}))}openDB(){return n_(this,0,void 0,(function*(){yield this._qosDB.openDB().then((()=>{this._intervalFlush()}))}))}flushExpired(){var e;return n_(this,0,void 0,(function*(){((yield null===(e=this._qosDB)||void 0===e?void 0:e.getAll())||[]).filter((({timestamp:e})=>e<Date.now())).forEach((e=>{var t;null===(t=this._qosDB)||void 0===t||t.del(e.message_id)}))}))}del(e){var t;return n_(this,0,void 0,(function*(){return null===(t=this._qosDB)||void 0===t?void 0:t.del(e)}))}set(e,t){var i;return n_(this,0,void 0,(function*(){return null===(i=this._qosDB)||void 0===i?void 0:i.set({message_id:e,timestamp:t})}))}get(e){var t;return n_(this,0,void 0,(function*(){return null===(t=this._qosDB)||void 0===t?void 0:t.get(e)}))}closeDB(){var e;return n_(this,0,void 0,(function*(){clearInterval(this._intervalTimeoutId),yield null===(e=this._qosDB)||void 0===e?void 0:e.closeDB()}))}get isReady(){var e;return null===(e=this._qosDB)||void 0===e?void 0:e.isReady}}function Gh(e,t){var i,o,s,n,r;return n_(this,0,void 0,(function*(){const a=gh(e.message.headers,"code","-1"),c=gh(e.message.headers,"is_ack","1"),d=fh(e.message.headers,"x_frontier_msgid"),l=Number(fh(e.message.headers,"x_frontier_ttl"))||0,p=gh(e.message.headers,"x_frontier_qos","2"),u=gh(e.message.headers,"x_frontier_qos_ack","1"),_=gh(e.message.headers,"x-msg-qos","2"),h=fh(e.message.headers,"x-msg-cursor_name"),m=Number(fh(e.message.headers,"x-msg-cursor_value"));if(p&&u)return t();if(_&&!(null===(i=this._cursorManager)||void 0===i?void 0:i.isReady))return t();if(p&&!this._QoSManager&&(this._QoSManager=new Nh),p&&this._QoSManager&&!this._QoSManager.isReady&&(yield this._QoSManager.openDB()),e.message.service>0&&c&&!a||e.message.service>0){if(d&&p){return!!(yield null===(o=this._QoSManager)||void 0===o?void 0:o.get(d))||(this._dispatchMessageEvent(e),yield null===(s=this._QoSManager)||void 0===s?void 0:s.set(d,Date.now()+l)),t()}if(_&&(null===(n=this._cursorManager)||void 0===n?void 0:n.isReady)){const i=null!==(r=yield this._cursorManager.get(h))&&void 0!==r?r:-1;if(!(i<m))throw new Error(`recevied message cursor ${m} larger than local cursor ${i}`);return this._dispatchMessageEvent(e),this._cursorManager.set(h,m,e.message.service),t()}return this._dispatchMessageEvent(e),t()}}))}function $h(e,t){var i,o;return n_(this,0,void 0,(function*(){const s=gh(e.message.headers,"x_frontier_qos","2"),n=gh(e.message.headers,"x_frontier_is_ack","1"),r=null===(i=fh(e.message.headers,"x_frontier_ack_msgid"))||void 0===i?void 0:i.split(",");if(!s)return t();if(this._QoSManager||(this._QoSManager=new Nh),this._QoSManager&&!this._QoSManager.isReady&&(yield this._QoSManager.openDB()),n&&r&&r.length)for(const e of r)yield null===(o=this._QoSManager)||void 0===o?void 0:o.del(e);t()}))}function Fh(e,t){let i=0,o=t;const s=t+4;for(;o<s;){const{value:t,offset:s}=Wh(e,o);o=s,i=i<<8>>>0,i+=t}return{value:i,offset:s}}function Vh(e,t){return{value:new D_(e[t+4]<<24|e[t+5]<<16|e[t+6]<<8|e[t+7],e[t+0]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],!0),offset:(t+=8)+8}}function Wh(e,t){return e.readUInt8?{value:e.readUInt8(t),offset:t+1}:{value:255&e[t],offset:t+1}}function Hh(e,t,i){return t.writeUint8?t.writeUint8(e,i):t[i]=255&e,i+1}const Jh="undefined"!=typeof Buffer?Buffer.allocUnsafe:function(e,t){const i=8192;let o=null,s=i;return function(n){if(n<1||n>4096)return e(n);s+n>i&&(o=e(i),s=0);const r=t.call(o,s,s+=n);return 7&s&&(s=1+(7|s)),r}}((function(e){return new Uint8Array(e)}),Uint8Array.prototype.subarray);function Kh(e,t,i){const[o,s]=function(e){let t=0;const i={};for(let o=0;o<e.length;o++)i[e[o].cursor_name]=ph(e[o].cursor_name),t+=14+i[e[o].cursor_name];return[t,i]}(e),n=Jh(o);let r=0;return e.forEach((e=>{console.log("cursor.service",e,e.service),r=Hh(0,n,r),console.log("header",r),r=function(e,t,i){if(i>4294967295)throw new Error("integer too large");let o=3;for(;o>=0;)Hh(255&i,e,t+o),i>>>=8,o--;return t+4}(n,r,e.service||0),console.log("service",r),r=Hh(s[e.cursor_name],n,r),console.log("service-name",r),r=function(e,t,i){return e?e.length<40?_h(e,t,i)+i:t.utf8Write?t.utf8Write(e,i)+i:t.write?t.write(e,i)+i:_h(e,t,i)+i:i}(e.cursor_name,n,r),console.log("name",r),r=function(e,t,i){const o=e.low,s=e.high;return t[i]=s>>>24,t[i+1]=s>>>16&255,t[i+2]=s>>>8&255,t[i+3]=255&s,t[i+4]=o>>>24,t[i+5]=o>>>16&255,t[i+6]=o>>>8&255,t[i+7]=255&o,i+8}(D_.fromNumber(e.cursor||t),n,r),console.log("curvalue",r)})),{frameType:32,headers:[{key:"cursor_file_name",value:i}],payload:n}}class Qh{constructor(e,t,i){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=i,this._qosDB=Mh(this._cursorNameSpace,"cursor_name")}openDB(){return n_(this,0,void 0,(function*(){yield this._qosDB.openDB()}))}getCursors(){return n_(this,0,void 0,(function*(){if(!this._qosDB.isReady)return;const e=this._messageStrategy,t=yield this._qosDB.getAll();switch(console.log("allCursorValues",t),e){case"ALL":return t&&t.length?Kh(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?Kh(t,0,this._cursorFileName):{frameType:32,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}}))}set(e,t,i){return n_(this,0,void 0,(function*(){return console.log("setdb",e,t,i),this._qosDB.set({cursor_name:e,cursor:t,service:i})}))}setCursors(e){return n_(this,0,void 0,(function*(){const t=function(e){let t=0;const i=[];for(;t<e.byteLength;){const{offset:o}=Wh(e,t);t=o;const s={cursor_name:"",cursor:0,service:0},{value:n,offset:r}=Fh(e,t);s.service=n,t=r;const{value:a,offset:c}=Wh(e,t);t=c,s.cursor_name=uh(e,t,t+a),t+=a;const{value:d,offset:l}=Vh(e,t);s.cursor=d.toNumber(),t=l,i.push(s)}return i}(e);for(const e of t)console.log("setcursor",t),yield this._qosDB.set(e)}))}get(e){var t;return n_(this,0,void 0,(function*(){return null===(t=yield this._qosDB.get(e))||void 0===t?void 0:t.cursor}))}closeDB(){return n_(this,0,void 0,(function*(){yield this._qosDB.closeDB()}))}get isReady(){return this._qosDB.isReady}}function Yh(e,t){return n_(this,0,void 0,(function*(){const i=16===e.message.frameType,o=32===e.message.frameType;if(!i&&!o)return t();const s=fh(e.message.headers,"cursor_file_name"),{aID:n,fpID:r,messageStrategy:a}=this._options;if(!s)return t();if(this._cursorManager||(this._cursorManager=new Qh(`${r}_${n}_${s}`,s,a)),this._cursorManager.isReady||(yield this._cursorManager.openDB()),i){const e=yield this._cursorManager.getCursors(),t=u_({frameType:null==e?void 0:e.frameType,SeqID:D_.fromNumber(this._seqId++),LogID:D_.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:null==e?void 0:e.headers,payload:null==e?void 0:e.payload});this._ws&&this._ws.readyState&&this._ws.send(t)}if(o){const t=e.message.payload;t&&this._cursorManager.setCursors(t)}}))}const Zh=function(e,t){return n_(this,0,void 0,(function*(){this._isInit=!1,clearTimeout(this._connectionTimeoutId),t()}))},Xh=function(e,t){var i;return n_(this,0,void 0,(function*(){const e=null===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpoint();this._debug(`open ${e}`),t()}))},em=function(e,t){var i,o;return n_(this,0,void 0,(function*(){if(!this._ws||this._ws.readyState!==this.OPEN)return t();const{pingInterval:s}=this._options;null===(i=this._endpointManager)||void 0===i||i.resetEndpointConfig();for(let e=0;e<this._messageQueue.length;e++){const t=this._messageQueue[e];if(this._ws.readyState!==this.OPEN||null===t)break;this._ws&&this._ws.send(t),this._messageQueue[e]=null}this._messageQueue=this._messageQueue.filter((e=>Boolean(e))),this._pingPongTimeoutId=setTimeout((()=>this._ping()),s),this._dispatchOpenEvent(e),this._isBrowser&&this._ws&&(this._ws.binaryType=this._binaryType);const n=null===(o=this._endpointManager)||void 0===o?void 0:o.getCurrentEndpoint();this._debug(`open ${n} success`),t()}))};class tm extends ch{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=oh,this._isNode=ah,this._isMiniTT=sh,this._isMiniWX=nh,this._isWorker=rh,this._messageQueue=[],this._endpointManager=null,this._readyClosed=!1,this._binaryType="arraybuffer",this._connectLock=!1,this._connectionTimeoutId=null,this._reconnectTimeoutId=null,this._pingPongTimeoutId=null,this._seqId=0,this._isInit=!1,this._url="",this._QoSManager=null,this._cursorManager=null,this._pingLossCounter=null,this._protocols="pbbp2",this.CLOSED=3,this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this._onOpen=e=>{try{lh(this,e,[Zh,em,Xh])}catch(e){const t=X_("error",{message:e.message,code:V_.OPEN_ERROR,error:e});this._dispatchErrorEvent(t)}},this._onMessage=e=>n_(this,0,void 0,(function*(){const{pingInterval:t,pingFrequency:i}=this._options;if(("hi"===e.data&&"always"===i||"auto"===i)&&(this._clearPingTimer(),this.emit("ping_once_success","success"),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),t)),"hi"!==e.data)try{lh(this,e,[wh,yh,$h,Yh,Gh,vh])}catch(e){const t=X_("error",{message:e.message,code:V_.MESSAGE_ERROR,error:e});this._dispatchErrorEvent(t)}})),this._onError=e=>{var t,i;const o=null===(t=this._endpointManager)||void 0===t?void 0:t.checkReachMaxTries(),s=null===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpoint();if(!o||e.message)this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(X_("error",{message:e.message,code:V_.NATIVE_ERROR,error:e}));else{const t=`connect ${s} fail, max retries reached`;this._dispatchErrorEvent(X_("error",{message:t,code:V_.MAX_RETRIES_ERROR,error:e}))}},this._onClose=e=>n_(this,0,void 0,(function*(){var t,i,o,s,n,r,a,c,d,l,p,u;this._clearTimer(),this._clearPingTimer(),this._removeWsListeners(),this._ws=null,this._connectLock=!1;const _=null===(t=this._endpointManager)||void 0===t?void 0:t.checkReachMaxTries();if(!_&&this._navigatorOnline()&&!this._readyClosed){const t=null===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpoint(),o=this._options.reconnectInterceptor(e.code,e.reason);return this._dispatchCloseEvent(eh("close",{code:1006,reason:e.reason||`connecting failed, unknown reason, hostname: ${t}`,willReconnect:o})),void(o&&this._connect())}if(1e3!==e.code&&this._readyClosed)return this._dispatchCloseEvent(eh("close",{code:1e3,reason:"bye"})),null===(o=this._endpointManager)||void 0===o||o.resetEndpointConfig(),void(null===(s=this._pingLossCounter)||void 0===s||s.resetCounter());if(1e3!==e.code&&_){const t=null===(n=this._endpointManager)||void 0===n?void 0:n.getCurrentEndpoint();let i=e.reason;i||(i=yield function(e){return n_(this,0,void 0,(function*(){return new Promise((t=>{if(!oh)return t("unknown reason");try{const i=document.createElement("script");window.frontierJSONP=e=>{document.body.removeChild(i),window.frontierJSONP=void 0,t(e&&e.msg||"unknown reason")},i.type="text/javascript",i.src=e.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(i)}catch(e){document.body.removeChild(i)}}catch(e){window.frontierJSONP=void 0,t("unknown reason")}}))}))}(this._url)),i=`connecting failed, ${i}, hostname: ${t}, max retries reached`,this._dispatchCloseEvent(eh("close",{code:e.code,reason:i}));const o=`connect ${t} fail, max retries reached`;return this._dispatchErrorEvent(X_("error",{message:o,code:V_.MAX_RETRIES_ERROR})),null===(r=this._endpointManager)||void 0===r||r.resetEndpointConfig(),void(null===(a=this._pingLossCounter)||void 0===a||a.resetCounter())}if(1e3!==e.code&&!e.reason){const t=null===(c=this._endpointManager)||void 0===c?void 0:c.getCurrentEndpoint();return this._dispatchCloseEvent(eh("close",{code:e.code,reason:`connecting failed, unknown reason, hostname: ${t}`})),null===(d=this._endpointManager)||void 0===d||d.resetEndpointConfig(),void(null===(l=this._pingLossCounter)||void 0===l||l.resetCounter())}this._dispatchCloseEvent(e),null===(p=this._endpointManager)||void 0===p||p.resetEndpointConfig(),null===(u=this._pingLossCounter)||void 0===u||u.resetCounter()})),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this.onStartReconnect=null,this.onReceiveAck=null,this.onStopImmediatelyReconnect=null,this._handleOnLine=this._handleOnLine.bind(this),this._handleOffLine=this._handleOffLine.bind(this),this._handlePageHide=this._handlePageHide.bind(this),this._handlePageShow=this._handlePageShow.bind(this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:c_,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:"auto",pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:"CONTINUE",env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};const{url:t,ws:i}=e,o=Array.isArray(t)?t:"string"==typeof t?[t]:[];if(!o||0===o.length)throw new Error("please provide valid url");if(!function(e){return!!(e||nh&&wx.connectSocket||sh&&tt.connectSocket||(oh||rh)&&"undefined"!=typeof WebSocket&&WebSocket)}(i))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new ih(o,this._options.maxRetries),this._pingLossCounter=new mh(this._options.pingLossCount),this._options.automaticOpen&&(this._isInit=!0,this._connect()),this._options.listenNetworkChanged&&(this._isMiniTT||this._isMiniWX?this._onPageNetWorkChange():this._isBrowser&&this._initGlobalEventListener())}_handleOnLine(){this._options.disableAutoReconnect||this._readyClosed||this._handleReconnect()}_handleOffLine(){this._destroyWebSocket();const e=th("reconnect",{message:"stop immediately reconnect"});this.onStopImmediatelyReconnect&&this.onStopImmediatelyReconnect(e)}_initGlobalEventListener(){this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine),this._isBrowser&&window.addEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.addEventListener("pageshow",this._handlePageShow)}_dropGlobalEventListener(){this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine),this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow)}_handlePageHide(e){e.persisted||(this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow),this.close()),this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine)}_handlePageShow(e){e.persisted&&(!this._navigatorOnline()||this._ws&&this._ws.readyState===this.OPEN&&this._ws.readyState===this.CONNECTING||this._handleOnLine(),this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine))}_generateUrl(e){return n_(this,0,void 0,(function*(){const{fpID:t,deviceID:i,bddID:o,ttwID:s,accessKey:n,aID:r,customParams:a={},enableAutoAck:c,enableQoS:d,QoSLevel:l,env:p}=this._options;let u,_,h;this._isBrowser||this._isMiniWX||this._isMiniTT?(u=location&&"https:"==location.protocol?"wss://":"ws://",_=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),h=/^wss(.*:\/\/)/.test(e)?e:`${u}${_}`):(u="wss://",_=e.replace(/(^http)((?:[s]*:\/\/))/,""),h=/(^ws)((?:[s]*:\/\/))/.test(_)?_:`${u}${_}`);const m=o?"bd_did":s?"ttwid":"device_id",g=o||(s||i);if(!g||!m)throw new Error("please provide bddID, deviceID or ttwID");const f="function"==typeof a?yield a():a,y=p?((e,t)=>{switch(e){case"boe":case"ppe":return{[`x-use-${e}`]:1,"x-tt-env":t};default:return{}}})(p.xUseEnv,p.xTTEnv):{},v=Object.assign(Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:n,fpid:t,aid:r,[m]:g,xsack:c?1:0,xaack:c?1:0,xsqos:d?1:0,qos_level:d?l:void 0,qos_sdk_version:2},y),f);return`${h}/ws/v2${Object.keys(v).reduce(((e,t)=>void 0!==v[t]?`${e}${e?"&":"?"}${t}=${v[t]}`:e),"")}`}))}_connect(){var e,t,i,o,s,n,r;return n_(this,0,void 0,(function*(){if(!this._connectLock&&!this._readyClosed){this._connectLock=!0;try{const d=null===(e=this._endpointManager)||void 0===e?void 0:e.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:l}=this._options;if(d){const e=null===(t=this._endpointManager)||void 0===t?void 0:t.getCurrentEndpoint(),s=null===(i=this._endpointManager)||void 0===i?void 0:i.replaceBackupEndpointAndUpdateCount(),n=null===(o=this._endpointManager)||void 0===o?void 0:o.getCurrentEndpointTriesCount();if(!s){const t=`connect ${e} timeout, max retries reached`;return this._debug(t),void this._dispatchErrorEvent(X_("error",{message:t,code:V_.MAX_RETRIES_ERROR}))}{const t=`connect ${e} timeout, max retries reached, will use backup endpoint ${s} to retry`,i=X_("error",{message:t,code:V_.MAX_RETRIES_ERROR});this._debug(t),this._dispatchErrorEvent(i),this._url=yield this._generateUrl(s),this._debug(`connect ${s} ${n} times`),this._removeWsListeners()}}else{const e=null===(s=this._endpointManager)||void 0===s?void 0:s.getCurrentEndpointAndUpdateCount(),t=null===(n=this._endpointManager)||void 0===n?void 0:n.getCurrentEndpointTriesCount();this._url=yield this._generateUrl(e||""),this._debug(`connect ${e} ${t} times`),this._removeWsListeners()}if(this._isInit)this._isInit=!1;else{const e=th("reconnect",{message:"start"});this.onStartReconnect&&this.onStartReconnect(e)}const p=(null===(r=this._endpointManager)||void 0===r?void 0:r.getCurrentEndpointTriesCount())||0;p>1&&(yield this._wait(p-1)),this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`),this._ws=(a={url:this._url,protocols:[this._protocols],headers:this._options.miniProgramParams.customHttpHeader},(c=this._options.ws)?new c(a.url,a.protocol):nh||sh?new dh(a.url,a.protocol,a.headers):(oh||rh)&&"undefined"!=typeof WebSocket&&WebSocket?new WebSocket(a.url,a.protocols):void 0),(this._isBrowser||this._isWorker)&&this._ws&&(this._ws.binaryType=this._binaryType),this._addWsListeners(),this._connectionTimeoutId=setTimeout(this._onTimeout.bind(this),l)}catch(e){throw this._connectLock=!1,e}var a,c}}))}_clearTimer(){clearTimeout(this._connectionTimeoutId),this._connectionTimeoutId=null}_clearPingTimer(){clearTimeout(this._pingPongTimeoutId),clearTimeout(this._reconnectTimeoutId),this._pingPongTimeoutId=null,this._reconnectTimeoutId=null}_debug(...e){this._options.debug&&console.log.apply(console,["FRONTIER>",...e])}_getIntervalValue(e){const{initReconnectInterval:t,maxReconnectInterval:i,reconnectIntervalGrowFactor:o}=this._options,s=t*Math.pow(o,e-1);return s>i?i:s}_ping(){if(this._ws&&this._ws.readyState===this.CONNECTING)return this._clearPingTimer(),void(this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval));this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send("hi"),this._reconnectTimeoutId=setTimeout(this._handleReconnectTimeout.bind(this),this._options.pingTimeoutInterval)):this._handleReconnect()}_handleReconnectTimeout(){var e,t;null===(e=this._pingLossCounter)||void 0===e||e.addCount(),this.emit("ping_once_timeout","timeout"),(null===(t=this._pingLossCounter)||void 0===t?void 0:t.checkReachMaxCount())?this._handleReconnect():this._ping()}_navigatorOnline(){return this._isMiniTT||this._isMiniWX?this._miniNavigatorOnline:!this._isBrowser&&!this._isWorker||!this._options.listenNetworkChanged||navigator.onLine}_handleReconnect(){var e,t;this._navigatorOnline()&&!this._readyClosed&&(null===(e=this._endpointManager)||void 0===e||e.resetEndpointConfig(),null===(t=this._pingLossCounter)||void 0===t||t.resetCounter(),this._ws?this._disconnect(1001,"going away, try reconnecting server",!0):this._connect())}_onPageNetWorkChange(){this._isMiniTT?tt.onNetworkStatusChange((({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()})):this._isMiniWX&&wx.onNetworkStatusChange((({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()}))}_wait(e){return new Promise((t=>{setTimeout(t,this._getIntervalValue(e))}))}_disconnect(e=1e3,t="",i=!1){this._ws&&this._destroyWebSocket(e,t,i)}_onTimeout(){var e;const t=null===(e=this._endpointManager)||void 0===e?void 0:e.getCurrentEndpoint();this._debug(`connect ${t} timeout`),this._disconnect(1001,"timeout, try reconnecting",!0)}_sendAck(e){const t=L_(e);this._ws&&this._ws.readyState===this.OPEN&&(this._ws&&this._ws.send(t),this._debug("send_ack",e))}_removeWsListeners(){this._ws&&(this._ws.removeEventListener("open",this._onOpen),this._ws.removeEventListener("close",this._onClose),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("error",this._onError))}_addWsListeners(){this._ws&&(this._ws.addEventListener("open",this._onOpen),this._ws.addEventListener("close",this._onClose),this._ws.addEventListener("message",this._onMessage),this._ws.addEventListener("error",this._onError))}_wsInstanceClose(e=1e3,t=""){try{this._ws&&this._ws.close(e,t)}catch(e){}}_destroyWebSocket(e=1e3,t="",i=!1){var o,s,n,r;if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,t),this._connectLock=!1,i&&this._navigatorOnline()&&!this._readyClosed){if(null===(o=this._endpointManager)||void 0===o?void 0:o.checkReachMaxTries()){const e=null===(s=this._endpointManager)||void 0===s?void 0:s.getCurrentEndpoint();this._dispatchCloseEvent(eh("close",{code:1006,reason:`connect ${e} timeout, max retries reached`,wasClean:!0}))}else{const i=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(eh("close",{code:e,reason:t,wasClean:!0,willReconnect:i})),i&&this._connect()}}else this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(eh("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(eh("close",{code:1006,reason:"going away, network offline"})),this._ws=null,null===(n=this._endpointManager)||void 0===n||n.resetEndpointConfig(),null===(r=this._pingLossCounter)||void 0===r||r.resetCounter()}_dispatchOpenEvent(e){this.emit("open",e),this.onopen&&this.onopen(e)}_dispatchMessageEvent(e){this.emit("message",e),this.onmessage&&this.onmessage(e)}_dispatchAckMessageEvent(e){this.emit("ack",e),this.onReceiveAck&&this.onReceiveAck(e)}_dispatchErrorEvent(e){this.emit("error",e),this.onerror&&this.onerror(e)}_dispatchCloseEvent(e){this.emit("close",e),this.onclose&&this.onclose(e)}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){var e;return(null===(e=this._endpointManager)||void 0===e?void 0:e.getCurrentEndpointTriesCount())||0}get bufferedAmount(){return this._messageQueue.reduce(((e,t)=>e+=t&&t.byteLength||0),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.automaticOpen?this.CONNECTING:this.CLOSED}get url(){return this._ws?this._ws.url:this._url}close(e=1e3,t){var i;this._readyClosed=!0,this._clearTimer(),this._clearPingTimer(),this._dropGlobalEventListener(),null===(i=this._QoSManager)||void 0===i||i.closeDB(),this._ws?this._ws.readyState!==this.CLOSED&&this._ws.readyState!==this.CLOSING?this._destroyWebSocket(e,t):this._debug("close, ws already closed"):this._debug("close, ws instance not initialized")}send(e,t){return n_(this,0,void 0,(function*(){if(null==e)throw new Error("please provide a valid data, data must be a string or an arraybuffer");"number"==typeof e&&(e=JSON.stringify(e)),"string"==typeof e||e instanceof ArrayBuffer||e.buffer&&e.buffer instanceof ArrayBuffer||(e=JSON.stringify(e));const i=yield hh(e),o=function(e){try{return"string"!=typeof e&&(e instanceof ArrayBuffer||e.buffer&&e.buffer instanceof ArrayBuffer)?"":"string"==typeof e?(JSON.parse(e),"application/json"):""}catch(t){return"string"==typeof e?"text/plain;charset=utf-8":""}}(e),{method:s=0,service:n=this._options.service,logID:r=this._options.logIDGenerator(),headers:a=this._options.headers,payloadEncoding:c=this._options.payloadEncoding,payloadType:d=this._options.payloadType,logIDNew:l=(this._options.logIDNewConfig.enableAutoGenerateLogIDNew?a_(this._options.logIDNewConfig.userIp):"")}=t||{};if(!n)throw new Error("please provide a valid service");const p={SeqID:D_.fromNumber(this._seqId++),LogID:D_.fromNumber(r),service:n,method:s,headers:a,payloadEncoding:c instanceof Object?c.encoding?c.encoding:"":c,payloadType:d instanceof Object?d.type?d.type:o:d||o,payload:i,LogIDNew:l},u=L_(p);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(u),this._debug("sent",p)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(u),this._debug("enqueue",p)):(this._messageQueue.shift(),this._messageQueue.push(u)),{seqID:this._seqId,logID:r,logIDNew:l}}))}reconnect(e){var t,i;return n_(this,0,void 0,(function*(){const{url:o}=e||{},s=Array.isArray(o)?o:"string"==typeof o?[o]:[];e&&Object.assign(this._options,e),s&&s.length?this._endpointManager=new ih(s,this._options.maxRetries):null===(t=this._endpointManager)||void 0===t||t.resetEndpointConfig(),null===(i=this._pingLossCounter)||void 0===i||i.resetCounter(this._options.pingLossCount),this._readyClosed=!1,this._ws&&this._ws.readyState!==this.CLOSED?this._disconnect(1e3,"manual reconnecting",!0):(this._isInit=!0,this._connect())}))}connect(){var e,t;return n_(this,0,void 0,(function*(){this._connectLock||(null===(e=this._endpointManager)||void 0===e||e.resetEndpointConfig(),null===(t=this._pingLossCounter)||void 0===t||t.resetCounter(),this._readyClosed=!1,this._isInit=!0,this._connect())}))}addEventListener(e,t){this.on(e,t)}dispatchEvent(e){const{type:t}=e;this.emit(t,e)}removeEventListener(e,t){this.off(e,t)}pingOnce(){return new Promise(((e,t)=>{this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);const i=()=>{e("success"),this.off("ping_once_success",i),this.off("ping_once_timeout",o)},o=()=>{t("timeout"),this.off("ping_once_success",i),this.off("ping_once_timeout",o)};this.on("ping_once_success",i),this.on("ping_once_timeout",o),this._ping()}))}}function im(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}class om extends w{constructor(e,t){super((e=>{const t=new URL(e);return t.searchParams.set("aid",Gu),t.toString()})(e),"pbbp2",{headers:{...t,Origin:"https://www.coze.cn"}})}}class sm{constructor(){sm.prototype.__init.call(this)}__init(){this.fws=null}connect(t,i,o){return new Promise(((s,n)=>{let r=!1,a=!1;const c=e=>{if(!a)return a=!0,void n(e);im([o,"optionalCall",t=>t(e)])},d={fpID:"1289",aID:Gu,accessKey:t.accessKey,deviceID:t.deviceId,url:"wss://frontier.coze.cn",automaticOpen:!0,enableQoS:!1,enableAutoAck:!1,ws:class extends om{constructor(e){super(e,t.headers)}}};this.fws=new tm(d);const l=setTimeout((()=>{a=!0,this.dispose(),n(new Error("Frontier connection timeout"))}),(p=t.timeoutMs,u=()=>1e4,null!=p?p:u()));var p,u;this.fws.onopen=()=>{r=!0,a=!0,clearTimeout(l),s()},this.fws.onerror=()=>{clearTimeout(l),c(new Error(r?"Frontier connection failed after connect":"Frontier connection failed"))},this.fws.onclose=()=>{clearTimeout(l),c(new Error(r?"Frontier connection closed after connect":"Frontier connection closed"))},this.fws.onmessage=t=>{const o=im([t,"access",e=>e.message,"optionalAccess",e=>e.payloadType]),s=im([t,"access",e=>e.message,"optionalAccess",e=>e.service]),n=im([t,"access",e=>e.message,"optionalAccess",e=>e.payload]);if(!o||!n)return;const r=new TextDecoder("utf-8").decode(n),a=e.safeJsonParse(r,r);i({service:s,event:o,data:a})}}))}dispose(){im([this,"access",e=>e.fws,"optionalAccess",e=>e.close,"call",e=>e()]),this.fws=null}}function nm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const rm=(e,t)=>{const i=t.toLowerCase(),o=Object.entries(e).find((([e])=>e.toLowerCase()===i));return nm([o,"optionalAccess",e=>e[1]])},am=e=>JSON.stringify({accessKey:e.accessKey,authorization:rm(e.headers,"authorization"),deviceId:e.deviceId,organizationId:e.organizationId,serviceId:e.serviceId,xTTEnv:rm(e.headers,"x-tt-env")}),cm=e=>"function"==typeof e.resolveConfig&&"string"==typeof e.scopeKey;class dm{__init(){this.entries=new Map}constructor(e){dm.prototype.__init.call(this),this.createClient=nm([e,"optionalAccess",e=>e.createClient])||(()=>new sm),this.getScopeKey=nm([e,"optionalAccess",e=>e.getScopeKey])||am}async subscribe(e,t){const i=((e,t)=>cm(e)?e.scopeKey:t(e))(e,this.getScopeKey);let o=this.entries.get(i);o||(o=this.createEntry(i,e),this.entries.set(i,o)),o.subscribers.add(t);try{await o.connectPromise}catch(e){throw o.subscribers.delete(t),e}let s=!1;return{release:()=>{s||(s=!0,this.releaseSubscriber(i,o,t))}}}createEntry(e,t){const i=this.createClient(),o={client:i,connectPromise:Promise.resolve(),subscribers:new Set};return o.connectPromise=(async e=>cm(e)?await e.resolveConfig():e)(t).then((async t=>{await i.connect(t,(t=>{this.emitEvent(e,t)}),(t=>{this.handleConnectionError(e,t)}))})).catch((t=>{throw this.entries.get(e)===o&&this.entries.delete(e),o.subscribers.clear(),i.dispose(),t})),o}emitEvent(e,t){const i=this.entries.get(e);if(i)for(const e of i.subscribers)e.onEvent(t)}handleConnectionError(e,t){const i=this.entries.get(e);if(!i)return;this.entries.delete(e);const o=[...i.subscribers];i.subscribers.clear(),i.client.dispose();for(const e of o)nm([e,"access",e=>e.onError,"optionalCall",e=>e(t)])}releaseSubscriber(e,t,i){t.subscribers.delete(i),t.subscribers.size>0||(this.entries.get(e)===t&&this.entries.delete(e),t.client.dispose())}}const lm=new dm;function pm(e,t){return null!=e?e:t()}function um(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const _m=e=>({...e,files:e.files?[...e.files]:void 0}),hm=e=>e?JSON.stringify(e.map((e=>({file_name:e.file_name,file_uri:e.file_uri,file_url:e.file_url,preview_url:e.preview_url})))):"";class mm{constructor(){mm.prototype.__init.call(this)}__init(){this.sessionStates=new Map}applyReplyEvent(t,i){const o=i.session_id;if(!o||!(e=>2===Number(e.source))(i))return null;const s=(({data:t,event:i})=>{const o=um([e.safeJsonParse(t.content,null),"optionalAccess",e=>e.message_data,"optionalAccess",e=>e.reply]),s=t.id,n="message"===i?um([o,"optionalAccess",e=>e.content])||t.content:um([o,"optionalAccess",e=>e.content]);return s&&n?{answerId:s,content:n,files:t.files,requestMessageId:um([o,"optionalAccess",e=>e.reply_to_message_id])}:null})({data:i,event:t});if(!s)return null;const n=this.getOrCreateSessionState(o),r=n.replies.get(s.answerId),a={answerId:s.answerId,content:"stream"===t&&r?r.content+s.content:s.content,files:pm(s.files,(()=>um([r,"optionalAccess",e=>e.files]))),requestMessageId:pm(s.requestMessageId,(()=>um([r,"optionalAccess",e=>e.requestMessageId])))};return"message"===t&&!r&&(({nextReply:e,sessionState:t})=>{for(const i of t.replies.values())if(i.requestMessageId===e.requestMessageId&&i.content===e.content&&hm(i.files)===hm(e.files))return!0;return!1})({nextReply:a,sessionState:n})?null:(n.replies.has(s.answerId)||n.replyOrder.push(s.answerId),n.replies.set(s.answerId,a),"stream"===t?{type:"reply_chunk",sessionId:o,source:"stream",chunk:{answerId:s.answerId,content:s.content,requestMessageId:s.requestMessageId}}:{type:"reply_update",sessionId:o,source:"message",reply:_m(a)})}applySessionIdleEvent(e){const t=um([e,"optionalAccess",e=>e.session_id]);if(!t||2!==Number(e.status))return null;const i=this.sessionStates.get(t);if(!i)return null;return{type:"session_idle",sessionId:t,replies:i.replyOrder.map((e=>i.replies.get(e))).filter((e=>Boolean(e))).map((e=>_m(e)))}}getOrCreateSessionState(e){const t=this.sessionStates.get(e);if(t)return t;const i={replies:new Map,replyOrder:[]};return this.sessionStates.set(e,i),i}}function gm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const fm=e=>({type:"progress_update",progress:e});class ym{constructor(){ym.prototype.__init.call(this)}__init(){this.progressStates=new Map}getKnownClawIds(){return this.progressStates.keys()}getKnownProgressEvents(e){const t=this.progressStates.get(e);return t?[...t.values()].map((t=>fm({progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:t.progressStatus}))):[]}applyFrontierEvent(e){const t=gm([e,"optionalAccess",e=>e.claw_id]),i=gm([e,"optionalAccess",e=>e.id]);if(!t||!i)return null;const o=2===Number(e.status)?"finished":1===Number(e.status)?"running":null;if(!o)return null;const s={progressId:i,clawId:t,name:e.name,progressType:e.type,progressStatus:o};return this.updateKnownProgressState(s),fm(s)}applySnapshot(e,t){const i=this.getOrCreateProgressState(e),o=new Set,s=[];t.forEach((t=>{o.add(t.progressId);const n={progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:t.progressStatus},r=i.get(t.progressId);i.set(t.progressId,n),((e,t)=>Boolean(e&&e.name===t.name&&e.progressType===t.progressType&&e.progressStatus===t.progressStatus))(r,n)||s.push(fm({progressId:n.progressId,clawId:e,name:n.name,progressType:n.progressType,progressStatus:n.progressStatus}))}));for(const t of[...i.values()])o.has(t.progressId)||(i.delete(t.progressId),s.push(fm({progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:"finished"})));return 0===i.size&&this.progressStates.delete(e),s}updateKnownProgressState(e){const t=this.getOrCreateProgressState(e.clawId);if("finished"===e.progressStatus)return t.delete(e.progressId),void(0===t.size&&this.progressStates.delete(e.clawId));t.set(e.progressId,{progressId:e.progressId,clawId:e.clawId,name:e.name,progressType:e.progressType,progressStatus:e.progressStatus})}getOrCreateProgressState(e){const t=this.progressStates.get(e);if(t)return t;const i=new Map;return this.progressStates.set(e,i),i}}class vm{__init(){this.progressPollTimers=new Map}__init2(){this.progressRefreshes=new Map}constructor({emitProgressUpdate:e,globalStreamKey:t,hasConnectionError:i,hasSubscribers:o,listProgresses:s,progressPollIntervalMs:n=3e4,progressStateStore:r}){vm.prototype.__init.call(this),vm.prototype.__init2.call(this),this.emitProgressUpdate=e,this.globalStreamKey=t,this.hasConnectionError=i,this.hasSubscribers=o,this.listProgresses=s,this.progressPollIntervalMs=n,this.progressStateStore=r}ensure(e){if(!this.listProgresses||this.progressPollTimers.has(e))return;const t=async()=>{if(this.progressPollTimers.delete(e),!this.hasSubscribers(e)||this.hasConnectionError())return;if(await this.refresh(e),!this.hasSubscribers(e)||this.hasConnectionError())return;const i=setTimeout((()=>{t()}),this.progressPollIntervalMs);this.progressPollTimers.set(e,i)},i=setTimeout((()=>{t()}),this.progressPollIntervalMs);this.progressPollTimers.set(e,i)}stop(e){const t=this.progressPollTimers.get(e);t&&(clearTimeout(t),this.progressPollTimers.delete(e))}stopAll(){for(const e of this.progressPollTimers.values())clearTimeout(e);this.progressPollTimers.clear()}async refresh(e){if(!this.listProgresses)return;const t=this.progressRefreshes.get(e);if(t)return void await t;const i=(async()=>{const{listProgresses:t}=this;if(!t)return;const i=await t(e);this.progressStateStore.applySnapshot(e,i).forEach((t=>{this.emitProgressUpdate(e,t),this.emitProgressUpdate(this.globalStreamKey,t)}))})().finally((()=>{this.progressRefreshes.delete(e)}));this.progressRefreshes.set(e,i),await i}}class wm{__init(){this.closed=!1}__init2(){this.error=null}__init3(){this.queue=[]}constructor(e){this.cleanup=e,wm.prototype.__init.call(this),wm.prototype.__init2.call(this),wm.prototype.__init3.call(this)}push(e){if(!this.closed){if(this.pending){const{pending:t}=this;return this.pending=void 0,void t.resolve({done:!1,value:e})}this.queue.push(e)}}close(){if(!this.closed&&(this.closed=!0,this.cleanup(),this.pending)){const{pending:e}=this;this.pending=void 0,e.resolve({done:!0,value:void 0})}}fail(e){if(!this.closed&&(this.closed=!0,this.error=e,this.queue.length=0,this.cleanup(),this.pending)){const{pending:t}=this;this.pending=void 0,t.reject(e)}}async next(){if(this.queue.length>0){return{done:!1,value:this.queue.shift()}}if(this.error)throw this.error;return this.closed?{done:!0,value:void 0}:await new Promise(((e,t)=>{this.pending={reject:t,resolve:e}}))}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}}function bm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const Sm="*";class Pm{__init(){this.connectionError=null}__init2(){this.disposed=!1}__init3(){this.replyStateStore=new mm}__init4(){this.progressStateStore=new ym}__init5(){this.sessionStreams=new Map}__init6(){this.progressStreams=new Map}constructor(e){Pm.prototype.__init.call(this),Pm.prototype.__init2.call(this),Pm.prototype.__init3.call(this),Pm.prototype.__init4.call(this),Pm.prototype.__init5.call(this),Pm.prototype.__init6.call(this),this.connectionManager=bm([e,"optionalAccess",e=>e.connectionManager])||(bm([e,"optionalAccess",e=>e.client])?new dm({createClient:()=>e.client}):lm),this.progressPoller=new vm({emitProgressUpdate:(e,t)=>{this.emitToProgress(e,t)},globalStreamKey:Sm,hasConnectionError:()=>Boolean(this.connectionError),hasSubscribers:e=>this.hasProgressSubscribers(e),listProgresses:bm([e,"optionalAccess",e=>e.listProgresses]),progressPollIntervalMs:bm([e,"optionalAccess",e=>e.progressPollIntervalMs]),progressStateStore:this.progressStateStore})}async connect(e){if(this.disposed)throw new Error("Frontier watcher disposed");if(this.lastConnectionRequest=e,this.connectionLease)return;this.connecting||(this.connecting=this.connectionManager.subscribe(e,{onError:e=>{this.handleConnectionError(e)},onEvent:e=>{this.handleEvent(e)}}).then((e=>(this.connectionLease=e,this.connectionError=null,e))).finally((()=>{this.connecting=void 0})));const t=await this.connecting;this.disposed&&(t.release(),this.connectionLease=void 0)}async ensureConnected(){if(this.connectionLease||this.connecting)await this.connecting;else{if(!this.lastConnectionRequest){if(this.connectionError)throw this.connectionError;throw new Error("Frontier watcher is not connected")}await this.connect(this.lastConnectionRequest)}}watchSession(e,t){const i=new wm((()=>{this.removeStream(e,i),bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.removeEventListener,"call",e=>e("abort",o)])})),o=()=>{i.close()};if(this.disposed)return i.fail(new Error("Frontier watcher disposed")),i;if(this.connectionError)return i.fail(this.connectionError),i;if(bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.aborted]))return i.close(),i;let s=this.sessionStreams.get(e);return s||(s=new Set,this.sessionStreams.set(e,s)),s.add(i),bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.addEventListener,"call",e=>e("abort",o,{once:!0})]),i}watchProgress(e,t){const i=e||Sm,o=new wm((()=>{this.removeProgressStream(i,o),bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.removeEventListener,"call",e=>e("abort",s)])})),s=()=>{o.close()};if(this.disposed)return o.fail(new Error("Frontier watcher disposed")),o;if(this.connectionError)return o.fail(this.connectionError),o;if(bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.aborted]))return o.close(),o;let n=this.progressStreams.get(i);if(n||(n=new Set,this.progressStreams.set(i,n)),n.add(o),bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.addEventListener,"call",e=>e("abort",s,{once:!0})]),e)this.emitKnownProgresses(o,e),this.progressPoller.refresh(e),this.progressPoller.ensure(e);else for(const e of this.progressStateStore.getKnownClawIds())this.emitKnownProgresses(o,e);return o}dispose(){if(!this.disposed){if(this.disposed=!0,this.progressPoller.stopAll(),this.failAllStreams(new Error("Frontier watcher disposed")),this.connectionLease)return this.connectionLease.release(),void(this.connectionLease=void 0);this.connecting&&this.connecting.then((e=>{e.release(),this.connectionLease===e&&(this.connectionLease=void 0)})).catch((()=>{}))}}removeStream(e,t){const i=this.sessionStreams.get(e);i&&(i.delete(t),0===i.size&&this.sessionStreams.delete(e))}removeProgressStream(e,t){const i=this.progressStreams.get(e);i&&(i.delete(t),0===i.size&&(this.progressStreams.delete(e),e!==Sm&&this.progressPoller.stop(e)))}failAllStreams(e){for(const t of this.sessionStreams.values())for(const i of t)i.fail(e);this.sessionStreams.clear();for(const t of this.progressStreams.values())for(const i of t)i.fail(e);this.progressStreams.clear()}handleConnectionError(e){this.connectionError=e,this.connectionLease=void 0,this.progressPoller.stopAll(),this.failAllStreams(e)}handleEvent(e){33555657===e.service&&("message"!==e.event&&"stream"!==e.event?"session"!==e.event?"process"===e.event&&this.handleProgressEvent(e.data):this.handleSessionEvent(e.data):this.handleReplyEvent(e.event,e.data))}handleReplyEvent(e,t){const i=this.replyStateStore.applyReplyEvent(e,t);i&&"sessionId"in i&&this.emitToSession(i.sessionId,i)}handleSessionEvent(e){const t=this.replyStateStore.applySessionIdleEvent(e);t&&"sessionId"in t&&this.emitToSession(t.sessionId,t)}handleProgressEvent(e){const t=this.progressStateStore.applyFrontierEvent(e);if(!t)return;const{clawId:i}=t.progress;this.emitToProgress(i,t),this.emitToProgress(Sm,t)}emitToSession(e,t){const i=this.sessionStreams.get(e);if(i&&0!==i.size)for(const e of i)e.push(t)}emitToProgress(e,t){const i=this.progressStreams.get(e);if(i&&0!==i.size)for(const e of i)e.push(t)}emitKnownProgresses(e,t){this.progressStateStore.getKnownProgressEvents(t).forEach((t=>{e.push(t)}))}hasProgressSubscribers(e){const t=this.progressStreams.get(e);return Boolean(t&&t.size>0)}}function Cm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const Tm=({replies:e,requestMessageId:t,source:i})=>{if(0===e.length)return null;const o=Cm([e,"access",t=>t[e.length-1],"optionalAccess",e=>e.answerId]);return o?{answerId:o,content:e.map((e=>e.content)).filter(Boolean).join("\n\n"),files:Cm([e,"access",t=>t[e.length-1],"optionalAccess",e=>e.files]),requestMessageId:t,source:i}:null},Em=({replies:e,replyOrder:t,reply:i})=>{e.has(i.answerId)||t.push(i.answerId),e.set(i.answerId,i)},km=({event:e,replies:t,replyOrder:i})=>{const o=t.get(e.chunk.answerId),s={answerId:e.chunk.answerId,content:`${Cm([o,"optionalAccess",e=>e.content])||""}${e.chunk.content}`,files:Cm([o,"optionalAccess",e=>e.files]),requestMessageId:e.chunk.requestMessageId||Cm([o,"optionalAccess",e=>e.requestMessageId])};return Em({replies:t,reply:s,replyOrder:i}),s},Im=({event:e,replies:t,replyOrder:i})=>(Em({replies:t,reply:e.reply,replyOrder:i}),e.reply);class Am{constructor(e){this.watcher=Cm([e,"optionalAccess",e=>e.watcher])||new Pm}async connect(e){await this.watcher.connect(e)}async waitForReply(e){const{onReplyChunk:t,onReplyUpdate:i,sessionId:o,requestMessageId:s,timeoutMs:n}=e;if(this.pending)throw new Error("Frontier waiter already has a pending reply request");await this.watcher.ensureConnected();const r=new AbortController;return await new Promise(((e,a)=>{const c=new Map,d=[];let l=!1;const p=t=>{l||(l=!0,Cm([this,"access",e=>e.pending,"optionalAccess",e=>e.timer])&&clearTimeout(this.pending.timer),this.pending=void 0,r.abort(),t({reject:a,resolve:e}))},u=void 0===n?void 0:setTimeout((()=>{const e=Tm({replies:d.map((e=>c.get(e))).filter((e=>Boolean(e))),requestMessageId:s,source:"timeout"});p((({reject:t,resolve:i})=>{e?i(e):t(new Error("Timed out waiting for Frontier reply"))}))}),n);this.pending={controller:r,reject:a,timer:u},(async()=>{try{const e=(async()=>{for await(const e of this.watcher.watchSession(o,{signal:r.signal})){if("reply_chunk"===e.type){if(e.chunk.requestMessageId!==s)continue;km({event:e,replies:c,replyOrder:d}),Cm([t,"optionalCall",t=>t(e)]);continue}if("reply_update"===e.type){if(e.reply.requestMessageId!==s)continue;Im({event:e,replies:c,replyOrder:d}),Cm([i,"optionalCall",t=>t(e)]);continue}if("session_idle"!==e.type)continue;const o=Tm({replies:e.replies.filter((e=>e.requestMessageId===s)),requestMessageId:s,source:"idle"});o&&p((({resolve:e})=>{e(o)}))}})();await e}catch(e){p((({reject:t})=>{t(e instanceof Error?e:new Error(String(e)))}))}})()}))}dispose(){this.pending&&(this.pending.timer&&clearTimeout(this.pending.timer),this.pending.controller.abort(),this.pending.reject(new Error("Frontier waiter disposed")),this.pending=void 0),this.watcher.dispose()}}const jm={skipOrgCheck:!0,skipSpaceCheck:!0},Rm=async t=>{if(t)return t;const i=s.createSessionConfigStore(),o=await i.get();if(o.sessionId)return o.sessionId;throw new e.CozeError(e.ErrorCode.E1000,"Missing session ID: provide --session-id or run `coze session create` first")},zm=async({clawId:e,sessionId:t})=>{const i=s.createSessionConfigStore();await i.save({sessionId:t,...e?{sessionClawId:e}:{}})},Um=({timeoutMs:e})=>{const t=new AbortController,i=()=>{t.abort()},o=void 0===e?void 0:setTimeout((()=>{i()}),e);return process.once("SIGINT",i),{abort:i,signal:t.signal,dispose:()=>{o&&clearTimeout(o),process.off("SIGINT",i)}}},Lm=async(t,i)=>{const o=(t=>{const i=t.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");return{ctx:i,service:s.createDefaultSessionService(i.config)}})(t);try{await i(o)}catch(t){V((t=>{if(t instanceof e.CozeError)return t;if(t instanceof s.SessionServiceError){const i="SESSION_AUTH_INVALID"===t.code?e.ErrorCode.E2001:e.ErrorCode.E5000;return new e.CozeError(i,t.message,{session_error:t.code})}return t instanceof Error?new e.CozeError(e.ErrorCode.E5000,t.message,t.stack):new e.CozeError(e.ErrorCode.E5000,String(t))})(t),o.ctx)}},Om=t=>{const i=Number.parseInt(t,10);if(!Number.isFinite(i)||i<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --limit: expected a positive integer");return i},xm=t=>{const i=Number.parseInt(t,10);if(!Number.isFinite(i)||i<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --timeout: expected a positive integer");return i},Bm=e=>{if(!e||0===e.length)return null;const t=["Files:"];return e.forEach(((e,i)=>{t.push(`${i+1}. ${String(e.file_name||"unnamed-file")}`),e.file_url&&t.push(`file_url: ${String(e.file_url)}`),e.preview_url&&t.push(`preview_url: ${String(e.preview_url)}`)})),t.join("\n")},qm=(e,t)=>{const i=Bm(t);return i?[e,"",i].join("\n"):e},Dm=({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,xTTEnv:n})=>{const r=o||t,a=(({accessToken:e,xTTEnv:t})=>{if(!e)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const i={Authorization:`Bearer ${e}`};return t&&(i["x-use-ppe"]="1",i["x-tt-env"]=t),i})({accessToken:e,xTTEnv:n});return{resolveConfig:async()=>({...await Fu({baseUrl:r,headers:a,xTTEnv:n}),headers:a,organizationId:i}),scopeKey:JSON.stringify({baseUrl:r,authorization:a.Authorization,organizationId:i,xTTEnv:n})}},Mm=async({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,progressPollIntervalMs:s,service:n,xTTEnv:r})=>{const a=new Pm({listProgresses:n?async e=>(await n.listProgresses({clawId:e})).map((t=>({progressId:t.progressId,clawId:e,name:t.name,progressType:t.type,progressStatus:t.progressStatus}))):void 0,progressPollIntervalMs:s});return await a.connect(Dm({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,xTTEnv:r})),a},Nm=e=>[`progress_id: ${e.progressId}`,e.name?`name: ${e.name}`:null,e.type?`type: ${e.type}`:null,`progress_status: ${e.progressStatus}`].filter(Boolean).join("\n"),Gm=e=>`${JSON.stringify(e)}\n`;class $m{__init(){this.replyStates=new Map}__init2(){this.requestPrintedContent=new Map}__init3(){this.endsWithNewline=!0}__init4(){this.hasStartedReply=!1}constructor(e){$m.prototype.__init.call(this),$m.prototype.__init2.call(this),$m.prototype.__init3.call(this),$m.prototype.__init4.call(this),this.format=e.format,this.includeReplyMetadata=e.includeReplyMetadata||!1,this.write=e.write||(e=>process.stdout.write(e))}writeChunk({chunk:e,sessionId:t}){if("text"!==this.format)return void this.write(Gm({type:"reply_chunk",session_id:t,answer_message_id:e.answerId,reply_to_message_id:e.requestMessageId,delta:e.content}));const i=this.getOrCreateReplyState(e.answerId);this.ensureReplyStarted({answerId:e.answerId,requestMessageId:e.requestMessageId,state:i}),this.writeRaw(e.content),i.printedContent+=e.content,this.updateRequestPrintedContent({requestMessageId:e.requestMessageId,printedContent:i.printedContent})}writeReply({files:e,reply:t,sessionId:i,source:o}){if("text"!==this.format)return void this.write(Gm({type:"message"===o?"reply_update":"reply_completed",session_id:i,answer_message_id:t.answerId,reply_to_message_id:t.requestMessageId,content:t.content,files:e,event_source:o}));const s=this.getOrCreateReplyState(t.answerId),n=this.getPreviousPrintedContent({reply:t,state:s}),r=this.getSnapshotDelta({nextContent:t.content,previousContent:n}),a=this.continuesPrintedRequest({reply:t,state:s});if(!r&&"message"!==o)return this.updateReplyStateContent({reply:t,state:s}),void this.writeFinalReplyMetadata({files:e});this.ensureReplyStarted({answerId:t.answerId,requestMessageId:t.requestMessageId,state:s,continuesPrintedRequest:a}),r&&this.writeRaw(r),this.updateReplyStateContent({reply:t,state:s}),"message"!==o&&this.writeFinalReplyMetadata({files:e})}writeFinalReplyMetadata({files:e}){this.endsWithNewline||this.writeRaw("\n");const t=Bm(e);t&&this.writeRaw(`\n${t}\n`)}writeProgress({progress:e,sessionId:t}){"text"===this.format?(this.endsWithNewline||this.writeRaw("\n"),this.writeRaw(`\n${Nm(e)}\n`)):this.write(Gm({type:"background_progress_started",session_id:t,progress_id:e.progressId,progress_name:e.name,progress_type:e.type,progress_status:e.progressStatus}))}getOrCreateReplyState(e){const t=this.replyStates.get(e);if(t)return t;const i={headerPrinted:!1,printedContent:""};return this.replyStates.set(e,i),i}ensureReplyStarted({answerId:e,continuesPrintedRequest:t=!1,requestMessageId:i,state:o}){if(!o.headerPrinted){if(t)return o.headerPrinted=!0,void(this.hasStartedReply=!0);if(this.hasStartedReply&&(this.endsWithNewline||this.writeRaw("\n"),this.writeRaw("\n")),this.includeReplyMetadata){const t=[`answer_message_id: ${e}`,i?`reply_to_message_id: ${i}`:null].filter(Boolean);this.writeRaw(`${t.join("\n")}\n`)}o.headerPrinted=!0,this.hasStartedReply=!0}}getSnapshotDelta({nextContent:e,previousContent:t}){return t?e===t?"":e.startsWith(t)?e.slice(t.length):`\n${e}`:e}getPreviousPrintedContent({reply:e,state:t}){return e.requestMessageId&&this.requestPrintedContent.has(e.requestMessageId)?this.requestPrintedContent.get(e.requestMessageId)||"":t.printedContent}continuesPrintedRequest({reply:e,state:t}){return Boolean(e.requestMessageId&&!t.headerPrinted&&this.requestPrintedContent.has(e.requestMessageId))}updateReplyStateContent({reply:e,state:t}){t.printedContent=e.content,this.updateRequestPrintedContent({requestMessageId:e.requestMessageId,printedContent:e.content})}updateRequestPrintedContent({printedContent:e,requestMessageId:t}){if(!t)return;const i=this.requestPrintedContent.get(t)||"";e.length>=i.length&&this.requestPrintedContent.set(t,e)}writeRaw(e){e&&(this.write(e),this.endsWithNewline=e.endsWith("\n"))}}function Fm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const Vm=({ctx:e,sessionId:t,reply:i,files:o,source:s})=>{"text"!==e.format?e.response.print({session_id:t,answer_message_id:i.answerId,reply_to_message_id:i.requestMessageId,content:i.content,files:o,event_source:s}):e.response.print((({reply:e,files:t,source:i})=>`${[`answer_message_id: ${e.answerId}`,e.requestMessageId?`reply_to_message_id: ${e.requestMessageId}`:null,`event_source: ${i}`].filter(Boolean).join("\n")}\n${qm(e.content,t)}`)({files:o,reply:i,source:s}))},Wm=({ctx:e,options:t,service:i,streamRenderer:o})=>{const n=t.snapshot?new Map:null,r=async t=>await s.resolveStoredSessionReplyFiles({files:t.files,apiBaseUrl:e.config.apiBaseUrl,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv,service:i}),a=async({reply:i,source:o})=>{const s=await r(i),a=(({files:e,reply:t})=>JSON.stringify({answerId:t.answerId,content:t.content,files:e,requestMessageId:t.requestMessageId}))({files:s,reply:i});Fm([n,"optionalAccess",e=>e.get,"call",e=>e(i.answerId)])!==a&&(Fm([n,"optionalAccess",e=>e.set,"call",e=>e(i.answerId,a)]),Vm({ctx:e,files:s,reply:i,sessionId:t.sessionId,source:o}))};return{handleReplyChunk:e=>{Fm([o,"optionalAccess",e=>e.writeChunk,"call",i=>i({chunk:e.chunk,sessionId:t.sessionId})])},handleReplyUpdate:async e=>{o?o.writeReply({reply:e.reply,sessionId:t.sessionId,source:"message"}):await a({reply:e.reply,source:"message"})},handleIdleReply:async e=>{o?o.writeReply({files:await r(e),reply:e,sessionId:t.sessionId,source:"idle"}):await a({reply:e,source:"idle"})}}},Hm=e=>{e.command("watch").description("Watch websocket replies for a claw session").option("-s, --session-id <sessionId>","Target session ID; defaults to the most recently used local session").option("--timeout <timeoutMs>","Stop watching after the specified timeout in milliseconds",xm).option("--snapshot","Print full reply snapshots instead of streaming chunks incrementally").config({...jm,help:{brief:"Continuously watch websocket replies for a session",description:"Subscribe to Frontier websocket events for the specified session and stream assistant output as it arrives. Use --snapshot to keep the previous snapshot-style behavior.",examples:[{desc:"Watch one session until interrupted",cmd:"coze session watch -s 123456789",tags:["[RECOMMENDED]"]},{desc:"Watch one session and exit after 30 seconds",cmd:"coze session watch -s 123456789 --timeout 30000"},{desc:"Keep the old snapshot-style output",cmd:"coze session watch -s 123456789 --snapshot"}],schema:{input:{session_id:{type:"string",required:!1,description:"Target session ID. Defaults to the most recently used local session"},timeout:{type:"number",required:!1,description:"Optional timeout in milliseconds"}},output:{type:"object",properties:{session_id:{type:"string"},answer_message_id:{type:"string"},reply_to_message_id:{type:"string"},content:{type:"string"},event_source:{type:"string"}}}}}}).action((async(e,t)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await Rm(e.sessionId),s={...e,sessionId:o},n=await Mm({accessToken:t.config.accessToken,apiBaseUrl:t.config.apiBaseUrl,organizationId:t.config.organizationId,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv});await zm({sessionId:o});const r=s.snapshot?null:new $m({format:t.format,includeReplyMetadata:"text"===t.format}),a=Um({timeoutMs:s.timeout}),c=Wm({ctx:t,options:s,service:i,streamRenderer:r});try{for await(const e of n.watchSession(o,{signal:a.signal}))if("reply_chunk"!==e.type)if("reply_update"!==e.type){if("progress_update"!==e.type){await i.updateSessionRuntimeStatus({sessionId:o,status:"idle"});for(const t of e.replies)await c.handleIdleReply(t)}}else await c.handleReplyUpdate(e);else c.handleReplyChunk(e)}finally{a.dispose(),n.dispose()}}))})(e,t)}))};function Jm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const Km=async e=>await new Promise((t=>setTimeout(t,e))),Qm=e=>{const t=e.contentPreview&&e.contentPreview!==e.replyContent?e.contentPreview:void 0,i=e.resultSummary&&e.resultSummary!==e.replyContent&&e.resultSummary!==e.contentPreview?e.resultSummary:void 0;return{contentPreview:t,replyContent:e.replyContent,resultSummary:i}},Ym=e=>{const t=Qm(e);return{answer_message_id:e.answerMessageId,artifacts:Jm([e,"access",e=>e.artifacts,"optionalAccess",e=>e.map,"call",e=>e((e=>({file_name:e.fileName,file_uri:e.fileUri,file_url:e.fileUrl,preview_url:e.previewUrl})))]),content_preview:t.contentPreview,created_at:e.createdAt,finished_at:e.finishedAt,kind:e.kind,last_progress_status:e.lastProgressStatus,last_refresh_error:e.lastRefreshError,message_id:e.messageId,progress_id:e.progressId,reply_content:t.replyContent,result_summary:t.resultSummary,session_id:e.sessionId,status:e.status,task_id:e.taskId,updated_at:e.updatedAt,worker_pid:e.workerPid}},Zm=e=>{const t=Qm(e);return[`task_id: ${e.taskId}`,`status: ${e.status}`,`session_id: ${e.sessionId}`,`message_id: ${e.messageId}`,`progress_id: ${e.progressId}`,e.answerMessageId?`answer_message_id: ${e.answerMessageId}`:null,t.contentPreview?`content_preview: ${t.contentPreview}`:null,t.replyContent?`reply_content: ${t.replyContent}`:null,t.resultSummary?`result_summary: ${t.resultSummary}`:null,e.lastProgressStatus?`last_progress_status: ${e.lastProgressStatus}`:null,e.lastRefreshError?`last_refresh_error: ${e.lastRefreshError}`:null,`created_at: ${e.createdAt}`,`updated_at: ${e.updatedAt}`,e.finishedAt?`finished_at: ${e.finishedAt}`:null].filter(Boolean).join("\n")},Xm=({ctx:e,task:t})=>{"text"!==e.format?e.response.print(Ym(t)):e.response.print(Zm(t))},eg=t=>t instanceof s.SessionTaskExpiredError||t instanceof s.SessionTaskNotFoundError?new e.CozeError(e.ErrorCode.E3000,t.message,{task_id:t.taskId}):t instanceof s.SessionTaskStoreError?new e.CozeError(e.ErrorCode.E5000,t.message):t instanceof Error?t:new e.CozeError(e.ErrorCode.E5000,String(t)),tg=e=>{const t=e.command("task").description("Inspect persisted session background tasks").config({...jm,help:{brief:"Inspect session background tasks",description:"List, show, refresh, watch, and garbage-collect persisted session progress tasks created from `coze session message --wait`."}});t.command("list").description("List persisted session tasks").option("--status <status>","Filter by task status").option("--session-id <sessionId>","Filter by session ID").option("--include-expired","Include expired terminal tasks").action((async(e,t)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{try{const o=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:i,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await o.listTasks({includeExpired:Boolean(e.includeExpired),sessionId:e.sessionId,status:e.status});if("text"===t.format)return void t.response.print(n.length>0?n.map(Zm).join("\n\n"):"No session tasks");t.response.print({items:n.map((e=>Ym(e)))})}catch(e){throw eg(e)}}))})(e,t)})),t.command("show <taskId>").description("Show one persisted session task snapshot").option("--include-expired","Read an expired task record").action((async(e,t,i)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{try{const o=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:i,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await o.getTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});Xm({ctx:t,task:n})}catch(e){throw eg(e)}}))})({includeExpired:t.includeExpired,taskId:e},i)})),t.command("refresh <taskId>").description("Refresh one persisted session task against the server").option("--include-expired","Read an expired task record").action((async(e,t,i)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{try{const o=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:i,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await o.refreshTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});Xm({ctx:t,task:n})}catch(e){throw eg(e)}}))})({includeExpired:t.includeExpired,taskId:e},i)})),t.command("watch <taskId>").description("Watch one persisted session task until it reaches a terminal state").option("--include-expired","Read an expired task record").option("--timeout <timeoutMs>","Stop watching after the specified timeout in milliseconds",xm).action((async(e,t,i)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{try{const o=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:i,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv});let n=await o.getTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});if(Xm({ctx:t,task:n}),s.isSessionTaskTerminal(n.status))return;const r=void 0===e.timeout?void 0:Date.now()+e.timeout;for(;;){const i=void 0===r?1e4:Math.min(1e4,r-Date.now());if(i<=0)return;if(await Km(i),n=await o.refreshTask(e.taskId,{includeExpired:Boolean(e.includeExpired)}),Xm({ctx:t,task:n}),s.isSessionTaskTerminal(n.status))return}}catch(e){throw eg(e)}}))})({includeExpired:t.includeExpired,taskId:e,timeout:t.timeout},i)})),t.command("gc").description("Remove expired terminal session tasks from local storage").action((async(e,t)=>{await(async e=>{await Lm(e,(async({ctx:e,service:t})=>{try{const i=s.createSessionTaskService({apiBaseUrl:e.config.apiBaseUrl,service:t,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv}),o=await i.gcTasks();if("text"===e.format)return void e.response.print(o.length>0?`Removed ${o.length} expired task(s)`:"No expired session tasks");e.response.print({count:o.length,items:o.map((e=>Ym(e)))})}catch(e){throw eg(e)}}))})(t)}))},ig=e=>`${[`message_id: ${e.messageId}`,e.replyToMessageId?`reply_to_message_id: ${e.replyToMessageId}`:null,e.messageType?`message_type: ${e.messageType}`:null,e.createTime?`create_time: ${e.createTime}`:null].filter(Boolean).join("\n")}\n${qm(e.content,e.files)}`,og=async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await Rm(e.sessionId),n=await i.listRepliesByMessage({sessionId:o,messageId:e.messageId});await zm({sessionId:n.sessionId});const r=s.createSessionConfigStore(),a=await r.get(),c=n.items.some((e=>e.files&&e.files.length>0)),d=c?a.sessionClawId||(await i.getStatus()).clawId:void 0,l=c?await(async({items:e,store:t,service:i,clawId:o,apiBaseUrl:n,sessionApiBaseUrl:r,xTTEnv:a})=>await Promise.all(e.map((async e=>({...e,files:await s.resolveStoredSessionReplyFiles({files:e.files,clawId:o,apiBaseUrl:n,sessionApiBaseUrl:r,xTTEnv:a,service:i,deps:{store:t}})})))))({items:n.items,store:r,service:i,clawId:d,apiBaseUrl:t.config.apiBaseUrl,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}):n.items;if("text"===t.format)return n.requestMessageFound||0!==l.length?0===l.length?void t.response.print(`No replies found for message: ${e.messageId}`):void t.response.print(l.map(ig).join("\n\n")):void t.response.print(`Message not found: ${e.messageId}`);t.response.print({session_id:n.sessionId,message_id:n.requestMessageId,request_message_found:n.requestMessageFound,count:l.length,items:l.map((e=>({message_id:e.messageId,reply_to_message_id:e.replyToMessageId,source:e.source,message_type:e.messageType,content:e.content,files:e.files,create_time:e.createTime,raw:e.raw})))})}))};function sg(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const ng=({ctx:e})=>{const t=new Map;return i=>{const o=t.get(i.progressId);o&&o.progressStatus===i.progressStatus&&o.name===i.name&&o.type===i.type&&"snapshot"!==i.eventSource||(t.set(i.progressId,{name:i.name,progressId:i.progressId,progressStatus:i.progressStatus,type:i.type}),(({ctx:e,progress:t})=>{"text"!==e.format?e.response.print({progress_id:t.progressId,name:t.name,type:t.type,progress_status:t.progressStatus,event_source:t.eventSource}):e.response.print(`${Nm(t)}\nevent_source: ${t.eventSource}`)})({ctx:e,progress:i}))}},rg=(e,t)=>!t||e.progressId===t,ag=async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{(({ctx:e,progresses:t})=>{"text"!==e.format?e.response.print({items:t.map((e=>({progress_id:e.progressId,name:e.name,type:e.type,progress_status:e.progressStatus,raw:e.raw})))}):e.response.print(t.length>0?t.map((e=>Nm(e))).join("\n\n"):"No active progress")})({ctx:t,progresses:await i.listProgresses({size:e.size})})}))},cg=async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await i.getStatus(),{clawId:n}=o;if(!o.authValid||!n)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const r=await Mm({accessToken:t.config.accessToken,apiBaseUrl:t.config.apiBaseUrl,organizationId:t.config.organizationId,progressPollIntervalMs:3e4,sessionApiBaseUrl:t.config.sessionApiBaseUrl,service:i,xTTEnv:t.config.xTTEnv}),a=Um({timeoutMs:e.timeout}),c=ng({ctx:t});try{await(async({clawId:e,emitProgress:t,options:i,service:o})=>{(await o.listProgresses({clawId:e})).filter((e=>rg(e,i.progressId))).forEach((e=>{t({...e,eventSource:"snapshot"})}))})({clawId:n,emitProgress:c,options:e,service:i}),await(async({abortScope:e,clawId:t,emitProgress:i,options:o,watcher:s})=>{for await(const n of s.watchProgress(t,{signal:e.signal}))rg(n.progress,o.progressId)&&(i({progressId:n.progress.progressId,name:n.progress.name,type:n.progress.progressType,progressStatus:n.progress.progressStatus,eventSource:"websocket"}),o.progressId&&"finished"===n.progress.progressStatus&&e.abort())})({abortScope:a,clawId:n,emitProgress:c,options:e,watcher:r})}finally{a.dispose(),r.dispose()}}))},dg=e=>{const t=e.command("progress").description("Inspect claw background progress").config({...jm,help:{brief:"Inspect claw background progress",description:"List and watch claw process-style background progress driven by websocket and process APIs."}});t.command("list").description("List current background progress").option("--size <size>","Maximum number of progress items to request",Om,100).action(ag),t.command("show <progressId>").description("Show one background progress snapshot").action((async(e,t,i)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await i.getProgress({progressId:e.progressId});"text"!==t.format?t.response.print({progress_id:e.progressId,found:Boolean(o),name:sg([o,"optionalAccess",e=>e.name]),type:sg([o,"optionalAccess",e=>e.type]),progress_status:sg([o,"optionalAccess",e=>e.progressStatus]),raw:sg([o,"optionalAccess",e=>e.raw])}):t.response.print(o?Nm(o):`Progress not found: ${e.progressId}`)}))})({progressId:e},i)})),t.command("poll <progressId>").description("Poll one background progress and treat missing as finished").action((async(e,t,i)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await i.getProgress({progressId:e.progressId}),s=sg([o,"optionalAccess",e=>e.progressStatus])||"finished";"text"!==t.format?t.response.print({progress_id:e.progressId,name:sg([o,"optionalAccess",e=>e.name]),type:sg([o,"optionalAccess",e=>e.type]),progress_status:s,raw:sg([o,"optionalAccess",e=>e.raw])}):t.response.print(Nm({progressId:e.progressId,name:sg([o,"optionalAccess",e=>e.name]),type:sg([o,"optionalAccess",e=>e.type]),progressStatus:s}))}))})({progressId:e},i)})),t.command("watch [progressId]").description("Watch one or all background progress updates").option("--timeout <timeoutMs>","Stop watching after the specified timeout in milliseconds",xm).action((async(e,t,i)=>{await cg({progressId:e,timeout:t.timeout},i)}))};function lg(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const pg={...jm,help:{brief:"Send a text message to a session",description:"Send a plain text message to the specified claw session. The message can be provided as a positional argument or via stdin. Use @<path> to mention and upload local files as attachments. With --wait, the CLI streams the current turn reply until the session becomes idle. If a new background progress starts within 3 seconds after idle, the CLI returns its progress_id instead of waiting for the background task to finish.",examples:[{desc:"Send a message to a session",cmd:'coze session message "hello" -s 123456789',tags:["[RECOMMENDED]"]},{desc:"Send stdin as the message body",cmd:"cat prompt.txt | coze session message -s 123456789"},{desc:"Wait for the streaming reply until the turn becomes idle",cmd:'coze session message "hello" -s 123456789 --wait'},{desc:"Upload local files and send them with the query",cmd:'coze session message "summarize these" -s 123456789 --file ./a.pdf --file ./b.png'},{desc:"Mention a local file with @ and send it as an attachment",cmd:'coze session message "summarize @docs/notes.md" -s 123456789'},{desc:"Use a podcast voice and inject the voice instruction into the message",cmd:'coze session message "@播客 制作一个介绍潮汕美食的播客" -s 123456789 --podcast-voice "鸡汤女生"'}],schema:{input:{message:{type:"string",required:!1,description:"Plain text message content"},session_id:{type:"string",required:!1,description:"Target session ID. Defaults to the most recently used local session"},file:{type:"array",required:!1,description:"Local file paths to upload and attach"},wait:{type:"boolean",required:!1,description:"Wait for idle and stream assistant reply events"},podcast_voice:{type:"string",required:!1,description:"Podcast voice label or value to inject into the message"},podcast_mode:{type:"string",required:!1,description:"Podcast mode label or value used to disambiguate the voice"}},output:{type:"object",properties:{session_id:{type:"string"},message_id:{type:"string"},status:{type:"string"},content:{type:"string"},answer_message_id:{type:"string"},progress_id:{type:"string"},task_id:{type:"string"},task_status:{type:"string"}}}}}},ug=async({ctx:t,options:i,resolvedContent:o})=>{if(!i.podcastVoice)return o;if(!o)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-voice requires MESSAGE or stdin content");const s=(({config:t,voice:i,mode:o})=>{const s=i_(i),n=s_({config:t,mode:o}).filter((e=>i_(e.label)===s||i_(e.value)===s));if(0===n.length)throw new e.CozeError(e.ErrorCode.E1000,`Podcast voice not found: ${i}`);if(n.length>1){const t=n.map((e=>e.mode_value||e.mode_label||"unknown")).join(", ");throw new e.CozeError(e.ErrorCode.E1000,`Voice "${i}" matched multiple podcast voices; specify --podcast-mode (${t})`)}return n[0]})({config:await o_({baseUrl:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,xTTEnv:t.config.xTTEnv}),voice:i.podcastVoice,mode:i.podcastMode}).label||i.podcastVoice;return(({content:t,voiceLabel:i})=>{if(t.includes('使用音色"'))throw new e.CozeError(e.ErrorCode.E1000,"Message already contains a podcast voice instruction");const o=`使用音色"${i}", `,s=t.length-t.trimStart().length,n=t.slice(0,s),r=t.trimStart();if(/^@播客(?=\s|$)/.test(r))return`${n}@播客 ${o}${r.slice(3).trimStart()}`;return`${o}${t}`})({content:o,voiceLabel:s})},_g=async({ctx:t,message:i,options:o,service:s})=>{const{content:n,filePaths:r}=await t_(i,{cwd:t.cwd,onWarn:e=>t.ui.warn(e)});(({options:t,resolvedContent:i})=>{if(t.podcastMode&&!t.podcastVoice)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-mode requires --podcast-voice");if(t.podcastVoice&&!i)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-voice requires MESSAGE or stdin content")})({options:o,resolvedContent:n});const a=await Hu({filePaths:[...o.file||[],...r],sessionId:o.sessionId,apiBaseUrl:t.config.apiBaseUrl,sessionApiBaseUrl:t.config.sessionApiBaseUrl,sessionSpaceWebId:t.config.sessionSpaceWebId,xTTEnv:t.config.xTTEnv,service:s}),c=await ug({ctx:t,options:o,resolvedContent:n});if(!c&&0===a.length)throw new e.CozeError(e.ErrorCode.E1000,"Missing message input: provide MESSAGE, stdin content, and/or --file");return{content:c||"",files:a}},hg=async({ctx:e,options:t,service:i})=>{if(!t.wait)return{streamRenderer:null,waiter:null};const o=new $m({format:e.format}),s=lg([await i.getStatus(),"optionalAccess",e=>e.clawId]);return{clawId:s,knownProgressIds:s?await i.listProgresses({clawId:s}).then((e=>new Set(e.map((e=>e.progressId))))).catch((()=>null)):void 0,streamRenderer:o,waiter:await(async({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,xTTEnv:s})=>new Am({watcher:await Mm({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,xTTEnv:s})}))({accessToken:e.config.accessToken,apiBaseUrl:e.config.apiBaseUrl,organizationId:e.config.organizationId,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv})}},mg=async({ctx:e,knownProgressIds:t,options:i,result:o,service:n,streamRenderer:r,waiter:a,clawId:c})=>{const d=await a.waitForReply({onReplyChunk:r?e=>{r.writeChunk({chunk:e.chunk,sessionId:i.sessionId})}:void 0,onReplyUpdate:r?e=>{r.writeReply({reply:e.reply,sessionId:i.sessionId,source:"message"})}:void 0,sessionId:i.sessionId,requestMessageId:o.messageId,timeoutMs:i.timeout}),l="idle"===d.source&&c&&t?await(async({clawId:e,knownProgressIds:t,listProgresses:i,pollIntervalMs:o=500,timeoutMs:s=3e3})=>{const n=Date.now()+s;for(;;){const s=(await i({clawId:e})).find((e=>!t.has(e.progressId)));if(s)return s;const r=n-Date.now();if(r<=0)return null;await qu(Math.min(o,r))}})({clawId:c,knownProgressIds:t,listProgresses:e=>n.listProgresses(e),timeoutMs:3e3}):null;"idle"===d.source&&await n.updateSessionRuntimeStatus({sessionId:i.sessionId,status:"idle"});const p=await s.resolveStoredSessionReplyFiles({files:d.files,apiBaseUrl:e.config.apiBaseUrl,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv,service:n});return r?(r.writeReply({files:p,reply:{answerId:d.answerId,content:d.content,requestMessageId:o.messageId},sessionId:i.sessionId,source:d.source}),l&&r.writeProgress({progress:l,sessionId:i.sessionId}),{answerMessageId:d.answerId,content:d.content,files:p,progress:l,rendered:!0}):{answerMessageId:d.answerId,content:d.content,files:p,progress:l,rendered:!1}},gg=async(e,t,i)=>{await Lm(i,(async({ctx:i,service:o})=>{const n=await Rm(t.sessionId),r={...t,sessionId:n},a=await _g({ctx:i,message:e,options:r,service:o}),c=await hg({ctx:i,options:r,service:o});try{const e=await o.sendMessage({sessionId:n,content:a.content,files:a.files});if(await zm({sessionId:e.sessionId}),c.waiter){const t=await mg({...c,ctx:i,options:r,result:e,service:o,waiter:c.waiter});if(t.progress)try{const r=s.createSessionTaskService({apiBaseUrl:i.config.apiBaseUrl,service:o,sessionApiBaseUrl:i.config.sessionApiBaseUrl,xTTEnv:i.config.xTTEnv});let a=await r.createOrUpdateTaskFromMessageWait({answerMessageId:t.answerMessageId,content:t.content,files:t.files,messageId:e.messageId,progress:t.progress,sessionId:n});try{const e=await s.startDetachedSessionTaskRefreshWorker({payload:{accessToken:i.config.accessToken||"",apiBaseUrl:i.config.apiBaseUrl,organizationId:i.config.organizationId,sessionApiBaseUrl:i.config.sessionApiBaseUrl,taskId:a.taskId,xTTEnv:i.config.xTTEnv}});e&&(a=await r.patchTask(a.taskId,{lastRefreshError:void 0,workerPid:e}))}catch(e){a=await r.patchTask(a.taskId,{lastRefreshError:e instanceof Error?`Failed to start auto refresh worker: ${e.message}`:`Failed to start auto refresh worker: ${String(e)}`})}if("json"===i.format)return void i.response.print({answer_message_id:t.answerMessageId,content:t.content,files:t.files,message_id:e.messageId,progress_id:t.progress.progressId,session_id:e.sessionId,status:e.status,task_id:a.taskId,task_status:a.status,worker_pid:a.workerPid})}catch(t){if(i.ui.warn(`Failed to persist task: ${t instanceof Error?t.message:String(t)}`),"json"===i.format)return void i.response.print({session_id:e.sessionId,message_id:e.messageId,status:e.status})}if(t.rendered)return}i.response.print({session_id:e.sessionId,message_id:e.messageId,status:e.status})}finally{lg([c,"access",e=>e.waiter,"optionalAccess",e=>e.dispose,"call",e=>e()])}}))};const fg={...jm,help:{brief:"Work with PPT artifacts generated by a session",description:"Target one specific PPT artifact with --file-uri. Page-scoped edit still needs --session-id because it sends a session chat message.",examples:[{desc:"Get PPT information",cmd:"coze session ppt info --file-uri task-1/deck.pptx.html",tags:["[RECOMMENDED]"]},{desc:"List page outline text",cmd:"coze session ppt pages --file-uri task-1/deck.pptx.html"},{desc:"Export the PPTX file",cmd:"coze session ppt export --file-uri task-1/deck.pptx.html --output-path ./deck.pptx"},{desc:"Edit one page through session chat",cmd:'coze session ppt edit "标题更突出" -s 123456789 --page 2 --wait'},{desc:"Create a share link",cmd:"coze session ppt share --file-uri task-1/deck.pptx.html"}]}},yg=t=>{const i=Number.parseInt(t,10);if(!Number.isFinite(i)||i<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --page: expected a positive integer");return i},vg=(e,t)=>[...t,yg(e)],wg=t=>{if("ppt"===t||"editable"===t)return t;throw new e.CozeError(e.ErrorCode.E1000,'Invalid value for --export-type: expected "ppt" or "editable"')},bg=async({options:t})=>{if(t.fileUri)return{fileName:t.fileUri,fileUri:t.fileUri,raw:{file_name:t.fileUri,file_uri:t.fileUri}};throw new e.CozeError(e.ErrorCode.E1000,"Missing PPT identifier: provide --file-uri.")},Sg=t=>{if(!t.fileUri)throw new e.CozeError(e.ErrorCode.E1000,"PPT file_uri is required for this operation. Provide --file-uri.");return t.fileUri},Pg=async({file:e,service:t})=>e.fileUrl?e.fileUrl:t.resolveFileUrl({fileUri:Sg(e)}),Cg=async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await bg({options:e}),n=await Pg({file:o,service:i}),r=await s.fetchSessionPptContent({url:n}),a=s.parseSessionPptContent(r);"text"!==t.format?t.response.print({file_name:o.fileName,file_uri:o.fileUri,file_url:n,type:a.type,page_count:a.pageCount}):t.response.print((({file:e,pageCount:t,type:i,url:o})=>[`PPT: ${e.fileName}`,e.fileUri?`file_uri: ${e.fileUri}`:null,`file_url: ${o}`,`type: ${i}`,`pages: ${t}`].filter(Boolean).join("\n"))({file:o,pageCount:a.pageCount,type:a.type,url:n}))}))},Tg=t=>{const i=t.command("ppt").description("Inspect, export, share, and edit session PPT artifacts").config(fg);i.command("info").description("Get PPT metadata and page count").option("--file-uri <uri>","Specific PPT file_uri").action(((e,t)=>Cg(e,t))),i.command("pages").description("List PPT page outline and preview text").option("--file-uri <uri>","Specific PPT file_uri").option("--limit <limit>","Maximum pages to print",Om).action(((e,t)=>(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await bg({options:e}),n=await Pg({file:o,service:i}),r=await s.fetchSessionPptContent({url:n}),a=s.parseSessionPptContent(r),c=e.limit?a.pages.slice(0,e.limit):a.pages;"text"!==t.format?t.response.print({file_name:o.fileName,file_uri:o.fileUri,file_url:n,type:a.type,page_count:a.pageCount,pages:c}):t.response.print((e=>e.map((e=>{const t=e.title?` ${e.title}`:"",i=(o=e.previewText||(e.previewUrl?`preview_url: ${e.previewUrl}`:"")).length>500?`${o.slice(0,500)}...`:o;var o;return i?`${e.page}.${t}\n${i}`:`${e.page}.${t}`})).join("\n\n"))(c))}))})(e,t))),i.command("export").description("Export a PPT artifact to PPTX").option("--file-uri <uri>","Specific PPT file_uri").option("--output-path <path>","Local path used to save the PPTX").option("--export-type <type>","Export type: ppt or editable",wg,"ppt").action(((e,t)=>(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await bg({options:e}),s=Sg(o),n=await i.exportPpt({fileUri:s,exportType:e.exportType}),r=await Nu({url:n.url,outputPath:e.outputPath});"text"!==t.format?t.response.print({status:"saved",path:r.path,filename:r.filename,size:r.size,file_uri:s,export_uri:n.uri,export_url:n.url,export_type:n.exportType}):t.response.print(r.path)}))})(e,t))),i.command("edit <message>").description("Send a page-scoped edit request through session chat").option("-s, --session-id <sessionId>","Target session ID; defaults to the most recently used local session").option("--page <page>","Target PPT page number, can be used multiple times",vg,[]).option("--wait","Wait until the edit turn becomes idle").option("--timeout <timeoutMs>","Timeout for --wait",xm).action(((t,i,o)=>(async(t,i,o)=>{if(!function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}([i,"access",e=>e.page,"optionalAccess",e=>e.length]))throw new e.CozeError(e.ErrorCode.E1000,"Missing --page: provide one or more target PPT page numbers");await gg(s.formatSessionPptEditQuery({pages:i.page,query:t}),{sessionId:i.sessionId,wait:i.wait,timeout:i.timeout},o)})(t,i,o))),i.command("share").description("Create a share URL for a PPT artifact").option("--file-uri <uri>","Specific PPT file_uri").option("--task-id <taskId>","PPT task ID used by the slide route").option("--no-short","Print the original share URL without short-link exchange").action(((e,t)=>(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await bg({options:e}),n=Sg(o),r=s.buildSessionPptSlideUrl({origin:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,fileUri:n,taskId:e.taskId}),a=!1===e.short?r:await i.shortenWebUrl({url:r});"text"!==t.format?t.response.print({file_name:o.fileName,file_uri:n,url:a,original_url:r,short:!1!==e.short}):t.response.print(a)}))})(e,t)))},Eg=e=>[e.mode_label||e.mode_value?`mode: ${e.mode_label||e.mode_value}${e.mode_label&&e.mode_value?` (${e.mode_value})`:""}`:null,`voice: ${e.label||e.value||"unknown"}`,e.value?`value: ${e.value}`:null,e.sample?`sample: ${e.sample}`:null,e.color_code?`color_code: ${e.color_code}`:null].filter(Boolean).join("\n"),kg=async(e,t)=>{await Lm(t,(async({ctx:t})=>{const i=await o_({baseUrl:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,xTTEnv:t.config.xTTEnv}),o=s_({config:i,mode:e.mode,keyword:e.keyword});"text"!==t.format?t.response.print({count:o.length,items:o}):t.response.print(o.length>0?o.map(Eg).join("\n\n"):"No podcast voices matched")}))},Ig=(e,t)=>[...t,e],Ag=async(t,i,o)=>{(t=>{if(t.mode&&!t.voice)throw new e.CozeError(e.ErrorCode.E1000,"--mode requires --voice")})(i),await gg(t,(e=>({file:e.file||[],podcastMode:e.mode,podcastVoice:e.voice,sessionId:e.sessionId,timeout:e.timeout,wait:e.wait}))(i),o)},jg=e=>{const t=e.command("podcast").description("Inspect podcast config");t.config({...jm,help:{brief:"Inspect podcast modes and voices",description:"Query the podcast voice configuration used by Coze Space so you can pick a valid voice name before sending a session message."}}),(e=>{e.command("message [message]").description("Send a podcast-oriented message to a claw session").option("-s, --session-id <sessionId>","Target session ID; defaults to the most recently used local session").option("--voice <voice>","Podcast voice label or value to inject into the message").option("--mode <mode>","Podcast mode label or value used to disambiguate --voice").option("--wait","Wait until the podcast turn becomes idle").option("--timeout <timeoutMs>","Timeout for --wait",xm).option("--file <path>","Local file to upload and attach (can be used multiple times)",Ig,[]).config({...jm,help:{brief:"Send a podcast message to a session",description:"Send a podcast-oriented message through the normal session message pipeline. Use --voice to inject a podcast voice instruction; --mode can disambiguate voices with the same label.",examples:[{desc:"Send a podcast message",cmd:'coze session podcast message "@播客 制作一个介绍潮汕美食的播客" -s 123456789 --voice "鸡汤女生" --wait',tags:["[RECOMMENDED]"]},{desc:"Send a podcast message without choosing a voice",cmd:'coze session podcast message "@播客 制作一个介绍潮汕美食的播客" -s 123456789 --wait'}],schema:{input:{message:{type:"string",required:!1,description:"Podcast message content"},session_id:{type:"string",required:!1,description:"Target session ID. Defaults to the most recently used local session"},voice:{type:"string",required:!1,description:"Podcast voice label or value"},mode:{type:"string",required:!1,description:"Podcast mode label or value used to disambiguate --voice"},wait:{type:"boolean",required:!1,description:"Wait for idle and stream assistant reply events"},file:{type:"array",required:!1,description:"Local file paths to upload and attach"}}}}}).action(Ag)})(t),(e=>{e.command("voice").description("Inspect podcast voices").command("list").description("List available podcast voices").option("--mode <mode>","Filter by podcast mode label or value").option("--keyword <keyword>","Filter voices by label or value keyword").config({...jm,help:{brief:"List available podcast voices",description:"Fetch podcast config from Coze Space and print flattened voice options. Text output includes the sample URL for quick inspection.",examples:[{desc:"List all podcast voices",cmd:"coze session podcast voice list",tags:["[RECOMMENDED]"]},{desc:"List solo voices only",cmd:"coze session podcast voice list --mode solo"},{desc:"Filter by keyword",cmd:"coze session podcast voice list --keyword 鸡汤"}],schema:{input:{mode:{type:"string",required:!1,description:"Podcast mode label or value"},keyword:{type:"string",required:!1,description:"Keyword used to filter label or value"}},output:{type:"object",properties:{count:{type:"number"},items:{type:"array"}}}}}}).action(kg)})(t)};function Rg(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const zg=e=>{e.command("current").description("Show the current locally selected default session").config({...jm,help:{brief:"Show the current default session",description:"Read the locally cached default session used by session commands when --session-id is omitted.",examples:[{desc:"Show the current default session",cmd:"coze session current"}],schema:{output:{type:"object",properties:{configured:{type:"boolean"},session_id:{type:"string"},claw_id:{type:"string"}}}}}}).action((async(e,t)=>{await(async e=>{const t=e.getContext(),i=s.createSessionConfigStore(),o=await i.get();if("text"===Rg([t,"optionalAccess",e=>e.format])){if(!o.sessionId)return void Rg([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e("No current session configured")]);const e=[`session_id: ${o.sessionId}`];return o.sessionClawId&&e.push(`claw_id: ${o.sessionClawId}`),void Rg([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e.join("\n"))])}Rg([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({configured:Boolean(o.sessionId),session_id:o.sessionId,claw_id:o.sessionClawId})])})(t)}))},Ug=e=>{e.command("use <sessionId>").description("Set the current locally selected default session").config({...jm,help:{brief:"Set the current default session",description:"Persist the provided session ID locally so session commands can reuse it by default.",examples:[{desc:"Use one session as the local default",cmd:"coze session use 7627441805839057179"}],schema:{input:{session_id:{type:"string",required:!0,description:"Session ID to persist as the local default"}},output:{type:"object",properties:{status:{type:"string"},session_id:{type:"string"}}}}}}).action((async(e,t,i)=>{await(async({cmd:e,sessionId:t})=>{const i=e.getContext();await zm({sessionId:t}),Rg([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"updated",session_id:t})])})({cmd:i,sessionId:e})}))},Lg=e=>{const t=e.command("session").description("Manage Coze session-based claw chat").config({...jm,help:{brief:"Manage claw chat sessions with token authentication",description:"Provides claw status lookup, session creation, session listing, and message sending for Coze Space claw chat using the current CLI token. Websocket watch flows also use the current CLI token through request headers.",examples:[{desc:"Check current claw status",cmd:"coze session status"},{desc:"Create a new session",cmd:"coze session create"}]}});(e=>{e.command("status").description("Get current claw status with token auth").option("-s, --session-id <sessionId>","Target session ID").config({...jm,help:{brief:"Validate token auth and resolve claw_id",description:"Use the current CLI token to fetch current claw information. If successful, the CLI refreshes the cached claw_id. With --session-id, the CLI reports session runtime status separately from claw-level background task activity.",examples:[{desc:"Validate token auth and show claw status",cmd:"coze session status"}],schema:{output:{type:"object",properties:{auth_configured:{type:"boolean"},auth_valid:{type:"boolean"},claw_id:{type:"string"},account_id:{type:"string"},updated_at:{type:"number"},display_status:{type:"string"},runtime_status:{type:"string"},claw_busy:{type:"boolean"},claw_progress_count:{type:"number"}}}}}}).action((async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{if(e.sessionId){const o=await i.getSessionDisplayStatus({sessionId:e.sessionId});return void t.response.print({session_id:o.sessionId,display_status:o.displayStatus,claw_busy:o.clawBusy,claw_progress_count:o.clawProgressCount,runtime_status:o.runtimeStatus,updated_at:o.updatedAt})}const o=await i.getStatus();t.response.print({auth_configured:o.authConfigured,auth_valid:o.authValid,claw_id:o.clawId,account_id:o.accountId,updated_at:o.updatedAt})}))}))})(t),(e=>{e.command("create").description("Create a new claw chat session").config({...jm,help:{brief:"Create a new claw session",description:"Create a normal claw chat session with the current claw_id resolved through token auth.",examples:[{desc:"Create a session",cmd:"coze session create"}],schema:{output:{type:"object",properties:{status:{type:"string"},claw_id:{type:"string"},session_id:{type:"string"}}}}}}).action((async(e,t)=>{await Lm(t,(async({ctx:e,service:t})=>{const i=await t.createSession();await zm({clawId:i.clawId,sessionId:i.sessionId}),e.response.print({status:"created",claw_id:i.clawId,session_id:i.sessionId})}))}))})(t),zg(t),Ug(t),(e=>{e.command("list").description("List claw chat sessions").option("--offset <offset>","Pagination offset returned by the previous list call").option("--limit <limit>","Maximum number of sessions to return",Om,20).config({...jm,help:{brief:"List sessions with offset pagination",description:"List claw chat sessions using the API native offset/limit pagination model.",examples:[{desc:"List the first 20 sessions",cmd:"coze session list"},{desc:"List the next page",cmd:"coze session list --offset next-token --limit 20"}],schema:{input:{offset:{type:"string",required:!1,description:"Pagination offset from a previous response"},limit:{type:"number",required:!1,description:"Maximum number of sessions to return"}},output:{type:"object",properties:{items:{type:"array",description:"Session items returned by the API"},next_offset:{type:"string",description:"Next pagination offset"},has_more:{type:"boolean",description:"Whether another page exists"}}}}}}).action((async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await i.listSessions({offset:e.offset,limit:e.limit});t.response.print({items:o.items,next_offset:o.nextOffset,has_more:o.hasMore})}))}))})(t),(e=>{e.command("file").description("Manage files returned by claw session replies").config({...jm,help:{brief:"Download files returned by session replies",description:"Work with file artifacts returned by session replies. Use the file_url from `coze session message --wait --format json` to save a file locally.",examples:[{desc:"Download a reply artifact to the current directory",cmd:'coze session file download "https://example.com/file"'},{desc:"Download a reply artifact to a specific path",cmd:'coze session file download "https://example.com/file" --output-path ./artifacts/result.md'}]}}).command("download <fileUrl>").description("Download a file from a session reply file_url").option("--output-path <path>","Local path used to save the file").config({...jm,help:{brief:"Download a session reply file",description:"Download a file using the file_url returned by `coze session message --wait`. If --output-path is omitted, the CLI derives a filename from the response headers or URL.",examples:[{desc:"Download using the inferred filename",cmd:'coze session file download "https://example.com/file"',tags:["[RECOMMENDED]"]},{desc:"Save to a custom path",cmd:'coze session file download "https://example.com/file" --output-path ./downloads/result.md'}],schema:{input:{file_url:{type:"string",required:!0,description:"Direct file URL returned by a session reply"},output_path:{type:"string",required:!1,description:"Local output path for the downloaded file"}},output:{type:"object",properties:{status:{type:"string"},path:{type:"string"},filename:{type:"string"},size:{type:"number"},url:{type:"string"}}}}}}).action((async(e,t,i)=>{await Lm(i,(async({ctx:i})=>{const o=await Nu({url:e,outputPath:t.outputPath});"text"!==i.format?i.response.print({status:"saved",path:o.path,filename:o.filename,size:o.size,url:o.url}):i.response.print(o.path)}))}))})(t),jg(t),(e=>{e.command("message [message]").description("Send a text message to a claw session").option("-s, --session-id <sessionId>","Target session ID; defaults to the most recently used local session").option("--file <path>","Local file to upload and attach (can be used multiple times)",((e,t)=>[...t,e]),[]).option("--wait","Wait until the current turn becomes idle and optionally return a background progress_id").option("--timeout <timeoutMs>","Timeout for waiting until the current turn becomes idle",xm).option("--podcast-voice <voice>","Inject a podcast voice instruction using the specified voice label or value").option("--podcast-mode <mode>","Podcast mode label or value used to disambiguate --podcast-voice").config(pg).action(gg)})(t),Tg(t),(e=>{e.command("replies <messageId>").description("List all replies that belong to one session message").option("-s, --session-id <sessionId>","Target session ID; defaults to the most recently used local session").config({...jm,help:{brief:"List replies for one message",description:"Fetch session messages via ListMessage and return only the replies whose reply_to_message_id matches the specified message ID.",examples:[{desc:"Get all replies for one message",cmd:"coze session replies 8f45d790-9062-4008-8784-999d86825fcc -s 7627441805839057179",tags:["[RECOMMENDED]"]}],schema:{input:{message_id:{type:"string",required:!0,description:"Original user message ID"},session_id:{type:"string",required:!1,description:"Target session ID. Defaults to the most recently used local session"}},output:{type:"object",properties:{session_id:{type:"string"},message_id:{type:"string"},request_message_found:{type:"boolean"},count:{type:"number"}}}}}}).action((async(e,t,i)=>{await og({messageId:e,sessionId:t.sessionId},i)}))})(t),Hm(t),dg(t),tg(t)};function Og(t){t.command("upgrade").description("Upgrade Coze CLI to the latest version").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Upgrade CLI to latest version",description:"Check for the latest version of Coze CLI and upgrade if a newer version is available. Detects the package manager used for the original installation (npm/pnpm/yarn) and runs the appropriate global install command.",examples:[{desc:"Upgrade to latest version",cmd:"coze upgrade",tags:["[RECOMMENDED]"]},{desc:"Force check and upgrade",cmd:"coze upgrade --force"},{desc:"Upgrade to a specific tag",cmd:"coze upgrade --tag beta"}],seeAlso:["coze --version"]}}).option("--force","Force upgrade even if already on the latest version").option("--tag <tag>","Specify the dist-tag to upgrade to","latest").action((async(t,s)=>{const n=s.getContext();n||process.exit(e.ExitCode.FAILURE),n.ui.info("Checking for updates...");try{const e=await Q(n,!0,t.tag);if(!e.hasUpdate&&!t.force)return void n.ui.success(`You are already on the latest version (${e.currentVersion}).`);e.hasUpdate&&n.ui.info(`New version available: ${i.gray(e.currentVersion)} → ${i.green(e.latestVersion)}`),n.ui.info("Upgrading Coze CLI...");const s=function(){const e=[{pm:"npm",cmd:"npm ls -g @coze/cli --json 2>/dev/null"},{pm:"pnpm",cmd:"pnpm ls -g @coze/cli --json 2>/dev/null"},{pm:"yarn",cmd:"yarn global list --json 2>/dev/null"}];for(const{pm:t,cmd:i}of e)try{if(o.execSync(i,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).includes("@coze/cli"))return t}catch(e){}return"npm"}(),r=function(e,t){switch(e){case"pnpm":return`pnpm add -g @coze/cli@${t}`;case"yarn":return`yarn global add @coze/cli@${t}`;default:return`npm install -g @coze/cli@${t}`}}(s,t.tag);n.ui.verbose(`Using package manager: ${s}`),n.ui.verbose(`Running: ${r}`),o.execSync(r,{stdio:"inherit"});const a=J();n.ui.success(`Successfully upgraded Coze CLI to ${e.latestVersion}. (was ${e.currentVersion})`),"json"===n.format&&n.response.print({previousVersion:e.currentVersion,currentVersion:a,latestVersion:e.latestVersion,status:"upgraded"})}catch(t){n.ui.error(`Failed to upgrade: ${t.message}`),n.ui.info("You can try upgrading manually with: npm install -g @coze/cli"),process.exit(e.ExitCode.FAILURE)}}))}const xg={skipOrgCheck:!0,skipSpaceCheck:!0},Bg=t=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,"The --project-id option is required. Example: coze agent info --project-id <id>");return t},qg=(t,i)=>{const o=Number.parseInt(t,10);if(!Number.isFinite(o)||o<=0||String(o)!==t)throw new e.CozeError(e.ErrorCode.E1000,`Invalid value for ${i}: expected a positive integer, got "${t}"`);return o},Dg=t=>{if(!t)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");return t.config.sessionApiBaseUrl||t.config.apiBaseUrl};const Mg=t=>{if(void 0!==t.code&&0!==t.code)throw new e.CozeError(e.ErrorCode.E5002,t.msg||"Agent API request failed",{code:t.code});return t},Ng=e=>({baseURL:e.baseUrl}),Gg={brief:"Manage Coze agent messages",description:"Commands for managing agent project messages.",examples:[{desc:"List agent messages",cmd:"coze agent message list --project-id <id>"}]},$g={brief:"List raw Coze agent messages as JSON",description:"Lists messages in a Coze agent (project) and outputs the raw API JSON envelope. Requires --project-id.",examples:[{desc:"List messages",cmd:"coze agent message list --project-id 123456"},{desc:"List with cursor",cmd:"coze agent message list --project-id 123456 --cursor <next_cursor> --size 5"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},cursor:{type:"string",required:!1,description:"Pagination cursor"},size:{type:"number",required:!1,description:"Max messages to return (positive integer, max 10)"},"asc-mode":{type:"boolean",required:!1,description:"Ascending order"},"need-reference":{type:"boolean",required:!1,description:"Include referenced messages"},"conversation-id":{type:"string",required:!1,description:"Filter by conversation ID"}},output:{type:"object",description:"Raw API envelope with code, msg, data fields"}}},Fg=e=>{e.command("message").description("Manage Coze agent messages").config({...xg,help:Gg}).command("list").description("List raw Coze agent messages as JSON").requiredOption("--project-id <projectId>","The agent project ID").option("--cursor <cursor>","Pagination cursor from a previous response").option("--size <size>","Number of messages to return (max 10)").option("--asc-mode","Load messages in ascending order").option("--need-reference","Include referenced messages").option("--conversation-id <conversationId>","Filter by conversation ID").config({...xg,help:$g}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=e.size?qg(e.size,"--size"):void 0,r=t.getContext(),a=Dg(r),c=await(async(e,t)=>{const i={session_id:t.projectId};return void 0!==t.cursor&&(i.cursor=t.cursor),void 0!==t.size&&(i.size=t.size),void 0!==t.ascMode&&(i.asc_mode=t.ascMode),void 0!==t.needReference&&(i.need_reference=t.needReference),void 0!==t.conversationId&&(i.conversation_id=t.conversationId),Mg(await s.Claw.ListMessage(i,Ng(e)))})({baseUrl:a},{projectId:o,cursor:e.cursor,size:n,ascMode:e.ascMode,needReference:e.needReference,conversationId:e.conversationId});i.print(c)}catch(e){V(e,t.getContext())}}))},Vg=e=>{e.command("member").description("Manage Coze agent members").config({...xg,help:{brief:"Manage Coze agent members",description:"Commands for managing agent project members.",examples:[{desc:"List agent members",cmd:"coze agent member list --project-id <id>"}]}}).command("list").description("List raw Coze agent members as JSON").requiredOption("--project-id <projectId>","The agent project ID").config({...xg,help:{brief:"List raw Coze agent members as JSON",description:"Lists members of a Coze agent (project) and outputs the raw API JSON envelope. Requires --project-id.",examples:[{desc:"List agent members",cmd:"coze agent member list --project-id 123456"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"}},output:{type:"object",description:"Raw API envelope with code, msg, data fields"}}}}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=t.getContext(),r=Dg(n),a=await(async(e,t)=>Mg(await s.Claw.GetProjectMembers({project_id:t.projectId},Ng(e))))({baseUrl:r},{projectId:o});i.print(a)}catch(e){V(e,t.getContext())}}))},Wg=e=>{e.command("info").description("Get raw Coze agent info as JSON").requiredOption("--project-id <projectId>","The agent project ID").config({...xg,help:{brief:"Get raw Coze agent info as JSON",description:"Retrieves detailed info for a single Coze agent (project) and outputs the raw API JSON envelope. Requires --project-id.",examples:[{desc:"Get agent info",cmd:"coze agent info --project-id 123456"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"}},output:{type:"object",description:"Raw API envelope with code, msg, data fields"}}}}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=t.getContext(),r=Dg(n),a=await(async(e,t)=>Mg(await s.Claw.GetProjectInfo({project_id:t.projectId},Ng(e))))({baseUrl:r},{projectId:o});i.print(a)}catch(e){V(e,t.getContext())}}))};const Hg=t=>{if(t instanceof e.CozeError)return i=t.desc,o=()=>t.message,null!=i?i:o();var i,o;if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return String(t)}},Jg=(e,t)=>{t.print({ok:!1,err_reason:Hg(e)}),process.exitCode=1};function Kg(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const Qg={brief:"Upload a local file to a Coze agent project as JSON",description:"Uploads a local file through the Claw file upload endpoint and outputs { ok, project_file_path }. Requires --project-id and --local-file-path.",examples:[{desc:"Upload a local file",cmd:"coze agent file upload --project-id 123456 --local-file-path ./report.md --project-dir /reports"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"local-file-path":{type:"string",required:!0,description:"Local file path to upload"},"project-dir":{type:"string",required:!1,description:"Target directory path in the remote project cloud disk; sent as project_dir"},"claw-id":{type:"string",required:!1,description:"Claw ID; defaults to empty string"}},output:{type:"object",description:"Result with ok and project_file_path fields"}}},Yg=(e,t)=>{const i=Kg([e,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!i||"/"===i)return`/${t}`;return`${(i.startsWith("/")?i:`/${i}`).replace(/\/+$/,"")}/${t}`},Zg=t=>{t.command("upload").description("Upload a local file to a Coze agent project as JSON").option("--project-id <projectId>","The agent project ID").option("--local-file-path <localFilePath>","Local file path to upload").option("--project-dir <projectDir>","Target directory path in the remote project cloud disk").option("--claw-id <clawId>","Claw ID (defaults to empty string)","").config({...xg,help:Qg}).action((async(t,i)=>{const o=new Lo({format:"json"});try{const a=Bg(t.projectId),d=((t,i)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${i}`);return t})(t.localFilePath,"--local-file-path");await(async t=>{try{await u.access(t)}catch(i){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${t}${i instanceof Error?` (${i.message})`:""}`)}})(d);const p=i.getContext(),_=Dg(p),h=c.basename(d),{projectDir:m}=t;await(async(e,t)=>{return Mg(await s.createSessionUploadFile({baseUrl:e.baseUrl,webOrigin:e.baseUrl,xTTEnv:e.xTTEnv})({projectId:t.projectId,fileName:t.fileName,fileContent:t.fileContent,projectDir:t.projectDir,clawId:(i=t.clawId,o=()=>"",null!=i?i:o())}));var i,o})({baseUrl:_,xTTEnv:Kg([p,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv])},{projectId:a,fileName:h,fileContent:await l.openAsBlob(d),projectDir:m,clawId:(n=t.clawId,r=()=>"",null!=n?n:r())}),o.print({ok:!0,project_file_path:Yg(m,h)})}catch(e){Jg(e,o)}var n,r}))};function Xg(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const ef={brief:"Download a Coze agent file as JSON",description:"Builds the project file URI from project-id and project-file-path, resolves it through get_url, downloads the resolved file_url through /api/coze_claw/file/download, and saves it under local-dir.",examples:[{desc:"Download to a local directory",cmd:"coze agent file download --project-id 123456 --project-file-path /reports/report.md --local-dir ./downloads"},{desc:"Download an uploaded project file",cmd:"coze agent file download --project-id 123456 --project-file-path /用户上传/report.md --local-dir ./downloads"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"project-file-path":{type:"string",required:!0,description:"Specific file path in the remote project cloud disk"},"local-dir":{type:"string",required:!0,description:"Local directory where the file will be saved"}},output:{type:"object",description:"Result with ok and local_file_path fields"}}},tf=(t,i)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${i}`);return t},of=t=>{t.command("download").description("Download a Coze agent file as JSON").option("--project-id <projectId>","The agent project ID").option("--project-file-path <projectFilePath>","Specific file path in the remote project cloud disk").option("--local-dir <localDir>","Local directory where the file will be saved").config({...xg,help:ef}).action((async(t,i)=>{const o=new Lo({format:"json"});try{const n=Bg(t.projectId),r=tf(t.projectFilePath,"--project-file-path"),a=tf(t.localDir,"--local-dir"),d=i.getContext(),l=await(async e=>{const t=e.getContext(),{data:i}=await po.GetUserProfile({},{baseURL:Xg([t,"optionalAccess",e=>e.config,"access",e=>e.openApiBaseUrl])});return tf(Xg([i,"optionalAccess",e=>e.user_id]),"current user id")})(i),p=await(async(t,i)=>{const o=s.createSessionApiClient({baseUrl:t.baseUrl,webOrigin:t.baseUrl,xTTEnv:t.xTTEnv}),n=i.accountId||"0",r=`${i.userId}_${n}/project_${i.projectId}-files${i.projectFilePath}`,a=await o.getUrl({uris:[r]},{headers:s.getCozeAccountHeaders(t.organizationId)}),d=function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}([a,"access",e=>e.data,"optionalAccess",e=>e.urls,"optionalAccess",e=>e[0]]);if(!d)throw new e.CozeError(e.ErrorCode.E5002,a.msg||"Failed to resolve agent file URL");const l=new URL("/api/coze_claw/file/download",s.normalizeBaseUrl(t.baseUrl));l.searchParams.set("file_url",d);const p=c.basename(i.projectFilePath)||"agent-file.bin";return{...await Nu({url:l.toString(),outputPath:c.join(i.localDir,p)}),fileUrl:d,projectFilePath:i.projectFilePath,resolvedUri:r}})({baseUrl:Dg(d),organizationId:Xg([d,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),xTTEnv:Xg([d,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv])},{projectId:n,projectFilePath:r,localDir:a,userId:l,accountId:Xg([d,"optionalAccess",e=>e.config,"access",e=>e.organizationId])||"0"});o.print({ok:!0,local_file_path:p.path})}catch(e){Jg(e,o)}}))};function sf(e,t){return null!=e?e:t()}function nf(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const rf={brief:"Manage Coze agent project files",description:"Commands for managing agent project files.",examples:[{desc:"List project files",cmd:"coze agent file list --project-id <id>"},{desc:"Read a project file",cmd:"coze agent file read --project-id <id> --project-file-path /app/workspace/main.py"},{desc:"Upload file content",cmd:"coze agent file upload --project-id <id> --local-file-path ./report.md --project-dir /reports"},{desc:"Download a file",cmd:"coze agent file download --project-id <id> --project-file-path /reports/report.md --local-dir ./downloads"}]},af={brief:"List Coze agent project files as JSON",description:"Lists files in a Coze agent project and outputs { ok, files }. Requires --project-id.",examples:[{desc:"List project files",cmd:"coze agent file list --project-id 123456"},{desc:"List files in a specific directory",cmd:"coze agent file list --project-id 123456 --project-dir /app/workspace"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"project-dir":{type:"string",required:!1,description:"Directory path in the remote project cloud disk (defaults to root)"},depth:{type:"number",required:!1,description:"Directory depth (defaults to 1)"}},output:{type:"object",description:"Result with ok and files fields"}}},cf={brief:"Write content to a Coze agent project file as JSON",description:"Writes content to a file in a Coze agent project and outputs the raw API JSON envelope. Requires --project-id, --project-file-path, and --content.",examples:[{desc:"Write a file",cmd:'coze agent file write --project-id 123456 --project-file-path /app/workspace/hello.txt --content "hello world"'}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"project-file-path":{type:"string",required:!0,description:"Specific file path in the remote project cloud disk (e.g. /app/workspace/hello.txt)"},content:{type:"string",required:!0,description:"File content to write (utf-8)"}},output:{type:"object",description:"Raw API envelope with code, msg, data fields"}}},df={brief:"Read a Coze agent project file as JSON",description:"Reads content from a file in a Coze agent project and outputs { ok, project_file_path, content }. Requires --project-id and --project-file-path.",examples:[{desc:"Read a file",cmd:"coze agent file read --project-id 123456 --project-file-path /app/workspace/main.py"},{desc:"Read with offset and limit",cmd:"coze agent file read --project-id 123456 --project-file-path /app/workspace/main.py --offset 10 --limit 50"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"project-file-path":{type:"string",required:!0,description:"Specific file path in the remote project cloud disk (e.g. /app/workspace/main.py)"},offset:{type:"number",required:!1,description:"Start line (from 1)"},limit:{type:"number",required:!1,description:"Number of lines to read"}},output:{type:"object",description:"Result with ok, project_file_path, and content fields"}}},lf={brief:"Edit a Coze agent project file as JSON",description:"Edits a file in a Coze agent project using the specified mode and outputs the raw API JSON envelope. Requires --project-id, --project-file-path, and --mode.",examples:[{desc:"Replace one occurrence",cmd:'coze agent file edit --project-id 123456 --project-file-path /app/workspace/main.py --mode replace_one --old-string "foo" --new-string "bar"'},{desc:"Append content",cmd:'coze agent file edit --project-id 123456 --project-file-path /app/workspace/main.py --mode append --append-content "# end"'}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"project-file-path":{type:"string",required:!0,description:"Specific file path in the remote project cloud disk (e.g. /app/workspace/main.py)"},mode:{type:"string",required:!0,description:"Edit mode: replace_one, replace_all, append, append_newline"},"old-string":{type:"string",required:!1,description:"String to find (for replace modes)"},"new-string":{type:"string",required:!1,description:"Replacement string (for replace modes)"},"append-content":{type:"string",required:!1,description:"Content to append (for append modes)"}},output:{type:"object",description:"Raw API envelope with code, msg, data fields"}}},pf=(t,i)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${i}`);return t},uf=e=>e.startsWith("/")?e:`/${e}`,_f=e=>{e.command("list").description("List Coze agent project files as JSON").option("--project-id <projectId>","The agent project ID").option("--project-dir <projectDir>","Directory path in the remote project cloud disk").option("--depth <depth>","Directory depth (defaults to 1)").config({...xg,help:af}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=e.depth?qg(e.depth,"--depth"):void 0,r=t.getContext(),a=Dg(r),c=await(async(e,t)=>Mg(await s.Claw.ListProjectFiles({project_id:t.projectId,file_path:t.filePath,depth:t.depth},Ng(e))))({baseUrl:a},{projectId:o,filePath:e.projectDir,depth:n});i.print((e=>({ok:!0,files:sf(nf([e,"access",e=>e.data,"optionalAccess",e=>e.files]),(()=>[])).map((e=>({path:uf(e.file_path||e.name||""),type:e.is_dir?"dir":"file"})))}))(c))}catch(e){Jg(e,i)}}))},hf=e=>{e.command("write").description("Write content to a Coze agent project file as JSON").requiredOption("--project-id <projectId>","The agent project ID").requiredOption("--project-file-path <projectFilePath>","Specific file path in the remote project cloud disk").requiredOption("--content <content>","File content to write (utf-8)").config({...xg,help:cf}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=pf(e.projectFilePath,"--project-file-path"),r=pf(e.content,"--content"),a=t.getContext(),c=Dg(a),d=await(async(e,t)=>Mg(await s.Claw.WriteProjectFile({project_id:t.projectId,file_path:t.filePath,content:t.content},Ng(e))))({baseUrl:c},{projectId:o,filePath:n,content:r});i.print(d)}catch(e){V(e,t.getContext())}}))},mf=e=>{e.command("read").description("Read a Coze agent project file as JSON").option("--project-id <projectId>","The agent project ID").option("--project-file-path <projectFilePath>","Specific file path in the remote project cloud disk").option("--offset <offset>","Start line (from 1)").option("--limit <limit>","Number of lines to read").config({...xg,help:df}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=pf(e.projectFilePath,"--project-file-path"),r=e.offset?qg(e.offset,"--offset"):void 0,a=e.limit?qg(e.limit,"--limit"):void 0,c=t.getContext(),d=Dg(c),l=await(async(e,t)=>{const i={project_id:t.projectId,file_path:t.filePath};return void 0!==t.offset&&(i.offset=t.offset),void 0!==t.limit&&(i.limit=t.limit),Mg(await s.Claw.ReadProjectFile(i,Ng(e)))})({baseUrl:d},{projectId:o,filePath:n,offset:r,limit:a});i.print({ok:!0,project_file_path:n,content:sf(nf([l,"access",e=>e.data,"optionalAccess",e=>e.content]),(()=>""))})}catch(e){Jg(e,i)}}))},gf=e=>{e.command("edit").description("Edit a Coze agent project file as JSON").requiredOption("--project-id <projectId>","The agent project ID").requiredOption("--project-file-path <projectFilePath>","Specific file path in the remote project cloud disk").requiredOption("--mode <mode>","Edit mode: replace_one, replace_all, append, append_newline").option("--old-string <oldString>","String to find (for replace modes)").option("--new-string <newString>","Replacement string (for replace modes)").option("--append-content <appendContent>","Content to append (for append modes)").config({...xg,help:lf}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=pf(e.projectFilePath,"--project-file-path"),r=pf(e.mode,"--mode"),a=t.getContext(),c=Dg(a),d=await(async(e,t)=>{const i={project_id:t.projectId,file_path:t.filePath,mode:t.mode};return void 0!==t.oldString&&(i.old_string=t.oldString),void 0!==t.newString&&(i.new_string=t.newString),void 0!==t.appendContent&&(i.append_content=t.appendContent),Mg(await s.Claw.EditProjectFile(i,Ng(e)))})({baseUrl:c},{projectId:o,filePath:n,mode:r,oldString:e.oldString,newString:e.newString,appendContent:e.appendContent});i.print(d)}catch(e){V(e,t.getContext())}}))},ff=e=>{const t=e.command("agent").description("Agent-facing Coze APIs backed by Claw project endpoints").config({...xg,help:{brief:"Agent-facing Coze APIs backed by Claw project endpoints",description:"Provides raw JSON access to Coze agent (project) APIs including info, members, and messages. All commands output raw API envelopes as JSON.",examples:[{desc:"Get agent info",cmd:"coze agent info --project-id <id>"},{desc:"List agent members",cmd:"coze agent member list --project-id <id>"},{desc:"List agent messages",cmd:"coze agent message list --project-id <id>"},{desc:"List project files",cmd:"coze agent file list --project-id <id>"},{desc:"Read a project file",cmd:"coze agent file read --project-id <id> --project-file-path /app/workspace/main.py"},{desc:"Upload file content",cmd:"coze agent file upload --project-id <id> --local-file-path ./report.md --project-dir /reports"},{desc:"Download a file",cmd:"coze agent file download --project-id <id> --project-file-path /reports/report.md --local-dir ./downloads"}]}});Wg(t),Vg(t),Fg(t),(e=>{const t=e.command("file").description("Manage Coze agent project files").config({...xg,help:rf});_f(t),hf(t),mf(t),gf(t),Zg(t),of(t)})(t)};function yf(t){!function(t){const i=t.command("auth").description("Manage user authentication and credentials").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Manage authentication and credentials",description:"Manage the full authentication lifecycle for Coze CLI. Supports interactive OAuth login via browser. All other commands require valid authentication.",examples:[{desc:"Interactive login via browser",cmd:"coze auth login --oauth",tags:["[RECOMMENDED]"]},{desc:"Check current login status",cmd:"coze auth status"},{desc:"Logout and clear credentials",cmd:"coze auth logout"}],seeAlso:["coze organization","coze space"]}});i.command("login").description("Login to obtain and persist access credentials").config({skipAuth:!0,help:{brief:"Login to Coze services",description:"Login to Coze services via OAuth authorization. Opens browser to complete authorization.",examples:[{desc:"Interactive login using OAuth",cmd:"coze auth login --oauth",tags:["[RECOMMENDED]"]}],errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Authentication failed",fix:"Please try again with `coze auth login --oauth`."}]}}).option("--token <PAT>","Login using an access token").option("--oauth","Start browser-based OAuth device authorization flow").action((async function(t,i){const o=i.getContext();if(!o)return void V(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"));await o.auth.login(t);const s=["Please use the following commands to manage organizations and spaces:"," coze organization list"," coze organization use <organization_id>"," coze space list"," coze space use <space_id>"];!function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}}([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])})),i.command("logout").description("Logout and clear stored credentials").config({skipOrgCheck:!0,skipAuth:!0,skipSpaceCheck:!0,help:{brief:"Logout",description:"Clear locally stored access credentials and log out of the current account.",examples:[{desc:"Execute logout",cmd:"coze auth logout"}]}}).action((async(t,i)=>{const o=i.getContext();o?await o.auth.logout():V(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))})),i.command("status").description("Check current login status and credential validity").config({skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Check login status",description:"Verify if the current locally cached credentials are valid and display current login account information. If the token was obtained via OAuth and is about to expire, it will be refreshed automatically.",examples:[{desc:"Check current authentication status",cmd:"coze auth status",tags:["[RECOMMENDED]"]},{desc:"Check status in JSON format",cmd:"coze auth status --format json"}],schema:{output:{type:"object",properties:{logged_in:{type:"boolean",description:"Whether the user is currently logged in"},user:{type:"object",description:"Current user profile information"},token_expires_at:{type:"string",description:"Token expiration time in ISO 8601 format"}}}},errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"No valid credentials found or token has expired",fix:"Run `coze auth login --oauth` to authenticate."}],seeAlso:["coze auth login","coze auth logout"]}}).action((async(t,i)=>{const o=i.getContext();o?await o.auth.status():V(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))}))}(t),Lg(t),rc(t),Bu(t),$a(t),gr(t),vr(t),Na(t),Ja(t),Og(t),ff(t),ac()}function vf(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}function wf(e,t){return null!=e?e:t()}function bf(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}function Sf(e){const t=[];let i=e;for(;i;)i.name()&&t.unshift(i.name()),i=i.parent;return t.join(" ")}function Pf(e){return e._args.map((e=>e.required?`<${e.name()}>`:`[${e.name()}]`)).join(" ")}const Cf=new Set(["--version","--format","--no-color","--config","--org-id","--space-id","--verbose","--debug","--log-file","--man","--schema","--commands"]);function Tf(e){const t=new Map,i=[];let o=e;for(;o;)i.unshift(o),o=o.parent;for(const e of i)for(const i of e.options){const e=i.flags.split(", ").find((e=>e.startsWith("--")));!e||t.has(e)||Cf.has(e)||t.set(e,i)}return Array.from(t.values())}function Ef(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}class kf extends b.Command{__init(){this.middlewares=[]}constructor(e){super(e),kf.prototype.__init.call(this),this.helpInformation=()=>{const e=process.argv.slice(2);if(e.includes("--schema"))return`${JSON.stringify(Ef([this,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help,"optionalAccess",e=>e.schema])||{},null,2)}\n`;if(e.includes("--commands")){const e=this.commands.filter((e=>!e._hidden)).map((e=>({name:e.name(),description:e.description()})));return`${JSON.stringify(e,null,2)}\n`}if(e.includes("--man")||e.includes("-m"))return`${function(e){const t=bf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=Sf(e);let o=`@MAN ${i}\n\n`;o+=`NAME\n ${i} — ${bf([t,"optionalAccess",e=>e.brief])||e.description()}\n\n`,o+=`SYNOPSIS\n ${i} ${Pf(e)}\n`,Tf(e).forEach((e=>{o+=` [${e.flags}]\n`})),o+="\n",bf([t,"optionalAccess",e=>e.description])&&(o+=`DESCRIPTION\n ${t.description.replace(/\n/g,"\n ")}\n\n`);const s=Tf(e);return s.length>0&&(o+="OPTIONS\n",s.forEach((e=>{const t=e.flags.split(", "),i=t.find((e=>e.startsWith("-")&&!e.startsWith("--")))||"",s=t.find((e=>e.startsWith("--")))||"";o+=` ${i?`${s}, ${i}`:s}\n`,o+=` Type: ${e.isBoolean()?"flag":"string"}\n`,o+=` Required: ${e.mandatory?"yes":"no"}\n`,o+=` Default: ${void 0!==e.defaultValue?String(e.defaultValue):"-"}\n`,o+=` Desc: ${e.description}\n\n`}))),bf([t,"optionalAccess",e=>e.schema])&&(o+="SCHEMA\n",t.schema.input&&(o+=` Input:\n ${JSON.stringify(t.schema.input,null,2).replace(/\n/g,"\n ")}\n`),t.schema.output&&(o+=` Output:\n ${JSON.stringify(t.schema.output,null,2).replace(/\n/g,"\n ")}\n`),o+="\n"),bf([t,"optionalAccess",e=>e.errors])&&t.errors.length>0&&(o+="ERRORS\n",o+=" CODE NAME TRIGGER RECOVERY\n",t.errors.forEach((e=>{o+=` ${e.code.padEnd(6)} ${e.name.padEnd(17)} ${e.desc.padEnd(37)} ${e.fix}\n`})),o+="\n"),bf([t,"optionalAccess",e=>e.caveats])&&t.caveats.length>0&&(o+="CAVEATS\n",t.caveats.forEach((e=>{o+=` - ${e}\n`})),o+="\n"),bf([t,"optionalAccess",e=>e.seeAlso])&&t.seeAlso.length>0&&(o+="SEE ALSO\n",t.seeAlso.forEach((e=>{o+=` ${e}\n`})),o+="\n"),o.trimEnd()}(this)}\n`;return e.includes("-h")||e.includes("--help")?`${function(e){const t=bf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=Sf(e);let o=`@HELP ${i}\n\n`;return bf([t,"optionalAccess",e=>e.brief])?o+=`BRIEF: ${t.brief}\n\n`:o+=`BRIEF: ${e.description()||"No description provided."}\n\n`,e.parent&&"coze"!==e.parent.name()&&(o+=`PARENT: ${Sf(e.parent)}\n\n`),o+=`SYNTAX:\n ${i} ${Pf(e)} [options]\n\n`,bf([t,"optionalAccess",e=>e.description])&&(o+=`DESCRIPTION:\n ${t.description.replace(/\n/g,"\n ")}\n\n`),o+="OPTIONS:\n",o+=" Name Type Required Default Description\n",o+=" ─────────────────────────────────────────────────────────\n",e._args.forEach((e=>{const t=`<${e.name()}>`,i=e.required?"Yes":"No",s=void 0!==e.defaultValue?String(e.defaultValue):"-",n=e.description||"";o+=` ${t.padEnd(16)} ${"string".padEnd(10)} ${i.padEnd(4)} ${s.padEnd(10)} ${n}\n`})),Tf(e).forEach((e=>{const t=e.flags.split(", "),i=t.find((e=>e.startsWith("-")&&!e.startsWith("--")))||"",s=t.find((e=>e.startsWith("--")))||"",n=i?`${s}, ${i}`:s;let r="string";e.isBoolean()&&(r="flag");const a=e.mandatory?"Yes":"No",c=void 0!==e.defaultValue?String(e.defaultValue):"-",d=e.description||"";o+=` ${n.padEnd(16)} ${r.padEnd(10)} ${a.padEnd(4)} ${c.padEnd(10)} ${d}\n`})),o+="\n",bf([t,"optionalAccess",e=>e.enums])&&(o+="ENUMS:\n",Object.keys(t.enums).forEach((e=>{o+=` --${e}:\n`;const i=wf(bf([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})));Object.keys(i).forEach((e=>{o+=` ${e.padEnd(12)} ${i[e]}\n`}))})),o+="\n"),bf([t,"optionalAccess",e=>e.examples])&&t.examples.length>0&&(o+="COMMON EXAMPLES:\n",t.examples.forEach((e=>{const t=e.tags?` ${e.tags.join(" ")}`:"";o+=` #${t} ${e.desc}\n ${e.cmd}\n\n`}))),bf([t,"optionalAccess",e=>e.errors])&&t.errors.length>0&&(o+="COMMON ERRORS:\n",o+=" CODE NAME DESCRIPTION FIX\n",t.errors.slice(0,5).forEach((e=>{o+=` ${e.code.padEnd(6)} ${e.name.padEnd(17)} ${e.desc.padEnd(30)} ${e.fix}\n`})),o+="\n"),bf([t,"optionalAccess",e=>e.seeAlso])&&t.seeAlso.length>0&&(o+="SEE ALSO:\n",t.seeAlso.forEach((e=>{o+=` ${e}\n`})),o+="\n"),o.trimEnd()}(this)}\n`:`${function(e){const t=bf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=Sf(e);let o=`@USAGE ${i}\n\n`;bf([t,"optionalAccess",e=>e.brief])?o+=`BRIEF: ${t.brief}\n\n`:o+=`BRIEF: ${e.description()||"No description provided."}\n\n`,o+=`SYNTAX:\n ${i} ${Pf(e)} [options]\n\n`,e.commands.length>0&&(o+="ACTIONS:\n",e.commands.forEach((e=>{const t=e;if(!t._hidden){const e=bf([t,"access",e=>e.getConfig,"optionalCall",e=>e(),"optionalAccess",e=>e.help,"optionalAccess",e=>e.brief])||t.description()||"";o+=` ${t.name().padEnd(10)} ${e}\n`}})),o+="\n"),bf([t,"optionalAccess",e=>e.examples])&&t.examples.length>0&&(o+="EXAMPLES:\n",t.examples.slice(0,5).forEach((e=>{o+=` # ${e.desc}\n ${e.cmd}\n\n`})));if(bf([t,"optionalAccess",e=>e.enums])){const e=Object.keys(t.enums).filter((e=>Object.keys(wf(bf([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})))).length<=7));e.length>0&&(o+="ENUMS:\n",e.forEach((e=>{const i=Object.keys(wf(bf([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})))).join(" | ");o+=` --${e}: ${i}\n`})),o+="\n")}return o.trimEnd()}(this)}\n`},this.hook("preAction",(e=>{}))}config(e){return this.commandConfig={...this.commandConfig,...e},this}setConfig(e){return this.commandConfig=e,this}getConfig(){return this.commandConfig}setContext(e){return this.context=e,this}getContext(){return this.context}use(e){return this.middlewares.push(e),this}createCommand(e){const t=new kf(e);return this.context&&t.setContext(this.context),t}action(e){return super.action((async(...t)=>{const i=this.getContext();let o={},s=[],n=this;if(t.length>0){const e=t[t.length-1];e instanceof kf&&(n=e),t.length>=2&&(r=t[t.length-2],a=()=>({}),o=null!=r?r:a(),s=t.slice(0,t.length-2))}var r,a;if(i&&(o&&(i.options=o),s&&(i.args=s),n)){i.commandName=n.name();const e=Ef([n,"access",e=>e.getConfig,"optionalCall",e=>e()]);e&&(i.commandConfig=e),n.setContext(i)}if(this.middlewares.length>0&&i){const o=ci(this.middlewares);await o(i,(async()=>{await e.apply(this,t)}))}else await e.apply(this,t)}))}}function If(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}function Af(e){e.exitOverride(),e.outputError=()=>{},e.commands.forEach((e=>Af(e)))}async function jf(t){const i=new kf;i.name("coze").description("Coze Coding CLI").version(W,"-v, --version").option("--format <fmt>","Specify output format (json, text). Default: text").option("--no-color","Disable ANSI color output").option("--config <path>","Specify config file path").option("--org-id <id>","Override Organization ID").option("--space-id <id>","Override Space ID").option("--verbose","Enable verbose mode, output more business process information").option("--debug","Enable debug mode, output all log information for diagnosing CLI execution issues").option("--log-file <path>","Output logs to a file").option("--man","Show full manual information").option("--schema","Output the command's JSON Schema").option("--commands","Output the list of subcommands"),i.config({help:{errors:[{code:e.ErrorCode.E1100,name:"UNKNOWN_OPTION",desc:"Unknown option provided",fix:"Check parameter spelling or use -h for help",example:"coze <command> -h"},{code:e.ErrorCode.E1101,name:"UNKNOWN_COMMAND",desc:"Unknown subcommand provided",fix:"Check subcommand spelling or use -h for help",example:"coze -h"},{code:e.ErrorCode.E1102,name:"MISSING_ARGUMENT",desc:"Missing required argument",fix:"Provide missing required parameters",example:"coze <command> -h"},{code:e.ErrorCode.E1103,name:"MISSING_OPTION",desc:"Missing required option value",fix:"Provide missing required options",example:"coze <command> -h"}]}}),yf(i),await async function(e){e.completionInstalled||process.stdout.isTTY}(t.config),function(e,t,i){const o=new Set;e.setContext(i),function e(s){o.has(s)||(o.add(s),s.setContext(i),t.forEach((e=>s.use(e))),s.commands.forEach((t=>{const i=vf([s,"access",e=>e.getConfig,"optionalCall",e=>e()]),o=vf([t,"access",e=>e.getConfig,"optionalCall",e=>e()]);t.setConfig({...i,...o}),e(t)})))}(e)}(i,[xo,pr],t),process.on("uncaughtException",(e=>{V(e,t)})),process.on("unhandledRejection",(e=>{V(e,t)})),(t.argv.includes("--schema")||t.argv.includes("--commands")||t.argv.includes("--man")||t.argv.includes("-m"))&&(t.argv.includes("--help")||t.argv.includes("-h")||t.argv.push("--help")),Af(i);try{await i.parseAsync(t.argv,{from:"user"})}catch(n){const r=n,a=function(e,t,i){let o=e;if(t.command)o=t.command;else if(i.commandName){const t=(e,i)=>{if(e.name()===i)return e;for(const o of e.commands){const e=t(o,i);if(e)return e}return null},s=t(e,i.commandName);s&&(o=s)}let s=e;for(const e of i.argv){if(e.startsWith("-"))break;const t=s.commands.find((t=>t.name()===e));t&&(s=t,o=s)}return o}(i,r,t);"commander.helpDisplayed"!==r.code&&"commander.help"!==r.code&&"commander.version"!==r.code||process.exit(e.ExitCode.SUCCESS);const c=If([a,"access",e=>e.getConfig,"optionalCall",e=>e()]),d=If([i,"access",e=>e.getConfig,"optionalCall",e=>e()]);if(t.commandConfig=(s=()=>d,null!=(o=c)?o:s()),"commander.unknownOption"===r.code){const i=G(new e.CozeError(e.ErrorCode.E1100,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),process.exit(e.exitCodeForError(i.code))}if("commander.unknownCommand"===r.code){const i=G(new e.CozeError(e.ErrorCode.E1101,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),process.exit(e.exitCodeForError(i.code))}if("commander.missingArgument"===r.code){const i=G(new e.CozeError(e.ErrorCode.E1102,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),"json"!==t.format&&process.stderr.write(`\n${a.helpInformation()}`),process.exit(e.exitCodeForError(i.code))}if("commander.missingMandatoryOptionValue"===r.code||"commander.optionMissingArgument"===r.code){const i=G(new e.CozeError(e.ErrorCode.E1103,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),"json"!==t.format&&process.stderr.write(`\n${a.helpInformation()}`),process.exit(e.exitCodeForError(i.code))}V(r,t)}var o,s}(async function(){const e=process.argv.slice(2),{globalOptions:t}=function(e){const t={};let i;const o=[];let s=!1;for(let n=0;n<e.length;n++){const r=e[n];if("--help"!==r&&"-h"!==r)if("--version"!==r&&"-v"!==r)if("--output"!==r)if("--format"!==r)"--no-color"!==r?"--config"!==r?"--org-id"!==r?"--space-id"!==r?"--verbose"!==r?"--debug"!==r?"--log-file"!==r?"--print-logs"!==r?s||r.startsWith("-")?o.push(r):(i=r,s=!0):t.printLogs=!0:t.logFile=e[++n]:t.debug=!0:t.verbose=!0:t.spaceId=e[++n]:t.orgId=e[++n]:t.config=e[++n]:t.noColor=!0;else{const i=e[++n];"json"!==i&&"text"!==i||(t.format=i)}else t.output=e[++n];else t.version=!0;else t.help=!0}return{globalOptions:t,commandName:i,commandArgs:o}}(e),i=function(e){const t=Oo(e.cwd,(()=>process.cwd())),i=Oo(e.env,(()=>process.env)),o=e.globalOptions||{};o.noColor&&(process.env.NO_COLOR="1");let s="text";o.format&&(s=o.format);const n={...e.config};o.orgId&&(n.organizationId=o.orgId),o.spaceId&&(n.spaceId=o.spaceId);const r=new St({format:"text",logFile:o.logFile,printToStderr:o.printLogs});let a="info";o.debug?a="debug":o.verbose&&(a="verbose");const c=new Uo(r,s,a),d=new Lo({format:s}),l={cwd:t,env:i,argv:e.argv,config:n,format:s,log:r,ui:c,response:d,globalOptions:o,auth:void 0};return l.auth=new go(l),l}({argv:e,config:await s.loadConfig(t.config),globalOptions:t});!function(e){kt=e.log,It=!0===Pt([e,"access",e=>e.globalOptions,"optionalAccess",e=>e.debug]),It&&(At||(Ht(),Jt(),At=!0))}(i);const o=ci([vt,ti,ai,Y]);await o(i,(async()=>{await jf(i)}))})().catch((e=>{V(e,void 0),process.exitCode=1}));
|
|
31
|
+
function n_(e,t,i,o){return new(i||(i=Promise))((function(t,s){function n(e){try{a(o.next(e))}catch(e){s(e)}}function r(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var o;e.done?t(e.value):(o=e.value,o instanceof i?o:new i((function(e){e(o)}))).then(n,r)}a((o=o.apply(e,[])).next())}))}let r_="";function a_(e=""){const t=`${Date.now()}`,i=r_||(r_=function(e){const t=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(e),i=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(e);return t?function(e){const t=e.split(/\./).map((e=>{return t=e,(Array(8).join("0")+parseInt(t,10).toString(2)).slice(-8);var t})),i=[];i[0]=d_(t[0]+t[1]),i[1]=d_(t[2]+t[3]);const o=["0000","0000","0000","0000","0000","ffff",i[0],i[1]];return o.join("")}(e):i?function(e){let t="";const i=[];let o=0,s=0,n=!0;const r="0000";if(e.indexOf("::")>-1){const a=e.split("::");for(let e=0;e<a.length;e++){const t=a[e];if(t.indexOf(":")>0){const e=t.split(":");n&&(o=e.length),s+=e.length;for(let t=0;t<e.length;t++)if(4!==e[t].length){const o=r.substring(0,4-e[t].length).concat(e[t]);i.push(o)}else i.push(e[t]);n=!1}else{if(4!==t.length){const e=r.substring(0,4-t.length).concat(t);i.push(e)}else i.push(t);n&&(o+=1),s+=1,n=!1}}let c="";for(let e=0;e<8-s;e++)c=c.concat(r);for(let e=0;e<i.length;e++)e===o?(t=t.concat(c),t=t.concat(i[e])):t=t.concat(i[e]);return t}{const i=e.split(":");for(let e=0;e<i.length;e++){const o=i[e];if(4!==i[e].length){const s=r.substring(0,4-i[e].length).concat(o);t=t.concat(s)}else t=t.concat(o)}return t}}(e):"00000000000000000000000000000000"}(e));return"02"+t+i+Math.random().toString(16).slice(-6)}function c_(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function d_(e){return(Array(4).join("0")+parseInt(e,2).toString(16)).slice(-4)}function l_(e,t){const i=e.key;void 0!==i&&(R_(t,10),E_(t,i));const o=e.value;void 0!==o&&(R_(t,18),E_(t,o))}function p_(e){const t={};e:for(;!b_(e);){const i=j_(e);switch(i>>>3){case 0:break e;case 1:t.key=T_(e,j_(e));break;case 2:t.value=T_(e,j_(e));break;default:m_(e,7&i)}}if(void 0===t.key)throw new Error("Missing required field: key");if(void 0===t.value)throw new Error("Missing required field: value");return t}function u_(e){const t=y_();return function(e,t){const i=e.SeqID;void 0!==i&&(R_(t,8),U_(t,i));const o=e.LogID;void 0!==o&&(R_(t,16),U_(t,o));const s=e.service;void 0!==s&&(R_(t,24),U_(t,g_(s)));const n=e.method;void 0!==n&&(R_(t,32),U_(t,g_(n)));const r=e.headers;if(void 0!==r)for(const e of r){R_(t,42);const i=y_();l_(e,i),R_(t,i.limit),k_(t,i),v_(i)}const a=e.payloadEncoding;void 0!==a&&(R_(t,50),E_(t,a));const c=e.payloadType;void 0!==c&&(R_(t,58),E_(t,c));const d=e.payload;void 0!==d&&(R_(t,66),R_(t,d.length),function(e,t){const i=S_(e,t.length);e.bytes.set(t,i)}(t,d));const l=e.LogIDNew;void 0!==l&&(R_(t,74),E_(t,l));const p=e.serverTiming;void 0!==p&&(R_(t,82),E_(t,p));const u=e.msgID;void 0!==u&&(R_(t,90),E_(t,u));const _=e.frameType;void 0!==_&&(R_(t,96),U_(t,g_(_)))}(e,t),function(e){const t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function __(e){return function(e){const t={};e:for(;!b_(e);){const i=j_(e);switch(i>>>3){case 0:break e;case 1:t.SeqID=z_(e,!0);break;case 2:t.LogID=z_(e,!0);break;case 3:t.service=j_(e);break;case 4:t.method=j_(e);break;case 5:{const i=h_(e);(t.headers||(t.headers=[])).push(p_(e)),e.limit=i;break}case 6:t.payloadEncoding=T_(e,j_(e));break;case 7:t.payloadType=T_(e,j_(e));break;case 8:t.payload=C_(e,j_(e));break;case 9:t.LogIDNew=T_(e,j_(e));break;case 10:t.serverTiming=T_(e,j_(e));break;case 11:t.msgID=T_(e,j_(e));break;case 12:t.frameType=j_(e);break;default:m_(e,7&i)}}if(void 0===t.SeqID)throw new Error("Missing required field: SeqID");if(void 0===t.LogID)throw new Error("Missing required field: LogID");if(void 0===t.service)throw new Error("Missing required field: service");if(void 0===t.method)throw new Error("Missing required field: method");return t}({bytes:t=e,offset:0,limit:t.length});var t}function h_(e){const t=j_(e),i=e.limit;return e.limit=e.offset+t,i}function m_(e,t){switch(t){case 0:for(;128&I_(e););break;case 2:w_(e,j_(e));break;case 5:w_(e,4);break;case 1:w_(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function g_(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}const f_=[];function y_(){const e=f_.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function v_(e){f_.push(e)}function w_(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function b_(e){return e.offset>=e.limit}function S_(e,t){const i=e.bytes,o=e.offset,s=e.limit,n=o+t;if(n>i.length){const t=new Uint8Array(2*n);t.set(i),e.bytes=t}return e.offset=n,n>s&&(e.limit=n),o}function P_(e,t){const i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function C_(e,t){const i=P_(e,t);return e.bytes.subarray(i,i+t)}function T_(e,t){const i=P_(e,t),o=String.fromCharCode,s=e.bytes,n="�";let r="";for(let e=0;e<t;e++){const a=s[e+i];let c,d,l,p;128&a?192==(224&a)?e+1>=t?r+=n:(c=s[e+i+1],128!=(192&c)?r+=n:(p=(31&a)<<6|63&c,p<128?r+=n:(r+=o(p),e++))):224==(240&a)?e+2>=t?r+=n:(c=s[e+i+1],d=s[e+i+2],32896!=(49344&(c|d<<8))?r+=n:(p=(15&a)<<12|(63&c)<<6|63&d,p<2048||p>=55296&&p<=57343?r+=n:(r+=o(p),e+=2))):240==(248&a)?e+3>=t?r+=n:(c=s[e+i+1],d=s[e+i+2],l=s[e+i+3],8421504!=(12632256&(c|d<<8|l<<16))?r+=n:(p=(7&a)<<18|(63&c)<<12|(63&d)<<6|63&l,p<65536||p>1114111?r+=n:(p-=65536,r+=o(55296+(p>>10),56320+(1023&p)),e+=3))):r+=n:r+=o(a)}return r}function E_(e,t){const i=t.length;let o=0;for(let e=0;e<i;e++){let s=t.charCodeAt(e);s>=55296&&s<=56319&&e+1<i&&(s=(s<<10)+t.charCodeAt(++e)-56613888),o+=s<128?1:s<2048?2:s<65536?3:4}R_(e,o);let s=S_(e,o);const n=e.bytes;for(let e=0;e<i;e++){let o=t.charCodeAt(e);o>=55296&&o<=56319&&e+1<i&&(o=(o<<10)+t.charCodeAt(++e)-56613888),o<128?n[s++]=o:(o<2048?n[s++]=o>>6&31|192:(o<65536?n[s++]=o>>12&15|224:(n[s++]=o>>18&7|240,n[s++]=o>>12&63|128),n[s++]=o>>6&63|128),n[s++]=63&o|128)}}function k_(e,t){const i=S_(e,t.limit),o=e.bytes,s=t.bytes;for(let e=0,n=t.limit;e<n;e++)o[e+i]=s[e]}function I_(e){return e.bytes[P_(e,1)]}function A_(e,t){const i=S_(e,1);e.bytes[i]=t}function j_(e){let t,i=0,o=0;do{t=I_(e),i<32&&(o|=(127&t)<<i),i+=7}while(128&t);return o}function R_(e,t){for(t>>>=0;t>=128;)A_(e,127&t|128),t>>>=7;A_(e,t)}function z_(e,t){let i,o=0,s=0,n=0;return i=I_(e),o=127&i,128&i&&(i=I_(e),o|=(127&i)<<7,128&i&&(i=I_(e),o|=(127&i)<<14,128&i&&(i=I_(e),o|=(127&i)<<21,128&i&&(i=I_(e),s=127&i,128&i&&(i=I_(e),s|=(127&i)<<7,128&i&&(i=I_(e),s|=(127&i)<<14,128&i&&(i=I_(e),s|=(127&i)<<21,128&i&&(i=I_(e),n=127&i,128&i&&(i=I_(e),n|=(127&i)<<7))))))))),{low:o|s<<28,high:s>>>4|n<<24,unsigned:t}}function U_(e,t){const i=t.low>>>0,o=(t.low>>>28|t.high<<4)>>>0,s=t.high>>>24,n=0===s?0===o?i<16384?i<128?1:2:i<1<<21?3:4:o<16384?o<128?5:6:o<1<<21?7:8:s<128?9:10,r=S_(e,n),a=e.bytes;switch(n){case 10:a[r+9]=s>>>7&1;case 9:a[r+8]=9!==n?128|s:127&s;case 8:a[r+7]=8!==n?o>>>21|128:o>>>21&127;case 7:a[r+6]=7!==n?o>>>14|128:o>>>14&127;case 6:a[r+5]=6!==n?o>>>7|128:o>>>7&127;case 5:a[r+4]=5!==n?128|o:127&o;case 4:a[r+3]=4!==n?i>>>21|128:i>>>21&127;case 3:a[r+2]=3!==n?i>>>14|128:i>>>14&127;case 2:a[r+1]=2!==n?i>>>7|128:i>>>7&127;case 1:a[r]=1!==n?128|i:127&i}}function L_(e){return u_(e)}const O_=4294967296,x_=0x10000000000000000,B_=x_/2,q_=String.prototype.charCodeAt;class D_{constructor(e,t,i){this.isLong=!0,this.low=0|e,this.high=0|t,this.unsigned=!!i}static isLong(e){return e&&!0===e.isLong}static fromBits(e,t,i){return new D_(e,t,i)}static fromBytes(e,t,i){return i?D_.fromBytesLE(e,t):D_.fromBytesBE(e,t)}static fromBytesLE(e,t){return new D_(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)}static fromBytesBE(e,t){return new D_(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}static fromHash(e){return"\0\0\0\0\0\0\0\0"===e?M_:new D_((q_.call(e,0)|q_.call(e,1)<<8|q_.call(e,2)<<16|q_.call(e,3)<<24)>>>0,(q_.call(e,4)|q_.call(e,5)<<8|q_.call(e,6)<<16|q_.call(e,7)<<24)>>>0,!0)}toHash(){return String.fromCharCode(255&this.low,this.low>>>8&255,this.low>>>16&255,this.low>>>24,255&this.high,this.high>>>8&255,this.high>>>16&255,this.high>>>24)}static fromNumber(e,t=!0){if(isNaN(e))return t?N_:M_;if(t){if(e>=x_)return $_}else{if(e<=-B_)return F_;if(e+1>=B_)return G_}return D_.fromBits(e%O_|0,e/O_|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*O_+(this.low>>>0):this.high*O_+(this.low>>>0)}isZero(){return 0===this.high&&0===this.low}add(e){D_.isLong(e)||(e=D_.fromNumber(e));const t=this.high>>>16,i=65535&this.high,o=this.low>>>16,s=65535&this.low,n=e.high>>>16,r=65535&e.high,a=e.low>>>16;let c=0,d=0,l=0,p=0;return p+=s+(65535&e.low),l+=p>>>16,p&=65535,l+=o+a,d+=l>>>16,l&=65535,d+=i+r,c+=d>>>16,d&=65535,c+=t+n,c&=65535,D_.fromBits(l<<16|p,c<<16|d,this.unsigned)}equals(e){return D_.isLong(e)||(e=D_.fromNumber(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)}addOne(){return-1===this.low&&-1===this.high?D_.fromBits(0,0,this.unsigned):-1===this.low?D_.fromBits(0,this.high+1,this.unsigned):D_.fromBits(this.low+1,this.high,this.unsigned)}toBytes(e){return e?this.toBytesLE():this.toBytesBE()}toBytesLE(){const e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}toBytesBE(){const e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]}}const M_=new D_(0,0,!1),N_=new D_(0,0,!0),G_=D_.fromBits(-1,2147483647,!1),$_=D_.fromBits(-1,-1,!0),F_=D_.fromBits(0,-2147483648,!1);var V_;!function(e){e[e.NATIVE_ERROR=5001]="NATIVE_ERROR",e[e.CONNECTING_ERROR=5002]="CONNECTING_ERROR",e[e.MAX_RETRIES_ERROR=5003]="MAX_RETRIES_ERROR",e[e.MESSAGE_ERROR=5004]="MESSAGE_ERROR",e[e.OPEN_ERROR=5005]="OPEN_ERROR"}(V_||(V_={}));class W_{constructor(e){this.type=e,this.target=null}}class H_ extends W_{constructor(e,t){super(e),this.message=t&&t.message||null}}class J_ extends W_{constructor(e,t){super(e),this.error=t&&t.error||null,this.colno=t&&t.colno||0,this.filename=t&&t.filename||"",this.lineno=t&&t.lineno||0,this.message=t&&t.message||"",this.code=t&&t.code||V_.NATIVE_ERROR}}class K_ extends W_{constructor(e,t){super(e),this.code=t&&t.code||0,this.reason=t&&t.reason||"",this.wasClean=t&&t.wasClean||!1,this.willReconnect=t&&t.willReconnect||!1}}class Q_ extends W_{constructor(e,t){super(e),this.data=t&&t.data||null}}class Y_ extends Q_{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}}class Z_ extends W_{constructor(e,t){super(e),this.data=t&&t.data||null}}function X_(e,{message:t,code:i,error:o}){return new J_(e,{message:t,code:i,error:o})}function eh(e,{code:t,reason:i,wasClean:o,willReconnect:s}){return new K_(e,{code:t,reason:i,wasClean:o,willReconnect:s})}function th(e,{message:t}){return new H_(e,{message:t})}class ih{constructor(e,t){this.endpoints=e,this.maxRetries=t,this.currentIndex=0,this.currentEndpointTriesCount=0}resetEndpointConfig(){this.currentIndex=0,this.currentEndpointTriesCount=0}resetTries(){this.currentEndpointTriesCount=0}getCurrentEndpoint(){return this.endpoints[this.currentIndex]}getCurrentEndpointTriesCount(){return this.currentEndpointTriesCount}checkReachMaxTries(){return this.currentIndex>=this.endpoints.length||this.currentIndex===this.endpoints.length-1&&this.currentEndpointTriesCount===this.maxRetries}checkCurrentEndpointReachedMaxRetries(){return this.currentIndex==this.endpoints.length||this.currentEndpointTriesCount>this.maxRetries}replaceBackupEndpointAndUpdateCount(){return this.currentEndpointTriesCount=1,this.currentIndex++,this.endpoints[this.currentIndex]}getCurrentEndpointAndUpdateCount(){return this.currentEndpointTriesCount++,this.getCurrentEndpoint()}}const oh=("undefined"!=typeof globalThis&&"Window"===globalThis.constructor.name||"undefined"!=typeof window&&"Window"===window.constructor.name)&&"undefined"!=typeof document,sh="undefined"!=typeof globalThis&&("Object"===globalThis.constructor.name||"DedicatedWorkerGlobalScope"===globalThis.constructor.name)&&"undefined"!=typeof tt,nh=("undefined"!=typeof globalThis&&"Object"===globalThis.constructor.name||"undefined"==typeof globalThis||"undefined"!=typeof globalThis&&!!globalThis.WeixinJSBridge)&&"undefined"!=typeof wx,rh="undefined"!=typeof globalThis&&("DedicatedWorkerGlobalScope"===globalThis.constructor.name||"SharedWorkerGlobalScope"===globalThis.constructor.name||"ServiceWorkerGlobalScope"===globalThis.constructor.name)&&"undefined"!=typeof self,ah="undefined"!=typeof globalThis&&"Object"===globalThis.constructor.name&&"undefined"!=typeof global&&"Object"===global.constructor.name&&"undefined"!=typeof process&&!!process.version;class ch{constructor(){this._listeners={}}emit(e,...t){const i=this._listeners[e];if(i)i.slice().forEach((e=>e.fn.apply(e.ctx,t)));else if("error"===e&&!this.onerror){const e=t.length&&t[0];if(e instanceof Error)throw e;throw new Error("Unhandled error."+(e?" ("+e.message+")":"")).context=e,e}return this}off(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=null;else{const i=this._listeners[e];if(i)for(let e=0;e<i.length;)i[e].fn===t?i.splice(e,1):++e}return this}on(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this}}class dh extends ch{constructor(e,t,i){super(),this._socket=null,nh&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:i,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),sh&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:t,header:i,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then((()=>{this._addWsListeners()}))}_createSocketFailHandler(e){Promise.resolve().then((()=>{const t=X_("error",{message:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)});this.emit("error",t);const i=eh("close",{reason:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)});this.emit("close",i)}))}_addWsListeners(){this._socket.onOpen((e=>{this.emit("open",function(e,{data:t}){return new Z_(e,{data:t})}("open",Object.assign(Object.assign({},e),{data:e.errMsg||""})))})),this._socket.onClose((e=>{this.emit("close",eh("close",Object.assign({},e)))})),this._socket.onMessage((e=>{this.emit("message",function(e,{data:t,message:i}){return new Y_(e,{data:t,message:i})}("message",Object.assign({},e)))})),this._socket.onError((e=>{this.emit("error",X_("error",Object.assign(Object.assign({},e),{message:e.errMsg||""})))}))}send(e){if(e instanceof Uint8Array){const t=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);this._socket&&this._socket.send({data:t,fail:e=>{this.emit("error",X_("error",{message:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)}))}})}else this._socket&&this._socket.send({data:e,fail:e=>{this.emit("error",X_("error",{message:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)}))}})}close(e,t){this._socket&&this._socket.close({code:e,reason:t})}addEventListener(e,t){this.on(e,t)}removeEventListener(e,t){this.off(e,t)}get readyState(){return this._socket.readyState}get binaryType(){return this._socket.binaryType}set binaryType(e){}get url(){return this._socket.url}get protocol(){return this._socket.protocol}get extensions(){return this._socket.extensions}get bufferedAmount(){return 0}}function lh(e,t,i){let o=-1;!function s(n){return n_(this,0,void 0,(function*(){if(n<=o)return Promise.reject(new Error("next() called multiple times in process"));if(o=n,n===i.length)return Promise.resolve();return i[n].bind(e)(t,s.bind(null,n+1))}))}(0)}function ph(e){let t=0,i=0;for(let o=0;o<e.length;++o)i=e.charCodeAt(o),i<128?t+=1:i<2048?t+=2:55296==(64512&i)&&56320==(64512&e.charCodeAt(o+1))?(++o,t+=4):t+=3;return t}function uh(e,t,i){if(i-t<1)return"";let o="";for(let s=t;s<i;){const t=e[s++];if(t<=127)o+=String.fromCharCode(t);else if(t>=192&&t<224)o+=String.fromCharCode((31&t)<<6|63&e[s++]);else if(t>=224&&t<240)o+=String.fromCharCode((15&t)<<12|(63&e[s++])<<6|63&e[s++]);else if(t>=240){const i=((7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;o+=String.fromCharCode(55296+(i>>10)),o+=String.fromCharCode(56320+(1023&i))}}return o}function _h(e,t,i){const o=i;let s,n;for(let o=0;o<e.length;++o)s=e.charCodeAt(o),s<128?t[i++]=s:s<2048?(t[i++]=s>>6|192,t[i++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(o+1)))?(s=65536+((1023&s)<<10)+(1023&n),++o,t[i++]=s>>18|240,t[i++]=s>>12&63|128,t[i++]=s>>6&63|128,t[i++]=63&s|128):(t[i++]=s>>12|224,t[i++]=s>>6&63|128,t[i++]=63&s|128);return i-o}function hh(e){return n_(this,0,void 0,(function*(){if("string"==typeof e){const t=new Uint8Array(ph(e));return _h(e,t,0),t}return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}))}class mh{constructor(e){this.maxLossCount=e,this.count=0}addCount(){this.count++}checkReachMaxCount(){return this.count>=this.maxLossCount}resetCounter(e=0){this.maxLossCount=e,this.count=0}}function gh(e,t,i){return!!(null==e?void 0:e.find((e=>e.key===t&&e.value===i)))}function fh(e,t){var i;return null===(i=null==e?void 0:e.find((e=>e.key===t)))||void 0===i?void 0:i.value}function yh(e,t){return n_(this,0,void 0,(function*(){const{enableAutoAck:i}=this._options,o=gh(e.message.headers,"need_ack","1"),s=gh(e.message.headers,"is_ack","1"),n=gh(e.message.headers,"x_frontier_qos_ack","1");if(i&&o){const{SeqID:t,LogID:i,service:o,LogIDNew:s,method:n}=e.message;this._sendAck({SeqID:t,LogID:i,LogIDNew:s,service:o,method:n,headers:[{key:"is_ack",value:"1"},{key:"ack_id",value:s||""},{key:"ack_code",value:"0"}]})}s&&!n&&this._dispatchAckMessageEvent(e),t()}))}function vh(e,t){return n_(this,0,void 0,(function*(){this._debug("received",e.message),t()}))}function wh(e,t){return n_(this,0,void 0,(function*(){const i=__(yield hh(e.data));try{if(i.payload instanceof Uint8Array){const e=this._options.payloadEncoding instanceof Object?{force:!!this._options.payloadEncoding.force,encoding:this._options.payloadEncoding.encoding?this._options.payloadEncoding.encoding.replace(/\s/g,"").toLowerCase():""}:{force:!1,encoding:this._options.payloadEncoding?this._options.payloadEncoding.replace(/\s/g,"").toLowerCase():""},t=i.payloadEncoding?i.payloadEncoding.replace(/\s/g,"").toLowerCase():"",o=this._options.payloadType instanceof Object?{force:!!this._options.payloadType.force,type:this._options.payloadType.type?this._options.payloadType.type.replace(/\s/g,"").toLowerCase():""}:{force:!1,type:this._options.payloadType?this._options.payloadType.replace(/\s/g,"").toLowerCase():""},s=i.payloadType?i.payloadType.replace(/\s/g,"").toLowerCase():"",n=o.force?o.type:s||o.type,r=e.force?e.encoding:t||e.encoding,a=["text/plain;charset=utf-8","application/json","application/json;charset=utf-8","string"],c=["none_none","binary"];this._options.enableTransformTextPayload&&a.includes(n)&&(!r||c.includes(r))?i.textPayload=uh(i.payload,0,i.payload.byteLength):i.textPayload=""}else i.textPayload=""}catch(e){i.textPayload="",console.log(e)}e.message=i,t()}))}let bh,Sh;const Ph=new WeakMap,Ch=new WeakMap,Th=new WeakMap,Eh=new WeakMap,kh=new WeakMap;let Ih={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return Ch.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Th.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return Rh(e[t])},set:(e,t,i)=>(e[t]=i,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Ah(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Sh||(Sh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(zh(this),t),Rh(Ph.get(this))}:function(...t){return Rh(e.apply(zh(this),t))}:function(t,...i){const o=e.call(zh(this),t,...i);return Th.set(o,t.sort?t.sort():[t]),Rh(o)}}function jh(e){return"function"==typeof e?Ah(e):(e instanceof IDBTransaction&&function(e){if(Ch.has(e))return;const t=new Promise(((t,i)=>{const o=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",n),e.removeEventListener("abort",n)},s=()=>{t(),o()},n=()=>{i(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",s),e.addEventListener("error",n),e.addEventListener("abort",n)}));Ch.set(e,t)}(e),t=e,(bh||(bh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some((e=>t instanceof e))?new Proxy(e,Ih):e);var t}function Rh(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,i)=>{const o=()=>{e.removeEventListener("success",s),e.removeEventListener("error",n)},s=()=>{t(Rh(e.result)),o()},n=()=>{i(e.error),o()};e.addEventListener("success",s),e.addEventListener("error",n)}));return t.then((t=>{t instanceof IDBCursor&&Ph.set(t,e)})).catch((()=>{})),kh.set(t,e),t}(e);if(Eh.has(e))return Eh.get(e);const t=jh(e);return t!==e&&(Eh.set(e,t),kh.set(t,e)),t}const zh=e=>kh.get(e);const Uh=["get","getKey","getAll","getAllKeys","count"],Lh=["put","add","delete","clear"],Oh=new Map;function xh(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Oh.get(t))return Oh.get(t);const i=t.replace(/FromIndex$/,""),o=t!==i,s=Lh.includes(i);if(!(i in(o?IDBIndex:IDBObjectStore).prototype)||!s&&!Uh.includes(i))return;const n=async function(e,...t){const n=this.transaction(e,s?"readwrite":"readonly");let r=n.store;return o&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),s&&n.done]))[0]};return Oh.set(t,n),n}Ih=(e=>({...e,get:(t,i,o)=>xh(t,i)||e.get(t,i,o),has:(t,i)=>!!xh(t,i)||e.has(t,i)}))(Ih);class Bh extends ch{constructor(e,t){super(),this._dbName=e,this._keyPath=t,this._qosDB=void 0,this._init()}openDB(){return n_(this,0,void 0,(function*(){yield this._init()}))}_init(){return n_(this,0,void 0,(function*(){try{const e=this._dbName,t=this._keyPath;return new Promise((i=>{this._qosDB?i(this):(function(e,t,{blocked:i,upgrade:o,blocking:s,terminated:n}={}){const r=indexedDB.open(e,t),a=Rh(r);return o&&r.addEventListener("upgradeneeded",(e=>{o(Rh(r.result),e.oldVersion,e.newVersion,Rh(r.transaction))})),i&&r.addEventListener("blocked",(()=>i())),a.then((e=>{n&&e.addEventListener("close",(()=>n())),s&&e.addEventListener("versionchange",(()=>s()))})).catch((()=>{})),a}(`frontier_${e}`,1,{upgrade(i){i.createObjectStore(e,{keyPath:t})}}).then((e=>{this._qosDB=e,this.emit("ready")})),this.on("ready",(()=>{i(this),this.off()})))}))}catch(e){console.log(e)}}))}get(e){var t;return n_(this,0,void 0,(function*(){try{return null===(t=this._qosDB)||void 0===t?void 0:t.get(this._dbName,e)}catch(e){console.log(e)}}))}set(e,t){var i;return n_(this,0,void 0,(function*(){return null===(i=this._qosDB)||void 0===i?void 0:i.put(this._dbName,e)}))}del(e){var t;return n_(this,0,void 0,(function*(){try{return null===(t=this._qosDB)||void 0===t?void 0:t.delete(this._dbName,e)}catch(e){console.log(e)}}))}clear(){var e;return n_(this,0,void 0,(function*(){try{return null===(e=this._qosDB)||void 0===e?void 0:e.clear(this._dbName)}catch(e){console.log(e)}}))}keys(){var e;return n_(this,0,void 0,(function*(){return null===(e=this._qosDB)||void 0===e?void 0:e.getAllKeys(this._dbName)}))}getAll(){var e;return n_(this,0,void 0,(function*(){return null===(e=this._qosDB)||void 0===e?void 0:e.getAll(this._dbName)}))}closeDB(){var e;return n_(this,0,void 0,(function*(){try{null===(e=this._qosDB)||void 0===e||e.close(),this._qosDB=void 0}catch(e){console.log(e)}}))}get isReady(){try{return!!this._qosDB}catch(e){return console.log(e),!1}}}class qh{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=localStorage}openDB(){return n_(this,0,void 0,(function*(){}))}get _prefix(){return`frontier_${this._DBName}`}get(e){return n_(this,0,void 0,(function*(){const t=this._qosDB.getItem(this._prefix);return JSON.parse(t||"{}")[e]}))}set(e,t){return n_(this,0,void 0,(function*(){const i=this._qosDB.getItem(this._prefix),o=JSON.parse(i||"{}");return o[t||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(o)),t||e[this._pathKey]}))}del(e){return n_(this,0,void 0,(function*(){const t=this._qosDB.getItem(this._prefix),i=JSON.parse(t||"{}");return i[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(i))}))}clear(){return n_(this,0,void 0,(function*(){return this._qosDB.clear()}))}keys(){return n_(this,0,void 0,(function*(){const e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}))}getAll(){return n_(this,0,void 0,(function*(){const e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}))}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}}class Dh{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=sh?tt:nh?wx:null}openDB(){return n_(this,0,void 0,(function*(){}))}get _prefix(){return`frontier_${this._DBName}`}get(e){return n_(this,0,void 0,(function*(){const t=this._qosDB.getStorageSync(this._prefix);return JSON.parse(t||"{}")[e]}))}set(e,t){return n_(this,0,void 0,(function*(){const i=this._qosDB.getStorageSync(this._prefix),o=JSON.parse(i||"{}");return o[t||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(o)),t||e[this._pathKey]}))}del(e){return n_(this,0,void 0,(function*(){const t=this._qosDB.getStorageSync(this._prefix),i=JSON.parse(t||"{}");return i[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(i))}))}clear(){return n_(this,0,void 0,(function*(){return this._qosDB.clearStorageSync()}))}keys(){return n_(this,0,void 0,(function*(){const e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}))}getAll(){return n_(this,0,void 0,(function*(){const e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}))}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}}function Mh(e,t){if(sh||sh)return new Dh(e,t);if((oh||rh)&&void 0!==typeof indexedDB)return new Bh(e,t);if((oh||rh)&&void 0!==typeof localStorage)return new qh(e,t);throw new Error("init QoSDB failed")}class Nh{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=Mh("qos","message_id")}_intervalFlush(){return n_(this,0,void 0,(function*(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval((()=>{this.flushExpired()}),this._interval)}))}openDB(){return n_(this,0,void 0,(function*(){yield this._qosDB.openDB().then((()=>{this._intervalFlush()}))}))}flushExpired(){var e;return n_(this,0,void 0,(function*(){((yield null===(e=this._qosDB)||void 0===e?void 0:e.getAll())||[]).filter((({timestamp:e})=>e<Date.now())).forEach((e=>{var t;null===(t=this._qosDB)||void 0===t||t.del(e.message_id)}))}))}del(e){var t;return n_(this,0,void 0,(function*(){return null===(t=this._qosDB)||void 0===t?void 0:t.del(e)}))}set(e,t){var i;return n_(this,0,void 0,(function*(){return null===(i=this._qosDB)||void 0===i?void 0:i.set({message_id:e,timestamp:t})}))}get(e){var t;return n_(this,0,void 0,(function*(){return null===(t=this._qosDB)||void 0===t?void 0:t.get(e)}))}closeDB(){var e;return n_(this,0,void 0,(function*(){clearInterval(this._intervalTimeoutId),yield null===(e=this._qosDB)||void 0===e?void 0:e.closeDB()}))}get isReady(){var e;return null===(e=this._qosDB)||void 0===e?void 0:e.isReady}}function Gh(e,t){var i,o,s,n,r;return n_(this,0,void 0,(function*(){const a=gh(e.message.headers,"code","-1"),c=gh(e.message.headers,"is_ack","1"),d=fh(e.message.headers,"x_frontier_msgid"),l=Number(fh(e.message.headers,"x_frontier_ttl"))||0,p=gh(e.message.headers,"x_frontier_qos","2"),u=gh(e.message.headers,"x_frontier_qos_ack","1"),_=gh(e.message.headers,"x-msg-qos","2"),h=fh(e.message.headers,"x-msg-cursor_name"),m=Number(fh(e.message.headers,"x-msg-cursor_value"));if(p&&u)return t();if(_&&!(null===(i=this._cursorManager)||void 0===i?void 0:i.isReady))return t();if(p&&!this._QoSManager&&(this._QoSManager=new Nh),p&&this._QoSManager&&!this._QoSManager.isReady&&(yield this._QoSManager.openDB()),e.message.service>0&&c&&!a||e.message.service>0){if(d&&p){return!!(yield null===(o=this._QoSManager)||void 0===o?void 0:o.get(d))||(this._dispatchMessageEvent(e),yield null===(s=this._QoSManager)||void 0===s?void 0:s.set(d,Date.now()+l)),t()}if(_&&(null===(n=this._cursorManager)||void 0===n?void 0:n.isReady)){const i=null!==(r=yield this._cursorManager.get(h))&&void 0!==r?r:-1;if(!(i<m))throw new Error(`recevied message cursor ${m} larger than local cursor ${i}`);return this._dispatchMessageEvent(e),this._cursorManager.set(h,m,e.message.service),t()}return this._dispatchMessageEvent(e),t()}}))}function $h(e,t){var i,o;return n_(this,0,void 0,(function*(){const s=gh(e.message.headers,"x_frontier_qos","2"),n=gh(e.message.headers,"x_frontier_is_ack","1"),r=null===(i=fh(e.message.headers,"x_frontier_ack_msgid"))||void 0===i?void 0:i.split(",");if(!s)return t();if(this._QoSManager||(this._QoSManager=new Nh),this._QoSManager&&!this._QoSManager.isReady&&(yield this._QoSManager.openDB()),n&&r&&r.length)for(const e of r)yield null===(o=this._QoSManager)||void 0===o?void 0:o.del(e);t()}))}function Fh(e,t){let i=0,o=t;const s=t+4;for(;o<s;){const{value:t,offset:s}=Wh(e,o);o=s,i=i<<8>>>0,i+=t}return{value:i,offset:s}}function Vh(e,t){return{value:new D_(e[t+4]<<24|e[t+5]<<16|e[t+6]<<8|e[t+7],e[t+0]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],!0),offset:(t+=8)+8}}function Wh(e,t){return e.readUInt8?{value:e.readUInt8(t),offset:t+1}:{value:255&e[t],offset:t+1}}function Hh(e,t,i){return t.writeUint8?t.writeUint8(e,i):t[i]=255&e,i+1}const Jh="undefined"!=typeof Buffer?Buffer.allocUnsafe:function(e,t){const i=8192;let o=null,s=i;return function(n){if(n<1||n>4096)return e(n);s+n>i&&(o=e(i),s=0);const r=t.call(o,s,s+=n);return 7&s&&(s=1+(7|s)),r}}((function(e){return new Uint8Array(e)}),Uint8Array.prototype.subarray);function Kh(e,t,i){const[o,s]=function(e){let t=0;const i={};for(let o=0;o<e.length;o++)i[e[o].cursor_name]=ph(e[o].cursor_name),t+=14+i[e[o].cursor_name];return[t,i]}(e),n=Jh(o);let r=0;return e.forEach((e=>{console.log("cursor.service",e,e.service),r=Hh(0,n,r),console.log("header",r),r=function(e,t,i){if(i>4294967295)throw new Error("integer too large");let o=3;for(;o>=0;)Hh(255&i,e,t+o),i>>>=8,o--;return t+4}(n,r,e.service||0),console.log("service",r),r=Hh(s[e.cursor_name],n,r),console.log("service-name",r),r=function(e,t,i){return e?e.length<40?_h(e,t,i)+i:t.utf8Write?t.utf8Write(e,i)+i:t.write?t.write(e,i)+i:_h(e,t,i)+i:i}(e.cursor_name,n,r),console.log("name",r),r=function(e,t,i){const o=e.low,s=e.high;return t[i]=s>>>24,t[i+1]=s>>>16&255,t[i+2]=s>>>8&255,t[i+3]=255&s,t[i+4]=o>>>24,t[i+5]=o>>>16&255,t[i+6]=o>>>8&255,t[i+7]=255&o,i+8}(D_.fromNumber(e.cursor||t),n,r),console.log("curvalue",r)})),{frameType:32,headers:[{key:"cursor_file_name",value:i}],payload:n}}class Qh{constructor(e,t,i){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=i,this._qosDB=Mh(this._cursorNameSpace,"cursor_name")}openDB(){return n_(this,0,void 0,(function*(){yield this._qosDB.openDB()}))}getCursors(){return n_(this,0,void 0,(function*(){if(!this._qosDB.isReady)return;const e=this._messageStrategy,t=yield this._qosDB.getAll();switch(console.log("allCursorValues",t),e){case"ALL":return t&&t.length?Kh(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?Kh(t,0,this._cursorFileName):{frameType:32,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}}))}set(e,t,i){return n_(this,0,void 0,(function*(){return console.log("setdb",e,t,i),this._qosDB.set({cursor_name:e,cursor:t,service:i})}))}setCursors(e){return n_(this,0,void 0,(function*(){const t=function(e){let t=0;const i=[];for(;t<e.byteLength;){const{offset:o}=Wh(e,t);t=o;const s={cursor_name:"",cursor:0,service:0},{value:n,offset:r}=Fh(e,t);s.service=n,t=r;const{value:a,offset:c}=Wh(e,t);t=c,s.cursor_name=uh(e,t,t+a),t+=a;const{value:d,offset:l}=Vh(e,t);s.cursor=d.toNumber(),t=l,i.push(s)}return i}(e);for(const e of t)console.log("setcursor",t),yield this._qosDB.set(e)}))}get(e){var t;return n_(this,0,void 0,(function*(){return null===(t=yield this._qosDB.get(e))||void 0===t?void 0:t.cursor}))}closeDB(){return n_(this,0,void 0,(function*(){yield this._qosDB.closeDB()}))}get isReady(){return this._qosDB.isReady}}function Yh(e,t){return n_(this,0,void 0,(function*(){const i=16===e.message.frameType,o=32===e.message.frameType;if(!i&&!o)return t();const s=fh(e.message.headers,"cursor_file_name"),{aID:n,fpID:r,messageStrategy:a}=this._options;if(!s)return t();if(this._cursorManager||(this._cursorManager=new Qh(`${r}_${n}_${s}`,s,a)),this._cursorManager.isReady||(yield this._cursorManager.openDB()),i){const e=yield this._cursorManager.getCursors(),t=u_({frameType:null==e?void 0:e.frameType,SeqID:D_.fromNumber(this._seqId++),LogID:D_.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:null==e?void 0:e.headers,payload:null==e?void 0:e.payload});this._ws&&this._ws.readyState&&this._ws.send(t)}if(o){const t=e.message.payload;t&&this._cursorManager.setCursors(t)}}))}const Zh=function(e,t){return n_(this,0,void 0,(function*(){this._isInit=!1,clearTimeout(this._connectionTimeoutId),t()}))},Xh=function(e,t){var i;return n_(this,0,void 0,(function*(){const e=null===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpoint();this._debug(`open ${e}`),t()}))},em=function(e,t){var i,o;return n_(this,0,void 0,(function*(){if(!this._ws||this._ws.readyState!==this.OPEN)return t();const{pingInterval:s}=this._options;null===(i=this._endpointManager)||void 0===i||i.resetEndpointConfig();for(let e=0;e<this._messageQueue.length;e++){const t=this._messageQueue[e];if(this._ws.readyState!==this.OPEN||null===t)break;this._ws&&this._ws.send(t),this._messageQueue[e]=null}this._messageQueue=this._messageQueue.filter((e=>Boolean(e))),this._pingPongTimeoutId=setTimeout((()=>this._ping()),s),this._dispatchOpenEvent(e),this._isBrowser&&this._ws&&(this._ws.binaryType=this._binaryType);const n=null===(o=this._endpointManager)||void 0===o?void 0:o.getCurrentEndpoint();this._debug(`open ${n} success`),t()}))};class tm extends ch{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=oh,this._isNode=ah,this._isMiniTT=sh,this._isMiniWX=nh,this._isWorker=rh,this._messageQueue=[],this._endpointManager=null,this._readyClosed=!1,this._binaryType="arraybuffer",this._connectLock=!1,this._connectionTimeoutId=null,this._reconnectTimeoutId=null,this._pingPongTimeoutId=null,this._seqId=0,this._isInit=!1,this._url="",this._QoSManager=null,this._cursorManager=null,this._pingLossCounter=null,this._protocols="pbbp2",this.CLOSED=3,this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this._onOpen=e=>{try{lh(this,e,[Zh,em,Xh])}catch(e){const t=X_("error",{message:e.message,code:V_.OPEN_ERROR,error:e});this._dispatchErrorEvent(t)}},this._onMessage=e=>n_(this,0,void 0,(function*(){const{pingInterval:t,pingFrequency:i}=this._options;if(("hi"===e.data&&"always"===i||"auto"===i)&&(this._clearPingTimer(),this.emit("ping_once_success","success"),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),t)),"hi"!==e.data)try{lh(this,e,[wh,yh,$h,Yh,Gh,vh])}catch(e){const t=X_("error",{message:e.message,code:V_.MESSAGE_ERROR,error:e});this._dispatchErrorEvent(t)}})),this._onError=e=>{var t,i;const o=null===(t=this._endpointManager)||void 0===t?void 0:t.checkReachMaxTries(),s=null===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpoint();if(!o||e.message)this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(X_("error",{message:e.message,code:V_.NATIVE_ERROR,error:e}));else{const t=`connect ${s} fail, max retries reached`;this._dispatchErrorEvent(X_("error",{message:t,code:V_.MAX_RETRIES_ERROR,error:e}))}},this._onClose=e=>n_(this,0,void 0,(function*(){var t,i,o,s,n,r,a,c,d,l,p,u;this._clearTimer(),this._clearPingTimer(),this._removeWsListeners(),this._ws=null,this._connectLock=!1;const _=null===(t=this._endpointManager)||void 0===t?void 0:t.checkReachMaxTries();if(!_&&this._navigatorOnline()&&!this._readyClosed){const t=null===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpoint(),o=this._options.reconnectInterceptor(e.code,e.reason);return this._dispatchCloseEvent(eh("close",{code:1006,reason:e.reason||`connecting failed, unknown reason, hostname: ${t}`,willReconnect:o})),void(o&&this._connect())}if(1e3!==e.code&&this._readyClosed)return this._dispatchCloseEvent(eh("close",{code:1e3,reason:"bye"})),null===(o=this._endpointManager)||void 0===o||o.resetEndpointConfig(),void(null===(s=this._pingLossCounter)||void 0===s||s.resetCounter());if(1e3!==e.code&&_){const t=null===(n=this._endpointManager)||void 0===n?void 0:n.getCurrentEndpoint();let i=e.reason;i||(i=yield function(e){return n_(this,0,void 0,(function*(){return new Promise((t=>{if(!oh)return t("unknown reason");try{const i=document.createElement("script");window.frontierJSONP=e=>{document.body.removeChild(i),window.frontierJSONP=void 0,t(e&&e.msg||"unknown reason")},i.type="text/javascript",i.src=e.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(i)}catch(e){document.body.removeChild(i)}}catch(e){window.frontierJSONP=void 0,t("unknown reason")}}))}))}(this._url)),i=`connecting failed, ${i}, hostname: ${t}, max retries reached`,this._dispatchCloseEvent(eh("close",{code:e.code,reason:i}));const o=`connect ${t} fail, max retries reached`;return this._dispatchErrorEvent(X_("error",{message:o,code:V_.MAX_RETRIES_ERROR})),null===(r=this._endpointManager)||void 0===r||r.resetEndpointConfig(),void(null===(a=this._pingLossCounter)||void 0===a||a.resetCounter())}if(1e3!==e.code&&!e.reason){const t=null===(c=this._endpointManager)||void 0===c?void 0:c.getCurrentEndpoint();return this._dispatchCloseEvent(eh("close",{code:e.code,reason:`connecting failed, unknown reason, hostname: ${t}`})),null===(d=this._endpointManager)||void 0===d||d.resetEndpointConfig(),void(null===(l=this._pingLossCounter)||void 0===l||l.resetCounter())}this._dispatchCloseEvent(e),null===(p=this._endpointManager)||void 0===p||p.resetEndpointConfig(),null===(u=this._pingLossCounter)||void 0===u||u.resetCounter()})),this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this.onStartReconnect=null,this.onReceiveAck=null,this.onStopImmediatelyReconnect=null,this._handleOnLine=this._handleOnLine.bind(this),this._handleOffLine=this._handleOffLine.bind(this),this._handlePageHide=this._handlePageHide.bind(this),this._handlePageShow=this._handlePageShow.bind(this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:c_,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:"auto",pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:"CONTINUE",env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};const{url:t,ws:i}=e,o=Array.isArray(t)?t:"string"==typeof t?[t]:[];if(!o||0===o.length)throw new Error("please provide valid url");if(!function(e){return!!(e||nh&&wx.connectSocket||sh&&tt.connectSocket||(oh||rh)&&"undefined"!=typeof WebSocket&&WebSocket)}(i))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new ih(o,this._options.maxRetries),this._pingLossCounter=new mh(this._options.pingLossCount),this._options.automaticOpen&&(this._isInit=!0,this._connect()),this._options.listenNetworkChanged&&(this._isMiniTT||this._isMiniWX?this._onPageNetWorkChange():this._isBrowser&&this._initGlobalEventListener())}_handleOnLine(){this._options.disableAutoReconnect||this._readyClosed||this._handleReconnect()}_handleOffLine(){this._destroyWebSocket();const e=th("reconnect",{message:"stop immediately reconnect"});this.onStopImmediatelyReconnect&&this.onStopImmediatelyReconnect(e)}_initGlobalEventListener(){this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine),this._isBrowser&&window.addEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.addEventListener("pageshow",this._handlePageShow)}_dropGlobalEventListener(){this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine),this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow)}_handlePageHide(e){e.persisted||(this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow),this.close()),this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine)}_handlePageShow(e){e.persisted&&(!this._navigatorOnline()||this._ws&&this._ws.readyState===this.OPEN&&this._ws.readyState===this.CONNECTING||this._handleOnLine(),this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine))}_generateUrl(e){return n_(this,0,void 0,(function*(){const{fpID:t,deviceID:i,bddID:o,ttwID:s,accessKey:n,aID:r,customParams:a={},enableAutoAck:c,enableQoS:d,QoSLevel:l,env:p}=this._options;let u,_,h;this._isBrowser||this._isMiniWX||this._isMiniTT?(u=location&&"https:"==location.protocol?"wss://":"ws://",_=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),h=/^wss(.*:\/\/)/.test(e)?e:`${u}${_}`):(u="wss://",_=e.replace(/(^http)((?:[s]*:\/\/))/,""),h=/(^ws)((?:[s]*:\/\/))/.test(_)?_:`${u}${_}`);const m=o?"bd_did":s?"ttwid":"device_id",g=o||(s||i);if(!g||!m)throw new Error("please provide bddID, deviceID or ttwID");const f="function"==typeof a?yield a():a,y=p?((e,t)=>{switch(e){case"boe":case"ppe":return{[`x-use-${e}`]:1,"x-tt-env":t};default:return{}}})(p.xUseEnv,p.xTTEnv):{},v=Object.assign(Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:n,fpid:t,aid:r,[m]:g,xsack:c?1:0,xaack:c?1:0,xsqos:d?1:0,qos_level:d?l:void 0,qos_sdk_version:2},y),f);return`${h}/ws/v2${Object.keys(v).reduce(((e,t)=>void 0!==v[t]?`${e}${e?"&":"?"}${t}=${v[t]}`:e),"")}`}))}_connect(){var e,t,i,o,s,n,r;return n_(this,0,void 0,(function*(){if(!this._connectLock&&!this._readyClosed){this._connectLock=!0;try{const d=null===(e=this._endpointManager)||void 0===e?void 0:e.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:l}=this._options;if(d){const e=null===(t=this._endpointManager)||void 0===t?void 0:t.getCurrentEndpoint(),s=null===(i=this._endpointManager)||void 0===i?void 0:i.replaceBackupEndpointAndUpdateCount(),n=null===(o=this._endpointManager)||void 0===o?void 0:o.getCurrentEndpointTriesCount();if(!s){const t=`connect ${e} timeout, max retries reached`;return this._debug(t),void this._dispatchErrorEvent(X_("error",{message:t,code:V_.MAX_RETRIES_ERROR}))}{const t=`connect ${e} timeout, max retries reached, will use backup endpoint ${s} to retry`,i=X_("error",{message:t,code:V_.MAX_RETRIES_ERROR});this._debug(t),this._dispatchErrorEvent(i),this._url=yield this._generateUrl(s),this._debug(`connect ${s} ${n} times`),this._removeWsListeners()}}else{const e=null===(s=this._endpointManager)||void 0===s?void 0:s.getCurrentEndpointAndUpdateCount(),t=null===(n=this._endpointManager)||void 0===n?void 0:n.getCurrentEndpointTriesCount();this._url=yield this._generateUrl(e||""),this._debug(`connect ${e} ${t} times`),this._removeWsListeners()}if(this._isInit)this._isInit=!1;else{const e=th("reconnect",{message:"start"});this.onStartReconnect&&this.onStartReconnect(e)}const p=(null===(r=this._endpointManager)||void 0===r?void 0:r.getCurrentEndpointTriesCount())||0;p>1&&(yield this._wait(p-1)),this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`),this._ws=(a={url:this._url,protocols:[this._protocols],headers:this._options.miniProgramParams.customHttpHeader},(c=this._options.ws)?new c(a.url,a.protocol):nh||sh?new dh(a.url,a.protocol,a.headers):(oh||rh)&&"undefined"!=typeof WebSocket&&WebSocket?new WebSocket(a.url,a.protocols):void 0),(this._isBrowser||this._isWorker)&&this._ws&&(this._ws.binaryType=this._binaryType),this._addWsListeners(),this._connectionTimeoutId=setTimeout(this._onTimeout.bind(this),l)}catch(e){throw this._connectLock=!1,e}var a,c}}))}_clearTimer(){clearTimeout(this._connectionTimeoutId),this._connectionTimeoutId=null}_clearPingTimer(){clearTimeout(this._pingPongTimeoutId),clearTimeout(this._reconnectTimeoutId),this._pingPongTimeoutId=null,this._reconnectTimeoutId=null}_debug(...e){this._options.debug&&console.log.apply(console,["FRONTIER>",...e])}_getIntervalValue(e){const{initReconnectInterval:t,maxReconnectInterval:i,reconnectIntervalGrowFactor:o}=this._options,s=t*Math.pow(o,e-1);return s>i?i:s}_ping(){if(this._ws&&this._ws.readyState===this.CONNECTING)return this._clearPingTimer(),void(this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval));this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send("hi"),this._reconnectTimeoutId=setTimeout(this._handleReconnectTimeout.bind(this),this._options.pingTimeoutInterval)):this._handleReconnect()}_handleReconnectTimeout(){var e,t;null===(e=this._pingLossCounter)||void 0===e||e.addCount(),this.emit("ping_once_timeout","timeout"),(null===(t=this._pingLossCounter)||void 0===t?void 0:t.checkReachMaxCount())?this._handleReconnect():this._ping()}_navigatorOnline(){return this._isMiniTT||this._isMiniWX?this._miniNavigatorOnline:!this._isBrowser&&!this._isWorker||!this._options.listenNetworkChanged||navigator.onLine}_handleReconnect(){var e,t;this._navigatorOnline()&&!this._readyClosed&&(null===(e=this._endpointManager)||void 0===e||e.resetEndpointConfig(),null===(t=this._pingLossCounter)||void 0===t||t.resetCounter(),this._ws?this._disconnect(1001,"going away, try reconnecting server",!0):this._connect())}_onPageNetWorkChange(){this._isMiniTT?tt.onNetworkStatusChange((({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()})):this._isMiniWX&&wx.onNetworkStatusChange((({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()}))}_wait(e){return new Promise((t=>{setTimeout(t,this._getIntervalValue(e))}))}_disconnect(e=1e3,t="",i=!1){this._ws&&this._destroyWebSocket(e,t,i)}_onTimeout(){var e;const t=null===(e=this._endpointManager)||void 0===e?void 0:e.getCurrentEndpoint();this._debug(`connect ${t} timeout`),this._disconnect(1001,"timeout, try reconnecting",!0)}_sendAck(e){const t=L_(e);this._ws&&this._ws.readyState===this.OPEN&&(this._ws&&this._ws.send(t),this._debug("send_ack",e))}_removeWsListeners(){this._ws&&(this._ws.removeEventListener("open",this._onOpen),this._ws.removeEventListener("close",this._onClose),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("error",this._onError))}_addWsListeners(){this._ws&&(this._ws.addEventListener("open",this._onOpen),this._ws.addEventListener("close",this._onClose),this._ws.addEventListener("message",this._onMessage),this._ws.addEventListener("error",this._onError))}_wsInstanceClose(e=1e3,t=""){try{this._ws&&this._ws.close(e,t)}catch(e){}}_destroyWebSocket(e=1e3,t="",i=!1){var o,s,n,r;if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,t),this._connectLock=!1,i&&this._navigatorOnline()&&!this._readyClosed){if(null===(o=this._endpointManager)||void 0===o?void 0:o.checkReachMaxTries()){const e=null===(s=this._endpointManager)||void 0===s?void 0:s.getCurrentEndpoint();this._dispatchCloseEvent(eh("close",{code:1006,reason:`connect ${e} timeout, max retries reached`,wasClean:!0}))}else{const i=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(eh("close",{code:e,reason:t,wasClean:!0,willReconnect:i})),i&&this._connect()}}else this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(eh("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(eh("close",{code:1006,reason:"going away, network offline"})),this._ws=null,null===(n=this._endpointManager)||void 0===n||n.resetEndpointConfig(),null===(r=this._pingLossCounter)||void 0===r||r.resetCounter()}_dispatchOpenEvent(e){this.emit("open",e),this.onopen&&this.onopen(e)}_dispatchMessageEvent(e){this.emit("message",e),this.onmessage&&this.onmessage(e)}_dispatchAckMessageEvent(e){this.emit("ack",e),this.onReceiveAck&&this.onReceiveAck(e)}_dispatchErrorEvent(e){this.emit("error",e),this.onerror&&this.onerror(e)}_dispatchCloseEvent(e){this.emit("close",e),this.onclose&&this.onclose(e)}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){var e;return(null===(e=this._endpointManager)||void 0===e?void 0:e.getCurrentEndpointTriesCount())||0}get bufferedAmount(){return this._messageQueue.reduce(((e,t)=>e+=t&&t.byteLength||0),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.automaticOpen?this.CONNECTING:this.CLOSED}get url(){return this._ws?this._ws.url:this._url}close(e=1e3,t){var i;this._readyClosed=!0,this._clearTimer(),this._clearPingTimer(),this._dropGlobalEventListener(),null===(i=this._QoSManager)||void 0===i||i.closeDB(),this._ws?this._ws.readyState!==this.CLOSED&&this._ws.readyState!==this.CLOSING?this._destroyWebSocket(e,t):this._debug("close, ws already closed"):this._debug("close, ws instance not initialized")}send(e,t){return n_(this,0,void 0,(function*(){if(null==e)throw new Error("please provide a valid data, data must be a string or an arraybuffer");"number"==typeof e&&(e=JSON.stringify(e)),"string"==typeof e||e instanceof ArrayBuffer||e.buffer&&e.buffer instanceof ArrayBuffer||(e=JSON.stringify(e));const i=yield hh(e),o=function(e){try{return"string"!=typeof e&&(e instanceof ArrayBuffer||e.buffer&&e.buffer instanceof ArrayBuffer)?"":"string"==typeof e?(JSON.parse(e),"application/json"):""}catch(t){return"string"==typeof e?"text/plain;charset=utf-8":""}}(e),{method:s=0,service:n=this._options.service,logID:r=this._options.logIDGenerator(),headers:a=this._options.headers,payloadEncoding:c=this._options.payloadEncoding,payloadType:d=this._options.payloadType,logIDNew:l=(this._options.logIDNewConfig.enableAutoGenerateLogIDNew?a_(this._options.logIDNewConfig.userIp):"")}=t||{};if(!n)throw new Error("please provide a valid service");const p={SeqID:D_.fromNumber(this._seqId++),LogID:D_.fromNumber(r),service:n,method:s,headers:a,payloadEncoding:c instanceof Object?c.encoding?c.encoding:"":c,payloadType:d instanceof Object?d.type?d.type:o:d||o,payload:i,LogIDNew:l},u=L_(p);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(u),this._debug("sent",p)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(u),this._debug("enqueue",p)):(this._messageQueue.shift(),this._messageQueue.push(u)),{seqID:this._seqId,logID:r,logIDNew:l}}))}reconnect(e){var t,i;return n_(this,0,void 0,(function*(){const{url:o}=e||{},s=Array.isArray(o)?o:"string"==typeof o?[o]:[];e&&Object.assign(this._options,e),s&&s.length?this._endpointManager=new ih(s,this._options.maxRetries):null===(t=this._endpointManager)||void 0===t||t.resetEndpointConfig(),null===(i=this._pingLossCounter)||void 0===i||i.resetCounter(this._options.pingLossCount),this._readyClosed=!1,this._ws&&this._ws.readyState!==this.CLOSED?this._disconnect(1e3,"manual reconnecting",!0):(this._isInit=!0,this._connect())}))}connect(){var e,t;return n_(this,0,void 0,(function*(){this._connectLock||(null===(e=this._endpointManager)||void 0===e||e.resetEndpointConfig(),null===(t=this._pingLossCounter)||void 0===t||t.resetCounter(),this._readyClosed=!1,this._isInit=!0,this._connect())}))}addEventListener(e,t){this.on(e,t)}dispatchEvent(e){const{type:t}=e;this.emit(t,e)}removeEventListener(e,t){this.off(e,t)}pingOnce(){return new Promise(((e,t)=>{this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);const i=()=>{e("success"),this.off("ping_once_success",i),this.off("ping_once_timeout",o)},o=()=>{t("timeout"),this.off("ping_once_success",i),this.off("ping_once_timeout",o)};this.on("ping_once_success",i),this.on("ping_once_timeout",o),this._ping()}))}}function im(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}class om extends w{constructor(e,t){super((e=>{const t=new URL(e);return t.searchParams.set("aid",Gu),t.toString()})(e),"pbbp2",{headers:{...t,Origin:"https://www.coze.cn"}})}}class sm{constructor(){sm.prototype.__init.call(this)}__init(){this.fws=null}connect(t,i,o){return new Promise(((s,n)=>{let r=!1,a=!1;const c=e=>{if(!a)return a=!0,void n(e);im([o,"optionalCall",t=>t(e)])},d={fpID:"1289",aID:Gu,accessKey:t.accessKey,deviceID:t.deviceId,url:"wss://frontier.coze.cn",automaticOpen:!0,enableQoS:!1,enableAutoAck:!1,ws:class extends om{constructor(e){super(e,t.headers)}}};this.fws=new tm(d);const l=setTimeout((()=>{a=!0,this.dispose(),n(new Error("Frontier connection timeout"))}),(p=t.timeoutMs,u=()=>1e4,null!=p?p:u()));var p,u;this.fws.onopen=()=>{r=!0,a=!0,clearTimeout(l),s()},this.fws.onerror=()=>{clearTimeout(l),c(new Error(r?"Frontier connection failed after connect":"Frontier connection failed"))},this.fws.onclose=()=>{clearTimeout(l),c(new Error(r?"Frontier connection closed after connect":"Frontier connection closed"))},this.fws.onmessage=t=>{const o=im([t,"access",e=>e.message,"optionalAccess",e=>e.payloadType]),s=im([t,"access",e=>e.message,"optionalAccess",e=>e.service]),n=im([t,"access",e=>e.message,"optionalAccess",e=>e.payload]);if(!o||!n)return;const r=new TextDecoder("utf-8").decode(n),a=e.safeJsonParse(r,r);i({service:s,event:o,data:a})}}))}dispose(){im([this,"access",e=>e.fws,"optionalAccess",e=>e.close,"call",e=>e()]),this.fws=null}}function nm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const rm=(e,t)=>{const i=t.toLowerCase(),o=Object.entries(e).find((([e])=>e.toLowerCase()===i));return nm([o,"optionalAccess",e=>e[1]])},am=e=>JSON.stringify({accessKey:e.accessKey,authorization:rm(e.headers,"authorization"),deviceId:e.deviceId,organizationId:e.organizationId,serviceId:e.serviceId,xTTEnv:rm(e.headers,"x-tt-env")}),cm=e=>"function"==typeof e.resolveConfig&&"string"==typeof e.scopeKey;class dm{__init(){this.entries=new Map}constructor(e){dm.prototype.__init.call(this),this.createClient=nm([e,"optionalAccess",e=>e.createClient])||(()=>new sm),this.getScopeKey=nm([e,"optionalAccess",e=>e.getScopeKey])||am}async subscribe(e,t){const i=((e,t)=>cm(e)?e.scopeKey:t(e))(e,this.getScopeKey);let o=this.entries.get(i);o||(o=this.createEntry(i,e),this.entries.set(i,o)),o.subscribers.add(t);try{await o.connectPromise}catch(e){throw o.subscribers.delete(t),e}let s=!1;return{release:()=>{s||(s=!0,this.releaseSubscriber(i,o,t))}}}createEntry(e,t){const i=this.createClient(),o={client:i,connectPromise:Promise.resolve(),subscribers:new Set};return o.connectPromise=(async e=>cm(e)?await e.resolveConfig():e)(t).then((async t=>{await i.connect(t,(t=>{this.emitEvent(e,t)}),(t=>{this.handleConnectionError(e,t)}))})).catch((t=>{throw this.entries.get(e)===o&&this.entries.delete(e),o.subscribers.clear(),i.dispose(),t})),o}emitEvent(e,t){const i=this.entries.get(e);if(i)for(const e of i.subscribers)e.onEvent(t)}handleConnectionError(e,t){const i=this.entries.get(e);if(!i)return;this.entries.delete(e);const o=[...i.subscribers];i.subscribers.clear(),i.client.dispose();for(const e of o)nm([e,"access",e=>e.onError,"optionalCall",e=>e(t)])}releaseSubscriber(e,t,i){t.subscribers.delete(i),t.subscribers.size>0||(this.entries.get(e)===t&&this.entries.delete(e),t.client.dispose())}}const lm=new dm;function pm(e,t){return null!=e?e:t()}function um(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const _m=e=>({...e,files:e.files?[...e.files]:void 0}),hm=e=>e?JSON.stringify(e.map((e=>({file_name:e.file_name,file_uri:e.file_uri,file_url:e.file_url,preview_url:e.preview_url})))):"";class mm{constructor(){mm.prototype.__init.call(this)}__init(){this.sessionStates=new Map}applyReplyEvent(t,i){const o=i.session_id;if(!o||!(e=>2===Number(e.source))(i))return null;const s=(({data:t,event:i})=>{const o=um([e.safeJsonParse(t.content,null),"optionalAccess",e=>e.message_data,"optionalAccess",e=>e.reply]),s=t.id,n="message"===i?um([o,"optionalAccess",e=>e.content])||t.content:um([o,"optionalAccess",e=>e.content]);return s&&n?{answerId:s,content:n,files:t.files,requestMessageId:um([o,"optionalAccess",e=>e.reply_to_message_id])}:null})({data:i,event:t});if(!s)return null;const n=this.getOrCreateSessionState(o),r=n.replies.get(s.answerId),a={answerId:s.answerId,content:"stream"===t&&r?r.content+s.content:s.content,files:pm(s.files,(()=>um([r,"optionalAccess",e=>e.files]))),requestMessageId:pm(s.requestMessageId,(()=>um([r,"optionalAccess",e=>e.requestMessageId])))};return"message"===t&&!r&&(({nextReply:e,sessionState:t})=>{for(const i of t.replies.values())if(i.requestMessageId===e.requestMessageId&&i.content===e.content&&hm(i.files)===hm(e.files))return!0;return!1})({nextReply:a,sessionState:n})?null:(n.replies.has(s.answerId)||n.replyOrder.push(s.answerId),n.replies.set(s.answerId,a),"stream"===t?{type:"reply_chunk",sessionId:o,source:"stream",chunk:{answerId:s.answerId,content:s.content,requestMessageId:s.requestMessageId}}:{type:"reply_update",sessionId:o,source:"message",reply:_m(a)})}applySessionIdleEvent(e){const t=um([e,"optionalAccess",e=>e.session_id]);if(!t||2!==Number(e.status))return null;const i=this.sessionStates.get(t);if(!i)return null;return{type:"session_idle",sessionId:t,replies:i.replyOrder.map((e=>i.replies.get(e))).filter((e=>Boolean(e))).map((e=>_m(e)))}}getOrCreateSessionState(e){const t=this.sessionStates.get(e);if(t)return t;const i={replies:new Map,replyOrder:[]};return this.sessionStates.set(e,i),i}}function gm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const fm=e=>({type:"progress_update",progress:e});class ym{constructor(){ym.prototype.__init.call(this)}__init(){this.progressStates=new Map}getKnownClawIds(){return this.progressStates.keys()}getKnownProgressEvents(e){const t=this.progressStates.get(e);return t?[...t.values()].map((t=>fm({progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:t.progressStatus}))):[]}applyFrontierEvent(e){const t=gm([e,"optionalAccess",e=>e.claw_id]),i=gm([e,"optionalAccess",e=>e.id]);if(!t||!i)return null;const o=2===Number(e.status)?"finished":1===Number(e.status)?"running":null;if(!o)return null;const s={progressId:i,clawId:t,name:e.name,progressType:e.type,progressStatus:o};return this.updateKnownProgressState(s),fm(s)}applySnapshot(e,t){const i=this.getOrCreateProgressState(e),o=new Set,s=[];t.forEach((t=>{o.add(t.progressId);const n={progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:t.progressStatus},r=i.get(t.progressId);i.set(t.progressId,n),((e,t)=>Boolean(e&&e.name===t.name&&e.progressType===t.progressType&&e.progressStatus===t.progressStatus))(r,n)||s.push(fm({progressId:n.progressId,clawId:e,name:n.name,progressType:n.progressType,progressStatus:n.progressStatus}))}));for(const t of[...i.values()])o.has(t.progressId)||(i.delete(t.progressId),s.push(fm({progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:"finished"})));return 0===i.size&&this.progressStates.delete(e),s}updateKnownProgressState(e){const t=this.getOrCreateProgressState(e.clawId);if("finished"===e.progressStatus)return t.delete(e.progressId),void(0===t.size&&this.progressStates.delete(e.clawId));t.set(e.progressId,{progressId:e.progressId,clawId:e.clawId,name:e.name,progressType:e.progressType,progressStatus:e.progressStatus})}getOrCreateProgressState(e){const t=this.progressStates.get(e);if(t)return t;const i=new Map;return this.progressStates.set(e,i),i}}class vm{__init(){this.progressPollTimers=new Map}__init2(){this.progressRefreshes=new Map}constructor({emitProgressUpdate:e,globalStreamKey:t,hasConnectionError:i,hasSubscribers:o,listProgresses:s,progressPollIntervalMs:n=3e4,progressStateStore:r}){vm.prototype.__init.call(this),vm.prototype.__init2.call(this),this.emitProgressUpdate=e,this.globalStreamKey=t,this.hasConnectionError=i,this.hasSubscribers=o,this.listProgresses=s,this.progressPollIntervalMs=n,this.progressStateStore=r}ensure(e){if(!this.listProgresses||this.progressPollTimers.has(e))return;const t=async()=>{if(this.progressPollTimers.delete(e),!this.hasSubscribers(e)||this.hasConnectionError())return;if(await this.refresh(e),!this.hasSubscribers(e)||this.hasConnectionError())return;const i=setTimeout((()=>{t()}),this.progressPollIntervalMs);this.progressPollTimers.set(e,i)},i=setTimeout((()=>{t()}),this.progressPollIntervalMs);this.progressPollTimers.set(e,i)}stop(e){const t=this.progressPollTimers.get(e);t&&(clearTimeout(t),this.progressPollTimers.delete(e))}stopAll(){for(const e of this.progressPollTimers.values())clearTimeout(e);this.progressPollTimers.clear()}async refresh(e){if(!this.listProgresses)return;const t=this.progressRefreshes.get(e);if(t)return void await t;const i=(async()=>{const{listProgresses:t}=this;if(!t)return;const i=await t(e);this.progressStateStore.applySnapshot(e,i).forEach((t=>{this.emitProgressUpdate(e,t),this.emitProgressUpdate(this.globalStreamKey,t)}))})().finally((()=>{this.progressRefreshes.delete(e)}));this.progressRefreshes.set(e,i),await i}}class wm{__init(){this.closed=!1}__init2(){this.error=null}__init3(){this.queue=[]}constructor(e){this.cleanup=e,wm.prototype.__init.call(this),wm.prototype.__init2.call(this),wm.prototype.__init3.call(this)}push(e){if(!this.closed){if(this.pending){const{pending:t}=this;return this.pending=void 0,void t.resolve({done:!1,value:e})}this.queue.push(e)}}close(){if(!this.closed&&(this.closed=!0,this.cleanup(),this.pending)){const{pending:e}=this;this.pending=void 0,e.resolve({done:!0,value:void 0})}}fail(e){if(!this.closed&&(this.closed=!0,this.error=e,this.queue.length=0,this.cleanup(),this.pending)){const{pending:t}=this;this.pending=void 0,t.reject(e)}}async next(){if(this.queue.length>0){return{done:!1,value:this.queue.shift()}}if(this.error)throw this.error;return this.closed?{done:!0,value:void 0}:await new Promise(((e,t)=>{this.pending={reject:t,resolve:e}}))}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}}function bm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const Sm="*";class Pm{__init(){this.connectionError=null}__init2(){this.disposed=!1}__init3(){this.replyStateStore=new mm}__init4(){this.progressStateStore=new ym}__init5(){this.sessionStreams=new Map}__init6(){this.progressStreams=new Map}constructor(e){Pm.prototype.__init.call(this),Pm.prototype.__init2.call(this),Pm.prototype.__init3.call(this),Pm.prototype.__init4.call(this),Pm.prototype.__init5.call(this),Pm.prototype.__init6.call(this),this.connectionManager=bm([e,"optionalAccess",e=>e.connectionManager])||(bm([e,"optionalAccess",e=>e.client])?new dm({createClient:()=>e.client}):lm),this.progressPoller=new vm({emitProgressUpdate:(e,t)=>{this.emitToProgress(e,t)},globalStreamKey:Sm,hasConnectionError:()=>Boolean(this.connectionError),hasSubscribers:e=>this.hasProgressSubscribers(e),listProgresses:bm([e,"optionalAccess",e=>e.listProgresses]),progressPollIntervalMs:bm([e,"optionalAccess",e=>e.progressPollIntervalMs]),progressStateStore:this.progressStateStore})}async connect(e){if(this.disposed)throw new Error("Frontier watcher disposed");if(this.lastConnectionRequest=e,this.connectionLease)return;this.connecting||(this.connecting=this.connectionManager.subscribe(e,{onError:e=>{this.handleConnectionError(e)},onEvent:e=>{this.handleEvent(e)}}).then((e=>(this.connectionLease=e,this.connectionError=null,e))).finally((()=>{this.connecting=void 0})));const t=await this.connecting;this.disposed&&(t.release(),this.connectionLease=void 0)}async ensureConnected(){if(this.connectionLease||this.connecting)await this.connecting;else{if(!this.lastConnectionRequest){if(this.connectionError)throw this.connectionError;throw new Error("Frontier watcher is not connected")}await this.connect(this.lastConnectionRequest)}}watchSession(e,t){const i=new wm((()=>{this.removeStream(e,i),bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.removeEventListener,"call",e=>e("abort",o)])})),o=()=>{i.close()};if(this.disposed)return i.fail(new Error("Frontier watcher disposed")),i;if(this.connectionError)return i.fail(this.connectionError),i;if(bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.aborted]))return i.close(),i;let s=this.sessionStreams.get(e);return s||(s=new Set,this.sessionStreams.set(e,s)),s.add(i),bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.addEventListener,"call",e=>e("abort",o,{once:!0})]),i}watchProgress(e,t){const i=e||Sm,o=new wm((()=>{this.removeProgressStream(i,o),bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.removeEventListener,"call",e=>e("abort",s)])})),s=()=>{o.close()};if(this.disposed)return o.fail(new Error("Frontier watcher disposed")),o;if(this.connectionError)return o.fail(this.connectionError),o;if(bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.aborted]))return o.close(),o;let n=this.progressStreams.get(i);if(n||(n=new Set,this.progressStreams.set(i,n)),n.add(o),bm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.addEventListener,"call",e=>e("abort",s,{once:!0})]),e)this.emitKnownProgresses(o,e),this.progressPoller.refresh(e),this.progressPoller.ensure(e);else for(const e of this.progressStateStore.getKnownClawIds())this.emitKnownProgresses(o,e);return o}dispose(){if(!this.disposed){if(this.disposed=!0,this.progressPoller.stopAll(),this.failAllStreams(new Error("Frontier watcher disposed")),this.connectionLease)return this.connectionLease.release(),void(this.connectionLease=void 0);this.connecting&&this.connecting.then((e=>{e.release(),this.connectionLease===e&&(this.connectionLease=void 0)})).catch((()=>{}))}}removeStream(e,t){const i=this.sessionStreams.get(e);i&&(i.delete(t),0===i.size&&this.sessionStreams.delete(e))}removeProgressStream(e,t){const i=this.progressStreams.get(e);i&&(i.delete(t),0===i.size&&(this.progressStreams.delete(e),e!==Sm&&this.progressPoller.stop(e)))}failAllStreams(e){for(const t of this.sessionStreams.values())for(const i of t)i.fail(e);this.sessionStreams.clear();for(const t of this.progressStreams.values())for(const i of t)i.fail(e);this.progressStreams.clear()}handleConnectionError(e){this.connectionError=e,this.connectionLease=void 0,this.progressPoller.stopAll(),this.failAllStreams(e)}handleEvent(e){33555657===e.service&&("message"!==e.event&&"stream"!==e.event?"session"!==e.event?"process"===e.event&&this.handleProgressEvent(e.data):this.handleSessionEvent(e.data):this.handleReplyEvent(e.event,e.data))}handleReplyEvent(e,t){const i=this.replyStateStore.applyReplyEvent(e,t);i&&"sessionId"in i&&this.emitToSession(i.sessionId,i)}handleSessionEvent(e){const t=this.replyStateStore.applySessionIdleEvent(e);t&&"sessionId"in t&&this.emitToSession(t.sessionId,t)}handleProgressEvent(e){const t=this.progressStateStore.applyFrontierEvent(e);if(!t)return;const{clawId:i}=t.progress;this.emitToProgress(i,t),this.emitToProgress(Sm,t)}emitToSession(e,t){const i=this.sessionStreams.get(e);if(i&&0!==i.size)for(const e of i)e.push(t)}emitToProgress(e,t){const i=this.progressStreams.get(e);if(i&&0!==i.size)for(const e of i)e.push(t)}emitKnownProgresses(e,t){this.progressStateStore.getKnownProgressEvents(t).forEach((t=>{e.push(t)}))}hasProgressSubscribers(e){const t=this.progressStreams.get(e);return Boolean(t&&t.size>0)}}function Cm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const Tm=({replies:e,requestMessageId:t,source:i})=>{if(0===e.length)return null;const o=Cm([e,"access",t=>t[e.length-1],"optionalAccess",e=>e.answerId]);return o?{answerId:o,content:e.map((e=>e.content)).filter(Boolean).join("\n\n"),files:Cm([e,"access",t=>t[e.length-1],"optionalAccess",e=>e.files]),requestMessageId:t,source:i}:null},Em=({replies:e,replyOrder:t,reply:i})=>{e.has(i.answerId)||t.push(i.answerId),e.set(i.answerId,i)},km=({event:e,replies:t,replyOrder:i})=>{const o=t.get(e.chunk.answerId),s={answerId:e.chunk.answerId,content:`${Cm([o,"optionalAccess",e=>e.content])||""}${e.chunk.content}`,files:Cm([o,"optionalAccess",e=>e.files]),requestMessageId:e.chunk.requestMessageId||Cm([o,"optionalAccess",e=>e.requestMessageId])};return Em({replies:t,reply:s,replyOrder:i}),s},Im=({event:e,replies:t,replyOrder:i})=>(Em({replies:t,reply:e.reply,replyOrder:i}),e.reply);class Am{constructor(e){this.watcher=Cm([e,"optionalAccess",e=>e.watcher])||new Pm}async connect(e){await this.watcher.connect(e)}async waitForReply(e){const{onReplyChunk:t,onReplyUpdate:i,sessionId:o,requestMessageId:s,timeoutMs:n}=e;if(this.pending)throw new Error("Frontier waiter already has a pending reply request");await this.watcher.ensureConnected();const r=new AbortController;return await new Promise(((e,a)=>{const c=new Map,d=[];let l=!1;const p=t=>{l||(l=!0,Cm([this,"access",e=>e.pending,"optionalAccess",e=>e.timer])&&clearTimeout(this.pending.timer),this.pending=void 0,r.abort(),t({reject:a,resolve:e}))},u=void 0===n?void 0:setTimeout((()=>{const e=Tm({replies:d.map((e=>c.get(e))).filter((e=>Boolean(e))),requestMessageId:s,source:"timeout"});p((({reject:t,resolve:i})=>{e?i(e):t(new Error("Timed out waiting for Frontier reply"))}))}),n);this.pending={controller:r,reject:a,timer:u},(async()=>{try{const e=(async()=>{for await(const e of this.watcher.watchSession(o,{signal:r.signal})){if("reply_chunk"===e.type){if(e.chunk.requestMessageId!==s)continue;km({event:e,replies:c,replyOrder:d}),Cm([t,"optionalCall",t=>t(e)]);continue}if("reply_update"===e.type){if(e.reply.requestMessageId!==s)continue;Im({event:e,replies:c,replyOrder:d}),Cm([i,"optionalCall",t=>t(e)]);continue}if("session_idle"!==e.type)continue;const o=Tm({replies:e.replies.filter((e=>e.requestMessageId===s)),requestMessageId:s,source:"idle"});o&&p((({resolve:e})=>{e(o)}))}})();await e}catch(e){p((({reject:t})=>{t(e instanceof Error?e:new Error(String(e)))}))}})()}))}dispose(){this.pending&&(this.pending.timer&&clearTimeout(this.pending.timer),this.pending.controller.abort(),this.pending.reject(new Error("Frontier waiter disposed")),this.pending=void 0),this.watcher.dispose()}}const jm={skipOrgCheck:!0,skipSpaceCheck:!0},Rm=async t=>{if(t)return t;const i=s.createSessionConfigStore(),o=await i.get();if(o.sessionId)return o.sessionId;throw new e.CozeError(e.ErrorCode.E1000,"Missing session ID: provide --session-id or run `coze session create` first")},zm=async({clawId:e,sessionId:t})=>{const i=s.createSessionConfigStore();await i.save({sessionId:t,...e?{sessionClawId:e}:{}})},Um=({timeoutMs:e})=>{const t=new AbortController,i=()=>{t.abort()},o=void 0===e?void 0:setTimeout((()=>{i()}),e);return process.once("SIGINT",i),{abort:i,signal:t.signal,dispose:()=>{o&&clearTimeout(o),process.off("SIGINT",i)}}},Lm=async(t,i)=>{const o=(t=>{const i=t.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");return{ctx:i,service:s.createDefaultSessionService(i.config)}})(t);try{await i(o)}catch(t){V((t=>{if(t instanceof e.CozeError)return t;if(t instanceof s.SessionServiceError){const i="SESSION_AUTH_INVALID"===t.code?e.ErrorCode.E2001:e.ErrorCode.E5000;return new e.CozeError(i,t.message,{session_error:t.code})}return t instanceof Error?new e.CozeError(e.ErrorCode.E5000,t.message,t.stack):new e.CozeError(e.ErrorCode.E5000,String(t))})(t),o.ctx)}},Om=t=>{const i=Number.parseInt(t,10);if(!Number.isFinite(i)||i<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --limit: expected a positive integer");return i},xm=t=>{const i=Number.parseInt(t,10);if(!Number.isFinite(i)||i<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --timeout: expected a positive integer");return i},Bm=e=>{if(!e||0===e.length)return null;const t=["Files:"];return e.forEach(((e,i)=>{t.push(`${i+1}. ${String(e.file_name||"unnamed-file")}`),e.file_url&&t.push(`file_url: ${String(e.file_url)}`),e.preview_url&&t.push(`preview_url: ${String(e.preview_url)}`)})),t.join("\n")},qm=(e,t)=>{const i=Bm(t);return i?[e,"",i].join("\n"):e},Dm=({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,xTTEnv:n})=>{const r=o||t,a=(({accessToken:e,xTTEnv:t})=>{if(!e)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const i={Authorization:`Bearer ${e}`};return t&&(i["x-use-ppe"]="1",i["x-tt-env"]=t),i})({accessToken:e,xTTEnv:n});return{resolveConfig:async()=>({...await Fu({baseUrl:r,headers:a,xTTEnv:n}),headers:a,organizationId:i}),scopeKey:JSON.stringify({baseUrl:r,authorization:a.Authorization,organizationId:i,xTTEnv:n})}},Mm=async({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,progressPollIntervalMs:s,service:n,xTTEnv:r})=>{const a=new Pm({listProgresses:n?async e=>(await n.listProgresses({clawId:e})).map((t=>({progressId:t.progressId,clawId:e,name:t.name,progressType:t.type,progressStatus:t.progressStatus}))):void 0,progressPollIntervalMs:s});return await a.connect(Dm({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,xTTEnv:r})),a},Nm=e=>[`progress_id: ${e.progressId}`,e.name?`name: ${e.name}`:null,e.type?`type: ${e.type}`:null,`progress_status: ${e.progressStatus}`].filter(Boolean).join("\n"),Gm=e=>`${JSON.stringify(e)}\n`;class $m{__init(){this.replyStates=new Map}__init2(){this.requestPrintedContent=new Map}__init3(){this.endsWithNewline=!0}__init4(){this.hasStartedReply=!1}constructor(e){$m.prototype.__init.call(this),$m.prototype.__init2.call(this),$m.prototype.__init3.call(this),$m.prototype.__init4.call(this),this.format=e.format,this.includeReplyMetadata=e.includeReplyMetadata||!1,this.write=e.write||(e=>process.stdout.write(e))}writeChunk({chunk:e,sessionId:t}){if("text"!==this.format)return void this.write(Gm({type:"reply_chunk",session_id:t,answer_message_id:e.answerId,reply_to_message_id:e.requestMessageId,delta:e.content}));const i=this.getOrCreateReplyState(e.answerId);this.ensureReplyStarted({answerId:e.answerId,requestMessageId:e.requestMessageId,state:i}),this.writeRaw(e.content),i.printedContent+=e.content,this.updateRequestPrintedContent({requestMessageId:e.requestMessageId,printedContent:i.printedContent})}writeReply({files:e,reply:t,sessionId:i,source:o}){if("text"!==this.format)return void this.write(Gm({type:"message"===o?"reply_update":"reply_completed",session_id:i,answer_message_id:t.answerId,reply_to_message_id:t.requestMessageId,content:t.content,files:e,event_source:o}));const s=this.getOrCreateReplyState(t.answerId),n=this.getPreviousPrintedContent({reply:t,state:s}),r=this.getSnapshotDelta({nextContent:t.content,previousContent:n}),a=this.continuesPrintedRequest({reply:t,state:s});if(!r&&"message"!==o)return this.updateReplyStateContent({reply:t,state:s}),void this.writeFinalReplyMetadata({files:e});this.ensureReplyStarted({answerId:t.answerId,requestMessageId:t.requestMessageId,state:s,continuesPrintedRequest:a}),r&&this.writeRaw(r),this.updateReplyStateContent({reply:t,state:s}),"message"!==o&&this.writeFinalReplyMetadata({files:e})}writeFinalReplyMetadata({files:e}){this.endsWithNewline||this.writeRaw("\n");const t=Bm(e);t&&this.writeRaw(`\n${t}\n`)}writeProgress({progress:e,sessionId:t}){"text"===this.format?(this.endsWithNewline||this.writeRaw("\n"),this.writeRaw(`\n${Nm(e)}\n`)):this.write(Gm({type:"background_progress_started",session_id:t,progress_id:e.progressId,progress_name:e.name,progress_type:e.type,progress_status:e.progressStatus}))}getOrCreateReplyState(e){const t=this.replyStates.get(e);if(t)return t;const i={headerPrinted:!1,printedContent:""};return this.replyStates.set(e,i),i}ensureReplyStarted({answerId:e,continuesPrintedRequest:t=!1,requestMessageId:i,state:o}){if(!o.headerPrinted){if(t)return o.headerPrinted=!0,void(this.hasStartedReply=!0);if(this.hasStartedReply&&(this.endsWithNewline||this.writeRaw("\n"),this.writeRaw("\n")),this.includeReplyMetadata){const t=[`answer_message_id: ${e}`,i?`reply_to_message_id: ${i}`:null].filter(Boolean);this.writeRaw(`${t.join("\n")}\n`)}o.headerPrinted=!0,this.hasStartedReply=!0}}getSnapshotDelta({nextContent:e,previousContent:t}){return t?e===t?"":e.startsWith(t)?e.slice(t.length):`\n${e}`:e}getPreviousPrintedContent({reply:e,state:t}){return e.requestMessageId&&this.requestPrintedContent.has(e.requestMessageId)?this.requestPrintedContent.get(e.requestMessageId)||"":t.printedContent}continuesPrintedRequest({reply:e,state:t}){return Boolean(e.requestMessageId&&!t.headerPrinted&&this.requestPrintedContent.has(e.requestMessageId))}updateReplyStateContent({reply:e,state:t}){t.printedContent=e.content,this.updateRequestPrintedContent({requestMessageId:e.requestMessageId,printedContent:e.content})}updateRequestPrintedContent({printedContent:e,requestMessageId:t}){if(!t)return;const i=this.requestPrintedContent.get(t)||"";e.length>=i.length&&this.requestPrintedContent.set(t,e)}writeRaw(e){e&&(this.write(e),this.endsWithNewline=e.endsWith("\n"))}}function Fm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const Vm=({ctx:e,sessionId:t,reply:i,files:o,source:s})=>{"text"!==e.format?e.response.print({session_id:t,answer_message_id:i.answerId,reply_to_message_id:i.requestMessageId,content:i.content,files:o,event_source:s}):e.response.print((({reply:e,files:t,source:i})=>`${[`answer_message_id: ${e.answerId}`,e.requestMessageId?`reply_to_message_id: ${e.requestMessageId}`:null,`event_source: ${i}`].filter(Boolean).join("\n")}\n${qm(e.content,t)}`)({files:o,reply:i,source:s}))},Wm=({ctx:e,options:t,service:i,streamRenderer:o})=>{const n=t.snapshot?new Map:null,r=async t=>await s.resolveStoredSessionReplyFiles({files:t.files,apiBaseUrl:e.config.apiBaseUrl,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv,service:i}),a=async({reply:i,source:o})=>{const s=await r(i),a=(({files:e,reply:t})=>JSON.stringify({answerId:t.answerId,content:t.content,files:e,requestMessageId:t.requestMessageId}))({files:s,reply:i});Fm([n,"optionalAccess",e=>e.get,"call",e=>e(i.answerId)])!==a&&(Fm([n,"optionalAccess",e=>e.set,"call",e=>e(i.answerId,a)]),Vm({ctx:e,files:s,reply:i,sessionId:t.sessionId,source:o}))};return{handleReplyChunk:e=>{Fm([o,"optionalAccess",e=>e.writeChunk,"call",i=>i({chunk:e.chunk,sessionId:t.sessionId})])},handleReplyUpdate:async e=>{o?o.writeReply({reply:e.reply,sessionId:t.sessionId,source:"message"}):await a({reply:e.reply,source:"message"})},handleIdleReply:async e=>{o?o.writeReply({files:await r(e),reply:e,sessionId:t.sessionId,source:"idle"}):await a({reply:e,source:"idle"})}}},Hm=e=>{e.command("watch").description("Watch websocket replies for a claw session").option("-s, --session-id <sessionId>","Target session ID; defaults to the most recently used local session").option("--timeout <timeoutMs>","Stop watching after the specified timeout in milliseconds",xm).option("--snapshot","Print full reply snapshots instead of streaming chunks incrementally").config({...jm,help:{brief:"Continuously watch websocket replies for a session",description:"Subscribe to Frontier websocket events for the specified session and stream assistant output as it arrives. Use --snapshot to keep the previous snapshot-style behavior.",examples:[{desc:"Watch one session until interrupted",cmd:"coze session watch -s 123456789",tags:["[RECOMMENDED]"]},{desc:"Watch one session and exit after 30 seconds",cmd:"coze session watch -s 123456789 --timeout 30000"},{desc:"Keep the old snapshot-style output",cmd:"coze session watch -s 123456789 --snapshot"}],schema:{input:{session_id:{type:"string",required:!1,description:"Target session ID. Defaults to the most recently used local session"},timeout:{type:"number",required:!1,description:"Optional timeout in milliseconds"}},output:{type:"object",properties:{session_id:{type:"string"},answer_message_id:{type:"string"},reply_to_message_id:{type:"string"},content:{type:"string"},event_source:{type:"string"}}}}}}).action((async(e,t)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await Rm(e.sessionId),s={...e,sessionId:o},n=await Mm({accessToken:t.config.accessToken,apiBaseUrl:t.config.apiBaseUrl,organizationId:t.config.organizationId,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv});await zm({sessionId:o});const r=s.snapshot?null:new $m({format:t.format,includeReplyMetadata:"text"===t.format}),a=Um({timeoutMs:s.timeout}),c=Wm({ctx:t,options:s,service:i,streamRenderer:r});try{for await(const e of n.watchSession(o,{signal:a.signal}))if("reply_chunk"!==e.type)if("reply_update"!==e.type){if("progress_update"!==e.type){await i.updateSessionRuntimeStatus({sessionId:o,status:"idle"});for(const t of e.replies)await c.handleIdleReply(t)}}else await c.handleReplyUpdate(e);else c.handleReplyChunk(e)}finally{a.dispose(),n.dispose()}}))})(e,t)}))};function Jm(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const Km=async e=>await new Promise((t=>setTimeout(t,e))),Qm=e=>{const t=e.contentPreview&&e.contentPreview!==e.replyContent?e.contentPreview:void 0,i=e.resultSummary&&e.resultSummary!==e.replyContent&&e.resultSummary!==e.contentPreview?e.resultSummary:void 0;return{contentPreview:t,replyContent:e.replyContent,resultSummary:i}},Ym=e=>{const t=Qm(e);return{answer_message_id:e.answerMessageId,artifacts:Jm([e,"access",e=>e.artifacts,"optionalAccess",e=>e.map,"call",e=>e((e=>({file_name:e.fileName,file_uri:e.fileUri,file_url:e.fileUrl,preview_url:e.previewUrl})))]),content_preview:t.contentPreview,created_at:e.createdAt,finished_at:e.finishedAt,kind:e.kind,last_progress_status:e.lastProgressStatus,last_refresh_error:e.lastRefreshError,message_id:e.messageId,progress_id:e.progressId,reply_content:t.replyContent,result_summary:t.resultSummary,session_id:e.sessionId,status:e.status,task_id:e.taskId,updated_at:e.updatedAt,worker_pid:e.workerPid}},Zm=e=>{const t=Qm(e);return[`task_id: ${e.taskId}`,`status: ${e.status}`,`session_id: ${e.sessionId}`,`message_id: ${e.messageId}`,`progress_id: ${e.progressId}`,e.answerMessageId?`answer_message_id: ${e.answerMessageId}`:null,t.contentPreview?`content_preview: ${t.contentPreview}`:null,t.replyContent?`reply_content: ${t.replyContent}`:null,t.resultSummary?`result_summary: ${t.resultSummary}`:null,e.lastProgressStatus?`last_progress_status: ${e.lastProgressStatus}`:null,e.lastRefreshError?`last_refresh_error: ${e.lastRefreshError}`:null,`created_at: ${e.createdAt}`,`updated_at: ${e.updatedAt}`,e.finishedAt?`finished_at: ${e.finishedAt}`:null].filter(Boolean).join("\n")},Xm=({ctx:e,task:t})=>{"text"!==e.format?e.response.print(Ym(t)):e.response.print(Zm(t))},eg=t=>t instanceof s.SessionTaskExpiredError||t instanceof s.SessionTaskNotFoundError?new e.CozeError(e.ErrorCode.E3000,t.message,{task_id:t.taskId}):t instanceof s.SessionTaskStoreError?new e.CozeError(e.ErrorCode.E5000,t.message):t instanceof Error?t:new e.CozeError(e.ErrorCode.E5000,String(t)),tg=e=>{const t=e.command("task").description("Inspect persisted session background tasks").config({...jm,help:{brief:"Inspect session background tasks",description:"List, show, refresh, watch, and garbage-collect persisted session progress tasks created from `coze session message --wait`."}});t.command("list").description("List persisted session tasks").option("--status <status>","Filter by task status").option("--session-id <sessionId>","Filter by session ID").option("--include-expired","Include expired terminal tasks").action((async(e,t)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{try{const o=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:i,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await o.listTasks({includeExpired:Boolean(e.includeExpired),sessionId:e.sessionId,status:e.status});if("text"===t.format)return void t.response.print(n.length>0?n.map(Zm).join("\n\n"):"No session tasks");t.response.print({items:n.map((e=>Ym(e)))})}catch(e){throw eg(e)}}))})(e,t)})),t.command("show <taskId>").description("Show one persisted session task snapshot").option("--include-expired","Read an expired task record").action((async(e,t,i)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{try{const o=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:i,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await o.getTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});Xm({ctx:t,task:n})}catch(e){throw eg(e)}}))})({includeExpired:t.includeExpired,taskId:e},i)})),t.command("refresh <taskId>").description("Refresh one persisted session task against the server").option("--include-expired","Read an expired task record").action((async(e,t,i)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{try{const o=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:i,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await o.refreshTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});Xm({ctx:t,task:n})}catch(e){throw eg(e)}}))})({includeExpired:t.includeExpired,taskId:e},i)})),t.command("watch <taskId>").description("Watch one persisted session task until it reaches a terminal state").option("--include-expired","Read an expired task record").option("--timeout <timeoutMs>","Stop watching after the specified timeout in milliseconds",xm).action((async(e,t,i)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{try{const o=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:i,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv});let n=await o.getTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});if(Xm({ctx:t,task:n}),s.isSessionTaskTerminal(n.status))return;const r=void 0===e.timeout?void 0:Date.now()+e.timeout;for(;;){const i=void 0===r?1e4:Math.min(1e4,r-Date.now());if(i<=0)return;if(await Km(i),n=await o.refreshTask(e.taskId,{includeExpired:Boolean(e.includeExpired)}),Xm({ctx:t,task:n}),s.isSessionTaskTerminal(n.status))return}}catch(e){throw eg(e)}}))})({includeExpired:t.includeExpired,taskId:e,timeout:t.timeout},i)})),t.command("gc").description("Remove expired terminal session tasks from local storage").action((async(e,t)=>{await(async e=>{await Lm(e,(async({ctx:e,service:t})=>{try{const i=s.createSessionTaskService({apiBaseUrl:e.config.apiBaseUrl,service:t,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv}),o=await i.gcTasks();if("text"===e.format)return void e.response.print(o.length>0?`Removed ${o.length} expired task(s)`:"No expired session tasks");e.response.print({count:o.length,items:o.map((e=>Ym(e)))})}catch(e){throw eg(e)}}))})(t)}))},ig=e=>`${[`message_id: ${e.messageId}`,e.replyToMessageId?`reply_to_message_id: ${e.replyToMessageId}`:null,e.messageType?`message_type: ${e.messageType}`:null,e.createTime?`create_time: ${e.createTime}`:null].filter(Boolean).join("\n")}\n${qm(e.content,e.files)}`,og=async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await Rm(e.sessionId),n=await i.listRepliesByMessage({sessionId:o,messageId:e.messageId});await zm({sessionId:n.sessionId});const r=s.createSessionConfigStore(),a=await r.get(),c=n.items.some((e=>e.files&&e.files.length>0)),d=c?a.sessionClawId||(await i.getStatus()).clawId:void 0,l=c?await(async({items:e,store:t,service:i,clawId:o,apiBaseUrl:n,sessionApiBaseUrl:r,xTTEnv:a})=>await Promise.all(e.map((async e=>({...e,files:await s.resolveStoredSessionReplyFiles({files:e.files,clawId:o,apiBaseUrl:n,sessionApiBaseUrl:r,xTTEnv:a,service:i,deps:{store:t}})})))))({items:n.items,store:r,service:i,clawId:d,apiBaseUrl:t.config.apiBaseUrl,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}):n.items;if("text"===t.format)return n.requestMessageFound||0!==l.length?0===l.length?void t.response.print(`No replies found for message: ${e.messageId}`):void t.response.print(l.map(ig).join("\n\n")):void t.response.print(`Message not found: ${e.messageId}`);t.response.print({session_id:n.sessionId,message_id:n.requestMessageId,request_message_found:n.requestMessageFound,count:l.length,items:l.map((e=>({message_id:e.messageId,reply_to_message_id:e.replyToMessageId,source:e.source,message_type:e.messageType,content:e.content,files:e.files,create_time:e.createTime,raw:e.raw})))})}))};function sg(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const ng=({ctx:e})=>{const t=new Map;return i=>{const o=t.get(i.progressId);o&&o.progressStatus===i.progressStatus&&o.name===i.name&&o.type===i.type&&"snapshot"!==i.eventSource||(t.set(i.progressId,{name:i.name,progressId:i.progressId,progressStatus:i.progressStatus,type:i.type}),(({ctx:e,progress:t})=>{"text"!==e.format?e.response.print({progress_id:t.progressId,name:t.name,type:t.type,progress_status:t.progressStatus,event_source:t.eventSource}):e.response.print(`${Nm(t)}\nevent_source: ${t.eventSource}`)})({ctx:e,progress:i}))}},rg=(e,t)=>!t||e.progressId===t,ag=async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{(({ctx:e,progresses:t})=>{"text"!==e.format?e.response.print({items:t.map((e=>({progress_id:e.progressId,name:e.name,type:e.type,progress_status:e.progressStatus,raw:e.raw})))}):e.response.print(t.length>0?t.map((e=>Nm(e))).join("\n\n"):"No active progress")})({ctx:t,progresses:await i.listProgresses({size:e.size})})}))},cg=async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await i.getStatus(),{clawId:n}=o;if(!o.authValid||!n)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const r=await Mm({accessToken:t.config.accessToken,apiBaseUrl:t.config.apiBaseUrl,organizationId:t.config.organizationId,progressPollIntervalMs:3e4,sessionApiBaseUrl:t.config.sessionApiBaseUrl,service:i,xTTEnv:t.config.xTTEnv}),a=Um({timeoutMs:e.timeout}),c=ng({ctx:t});try{await(async({clawId:e,emitProgress:t,options:i,service:o})=>{(await o.listProgresses({clawId:e})).filter((e=>rg(e,i.progressId))).forEach((e=>{t({...e,eventSource:"snapshot"})}))})({clawId:n,emitProgress:c,options:e,service:i}),await(async({abortScope:e,clawId:t,emitProgress:i,options:o,watcher:s})=>{for await(const n of s.watchProgress(t,{signal:e.signal}))rg(n.progress,o.progressId)&&(i({progressId:n.progress.progressId,name:n.progress.name,type:n.progress.progressType,progressStatus:n.progress.progressStatus,eventSource:"websocket"}),o.progressId&&"finished"===n.progress.progressStatus&&e.abort())})({abortScope:a,clawId:n,emitProgress:c,options:e,watcher:r})}finally{a.dispose(),r.dispose()}}))},dg=e=>{const t=e.command("progress").description("Inspect claw background progress").config({...jm,help:{brief:"Inspect claw background progress",description:"List and watch claw process-style background progress driven by websocket and process APIs."}});t.command("list").description("List current background progress").option("--size <size>","Maximum number of progress items to request",Om,100).action(ag),t.command("show <progressId>").description("Show one background progress snapshot").action((async(e,t,i)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await i.getProgress({progressId:e.progressId});"text"!==t.format?t.response.print({progress_id:e.progressId,found:Boolean(o),name:sg([o,"optionalAccess",e=>e.name]),type:sg([o,"optionalAccess",e=>e.type]),progress_status:sg([o,"optionalAccess",e=>e.progressStatus]),raw:sg([o,"optionalAccess",e=>e.raw])}):t.response.print(o?Nm(o):`Progress not found: ${e.progressId}`)}))})({progressId:e},i)})),t.command("poll <progressId>").description("Poll one background progress and treat missing as finished").action((async(e,t,i)=>{await(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await i.getProgress({progressId:e.progressId}),s=sg([o,"optionalAccess",e=>e.progressStatus])||"finished";"text"!==t.format?t.response.print({progress_id:e.progressId,name:sg([o,"optionalAccess",e=>e.name]),type:sg([o,"optionalAccess",e=>e.type]),progress_status:s,raw:sg([o,"optionalAccess",e=>e.raw])}):t.response.print(Nm({progressId:e.progressId,name:sg([o,"optionalAccess",e=>e.name]),type:sg([o,"optionalAccess",e=>e.type]),progressStatus:s}))}))})({progressId:e},i)})),t.command("watch [progressId]").description("Watch one or all background progress updates").option("--timeout <timeoutMs>","Stop watching after the specified timeout in milliseconds",xm).action((async(e,t,i)=>{await cg({progressId:e,timeout:t.timeout},i)}))};function lg(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const pg={...jm,help:{brief:"Send a text message to a session",description:"Send a plain text message to the specified claw session. The message can be provided as a positional argument or via stdin. Use @<path> to mention and upload local files as attachments. With --wait, the CLI streams the current turn reply until the session becomes idle. If a new background progress starts within 3 seconds after idle, the CLI returns its progress_id instead of waiting for the background task to finish.",examples:[{desc:"Send a message to a session",cmd:'coze session message "hello" -s 123456789',tags:["[RECOMMENDED]"]},{desc:"Send stdin as the message body",cmd:"cat prompt.txt | coze session message -s 123456789"},{desc:"Wait for the streaming reply until the turn becomes idle",cmd:'coze session message "hello" -s 123456789 --wait'},{desc:"Upload local files and send them with the query",cmd:'coze session message "summarize these" -s 123456789 --file ./a.pdf --file ./b.png'},{desc:"Mention a local file with @ and send it as an attachment",cmd:'coze session message "summarize @docs/notes.md" -s 123456789'},{desc:"Use a podcast voice and inject the voice instruction into the message",cmd:'coze session message "@播客 制作一个介绍潮汕美食的播客" -s 123456789 --podcast-voice "鸡汤女生"'}],schema:{input:{message:{type:"string",required:!1,description:"Plain text message content"},session_id:{type:"string",required:!1,description:"Target session ID. Defaults to the most recently used local session"},file:{type:"array",required:!1,description:"Local file paths to upload and attach"},wait:{type:"boolean",required:!1,description:"Wait for idle and stream assistant reply events"},podcast_voice:{type:"string",required:!1,description:"Podcast voice label or value to inject into the message"},podcast_mode:{type:"string",required:!1,description:"Podcast mode label or value used to disambiguate the voice"}},output:{type:"object",properties:{session_id:{type:"string"},message_id:{type:"string"},status:{type:"string"},content:{type:"string"},answer_message_id:{type:"string"},progress_id:{type:"string"},task_id:{type:"string"},task_status:{type:"string"}}}}}},ug=async({ctx:t,options:i,resolvedContent:o})=>{if(!i.podcastVoice)return o;if(!o)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-voice requires MESSAGE or stdin content");const s=(({config:t,voice:i,mode:o})=>{const s=i_(i),n=s_({config:t,mode:o}).filter((e=>i_(e.label)===s||i_(e.value)===s));if(0===n.length)throw new e.CozeError(e.ErrorCode.E1000,`Podcast voice not found: ${i}`);if(n.length>1){const t=n.map((e=>e.mode_value||e.mode_label||"unknown")).join(", ");throw new e.CozeError(e.ErrorCode.E1000,`Voice "${i}" matched multiple podcast voices; specify --podcast-mode (${t})`)}return n[0]})({config:await o_({baseUrl:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,xTTEnv:t.config.xTTEnv}),voice:i.podcastVoice,mode:i.podcastMode}).label||i.podcastVoice;return(({content:t,voiceLabel:i})=>{if(t.includes('使用音色"'))throw new e.CozeError(e.ErrorCode.E1000,"Message already contains a podcast voice instruction");const o=`使用音色"${i}", `,s=t.length-t.trimStart().length,n=t.slice(0,s),r=t.trimStart();if(/^@播客(?=\s|$)/.test(r))return`${n}@播客 ${o}${r.slice(3).trimStart()}`;return`${o}${t}`})({content:o,voiceLabel:s})},_g=async({ctx:t,message:i,options:o,service:s})=>{const{content:n,filePaths:r}=await t_(i,{cwd:t.cwd,onWarn:e=>t.ui.warn(e)});(({options:t,resolvedContent:i})=>{if(t.podcastMode&&!t.podcastVoice)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-mode requires --podcast-voice");if(t.podcastVoice&&!i)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-voice requires MESSAGE or stdin content")})({options:o,resolvedContent:n});const a=await Hu({filePaths:[...o.file||[],...r],sessionId:o.sessionId,apiBaseUrl:t.config.apiBaseUrl,sessionApiBaseUrl:t.config.sessionApiBaseUrl,sessionSpaceWebId:t.config.sessionSpaceWebId,xTTEnv:t.config.xTTEnv,service:s}),c=await ug({ctx:t,options:o,resolvedContent:n});if(!c&&0===a.length)throw new e.CozeError(e.ErrorCode.E1000,"Missing message input: provide MESSAGE, stdin content, and/or --file");return{content:c||"",files:a}},hg=async({ctx:e,options:t,service:i})=>{if(!t.wait)return{streamRenderer:null,waiter:null};const o=new $m({format:e.format}),s=lg([await i.getStatus(),"optionalAccess",e=>e.clawId]);return{clawId:s,knownProgressIds:s?await i.listProgresses({clawId:s}).then((e=>new Set(e.map((e=>e.progressId))))).catch((()=>null)):void 0,streamRenderer:o,waiter:await(async({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,xTTEnv:s})=>new Am({watcher:await Mm({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,xTTEnv:s})}))({accessToken:e.config.accessToken,apiBaseUrl:e.config.apiBaseUrl,organizationId:e.config.organizationId,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv})}},mg=async({ctx:e,knownProgressIds:t,options:i,result:o,service:n,streamRenderer:r,waiter:a,clawId:c})=>{const d=await a.waitForReply({onReplyChunk:r?e=>{r.writeChunk({chunk:e.chunk,sessionId:i.sessionId})}:void 0,onReplyUpdate:r?e=>{r.writeReply({reply:e.reply,sessionId:i.sessionId,source:"message"})}:void 0,sessionId:i.sessionId,requestMessageId:o.messageId,timeoutMs:i.timeout}),l="idle"===d.source&&c&&t?await(async({clawId:e,knownProgressIds:t,listProgresses:i,pollIntervalMs:o=500,timeoutMs:s=3e3})=>{const n=Date.now()+s;for(;;){const s=(await i({clawId:e})).find((e=>!t.has(e.progressId)));if(s)return s;const r=n-Date.now();if(r<=0)return null;await qu(Math.min(o,r))}})({clawId:c,knownProgressIds:t,listProgresses:e=>n.listProgresses(e),timeoutMs:3e3}):null;"idle"===d.source&&await n.updateSessionRuntimeStatus({sessionId:i.sessionId,status:"idle"});const p=await s.resolveStoredSessionReplyFiles({files:d.files,apiBaseUrl:e.config.apiBaseUrl,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv,service:n});return r?(r.writeReply({files:p,reply:{answerId:d.answerId,content:d.content,requestMessageId:o.messageId},sessionId:i.sessionId,source:d.source}),l&&r.writeProgress({progress:l,sessionId:i.sessionId}),{answerMessageId:d.answerId,content:d.content,files:p,progress:l,rendered:!0}):{answerMessageId:d.answerId,content:d.content,files:p,progress:l,rendered:!1}},gg=async(e,t,i)=>{await Lm(i,(async({ctx:i,service:o})=>{const n=await Rm(t.sessionId),r={...t,sessionId:n},a=await _g({ctx:i,message:e,options:r,service:o}),c=await hg({ctx:i,options:r,service:o});try{const e=await o.sendMessage({sessionId:n,content:a.content,files:a.files});if(await zm({sessionId:e.sessionId}),c.waiter){const t=await mg({...c,ctx:i,options:r,result:e,service:o,waiter:c.waiter});if(t.progress)try{const r=s.createSessionTaskService({apiBaseUrl:i.config.apiBaseUrl,service:o,sessionApiBaseUrl:i.config.sessionApiBaseUrl,xTTEnv:i.config.xTTEnv});let a=await r.createOrUpdateTaskFromMessageWait({answerMessageId:t.answerMessageId,content:t.content,files:t.files,messageId:e.messageId,progress:t.progress,sessionId:n});try{const e=await s.startDetachedSessionTaskRefreshWorker({payload:{accessToken:i.config.accessToken||"",apiBaseUrl:i.config.apiBaseUrl,organizationId:i.config.organizationId,sessionApiBaseUrl:i.config.sessionApiBaseUrl,taskId:a.taskId,xTTEnv:i.config.xTTEnv}});e&&(a=await r.patchTask(a.taskId,{lastRefreshError:void 0,workerPid:e}))}catch(e){a=await r.patchTask(a.taskId,{lastRefreshError:e instanceof Error?`Failed to start auto refresh worker: ${e.message}`:`Failed to start auto refresh worker: ${String(e)}`})}if("json"===i.format)return void i.response.print({answer_message_id:t.answerMessageId,content:t.content,files:t.files,message_id:e.messageId,progress_id:t.progress.progressId,session_id:e.sessionId,status:e.status,task_id:a.taskId,task_status:a.status,worker_pid:a.workerPid})}catch(t){if(i.ui.warn(`Failed to persist task: ${t instanceof Error?t.message:String(t)}`),"json"===i.format)return void i.response.print({session_id:e.sessionId,message_id:e.messageId,status:e.status})}if(t.rendered)return}i.response.print({session_id:e.sessionId,message_id:e.messageId,status:e.status})}finally{lg([c,"access",e=>e.waiter,"optionalAccess",e=>e.dispose,"call",e=>e()])}}))};const fg={...jm,help:{brief:"Work with PPT artifacts generated by a session",description:"Target one specific PPT artifact with --file-uri. Page-scoped edit still needs --session-id because it sends a session chat message.",examples:[{desc:"Get PPT information",cmd:"coze session ppt info --file-uri task-1/deck.pptx.html",tags:["[RECOMMENDED]"]},{desc:"List page outline text",cmd:"coze session ppt pages --file-uri task-1/deck.pptx.html"},{desc:"Export the PPTX file",cmd:"coze session ppt export --file-uri task-1/deck.pptx.html --output-path ./deck.pptx"},{desc:"Edit one page through session chat",cmd:'coze session ppt edit "标题更突出" -s 123456789 --page 2 --wait'},{desc:"Create a share link",cmd:"coze session ppt share --file-uri task-1/deck.pptx.html"}]}},yg=t=>{const i=Number.parseInt(t,10);if(!Number.isFinite(i)||i<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --page: expected a positive integer");return i},vg=(e,t)=>[...t,yg(e)],wg=t=>{if("ppt"===t||"editable"===t)return t;throw new e.CozeError(e.ErrorCode.E1000,'Invalid value for --export-type: expected "ppt" or "editable"')},bg=async({options:t})=>{if(t.fileUri)return{fileName:t.fileUri,fileUri:t.fileUri,raw:{file_name:t.fileUri,file_uri:t.fileUri}};throw new e.CozeError(e.ErrorCode.E1000,"Missing PPT identifier: provide --file-uri.")},Sg=t=>{if(!t.fileUri)throw new e.CozeError(e.ErrorCode.E1000,"PPT file_uri is required for this operation. Provide --file-uri.");return t.fileUri},Pg=async({file:e,service:t})=>e.fileUrl?e.fileUrl:t.resolveFileUrl({fileUri:Sg(e)}),Cg=async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await bg({options:e}),n=await Pg({file:o,service:i}),r=await s.fetchSessionPptContent({url:n}),a=s.parseSessionPptContent(r);"text"!==t.format?t.response.print({file_name:o.fileName,file_uri:o.fileUri,file_url:n,type:a.type,page_count:a.pageCount}):t.response.print((({file:e,pageCount:t,type:i,url:o})=>[`PPT: ${e.fileName}`,e.fileUri?`file_uri: ${e.fileUri}`:null,`file_url: ${o}`,`type: ${i}`,`pages: ${t}`].filter(Boolean).join("\n"))({file:o,pageCount:a.pageCount,type:a.type,url:n}))}))},Tg=t=>{const i=t.command("ppt").description("Inspect, export, share, and edit session PPT artifacts").config(fg);i.command("info").description("Get PPT metadata and page count").option("--file-uri <uri>","Specific PPT file_uri").action(((e,t)=>Cg(e,t))),i.command("pages").description("List PPT page outline and preview text").option("--file-uri <uri>","Specific PPT file_uri").option("--limit <limit>","Maximum pages to print",Om).action(((e,t)=>(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await bg({options:e}),n=await Pg({file:o,service:i}),r=await s.fetchSessionPptContent({url:n}),a=s.parseSessionPptContent(r),c=e.limit?a.pages.slice(0,e.limit):a.pages;"text"!==t.format?t.response.print({file_name:o.fileName,file_uri:o.fileUri,file_url:n,type:a.type,page_count:a.pageCount,pages:c}):t.response.print((e=>e.map((e=>{const t=e.title?` ${e.title}`:"",i=(o=e.previewText||(e.previewUrl?`preview_url: ${e.previewUrl}`:"")).length>500?`${o.slice(0,500)}...`:o;var o;return i?`${e.page}.${t}\n${i}`:`${e.page}.${t}`})).join("\n\n"))(c))}))})(e,t))),i.command("export").description("Export a PPT artifact to PPTX").option("--file-uri <uri>","Specific PPT file_uri").option("--output-path <path>","Local path used to save the PPTX").option("--export-type <type>","Export type: ppt or editable",wg,"ppt").action(((e,t)=>(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await bg({options:e}),s=Sg(o),n=await i.exportPpt({fileUri:s,exportType:e.exportType}),r=await Nu({url:n.url,outputPath:e.outputPath});"text"!==t.format?t.response.print({status:"saved",path:r.path,filename:r.filename,size:r.size,file_uri:s,export_uri:n.uri,export_url:n.url,export_type:n.exportType}):t.response.print(r.path)}))})(e,t))),i.command("edit <message>").description("Send a page-scoped edit request through session chat").option("-s, --session-id <sessionId>","Target session ID; defaults to the most recently used local session").option("--page <page>","Target PPT page number, can be used multiple times",vg,[]).option("--wait","Wait until the edit turn becomes idle").option("--timeout <timeoutMs>","Timeout for --wait",xm).action(((t,i,o)=>(async(t,i,o)=>{if(!function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}([i,"access",e=>e.page,"optionalAccess",e=>e.length]))throw new e.CozeError(e.ErrorCode.E1000,"Missing --page: provide one or more target PPT page numbers");await gg(s.formatSessionPptEditQuery({pages:i.page,query:t}),{sessionId:i.sessionId,wait:i.wait,timeout:i.timeout},o)})(t,i,o))),i.command("share").description("Create a share URL for a PPT artifact").option("--file-uri <uri>","Specific PPT file_uri").option("--task-id <taskId>","PPT task ID used by the slide route").option("--no-short","Print the original share URL without short-link exchange").action(((e,t)=>(async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await bg({options:e}),n=Sg(o),r=s.buildSessionPptSlideUrl({origin:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,fileUri:n,taskId:e.taskId}),a=!1===e.short?r:await i.shortenWebUrl({url:r});"text"!==t.format?t.response.print({file_name:o.fileName,file_uri:n,url:a,original_url:r,short:!1!==e.short}):t.response.print(a)}))})(e,t)))},Eg=e=>[e.mode_label||e.mode_value?`mode: ${e.mode_label||e.mode_value}${e.mode_label&&e.mode_value?` (${e.mode_value})`:""}`:null,`voice: ${e.label||e.value||"unknown"}`,e.value?`value: ${e.value}`:null,e.sample?`sample: ${e.sample}`:null,e.color_code?`color_code: ${e.color_code}`:null].filter(Boolean).join("\n"),kg=async(e,t)=>{await Lm(t,(async({ctx:t})=>{const i=await o_({baseUrl:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,xTTEnv:t.config.xTTEnv}),o=s_({config:i,mode:e.mode,keyword:e.keyword});"text"!==t.format?t.response.print({count:o.length,items:o}):t.response.print(o.length>0?o.map(Eg).join("\n\n"):"No podcast voices matched")}))},Ig=(e,t)=>[...t,e],Ag=async(t,i,o)=>{(t=>{if(t.mode&&!t.voice)throw new e.CozeError(e.ErrorCode.E1000,"--mode requires --voice")})(i),await gg(t,(e=>({file:e.file||[],podcastMode:e.mode,podcastVoice:e.voice,sessionId:e.sessionId,timeout:e.timeout,wait:e.wait}))(i),o)},jg=e=>{const t=e.command("podcast").description("Inspect podcast config");t.config({...jm,help:{brief:"Inspect podcast modes and voices",description:"Query the podcast voice configuration used by Coze Space so you can pick a valid voice name before sending a session message."}}),(e=>{e.command("message [message]").description("Send a podcast-oriented message to a claw session").option("-s, --session-id <sessionId>","Target session ID; defaults to the most recently used local session").option("--voice <voice>","Podcast voice label or value to inject into the message").option("--mode <mode>","Podcast mode label or value used to disambiguate --voice").option("--wait","Wait until the podcast turn becomes idle").option("--timeout <timeoutMs>","Timeout for --wait",xm).option("--file <path>","Local file to upload and attach (can be used multiple times)",Ig,[]).config({...jm,help:{brief:"Send a podcast message to a session",description:"Send a podcast-oriented message through the normal session message pipeline. Use --voice to inject a podcast voice instruction; --mode can disambiguate voices with the same label.",examples:[{desc:"Send a podcast message",cmd:'coze session podcast message "@播客 制作一个介绍潮汕美食的播客" -s 123456789 --voice "鸡汤女生" --wait',tags:["[RECOMMENDED]"]},{desc:"Send a podcast message without choosing a voice",cmd:'coze session podcast message "@播客 制作一个介绍潮汕美食的播客" -s 123456789 --wait'}],schema:{input:{message:{type:"string",required:!1,description:"Podcast message content"},session_id:{type:"string",required:!1,description:"Target session ID. Defaults to the most recently used local session"},voice:{type:"string",required:!1,description:"Podcast voice label or value"},mode:{type:"string",required:!1,description:"Podcast mode label or value used to disambiguate --voice"},wait:{type:"boolean",required:!1,description:"Wait for idle and stream assistant reply events"},file:{type:"array",required:!1,description:"Local file paths to upload and attach"}}}}}).action(Ag)})(t),(e=>{e.command("voice").description("Inspect podcast voices").command("list").description("List available podcast voices").option("--mode <mode>","Filter by podcast mode label or value").option("--keyword <keyword>","Filter voices by label or value keyword").config({...jm,help:{brief:"List available podcast voices",description:"Fetch podcast config from Coze Space and print flattened voice options. Text output includes the sample URL for quick inspection.",examples:[{desc:"List all podcast voices",cmd:"coze session podcast voice list",tags:["[RECOMMENDED]"]},{desc:"List solo voices only",cmd:"coze session podcast voice list --mode solo"},{desc:"Filter by keyword",cmd:"coze session podcast voice list --keyword 鸡汤"}],schema:{input:{mode:{type:"string",required:!1,description:"Podcast mode label or value"},keyword:{type:"string",required:!1,description:"Keyword used to filter label or value"}},output:{type:"object",properties:{count:{type:"number"},items:{type:"array"}}}}}}).action(kg)})(t)};function Rg(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const zg=e=>{e.command("current").description("Show the current locally selected default session").config({...jm,help:{brief:"Show the current default session",description:"Read the locally cached default session used by session commands when --session-id is omitted.",examples:[{desc:"Show the current default session",cmd:"coze session current"}],schema:{output:{type:"object",properties:{configured:{type:"boolean"},session_id:{type:"string"},claw_id:{type:"string"}}}}}}).action((async(e,t)=>{await(async e=>{const t=e.getContext(),i=s.createSessionConfigStore(),o=await i.get();if("text"===Rg([t,"optionalAccess",e=>e.format])){if(!o.sessionId)return void Rg([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e("No current session configured")]);const e=[`session_id: ${o.sessionId}`];return o.sessionClawId&&e.push(`claw_id: ${o.sessionClawId}`),void Rg([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e.join("\n"))])}Rg([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({configured:Boolean(o.sessionId),session_id:o.sessionId,claw_id:o.sessionClawId})])})(t)}))},Ug=e=>{e.command("use <sessionId>").description("Set the current locally selected default session").config({...jm,help:{brief:"Set the current default session",description:"Persist the provided session ID locally so session commands can reuse it by default.",examples:[{desc:"Use one session as the local default",cmd:"coze session use 7627441805839057179"}],schema:{input:{session_id:{type:"string",required:!0,description:"Session ID to persist as the local default"}},output:{type:"object",properties:{status:{type:"string"},session_id:{type:"string"}}}}}}).action((async(e,t,i)=>{await(async({cmd:e,sessionId:t})=>{const i=e.getContext();await zm({sessionId:t}),Rg([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"updated",session_id:t})])})({cmd:i,sessionId:e})}))},Lg=e=>{const t=e.command("session").description("Manage Coze session-based claw chat").config({...jm,help:{brief:"Manage claw chat sessions with token authentication",description:"Provides claw status lookup, session creation, session listing, and message sending for Coze Space claw chat using the current CLI token. Websocket watch flows also use the current CLI token through request headers.",examples:[{desc:"Check current claw status",cmd:"coze session status"},{desc:"Create a new session",cmd:"coze session create"}]}});(e=>{e.command("status").description("Get current claw status with token auth").option("-s, --session-id <sessionId>","Target session ID").config({...jm,help:{brief:"Validate token auth and resolve claw_id",description:"Use the current CLI token to fetch current claw information. If successful, the CLI refreshes the cached claw_id. With --session-id, the CLI reports session runtime status separately from claw-level background task activity.",examples:[{desc:"Validate token auth and show claw status",cmd:"coze session status"}],schema:{output:{type:"object",properties:{auth_configured:{type:"boolean"},auth_valid:{type:"boolean"},claw_id:{type:"string"},account_id:{type:"string"},updated_at:{type:"number"},display_status:{type:"string"},runtime_status:{type:"string"},claw_busy:{type:"boolean"},claw_progress_count:{type:"number"}}}}}}).action((async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{if(e.sessionId){const o=await i.getSessionDisplayStatus({sessionId:e.sessionId});return void t.response.print({session_id:o.sessionId,display_status:o.displayStatus,claw_busy:o.clawBusy,claw_progress_count:o.clawProgressCount,runtime_status:o.runtimeStatus,updated_at:o.updatedAt})}const o=await i.getStatus();t.response.print({auth_configured:o.authConfigured,auth_valid:o.authValid,claw_id:o.clawId,account_id:o.accountId,updated_at:o.updatedAt})}))}))})(t),(e=>{e.command("create").description("Create a new claw chat session").config({...jm,help:{brief:"Create a new claw session",description:"Create a normal claw chat session with the current claw_id resolved through token auth.",examples:[{desc:"Create a session",cmd:"coze session create"}],schema:{output:{type:"object",properties:{status:{type:"string"},claw_id:{type:"string"},session_id:{type:"string"}}}}}}).action((async(e,t)=>{await Lm(t,(async({ctx:e,service:t})=>{const i=await t.createSession();await zm({clawId:i.clawId,sessionId:i.sessionId}),e.response.print({status:"created",claw_id:i.clawId,session_id:i.sessionId})}))}))})(t),zg(t),Ug(t),(e=>{e.command("list").description("List claw chat sessions").option("--offset <offset>","Pagination offset returned by the previous list call").option("--limit <limit>","Maximum number of sessions to return",Om,20).config({...jm,help:{brief:"List sessions with offset pagination",description:"List claw chat sessions using the API native offset/limit pagination model.",examples:[{desc:"List the first 20 sessions",cmd:"coze session list"},{desc:"List the next page",cmd:"coze session list --offset next-token --limit 20"}],schema:{input:{offset:{type:"string",required:!1,description:"Pagination offset from a previous response"},limit:{type:"number",required:!1,description:"Maximum number of sessions to return"}},output:{type:"object",properties:{items:{type:"array",description:"Session items returned by the API"},next_offset:{type:"string",description:"Next pagination offset"},has_more:{type:"boolean",description:"Whether another page exists"}}}}}}).action((async(e,t)=>{await Lm(t,(async({ctx:t,service:i})=>{const o=await i.listSessions({offset:e.offset,limit:e.limit});t.response.print({items:o.items,next_offset:o.nextOffset,has_more:o.hasMore})}))}))})(t),(e=>{e.command("file").description("Manage files returned by claw session replies").config({...jm,help:{brief:"Download files returned by session replies",description:"Work with file artifacts returned by session replies. Use the file_url from `coze session message --wait --format json` to save a file locally.",examples:[{desc:"Download a reply artifact to the current directory",cmd:'coze session file download "https://example.com/file"'},{desc:"Download a reply artifact to a specific path",cmd:'coze session file download "https://example.com/file" --output-path ./artifacts/result.md'}]}}).command("download <fileUrl>").description("Download a file from a session reply file_url").option("--output-path <path>","Local path used to save the file").config({...jm,help:{brief:"Download a session reply file",description:"Download a file using the file_url returned by `coze session message --wait`. If --output-path is omitted, the CLI derives a filename from the response headers or URL.",examples:[{desc:"Download using the inferred filename",cmd:'coze session file download "https://example.com/file"',tags:["[RECOMMENDED]"]},{desc:"Save to a custom path",cmd:'coze session file download "https://example.com/file" --output-path ./downloads/result.md'}],schema:{input:{file_url:{type:"string",required:!0,description:"Direct file URL returned by a session reply"},output_path:{type:"string",required:!1,description:"Local output path for the downloaded file"}},output:{type:"object",properties:{status:{type:"string"},path:{type:"string"},filename:{type:"string"},size:{type:"number"},url:{type:"string"}}}}}}).action((async(e,t,i)=>{await Lm(i,(async({ctx:i})=>{const o=await Nu({url:e,outputPath:t.outputPath});"text"!==i.format?i.response.print({status:"saved",path:o.path,filename:o.filename,size:o.size,url:o.url}):i.response.print(o.path)}))}))})(t),jg(t),(e=>{e.command("message [message]").description("Send a text message to a claw session").option("-s, --session-id <sessionId>","Target session ID; defaults to the most recently used local session").option("--file <path>","Local file to upload and attach (can be used multiple times)",((e,t)=>[...t,e]),[]).option("--wait","Wait until the current turn becomes idle and optionally return a background progress_id").option("--timeout <timeoutMs>","Timeout for waiting until the current turn becomes idle",xm).option("--podcast-voice <voice>","Inject a podcast voice instruction using the specified voice label or value").option("--podcast-mode <mode>","Podcast mode label or value used to disambiguate --podcast-voice").config(pg).action(gg)})(t),Tg(t),(e=>{e.command("replies <messageId>").description("List all replies that belong to one session message").option("-s, --session-id <sessionId>","Target session ID; defaults to the most recently used local session").config({...jm,help:{brief:"List replies for one message",description:"Fetch session messages via ListMessage and return only the replies whose reply_to_message_id matches the specified message ID.",examples:[{desc:"Get all replies for one message",cmd:"coze session replies 8f45d790-9062-4008-8784-999d86825fcc -s 7627441805839057179",tags:["[RECOMMENDED]"]}],schema:{input:{message_id:{type:"string",required:!0,description:"Original user message ID"},session_id:{type:"string",required:!1,description:"Target session ID. Defaults to the most recently used local session"}},output:{type:"object",properties:{session_id:{type:"string"},message_id:{type:"string"},request_message_found:{type:"boolean"},count:{type:"number"}}}}}}).action((async(e,t,i)=>{await og({messageId:e,sessionId:t.sessionId},i)}))})(t),Hm(t),dg(t),tg(t)};function Og(t){t.command("upgrade").description("Upgrade Coze CLI to the latest version").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Upgrade CLI to latest version",description:"Check for the latest version of Coze CLI and upgrade if a newer version is available. Detects the package manager used for the original installation (npm/pnpm/yarn) and runs the appropriate global install command.",examples:[{desc:"Upgrade to latest version",cmd:"coze upgrade",tags:["[RECOMMENDED]"]},{desc:"Force check and upgrade",cmd:"coze upgrade --force"},{desc:"Upgrade to a specific tag",cmd:"coze upgrade --tag beta"}],seeAlso:["coze --version"]}}).option("--force","Force upgrade even if already on the latest version").option("--tag <tag>","Specify the dist-tag to upgrade to","latest").action((async(t,s)=>{const n=s.getContext();n||process.exit(e.ExitCode.FAILURE),n.ui.info("Checking for updates...");try{const e=await Q(n,!0,t.tag);if(!e.hasUpdate&&!t.force)return void n.ui.success(`You are already on the latest version (${e.currentVersion}).`);e.hasUpdate&&n.ui.info(`New version available: ${i.gray(e.currentVersion)} → ${i.green(e.latestVersion)}`),n.ui.info("Upgrading Coze CLI...");const s=function(){const e=[{pm:"npm",cmd:"npm ls -g @coze/cli --json 2>/dev/null"},{pm:"pnpm",cmd:"pnpm ls -g @coze/cli --json 2>/dev/null"},{pm:"yarn",cmd:"yarn global list --json 2>/dev/null"}];for(const{pm:t,cmd:i}of e)try{if(o.execSync(i,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).includes("@coze/cli"))return t}catch(e){}return"npm"}(),r=function(e,t){switch(e){case"pnpm":return`pnpm add -g @coze/cli@${t}`;case"yarn":return`yarn global add @coze/cli@${t}`;default:return`npm install -g @coze/cli@${t}`}}(s,t.tag);n.ui.verbose(`Using package manager: ${s}`),n.ui.verbose(`Running: ${r}`),o.execSync(r,{stdio:"inherit"});const a=J();n.ui.success(`Successfully upgraded Coze CLI to ${e.latestVersion}. (was ${e.currentVersion})`),"json"===n.format&&n.response.print({previousVersion:e.currentVersion,currentVersion:a,latestVersion:e.latestVersion,status:"upgraded"})}catch(t){n.ui.error(`Failed to upgrade: ${t.message}`),n.ui.info("You can try upgrading manually with: npm install -g @coze/cli"),process.exit(e.ExitCode.FAILURE)}}))}const xg={skipOrgCheck:!0,skipSpaceCheck:!0},Bg=t=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,"The --project-id option is required. Example: coze agent info --project-id <id>");return t},qg=e=>function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}([e,"optionalAccess",e=>e.trim,"call",e=>e()])||"/",Dg=(t,i)=>{const o=Number.parseInt(t,10);if(!Number.isFinite(o)||o<=0||String(o)!==t)throw new e.CozeError(e.ErrorCode.E1000,`Invalid value for ${i}: expected a positive integer, got "${t}"`);return o},Mg=t=>{if(!t)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");return t.config.sessionApiBaseUrl||t.config.apiBaseUrl};const Ng=t=>{if(void 0!==t.code&&0!==t.code)throw new e.CozeError(e.ErrorCode.E5002,t.msg||"Agent API request failed",{code:t.code});return t},Gg=e=>({baseURL:e.baseUrl}),$g={brief:"Manage Coze agent messages",description:"Commands for managing agent project messages.",examples:[{desc:"List agent messages",cmd:"coze agent message list --project-id <id>"}]},Fg={brief:"List raw Coze agent messages as JSON",description:"Lists messages in a Coze agent (project) and outputs the raw API JSON envelope. Requires --project-id.",examples:[{desc:"List messages",cmd:"coze agent message list --project-id 123456"},{desc:"List with cursor",cmd:"coze agent message list --project-id 123456 --cursor <next_cursor> --size 5"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},cursor:{type:"string",required:!1,description:"Pagination cursor"},size:{type:"number",required:!1,description:"Max messages to return (positive integer, max 10)"},"asc-mode":{type:"boolean",required:!1,description:"Ascending order"},"need-reference":{type:"boolean",required:!1,description:"Include referenced messages"},"conversation-id":{type:"string",required:!1,description:"Filter by conversation ID"}},output:{type:"object",description:"Raw API envelope with code, msg, data fields"}}},Vg=e=>{e.command("message").description("Manage Coze agent messages").config({...xg,help:$g}).command("list").description("List raw Coze agent messages as JSON").requiredOption("--project-id <projectId>","The agent project ID").option("--cursor <cursor>","Pagination cursor from a previous response").option("--size <size>","Number of messages to return (max 10)").option("--asc-mode","Load messages in ascending order").option("--need-reference","Include referenced messages").option("--conversation-id <conversationId>","Filter by conversation ID").config({...xg,help:Fg}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=e.size?Dg(e.size,"--size"):void 0,r=t.getContext(),a=Mg(r),c=await(async(e,t)=>{const i={session_id:t.projectId};return void 0!==t.cursor&&(i.cursor=t.cursor),void 0!==t.size&&(i.size=t.size),void 0!==t.ascMode&&(i.asc_mode=t.ascMode),void 0!==t.needReference&&(i.need_reference=t.needReference),void 0!==t.conversationId&&(i.conversation_id=t.conversationId),Ng(await s.Claw.ListMessage(i,Gg(e)))})({baseUrl:a},{projectId:o,cursor:e.cursor,size:n,ascMode:e.ascMode,needReference:e.needReference,conversationId:e.conversationId});i.print(c)}catch(e){V(e,t.getContext())}}))},Wg=e=>{e.command("member").description("Manage Coze agent members").config({...xg,help:{brief:"Manage Coze agent members",description:"Commands for managing agent project members.",examples:[{desc:"List agent members",cmd:"coze agent member list --project-id <id>"}]}}).command("list").description("List raw Coze agent members as JSON").requiredOption("--project-id <projectId>","The agent project ID").config({...xg,help:{brief:"List raw Coze agent members as JSON",description:"Lists members of a Coze agent (project) and outputs the raw API JSON envelope. Requires --project-id.",examples:[{desc:"List agent members",cmd:"coze agent member list --project-id 123456"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"}},output:{type:"object",description:"Raw API envelope with code, msg, data fields"}}}}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=t.getContext(),r=Mg(n),a=await(async(e,t)=>Ng(await s.Claw.GetProjectMembers({project_id:t.projectId},Gg(e))))({baseUrl:r},{projectId:o});i.print(a)}catch(e){V(e,t.getContext())}}))},Hg=e=>{e.command("info").description("Get raw Coze agent info as JSON").requiredOption("--project-id <projectId>","The agent project ID").config({...xg,help:{brief:"Get raw Coze agent info as JSON",description:"Retrieves detailed info for a single Coze agent (project) and outputs the raw API JSON envelope. Requires --project-id.",examples:[{desc:"Get agent info",cmd:"coze agent info --project-id 123456"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"}},output:{type:"object",description:"Raw API envelope with code, msg, data fields"}}}}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=t.getContext(),r=Mg(n),a=await(async(e,t)=>Ng(await s.Claw.GetProjectInfo({project_id:t.projectId},Gg(e))))({baseUrl:r},{projectId:o});i.print(a)}catch(e){V(e,t.getContext())}}))};const Jg=t=>{if(t instanceof e.CozeError)return i=t.desc,o=()=>t.message,null!=i?i:o();var i,o;if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return String(t)}},Kg=(e,t)=>{t.print({ok:!1,err_reason:Jg(e)}),process.exitCode=1};function Qg(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const Yg={brief:"Upload a local file to a Coze agent project as JSON",description:"Uploads a local file through the Claw file upload endpoint and outputs { ok, project_file_path }. Requires --project-id and --local-file-path.",examples:[{desc:"Upload a local file",cmd:"coze agent file upload --project-id 123456 --local-file-path ./report.md --project-dir /reports"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"local-file-path":{type:"string",required:!0,description:"Local file path to upload"},"project-dir":{type:"string",required:!1,description:"Target directory path in the remote project cloud disk; sent as project_dir and defaults to root"},"claw-id":{type:"string",required:!1,description:"Claw ID; defaults to empty string"}},output:{type:"object",description:"Result with ok and project_file_path fields"}}},Zg=(e,t)=>{const i=Qg([e,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!i||"/"===i)return`/${t}`;return`${(i.startsWith("/")?i:`/${i}`).replace(/\/+$/,"")}/${t}`},Xg=t=>{t.command("upload").description("Upload a local file to a Coze agent project as JSON").option("--project-id <projectId>","The agent project ID").option("--local-file-path <localFilePath>","Local file path to upload").option("--project-dir <projectDir>","Target directory path in the remote project cloud disk (defaults to root)").option("--claw-id <clawId>","Claw ID (defaults to empty string)","").config({...xg,help:Yg}).action((async(t,i)=>{const o=new Lo({format:"json"});try{const a=Bg(t.projectId),d=((t,i)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${i}`);return t})(t.localFilePath,"--local-file-path");await(async t=>{try{await u.access(t)}catch(i){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${t}${i instanceof Error?` (${i.message})`:""}`)}})(d);const p=i.getContext(),_=Mg(p),h=c.basename(d),m=qg(t.projectDir);await(async(e,t)=>{return Ng(await s.createSessionUploadFile({baseUrl:e.baseUrl,webOrigin:e.baseUrl,xTTEnv:e.xTTEnv})({projectId:t.projectId,fileName:t.fileName,fileContent:t.fileContent,projectDir:t.projectDir,clawId:(i=t.clawId,o=()=>"",null!=i?i:o())}));var i,o})({baseUrl:_,xTTEnv:Qg([p,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv])},{projectId:a,fileName:h,fileContent:await l.openAsBlob(d),projectDir:m,clawId:(n=t.clawId,r=()=>"",null!=n?n:r())}),o.print({ok:!0,project_file_path:Zg(m,h)})}catch(e){Kg(e,o)}var n,r}))};function ef(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const tf={brief:"Download a Coze agent file as JSON",description:"Builds the project file URI from project-id and project-file-path, resolves it through get_url, downloads the resolved file_url through /api/coze_claw/file/download, and saves it under the current directory.",examples:[{desc:"Download to the current directory",cmd:"coze agent file download --project-id 123456 --project-file-path /reports/report.md"},{desc:"Download an uploaded project file",cmd:"coze agent file download --project-id 123456 --project-file-path /用户上传/report.md"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"project-file-path":{type:"string",required:!0,description:"Specific file path in the remote project cloud disk"}},output:{type:"object",description:"Result with ok and local_file_path fields"}}},of=(t,i)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${i}`);return t},sf=t=>{t.command("download").description("Download a Coze agent file as JSON").option("--project-id <projectId>","The agent project ID").option("--project-file-path <projectFilePath>","Specific file path in the remote project cloud disk").config({...xg,help:tf}).action((async(t,i)=>{const o=new Lo({format:"json"});try{const n=Bg(t.projectId),r=of(t.projectFilePath,"--project-file-path"),a=i.getContext(),d=ef([a,"optionalAccess",e=>e.cwd])||process.cwd(),l=await(async e=>{const t=e.getContext(),{data:i}=await po.GetUserProfile({},{baseURL:ef([t,"optionalAccess",e=>e.config,"access",e=>e.openApiBaseUrl])});return of(ef([i,"optionalAccess",e=>e.user_id]),"current user id")})(i),p=await(async(t,i)=>{const o=s.createSessionApiClient({baseUrl:t.baseUrl,webOrigin:t.baseUrl,xTTEnv:t.xTTEnv}),n=i.accountId||"0",r=`${i.userId}_${n}/project_${i.projectId}-files${i.projectFilePath}`,a=await o.getUrl({uris:[r]},{headers:s.getCozeAccountHeaders(t.organizationId)}),d=function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}([a,"access",e=>e.data,"optionalAccess",e=>e.urls,"optionalAccess",e=>e[0]]);if(!d)throw new e.CozeError(e.ErrorCode.E5002,a.msg||"Failed to resolve agent file URL");const l=new URL("/api/coze_claw/file/download",s.normalizeBaseUrl(t.baseUrl));l.searchParams.set("file_url",d);const p=c.basename(i.projectFilePath)||"agent-file.bin";return{...await Nu({url:l.toString(),outputPath:c.join(i.localDir,p)}),fileUrl:d,projectFilePath:i.projectFilePath,resolvedUri:r}})({baseUrl:Mg(a),organizationId:ef([a,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),xTTEnv:ef([a,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv])},{projectId:n,projectFilePath:r,localDir:d,userId:l,accountId:ef([a,"optionalAccess",e=>e.config,"access",e=>e.organizationId])||"0"});o.print({ok:!0,local_file_path:p.path})}catch(e){Kg(e,o)}}))};function nf(e,t){return null!=e?e:t()}function rf(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}const af={brief:"Manage Coze agent project files",description:"Commands for managing agent project files.",examples:[{desc:"List project files",cmd:"coze agent file list --project-id <id>"},{desc:"Read a project file",cmd:"coze agent file read --project-id <id> --project-file-path /app/workspace/main.py"},{desc:"Upload file content",cmd:"coze agent file upload --project-id <id> --local-file-path ./report.md --project-dir /reports"},{desc:"Download a file",cmd:"coze agent file download --project-id <id> --project-file-path /reports/report.md"}]},cf={brief:"List Coze agent project files as JSON",description:"Lists files in a Coze agent project and outputs { ok, files }. Requires --project-id.",examples:[{desc:"List project files",cmd:"coze agent file list --project-id 123456"},{desc:"List files in a specific directory",cmd:"coze agent file list --project-id 123456 --project-dir /app/workspace"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"project-dir":{type:"string",required:!1,description:"Directory path in the remote project cloud disk (defaults to root)"},depth:{type:"number",required:!1,description:"Directory depth (defaults to 1)"}},output:{type:"object",description:"Result with ok and files fields"}}},df={brief:"Write content to a Coze agent project file as JSON",description:"Writes content to a file in a Coze agent project and outputs the raw API JSON envelope. Requires --project-id, --project-file-path, and --content.",examples:[{desc:"Write a file",cmd:'coze agent file write --project-id 123456 --project-file-path /app/workspace/hello.txt --content "hello world"'}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"project-file-path":{type:"string",required:!0,description:"Specific file path in the remote project cloud disk (e.g. /app/workspace/hello.txt)"},content:{type:"string",required:!0,description:"File content to write (utf-8)"}},output:{type:"object",description:"Raw API envelope with code, msg, data fields"}}},lf={brief:"Read a Coze agent project file as JSON",description:"Reads content from a file in a Coze agent project and outputs { ok, project_file_path, content }. Requires --project-id and --project-file-path.",examples:[{desc:"Read a file",cmd:"coze agent file read --project-id 123456 --project-file-path /app/workspace/main.py"},{desc:"Read with offset and limit",cmd:"coze agent file read --project-id 123456 --project-file-path /app/workspace/main.py --offset 10 --limit 50"}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"project-file-path":{type:"string",required:!0,description:"Specific file path in the remote project cloud disk (e.g. /app/workspace/main.py)"},offset:{type:"number",required:!1,description:"Start line (from 1)"},limit:{type:"number",required:!1,description:"Number of lines to read"}},output:{type:"object",description:"Result with ok, project_file_path, and content fields"}}},pf={brief:"Edit a Coze agent project file as JSON",description:"Edits a file in a Coze agent project using the specified mode and outputs the raw API JSON envelope. Requires --project-id, --project-file-path, and --mode.",examples:[{desc:"Replace one occurrence",cmd:'coze agent file edit --project-id 123456 --project-file-path /app/workspace/main.py --mode replace_one --old-string "foo" --new-string "bar"'},{desc:"Append content",cmd:'coze agent file edit --project-id 123456 --project-file-path /app/workspace/main.py --mode append --append-content "# end"'}],schema:{input:{"project-id":{type:"string",required:!0,description:"The agent project ID"},"project-file-path":{type:"string",required:!0,description:"Specific file path in the remote project cloud disk (e.g. /app/workspace/main.py)"},mode:{type:"string",required:!0,description:"Edit mode: replace_one, replace_all, append, append_newline"},"old-string":{type:"string",required:!1,description:"String to find (for replace modes)"},"new-string":{type:"string",required:!1,description:"Replacement string (for replace modes)"},"append-content":{type:"string",required:!1,description:"Content to append (for append modes)"}},output:{type:"object",description:"Raw API envelope with code, msg, data fields"}}},uf=(t,i)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${i}`);return t},_f=e=>e.startsWith("/")?e:`/${e}`,hf=e=>{e.command("list").description("List Coze agent project files as JSON").option("--project-id <projectId>","The agent project ID").option("--project-dir <projectDir>","Directory path in the remote project cloud disk (defaults to root)").option("--depth <depth>","Directory depth (defaults to 1)").config({...xg,help:cf}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=e.depth?Dg(e.depth,"--depth"):void 0,r=t.getContext(),a=Mg(r),c=qg(e.projectDir),d=await(async(e,t)=>Ng(await s.Claw.ListProjectFiles({project_id:t.projectId,file_path:t.filePath,depth:t.depth},Gg(e))))({baseUrl:a},{projectId:o,filePath:c,depth:n});i.print((e=>({ok:!0,files:nf(rf([e,"access",e=>e.data,"optionalAccess",e=>e.files]),(()=>[])).map((e=>({path:_f(e.file_path||e.name||""),type:e.is_dir?"dir":"file"})))}))(d))}catch(e){Kg(e,i)}}))},mf=e=>{e.command("write").description("Write content to a Coze agent project file as JSON").requiredOption("--project-id <projectId>","The agent project ID").requiredOption("--project-file-path <projectFilePath>","Specific file path in the remote project cloud disk").requiredOption("--content <content>","File content to write (utf-8)").config({...xg,help:df}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=uf(e.projectFilePath,"--project-file-path"),r=uf(e.content,"--content"),a=t.getContext(),c=Mg(a),d=await(async(e,t)=>Ng(await s.Claw.WriteProjectFile({project_id:t.projectId,file_path:t.filePath,content:t.content},Gg(e))))({baseUrl:c},{projectId:o,filePath:n,content:r});i.print(d)}catch(e){V(e,t.getContext())}}))},gf=e=>{e.command("read").description("Read a Coze agent project file as JSON").option("--project-id <projectId>","The agent project ID").option("--project-file-path <projectFilePath>","Specific file path in the remote project cloud disk").option("--offset <offset>","Start line (from 1)").option("--limit <limit>","Number of lines to read").config({...xg,help:lf}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=uf(e.projectFilePath,"--project-file-path"),r=e.offset?Dg(e.offset,"--offset"):void 0,a=e.limit?Dg(e.limit,"--limit"):void 0,c=t.getContext(),d=Mg(c),l=await(async(e,t)=>{const i={project_id:t.projectId,file_path:t.filePath};return void 0!==t.offset&&(i.offset=t.offset),void 0!==t.limit&&(i.limit=t.limit),Ng(await s.Claw.ReadProjectFile(i,Gg(e)))})({baseUrl:d},{projectId:o,filePath:n,offset:r,limit:a});i.print({ok:!0,project_file_path:n,content:nf(rf([l,"access",e=>e.data,"optionalAccess",e=>e.content]),(()=>""))})}catch(e){Kg(e,i)}}))},ff=e=>{e.command("edit").description("Edit a Coze agent project file as JSON").requiredOption("--project-id <projectId>","The agent project ID").requiredOption("--project-file-path <projectFilePath>","Specific file path in the remote project cloud disk").requiredOption("--mode <mode>","Edit mode: replace_one, replace_all, append, append_newline").option("--old-string <oldString>","String to find (for replace modes)").option("--new-string <newString>","Replacement string (for replace modes)").option("--append-content <appendContent>","Content to append (for append modes)").config({...xg,help:pf}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=uf(e.projectFilePath,"--project-file-path"),r=uf(e.mode,"--mode"),a=t.getContext(),c=Mg(a),d=await(async(e,t)=>{const i={project_id:t.projectId,file_path:t.filePath,mode:t.mode};return void 0!==t.oldString&&(i.old_string=t.oldString),void 0!==t.newString&&(i.new_string=t.newString),void 0!==t.appendContent&&(i.append_content=t.appendContent),Ng(await s.Claw.EditProjectFile(i,Gg(e)))})({baseUrl:c},{projectId:o,filePath:n,mode:r,oldString:e.oldString,newString:e.newString,appendContent:e.appendContent});i.print(d)}catch(e){V(e,t.getContext())}}))},yf=e=>{const t=e.command("agent").description("Agent-facing Coze APIs backed by Claw project endpoints").config({...xg,help:{brief:"Agent-facing Coze APIs backed by Claw project endpoints",description:"Provides raw JSON access to Coze agent (project) APIs including info, members, and messages. All commands output raw API envelopes as JSON.",examples:[{desc:"Get agent info",cmd:"coze agent info --project-id <id>"},{desc:"List agent members",cmd:"coze agent member list --project-id <id>"},{desc:"List agent messages",cmd:"coze agent message list --project-id <id>"},{desc:"List project files",cmd:"coze agent file list --project-id <id>"},{desc:"Read a project file",cmd:"coze agent file read --project-id <id> --project-file-path /app/workspace/main.py"},{desc:"Upload file content",cmd:"coze agent file upload --project-id <id> --local-file-path ./report.md --project-dir /reports"},{desc:"Download a file",cmd:"coze agent file download --project-id <id> --project-file-path /reports/report.md"}]}});Hg(t),Wg(t),Vg(t),(e=>{const t=e.command("file").description("Manage Coze agent project files").config({...xg,help:af});hf(t),mf(t),gf(t),ff(t),Xg(t),sf(t)})(t)};function vf(t){!function(t){const i=t.command("auth").description("Manage user authentication and credentials").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Manage authentication and credentials",description:"Manage the full authentication lifecycle for Coze CLI. Supports interactive OAuth login via browser. All other commands require valid authentication.",examples:[{desc:"Interactive login via browser",cmd:"coze auth login --oauth",tags:["[RECOMMENDED]"]},{desc:"Check current login status",cmd:"coze auth status"},{desc:"Logout and clear credentials",cmd:"coze auth logout"}],seeAlso:["coze organization","coze space"]}});i.command("login").description("Login to obtain and persist access credentials").config({skipAuth:!0,help:{brief:"Login to Coze services",description:"Login to Coze services via OAuth authorization. Opens browser to complete authorization.",examples:[{desc:"Interactive login using OAuth",cmd:"coze auth login --oauth",tags:["[RECOMMENDED]"]}],errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Authentication failed",fix:"Please try again with `coze auth login --oauth`."}]}}).option("--token <PAT>","Login using an access token").option("--oauth","Start browser-based OAuth device authorization flow").action((async function(t,i){const o=i.getContext();if(!o)return void V(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"));await o.auth.login(t);const s=["Please use the following commands to manage organizations and spaces:"," coze organization list"," coze organization use <organization_id>"," coze space list"," coze space use <space_id>"];!function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}}([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])})),i.command("logout").description("Logout and clear stored credentials").config({skipOrgCheck:!0,skipAuth:!0,skipSpaceCheck:!0,help:{brief:"Logout",description:"Clear locally stored access credentials and log out of the current account.",examples:[{desc:"Execute logout",cmd:"coze auth logout"}]}}).action((async(t,i)=>{const o=i.getContext();o?await o.auth.logout():V(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))})),i.command("status").description("Check current login status and credential validity").config({skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Check login status",description:"Verify if the current locally cached credentials are valid and display current login account information. If the token was obtained via OAuth and is about to expire, it will be refreshed automatically.",examples:[{desc:"Check current authentication status",cmd:"coze auth status",tags:["[RECOMMENDED]"]},{desc:"Check status in JSON format",cmd:"coze auth status --format json"}],schema:{output:{type:"object",properties:{logged_in:{type:"boolean",description:"Whether the user is currently logged in"},user:{type:"object",description:"Current user profile information"},token_expires_at:{type:"string",description:"Token expiration time in ISO 8601 format"}}}},errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"No valid credentials found or token has expired",fix:"Run `coze auth login --oauth` to authenticate."}],seeAlso:["coze auth login","coze auth logout"]}}).action((async(t,i)=>{const o=i.getContext();o?await o.auth.status():V(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))}))}(t),Lg(t),rc(t),Bu(t),$a(t),gr(t),vr(t),Na(t),Ja(t),Og(t),yf(t),ac()}function wf(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}function bf(e,t){return null!=e?e:t()}function Sf(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}function Pf(e){const t=[];let i=e;for(;i;)i.name()&&t.unshift(i.name()),i=i.parent;return t.join(" ")}function Cf(e){return e._args.map((e=>e.required?`<${e.name()}>`:`[${e.name()}]`)).join(" ")}const Tf=new Set(["--version","--format","--no-color","--config","--org-id","--space-id","--verbose","--debug","--log-file","--man","--schema","--commands"]);function Ef(e){const t=new Map,i=[];let o=e;for(;o;)i.unshift(o),o=o.parent;for(const e of i)for(const i of e.options){const e=i.flags.split(", ").find((e=>e.startsWith("--")));!e||t.has(e)||Tf.has(e)||t.set(e,i)}return Array.from(t.values())}function kf(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}class If extends b.Command{__init(){this.middlewares=[]}constructor(e){super(e),If.prototype.__init.call(this),this.helpInformation=()=>{const e=process.argv.slice(2);if(e.includes("--schema"))return`${JSON.stringify(kf([this,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help,"optionalAccess",e=>e.schema])||{},null,2)}\n`;if(e.includes("--commands")){const e=this.commands.filter((e=>!e._hidden)).map((e=>({name:e.name(),description:e.description()})));return`${JSON.stringify(e,null,2)}\n`}if(e.includes("--man")||e.includes("-m"))return`${function(e){const t=Sf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=Pf(e);let o=`@MAN ${i}\n\n`;o+=`NAME\n ${i} — ${Sf([t,"optionalAccess",e=>e.brief])||e.description()}\n\n`,o+=`SYNOPSIS\n ${i} ${Cf(e)}\n`,Ef(e).forEach((e=>{o+=` [${e.flags}]\n`})),o+="\n",Sf([t,"optionalAccess",e=>e.description])&&(o+=`DESCRIPTION\n ${t.description.replace(/\n/g,"\n ")}\n\n`);const s=Ef(e);return s.length>0&&(o+="OPTIONS\n",s.forEach((e=>{const t=e.flags.split(", "),i=t.find((e=>e.startsWith("-")&&!e.startsWith("--")))||"",s=t.find((e=>e.startsWith("--")))||"";o+=` ${i?`${s}, ${i}`:s}\n`,o+=` Type: ${e.isBoolean()?"flag":"string"}\n`,o+=` Required: ${e.mandatory?"yes":"no"}\n`,o+=` Default: ${void 0!==e.defaultValue?String(e.defaultValue):"-"}\n`,o+=` Desc: ${e.description}\n\n`}))),Sf([t,"optionalAccess",e=>e.schema])&&(o+="SCHEMA\n",t.schema.input&&(o+=` Input:\n ${JSON.stringify(t.schema.input,null,2).replace(/\n/g,"\n ")}\n`),t.schema.output&&(o+=` Output:\n ${JSON.stringify(t.schema.output,null,2).replace(/\n/g,"\n ")}\n`),o+="\n"),Sf([t,"optionalAccess",e=>e.errors])&&t.errors.length>0&&(o+="ERRORS\n",o+=" CODE NAME TRIGGER RECOVERY\n",t.errors.forEach((e=>{o+=` ${e.code.padEnd(6)} ${e.name.padEnd(17)} ${e.desc.padEnd(37)} ${e.fix}\n`})),o+="\n"),Sf([t,"optionalAccess",e=>e.caveats])&&t.caveats.length>0&&(o+="CAVEATS\n",t.caveats.forEach((e=>{o+=` - ${e}\n`})),o+="\n"),Sf([t,"optionalAccess",e=>e.seeAlso])&&t.seeAlso.length>0&&(o+="SEE ALSO\n",t.seeAlso.forEach((e=>{o+=` ${e}\n`})),o+="\n"),o.trimEnd()}(this)}\n`;return e.includes("-h")||e.includes("--help")?`${function(e){const t=Sf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=Pf(e);let o=`@HELP ${i}\n\n`;return Sf([t,"optionalAccess",e=>e.brief])?o+=`BRIEF: ${t.brief}\n\n`:o+=`BRIEF: ${e.description()||"No description provided."}\n\n`,e.parent&&"coze"!==e.parent.name()&&(o+=`PARENT: ${Pf(e.parent)}\n\n`),o+=`SYNTAX:\n ${i} ${Cf(e)} [options]\n\n`,Sf([t,"optionalAccess",e=>e.description])&&(o+=`DESCRIPTION:\n ${t.description.replace(/\n/g,"\n ")}\n\n`),o+="OPTIONS:\n",o+=" Name Type Required Default Description\n",o+=" ─────────────────────────────────────────────────────────\n",e._args.forEach((e=>{const t=`<${e.name()}>`,i=e.required?"Yes":"No",s=void 0!==e.defaultValue?String(e.defaultValue):"-",n=e.description||"";o+=` ${t.padEnd(16)} ${"string".padEnd(10)} ${i.padEnd(4)} ${s.padEnd(10)} ${n}\n`})),Ef(e).forEach((e=>{const t=e.flags.split(", "),i=t.find((e=>e.startsWith("-")&&!e.startsWith("--")))||"",s=t.find((e=>e.startsWith("--")))||"",n=i?`${s}, ${i}`:s;let r="string";e.isBoolean()&&(r="flag");const a=e.mandatory?"Yes":"No",c=void 0!==e.defaultValue?String(e.defaultValue):"-",d=e.description||"";o+=` ${n.padEnd(16)} ${r.padEnd(10)} ${a.padEnd(4)} ${c.padEnd(10)} ${d}\n`})),o+="\n",Sf([t,"optionalAccess",e=>e.enums])&&(o+="ENUMS:\n",Object.keys(t.enums).forEach((e=>{o+=` --${e}:\n`;const i=bf(Sf([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})));Object.keys(i).forEach((e=>{o+=` ${e.padEnd(12)} ${i[e]}\n`}))})),o+="\n"),Sf([t,"optionalAccess",e=>e.examples])&&t.examples.length>0&&(o+="COMMON EXAMPLES:\n",t.examples.forEach((e=>{const t=e.tags?` ${e.tags.join(" ")}`:"";o+=` #${t} ${e.desc}\n ${e.cmd}\n\n`}))),Sf([t,"optionalAccess",e=>e.errors])&&t.errors.length>0&&(o+="COMMON ERRORS:\n",o+=" CODE NAME DESCRIPTION FIX\n",t.errors.slice(0,5).forEach((e=>{o+=` ${e.code.padEnd(6)} ${e.name.padEnd(17)} ${e.desc.padEnd(30)} ${e.fix}\n`})),o+="\n"),Sf([t,"optionalAccess",e=>e.seeAlso])&&t.seeAlso.length>0&&(o+="SEE ALSO:\n",t.seeAlso.forEach((e=>{o+=` ${e}\n`})),o+="\n"),o.trimEnd()}(this)}\n`:`${function(e){const t=Sf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=Pf(e);let o=`@USAGE ${i}\n\n`;Sf([t,"optionalAccess",e=>e.brief])?o+=`BRIEF: ${t.brief}\n\n`:o+=`BRIEF: ${e.description()||"No description provided."}\n\n`,o+=`SYNTAX:\n ${i} ${Cf(e)} [options]\n\n`,e.commands.length>0&&(o+="ACTIONS:\n",e.commands.forEach((e=>{const t=e;if(!t._hidden){const e=Sf([t,"access",e=>e.getConfig,"optionalCall",e=>e(),"optionalAccess",e=>e.help,"optionalAccess",e=>e.brief])||t.description()||"";o+=` ${t.name().padEnd(10)} ${e}\n`}})),o+="\n"),Sf([t,"optionalAccess",e=>e.examples])&&t.examples.length>0&&(o+="EXAMPLES:\n",t.examples.slice(0,5).forEach((e=>{o+=` # ${e.desc}\n ${e.cmd}\n\n`})));if(Sf([t,"optionalAccess",e=>e.enums])){const e=Object.keys(t.enums).filter((e=>Object.keys(bf(Sf([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})))).length<=7));e.length>0&&(o+="ENUMS:\n",e.forEach((e=>{const i=Object.keys(bf(Sf([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})))).join(" | ");o+=` --${e}: ${i}\n`})),o+="\n")}return o.trimEnd()}(this)}\n`},this.hook("preAction",(e=>{}))}config(e){return this.commandConfig={...this.commandConfig,...e},this}setConfig(e){return this.commandConfig=e,this}getConfig(){return this.commandConfig}setContext(e){return this.context=e,this}getContext(){return this.context}use(e){return this.middlewares.push(e),this}createCommand(e){const t=new If(e);return this.context&&t.setContext(this.context),t}action(e){return super.action((async(...t)=>{const i=this.getContext();let o={},s=[],n=this;if(t.length>0){const e=t[t.length-1];e instanceof If&&(n=e),t.length>=2&&(r=t[t.length-2],a=()=>({}),o=null!=r?r:a(),s=t.slice(0,t.length-2))}var r,a;if(i&&(o&&(i.options=o),s&&(i.args=s),n)){i.commandName=n.name();const e=kf([n,"access",e=>e.getConfig,"optionalCall",e=>e()]);e&&(i.commandConfig=e),n.setContext(i)}if(this.middlewares.length>0&&i){const o=ci(this.middlewares);await o(i,(async()=>{await e.apply(this,t)}))}else await e.apply(this,t)}))}}function Af(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n(((...e)=>i.call(t,...e))),t=void 0)}return i}function jf(e){e.exitOverride(),e.outputError=()=>{},e.commands.forEach((e=>jf(e)))}async function Rf(t){const i=new If;i.name("coze").description("Coze Coding CLI").version(W,"-v, --version").option("--format <fmt>","Specify output format (json, text). Default: text").option("--no-color","Disable ANSI color output").option("--config <path>","Specify config file path").option("--org-id <id>","Override Organization ID").option("--space-id <id>","Override Space ID").option("--verbose","Enable verbose mode, output more business process information").option("--debug","Enable debug mode, output all log information for diagnosing CLI execution issues").option("--log-file <path>","Output logs to a file").option("--man","Show full manual information").option("--schema","Output the command's JSON Schema").option("--commands","Output the list of subcommands"),i.config({help:{errors:[{code:e.ErrorCode.E1100,name:"UNKNOWN_OPTION",desc:"Unknown option provided",fix:"Check parameter spelling or use -h for help",example:"coze <command> -h"},{code:e.ErrorCode.E1101,name:"UNKNOWN_COMMAND",desc:"Unknown subcommand provided",fix:"Check subcommand spelling or use -h for help",example:"coze -h"},{code:e.ErrorCode.E1102,name:"MISSING_ARGUMENT",desc:"Missing required argument",fix:"Provide missing required parameters",example:"coze <command> -h"},{code:e.ErrorCode.E1103,name:"MISSING_OPTION",desc:"Missing required option value",fix:"Provide missing required options",example:"coze <command> -h"}]}}),vf(i),await async function(e){e.completionInstalled||process.stdout.isTTY}(t.config),function(e,t,i){const o=new Set;e.setContext(i),function e(s){o.has(s)||(o.add(s),s.setContext(i),t.forEach((e=>s.use(e))),s.commands.forEach((t=>{const i=wf([s,"access",e=>e.getConfig,"optionalCall",e=>e()]),o=wf([t,"access",e=>e.getConfig,"optionalCall",e=>e()]);t.setConfig({...i,...o}),e(t)})))}(e)}(i,[xo,pr],t),process.on("uncaughtException",(e=>{V(e,t)})),process.on("unhandledRejection",(e=>{V(e,t)})),(t.argv.includes("--schema")||t.argv.includes("--commands")||t.argv.includes("--man")||t.argv.includes("-m"))&&(t.argv.includes("--help")||t.argv.includes("-h")||t.argv.push("--help")),jf(i);try{await i.parseAsync(t.argv,{from:"user"})}catch(n){const r=n,a=function(e,t,i){let o=e;if(t.command)o=t.command;else if(i.commandName){const t=(e,i)=>{if(e.name()===i)return e;for(const o of e.commands){const e=t(o,i);if(e)return e}return null},s=t(e,i.commandName);s&&(o=s)}let s=e;for(const e of i.argv){if(e.startsWith("-"))break;const t=s.commands.find((t=>t.name()===e));t&&(s=t,o=s)}return o}(i,r,t);"commander.helpDisplayed"!==r.code&&"commander.help"!==r.code&&"commander.version"!==r.code||process.exit(e.ExitCode.SUCCESS);const c=Af([a,"access",e=>e.getConfig,"optionalCall",e=>e()]),d=Af([i,"access",e=>e.getConfig,"optionalCall",e=>e()]);if(t.commandConfig=(s=()=>d,null!=(o=c)?o:s()),"commander.unknownOption"===r.code){const i=G(new e.CozeError(e.ErrorCode.E1100,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),process.exit(e.exitCodeForError(i.code))}if("commander.unknownCommand"===r.code){const i=G(new e.CozeError(e.ErrorCode.E1101,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),process.exit(e.exitCodeForError(i.code))}if("commander.missingArgument"===r.code){const i=G(new e.CozeError(e.ErrorCode.E1102,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),"json"!==t.format&&process.stderr.write(`\n${a.helpInformation()}`),process.exit(e.exitCodeForError(i.code))}if("commander.missingMandatoryOptionValue"===r.code||"commander.optionMissingArgument"===r.code){const i=G(new e.CozeError(e.ErrorCode.E1103,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),"json"!==t.format&&process.stderr.write(`\n${a.helpInformation()}`),process.exit(e.exitCodeForError(i.code))}V(r,t)}var o,s}(async function(){const e=process.argv.slice(2),{globalOptions:t}=function(e){const t={};let i;const o=[];let s=!1;for(let n=0;n<e.length;n++){const r=e[n];if("--help"!==r&&"-h"!==r)if("--version"!==r&&"-v"!==r)if("--output"!==r)if("--format"!==r)"--no-color"!==r?"--config"!==r?"--org-id"!==r?"--space-id"!==r?"--verbose"!==r?"--debug"!==r?"--log-file"!==r?"--print-logs"!==r?s||r.startsWith("-")?o.push(r):(i=r,s=!0):t.printLogs=!0:t.logFile=e[++n]:t.debug=!0:t.verbose=!0:t.spaceId=e[++n]:t.orgId=e[++n]:t.config=e[++n]:t.noColor=!0;else{const i=e[++n];"json"!==i&&"text"!==i||(t.format=i)}else t.output=e[++n];else t.version=!0;else t.help=!0}return{globalOptions:t,commandName:i,commandArgs:o}}(e),i=function(e){const t=Oo(e.cwd,(()=>process.cwd())),i=Oo(e.env,(()=>process.env)),o=e.globalOptions||{};o.noColor&&(process.env.NO_COLOR="1");let s="text";o.format&&(s=o.format);const n={...e.config};o.orgId&&(n.organizationId=o.orgId),o.spaceId&&(n.spaceId=o.spaceId);const r=new St({format:"text",logFile:o.logFile,printToStderr:o.printLogs});let a="info";o.debug?a="debug":o.verbose&&(a="verbose");const c=new Uo(r,s,a),d=new Lo({format:s}),l={cwd:t,env:i,argv:e.argv,config:n,format:s,log:r,ui:c,response:d,globalOptions:o,auth:void 0};return l.auth=new go(l),l}({argv:e,config:await s.loadConfig(t.config),globalOptions:t});!function(e){kt=e.log,It=!0===Pt([e,"access",e=>e.globalOptions,"optionalAccess",e=>e.debug]),It&&(At||(Ht(),Jt(),At=!0))}(i);const o=ci([vt,ti,ai,Y]);await o(i,(async()=>{await Rf(i)}))})().catch((e=>{V(e,void 0),process.exitCode=1}));
|