@coze/cli 0.1.7-alpha.ef8524 → 0.1.8-alpha.618a4c

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 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.ef8524",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-BC9PFu7i.js"),i=require("chalk"),o=require("node:child_process"),s=require("./task-worker-CxZeBKqU.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 I(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 k(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+=I(n)?2:1)}return o}function A(e,t){const i=k(e);return i>=t?e:`${e}${" ".repeat(t-i)}`}function j(e,t){if(t<=0)return"";if(k(e)<=t)return e;if(1===t)return"…";const i=E(e),o=Array.from(i),s=Math.max(0,t-k("…"));let n="",r=0;for(let e=0;e<o.length;e+=1){const t=C(o[e],(()=>"")),i=k(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=k(t);for(const o of e){const e=o[t],s=void 0===e?"":String(e);i=Math.max(i,k(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,k(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 L(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=L(n,e,i+1);Object.assign(o,t)}else o[e]=n}return o}function U(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=>L(e))))}return function(e){return Array.isArray(e)&&e.length>0&&e.every((e=>null==e||"object"!=typeof e))}(e)?`${e.map((e=>String(U(e,(()=>"null"))))).join("\n")}\n`:"[Array]\n"}var t;if(O(e)){const t=L(e);return 0===Object.keys(t).length?"{}\n":z(t)}return`${String(e)}\n`}formatError(e){const t=[],i=U(e.errorName,(()=>"UNKNOWN_ERROR")),o=U(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(L(e)):String(e))).map((e=>`${t}- ${e.trim()}`)).join("\n")}\n`;if(O(e)){const i=L(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.8-alpha.618a4c",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
 
@@ -13,7 +13,7 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
13
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
14
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
15
  PERFORMANCE OF THIS SOFTWARE.
16
- ***************************************************************************** */var te=function(){return te=Object.assign||function(e){for(var t,i=1,o=arguments.length;i<o;i++)for(var s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},te.apply(this,arguments)};function ie(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var o,s,n=i.call(e),r=[];try{for(;(void 0===t||t-- >0)&&!(o=n.next()).done;)r.push(o.value)}catch(e){s={error:e}}finally{try{o&&!o.done&&(i=n.return)&&i.call(n)}finally{if(s)throw s.error}}return r}function oe(e,t,i){if(2===arguments.length)for(var o,s=0,n=t.length;s<n;s++)!o&&s in t||(o||(o=Array.prototype.slice.call(t,0,s)),o[s]=t[s]);return e.concat(o||Array.prototype.slice.call(t))}var se=function(){return{}};function ne(e){return e}function re(e){return"object"==typeof e&&null!==e}var ae=Object.prototype;function ce(e){return"[object Array]"===ae.toString.call(e)}function de(e){return"number"==typeof e}function le(e){return"string"==typeof e}function pe(e,t){if(!ce(e))return!1;if(0===e.length)return!1;for(var i=0;i<e.length;){if(e[i]===t)return!0;i++}return!1}var ue=function(e,t){if(!ce(e))return e;var i=e.indexOf(t);if(i>=0){var o=e.slice();return o.splice(i,1),o}return e};function _e(e){try{return le(e)?e:JSON.stringify(e)}catch(e){return"[FAILED_TO_STRINGIFY]:"+String(e)}}var he="".padStart?function(e,t){return void 0===t&&(t=8),e.padStart(t," ")}:function(e){return e},me=0,ge=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,oe(["[SDK]",Date.now(),he(""+me++)],ie(e),!1))},fe=0,ye=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,oe(["[SDK]",Date.now(),he(""+fe++)],ie(e),!1))},ve=function(e){return Math.random()<Number(e)},we=function(e,t){return e<Number(t)},be=function(e){return function(t){for(var i=t,o=0;o<e.length&&i;o++)try{i=e[o](i)}catch(e){ge(e)}return i}};function Se(){var e=function(){for(var e=new Array(16),t=0,i=0;i<16;i++)3&i||(t=4294967296*Math.random()),e[i]=t>>>((3&i)<<3)&255;return e}();return e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){for(var t=[],i=0;i<256;++i)t[i]=(i+256).toString(16).substr(1);var o=0,s=t;return[s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]]].join("")}(e)}var Pe=["init","start","config","beforeDestroy","provide","beforeReport","report","beforeBuild","build","beforeSend","send","beforeConfig"];function Ce(e){var t,i,o=e.builder,s=e.createSender,n=e.createDefaultConfig,r=e.createConfigManager,a=e.userConfigNormalizer,c=e.initConfigNormalizer,d=e.validateInitConfig,l={};Pe.forEach((function(e){return l[e]=[]}));var p=!1,u=!1,_=!1,h=[],m=[],g=function(){var e=!1,t={},i=function(e){e.length&&e.forEach((function(e){try{e()}catch(e){}})),e.length=0},o=function(e){t[e]&&t[e].forEach((function(e){i(e[1])})),t[e]=void 0};return{set:function(o,s,n){t[o]?t[o].push([s,n]):t[o]=[[s,n]],e&&i(n)},has:function(e){return!!t[e]},remove:o,removeByEvType:function(e){Object.keys(t).forEach((function(o){t[o]&&t[o].forEach((function(t){t[0]===e&&i(t[1])}))}))},clear:function(){e=!0,Object.keys(t).forEach((function(e){o(e)}))}}}(),f={getBuilder:function(){return o},getSender:function(){return t},getPreStartQueue:function(){return h},init:function(e){if(p)ye("already inited");else{if(!(e&&re(e)&&d(e)))throw new Error("invalid InitConfig, init failed");var o=n(e);if(!o)throw new Error("defaultConfig missing");var a=c(e);if((i=r(o)).setConfig(a),i.onChange((function(){y("config")})),!(t=s(i.getConfig())))throw new Error("sender missing");p=!0,y("init",!0)}},set:function(e){p&&e&&re(e)&&(y("beforeConfig",!1,e),null==i||i.setConfig(e))},config:function(e){if(p)return e&&re(e)&&(y("beforeConfig",!1,e),null==i||i.setConfig(a(e))),null==i?void 0:i.getConfig()},provide:function(e,t){pe(m,e)?ye("cannot provide "+e+", reserved"):(f[e]=t,y("provide",!1,e))},start:function(){p&&(u||null==i||i.onReady((function(){u=!0,y("start",!0),function(e){var t=e.getPreStartQueue();t.forEach((function(t){return e.build(t)})),t.length=0}(f)})))},report:function(e){if(e){var t=be(l.beforeReport)(e);if(t){var i=be(l.report)(t);i&&(u?this.build(i):function(e,t,i){if(t.push(i),!(t.length<500)){var o=t.splice(0,50);e.savePreStartDataToDb&&e.savePreStartDataToDb(o)}}(f,h,i))}}},build:function(e){if(u){var t=be(l.beforeBuild)(e);if(t){var i=o.build(t);if(i){var s=be(l.build)(i);s&&this.send(s)}}}},send:function(e){if(u){var i=be(l.beforeSend)(e);i&&(t.send(i),y("send",!1,i))}},destroy:function(){g.clear(),_=!0,h.length=0,y("beforeDestroy",!0)},on:function(e,t){if("init"===e&&p||"start"===e&&u||"beforeDestroy"===e&&_)try{t()}catch(e){}else l[e]&&l[e].push(t)},off:function(e,t){l[e]&&(l[e]=ue(l[e],t))},destroyAgent:g};return m=Object.keys(f),f;function y(e,t){void 0===t&&(t=!1);for(var i=[],o=2;o<arguments.length;o++)i[o-2]=arguments[o];l[e].forEach((function(e){try{e.apply(void 0,oe([],ie(i),!1))}catch(e){}})),t&&(l[e].length=0)}}var Te=function(e){var t=function(){var e={},t={},i={set:function(o,s){return e[o]=s,t[o]=_e(s),i},merge:function(o){return e=te(te({},e),o),Object.keys(o).forEach((function(e){t[e]=_e(o[e])})),i},delete:function(o){return delete e[o],delete t[o],i},clear:function(){return e={},t={},i},get:function(e){return t[e]},toString:function(){return te({},t)}};return i}();e.provide("context",t),e.on("report",(function(e){return e.extra||(e.extra={}),e.extra.context=t.toString(),e}))};var Ee=function(){return Date.now()};var ke=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=function(e){if(e)return e.__SLARDAR_REGISTRY__||(e.__SLARDAR_REGISTRY__={Slardar:{plugins:[],errors:[],subject:{}}}),e.__SLARDAR_REGISTRY__.Slardar}(function(){if("object"==typeof window&&re(window))return window}());i&&(i.errors||(i.errors=[]),i.errors.push(e))},Ie="custom",Ae=function(e){var t=function(i){var o=function(e){if(e&&re(e)&&e.name&&le(e.name)){var t={name:e.name,type:"event"};if("metrics"in e&&re(e.metrics)){var i=e.metrics,o={};for(var s in i)de(i[s])&&(o[s]=i[s]);t.metrics=o}if("categories"in e&&re(e.categories)){var n=e.categories,r={};for(var s in n)r[s]=_e(n[s]);t.categories=r}return"attached_log"in e&&le(e.attached_log)&&(t.attached_log=e.attached_log),t}}(i);if(o){var s=function(e){var t;if("object"==typeof window&&window.__perfsee__){var i={};return null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,i,e),i.stack}}(t);s&&(o.stacks=s),e.report({ev_type:Ie,payload:o,extra:{timestamp:Ee()}})}};e.provide("sendEvent",t),e.provide("sendLog",(function(t){var i=function(e){if(e&&re(e)&&e.content&&le(e.content)){var t={content:_e(e.content),type:"log",level:"info"};if("level"in e&&(t.level=e.level),"extra"in e&&re(e.extra)){var i=e.extra,o={},s={};for(var n in i)de(i[n])?o[n]=i[n]:s[n]=_e(i[n]);t.metrics=o,t.categories=s}return"attached_log"in e&&le(e.attached_log)&&(t.attached_log=e.attached_log),t}}(t);i&&e.report({ev_type:Ie,payload:i,extra:{timestamp:Ee()}})}))},je=function(e,t){var i=e.common||{};return i.sample_rate=t,e.common=i,e},Re=function(e,t,i,o,s){return e?(n=s(o,t),function(){return n}):function(){return i(t)};var n},ze=function(e,t,i,o){var s=function(e,t,i){for(var o,s=ie(t.split(".")),n=s[0],r=s.slice(1);e&&r.length>0;)e=e[n],n=(o=ie(r))[0],r=o.slice(1);if(e)return i(e,n)}(e,t,(function(e,t){return e[t]}));return void 0!==s&&function(e,t,i){switch(i){case"eq":return pe(t,e);case"neq":return!pe(t,e);case"gt":return e>t[0];case"gte":return e>=t[0];case"lt":return e<t[0];case"lte":return e<=t[0];case"regex":return Boolean(e.match(new RegExp(t.join("|"))));case"not_regex":return!e.match(new RegExp(t.join("|")));default:return!1}}(s,function(e,t){return e.map((function(e){switch(t){case"number":return Number(e);case"boolean":return"1"===e;default:return String(e)}}))}(o,"boolean"==typeof s?"bool":de(s)?"number":"string"),i)},Ue=function(e,t){try{return"rule"===t.type?ze(e,t.field,t.op,t.values):"and"===t.type?t.children.every((function(t){return Ue(e,t)})):t.children.some((function(t){return Ue(e,t)}))}catch(e){return ke(e),!1}},Le=function(e,t,i,o,s){if(!t)return ne;var n=t.sample_rate,r=t.include_users,a=t.sample_granularity,c=t.rules,d=t.r,l=void 0===d?Math.random():d;if(pe(r,e))return function(e){return je(e,1)};var p="session"===a,u=Re(p,n,i,l,o),_=function(e,t,i,o,s,n){var r={};return Object.keys(e).forEach((function(a){var c=e[a],d=c.enable,l=c.sample_rate,p=c.conditional_sample_rules;d?(r[a]={enable:d,sample_rate:l,effectiveSampleRate:l*i,hit:Re(t,l,o,s,n)},p&&(r[a].conditional_hit_rules=p.map((function(e){var r=e.sample_rate,a=e.filter;return{sample_rate:r,hit:Re(t,r,o,s,n),effectiveSampleRate:r*i,filter:a}})))):r[a]={enable:d,hit:function(){return!1},sample_rate:0,effectiveSampleRate:0}})),r}(c,p,n,i,l,o);return function(e){var t;if(!u())return p&&s[0](),!1;if(!(e.ev_type in _))return je(e,n);if(!_[e.ev_type].enable)return p&&s[1](e.ev_type),!1;if(null===(t=e.common)||void 0===t?void 0:t.sample_rate)return e;var i=_[e.ev_type],o=i.conditional_hit_rules;if(o)for(var r=0;r<o.length;r++)if(Ue(e,o[r].filter))return!!o[r].hit()&&je(e,o[r].effectiveSampleRate);return i.hit()?je(e,i.effectiveSampleRate):((!o||!o.length)&&p&&s[1](e.ev_type),!1)}},Oe={build:function(e){return{ev_type:e.ev_type,payload:e.payload,common:te(te({},e.extra||{}),e.overrides||{})}}},xe={sample_rate:1,include_users:[],sample_granularity:"session",rules:{}};function Be(e){var t,i;try{for(var o=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],o=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&o>=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(["userId","deviceId","sessionId","env"]),s=o.next();!s.done;s=o.next()){var n=s.value;e[n]||delete e[n]}}catch(e){t={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}return e}function qe(e){return Be(te({},e))}function De(e){return re(e)&&"bid"in e&&"transport"in e}function Me(e){return Be(te({},e))}var Ne=function(e,t){return void 0===t&&(t="/monitor_browser/collect/batch/"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Ge=function(e,t){return void 0===t&&(t="/monitor_web/settings/browser-settings"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},$e=function(e){var t,i,o=e,s={},n=se,r=se;return{getConfig:function(){return o},setConfig:function(e){return s=te(te({},s),e||{}),a(),t||(t=e,o.useLocalConfig||!o.bid?(i={},n()):function(e,t,i,o){if(!e.get)return o({});e.get({withCredentials:!0,url:Ge(t)+"?bid="+i+"&store=1",success:function(e){o(e.data||{})},fail:function(){o({sample:{sample_rate:.001}})}})}(o.transport,o.domain,o.bid,(function(e){i=function(e){if(!e)return{};var t=e.sample,i=e.timestamp,o=e.quota_rate,s=void 0===o?1:o;if(!t)return{};var n=t.sample_rate,r=t.sample_granularity,a=void 0===r?"session":r,c=t.include_users,d=t.rules;return{sample:{include_users:c,sample_rate:n*s,sample_granularity:a,rules:(void 0===d?[]:d).reduce((function(e,t){var i=t.name,o=t.enable,s=t.sample_rate,n=t.conditional_sample_rules;return e[i]={enable:o,sample_rate:s,conditional_sample_rules:n},e}),{})},serverTimestamp:i}}(e),a(),n()}))),o},onChange:function(e){r=e},onReady:function(e){n=e,i&&n()}};function a(){var t=te(te(te({},e),i||{}),s);t.sample=Fe(Fe(e.sample,null==i?void 0:i.sample),s.sample),o=t,r()}};function Fe(e,t){if(!e||!t)return e||t;var i=te(te({},e),t);return i.include_users=oe(oe([],ie(e.include_users||[]),!1),ie(t.include_users||[]),!1),i.rules=oe(oe([],ie(Object.keys(e.rules||{})),!1),ie(Object.keys(t.rules||{})),!1).reduce((function(i,o){var s,n;return o in i||(o in(e.rules||{})&&o in(t.rules||{})?(i[o]=te(te({},e.rules[o]),t.rules[o]),i[o].conditional_sample_rules=oe(oe([],ie(e.rules[o].conditional_sample_rules||[]),!1),ie(t.rules[o].conditional_sample_rules||[]),!1)):i[o]=(null===(s=e.rules)||void 0===s?void 0:s[o])||(null===(n=t.rules)||void 0===n?void 0:n[o])),i}),{}),i}var Ve=function(e){e.on("report",(function(t){return function(e,t){var i=t||{},o=i.version,s=i.name,n={url:"",protocol:"",domain:"",path:"",query:"",timestamp:Date.now(),sdk_version:o||"2.1.8",sdk_name:s||"SDK_BASE"};return te(te({},e),{extra:te(te({},n),e.extra||{})})}(t,e.config())}))},We=function(e){e.on("beforeBuild",(function(t){return function(e,t){var i={};return i.bid=t.bid,i.pid=t.pid,i.view_id=t.viewId,i.user_id=t.userId,i.device_id=t.deviceId,i.session_id=t.sessionId,i.release=t.release,i.env=t.env,te(te({},e),{extra:te(te({},i),e.extra||{})})}(t,e.config())}))};var He=function(e){return{bid:"",pid:"",viewId:(t="_",t+"_"+Date.now()),userId:Se(),deviceId:Se(),sessionId:Se(),domain:"mon.zijieapi.com",release:"",env:"production",sample:xe,plugins:{},transport:{get:se,post:se},useLocalConfig:!1};var t},Je=function(e){var t=void 0===e?{}:e,i=t.createSender,o=void 0===i?function(e){return function(e){return ee(e)}({size:20,endpoint:Ne(e.domain),transport:e.transport})}:i,s=t.builder,n=void 0===s?Oe:s,r=t.createDefaultConfig,a=Ce({validateInitConfig:De,initConfigNormalizer:qe,userConfigNormalizer:Me,createSender:o,builder:n,createDefaultConfig:void 0===r?He:r,createConfigManager:$e});return Te(a),We(a),Ve(a),function(e){e.on("init",(function(){var t=[],i=function(i){i.forEach((function(i){var o=i.name;pe(t,o)||(t.push(o),i.setup(e),e.destroyAgent.set(o,o,[function(){t=ue(t,o),i.tearDown&&i.tearDown()}]))}))};e.provide("applyIntegrations",i);var o=e.config();o&&o.integrations&&i(o.integrations)}))}(a),function(e){try{"object"==typeof window&&re(window)&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__.push(e)}catch(e){}}(a),a},Ke=function(e){void 0===e&&(e={});var t=Je(e);return function(e){e.on("start",(function(){var t=e.config(),i=t.userId,o=t.sample,s=Le(i,o,ve,we,[function(){e.destroy()},function(t){e.destroyAgent.removeByEvType(t)}]);e.on("build",s)}))}(t),Ae(t),t}();const Qe=X("slardar:transport"),Ye=()=>{};function Ze(e){const{url:t,method:i,data:o,success:s=Ye,fail:a=Ye,getResponseText:c=Ye}=e;if(Qe("Making %s request to %s",i,t),o&&Qe("Request data: %s",o.slice(0,200)),!t||"string"!=typeof t){const e=new Error(`Invalid URL: ${t}`);return Qe("Invalid URL provided: %o",t),void a(e)}try{const e=new URL(t);Qe("Parsed URL - protocol: %s, hostname: %s, port: %s, path: %s",e.protocol,e.hostname,e.port,e.pathname);const d="https:"===e.protocol,l=(d?r.request:n.request)({hostname:e.hostname,port:e.port,path:e.pathname+e.search,method:i,headers:{"Content-Type":"application/json",...o&&{"Content-Length":Buffer.byteLength(o)}}},(e=>{Qe("Response callback triggered: status=%s",e.statusCode);let t="";e.on("data",(e=>{Qe("Response data chunk received: %s bytes",e.length),t+=e.toString()})),e.on("end",(()=>{Qe("Response end event fired"),Qe("Response received: status=%s, body=%s",e.statusCode,t.slice(0,200)),c(t);try{if(e.statusCode&&e.statusCode>=400)Qe("Request failed with status %s: %s",e.statusCode,t),a(new Error(t||e.statusMessage||"Request failed"));else if(t){const e=JSON.parse(t);Qe("Request succeeded"),s(e)}else Qe("Request succeeded with empty response"),s({})}catch(e){Qe("Failed to parse response: %s",e.message),a(e)}}))}));l.on("error",(e=>{Qe("Request error: %s",e.message),a(e)})),l.on("timeout",(()=>{Qe("Request timeout"),l.destroy(),a(new Error("Request timeout"))})),o&&l.write(o),l.end()}catch(e){Qe("Exception during request: %s",e.message),a(e)}}function Xe(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 et=X("slardar:reporter");class it{constructor(){it.prototype.__init.call(this),it.prototype.__init2.call(this)}__init(){this.initialized=!1}__init2(){this.client=Ke}setup(e){var t,i;if(this.initialized)et("Already initialized, skipping setup");else try{et("Initializing Slardar with config:",{bid:e.bid,release:e.release,env:e.env,userId:e.userId,projectId:e.projectId});const o={get(e){Qe("Transport GET called: %s",e.url),Ze({method:"GET",...e})},post({url:e,data:t}){Qe("Transport POST called: %s",e),Ze({method:"POST",url:e,data:t?"string"==typeof t?t:JSON.stringify(t):void 0})}};this.client.init({bid:e.bid,transport:o,userId:e.userId,pid:e.projectId,deviceId:e.deviceId,sessionId:e.sessionId,release:e.release,env:e.env,name:e.name,useLocalConfig:(t=e.useLocalConfig,i=()=>!1,null!=t?t:i()),domain:e.domain,sample:{sample_rate:1,include_users:[],sample_granularity:"session",rules:{}}}),this.client.on("send",(e=>{et("send hook called for event: %s",Xe([e,"optionalAccess",e=>e.ev_type])||"unknown")})),this.client.start(),this.initialized=!0,et("Slardar initialized successfully")}catch(e){et("Failed to initialize:",e)}}ensureInitialized(){return!!this.initialized||(et("Not initialized, call setup() first"),!1)}sendEvent(e,t,i){if(this.ensureInitialized())try{et("Sending event:",{name:e,metrics:t,categories:i});const o=t?Object.fromEntries(Object.entries(t).filter((([,e])=>void 0!==e))):void 0,s=i?Object.fromEntries(Object.entries(i).filter((([,e])=>void 0!==e))):void 0;Xe([this,"access",e=>e.client,"access",e=>e.sendEvent,"optionalCall",t=>t({name:e,metrics:o,categories:s})])}catch(e){et("Failed to send event:",e)}}sendLog(e,t,i){if(this.ensureInitialized())try{et("Sending log:",{level:e,message:t,extra:i}),this.sendEvent("cli_log",void 0,{level:e,message:t,...i})}catch(e){et("Failed to send log:",e)}}reportError(e,t,i){if(this.ensureInitialized())try{const o={ev_type:"js_error",payload:{error:{name:e.name,message:e.message,stack:e.stack},breadcrumbs:[],extra:t,source:i||{type:"manual"}}};et("Reporting JS error:",{name:e.name,message:e.message.slice(0,100),stack:Xe([e,"access",e=>e.stack,"optionalAccess",e=>e.slice,"call",e=>e(0,200)]),extra:t,source:i}),this.client.report(o),et("JS error reported successfully")}catch(e){et("Failed to report error:",e)}}setContext(e,t){this.ensureInitialized()&&Xe([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.set,"call",i=>i(e,t)])}mergeContext(e){this.ensureInitialized()&&(et("Merging context:",e),Xe([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.merge,"call",t=>t(e)]))}deleteContext(e){this.ensureInitialized()&&Xe([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.delete,"call",t=>t(e)])}clearContext(){this.ensureInitialized()&&Xe([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.clear,"call",e=>e()])}updateConfig(e){if(this.ensureInitialized())try{et("Updating config:",e),this.client.config({userId:e.userId,release:e.release,sessionId:e.sessionId,env:e.env})}catch(e){et("Failed to update config:",e)}}async flush(e=1500){this.ensureInitialized()&&(et("Flushing Slardar data..."),Xe([this,"access",e=>e.client,"access",e=>e.getSender,"optionalCall",e=>e(),"optionalAccess",e=>e.flush,"call",e=>e()]),et("Waiting %dms for events to be sent...",e),await new Promise((t=>setTimeout(t,e))),et("Slardar data flushed"))}getRawClient(){return this.client}}const ot=new it;function st(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 nt="cli_start",rt="cli_command",at="cli_command_complete",ct="cli_error",dt="network_request",lt="file_operation",pt={cliStart:e=>({name:nt,metrics:{duration:0,...e}}),cliCommand:(e,t)=>({name:rt,categories:{command:e,args:st([t,"optionalAccess",e=>e.args]),status:"running",...st([t,"optionalAccess",e=>e.categories])},metrics:st([t,"optionalAccess",e=>e.metrics])}),cliCommandComplete:(e,t,i,o)=>({name:at,categories:{command:e,args:st([o,"optionalAccess",e=>e.args]),status:t?"success":"fail",...st([o,"optionalAccess",e=>e.categories])},metrics:{duration:i,...st([o,"optionalAccess",e=>e.errorCode])&&{errorCode:o.errorCode}}}),networkRequest:(e,t)=>({name:dt,categories:{url:e,method:st([t,"optionalAccess",e=>e.method])||"GET",statusCode:st([t,"optionalAccess",e=>e.statusCode,"optionalAccess",e=>e.toString,"call",e=>e()]),status:st([t,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:st([t,"optionalAccess",e=>e.duration])}}),fileOperation:(e,t,i)=>({name:lt,categories:{operation:e,filePath:t,status:st([i,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:st([i,"optionalAccess",e=>e.duration]),fileSize:st([i,"optionalAccess",e=>e.fileSize])}}),cliError:(e,t)=>({name:ct,categories:{errorName:e.name,errorMessage:e.message,stack:e.stack||"",...t},metrics:{errorCode:1}})};function ut(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 _t(e){return(...t)=>{try{const i=e(...t);return i instanceof Promise?i.catch((()=>{})):i}catch(e){}}}const ht=_t((()=>{var e,t;ot.setup({bid:"coze_cli",release:W,env:"production",userId:process.env.USER||"",useLocalConfig:!1,domain:"mon.zijieapi.com"}),ot.mergeContext({platform:process.platform,callerPlatform:(e=process.env.COZE_CLI_PLATFORM,t=()=>"unknown",null!=e?e:t()),nodeVersion:process.version,cliVersion:W})})),mt=_t((e=>{const t=pt.cliCommand(e);ot.sendEvent(t.name,t.metrics,t.categories)})),gt=_t(((e,t,i,o)=>{const s=pt.cliCommandComplete(e,t,i,{errorCode:ut([o,"optionalAccess",e=>e.errorCode])});ot.sendEvent(s.name,s.metrics,s.categories)})),ft=_t(((e,t)=>{ot.reportError(e,t,{type:"cli",data:t})})),yt=_t((async()=>{await ot.flush()}));async function vt(e,t){if(e.config.disableTelemetry)return void await t();ht();const i=function(e){if(e.commandName)return e.commandName;const t=[];for(const i of e.argv){if(i.startsWith("-"))break;t.push(i)}return t.join(" ")||"unknown"}(e);mt(i);const o=Date.now();let s,n=!0;try{await t()}catch(e){throw n=!1,s=e instanceof Error?e:new Error(String(e)),e}finally{const e=Date.now()-o;try{n?gt(i,!0,e):(s&&ft(s,{command:i}),gt(i,!1,e)),await yt()}catch(e){}}}function wt(e,t){return null!=e?e:t()}const bt=c.join(d.homedir(),".coze","logs");class St{__init(){this.fileStream=null}__init2(){this.writeError=!1}constructor(e={}){St.prototype.__init.call(this),St.prototype.__init2.call(this),this.format=wt(e.format,(()=>"text")),this.printToStderr=wt(e.printToStderr,(()=>!1)),this.tags=wt(e.tags,(()=>({}))),this.startTime=Date.now();const t=wt(e.logFile,(()=>this.getDefaultLogPath()));this.logFile=t;try{this.ensureLogDir(),this.rotateLogFiles(),this.fileStream=l.createWriteStream(t,{flags:"a"}),this.fileStream.on("error",(()=>{this.fileStream=null}))}catch(e){this.logFile=null,this.fileStream=null}}getDefaultLogPath(){const e=(new Date).toISOString().replace(/[:.]/g,"-"),{pid:t}=process;return c.join(bt,`${e}-${t}.log`)}ensureLogDir(){l.existsSync(bt)||l.mkdirSync(bt,{recursive:!0})}rotateLogFiles(){try{const e=l.readdirSync(bt).filter((e=>e.endsWith(".log"))).map((e=>({name:e,path:c.join(bt,e),mtime:l.statSync(c.join(bt,e)).mtime.getTime()}))).sort(((e,t)=>t.mtime-e.mtime));e.length>=10&&e.slice(9).forEach((e=>{try{l.unlinkSync(e.path)}catch(e){}}))}catch(e){}}verbose(e,...t){this.log("verbose",e,t)}info(e,...t){this.log("info",e,t)}warn(e,...t){this.log("warn",e,t)}error(e,...t){this.log("error",e,t)}success(e,...t){this.log("success",e,t)}debug(e,...t){this.log("debug",e,t)}debugFileOnly(e,...t){this.log("debug",e,t,!1)}log(e,t,i,o=this.printToStderr){const s=this.formatEntry(e,t,i);if(this.fileStream)try{this.fileStream.write(`${s}\n`)}catch(e){!this.writeError&&o&&(process.stderr.write("Warning: Log write failed\n"),this.writeError=!0)}o&&process.stderr.write(`${s}\n`)}formatEntry(e,t,i){const o=(new Date).toISOString(),s=Date.now()-this.startTime;if("json"===this.format){const n={level:e,timestamp:o,delta:s,...this.tags,message:t};return i.length>0&&(n.args=i),JSON.stringify(n)}const n=Object.entries(this.tags).map((([e,t])=>`${e}=${t}`)).join(" "),r=i.length>0?` ${i.map(String).join(" ")}`:"";return`${e.toUpperCase().padEnd(7)} [${o}] +${s}ms ${n} ${t}${r}`}close(){if(this.fileStream)try{this.fileStream.end()}catch(e){}}}function Pt(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 Ct=new Set(["authorization","cookie","set-cookie"]),Tt=/(^|_|-)(token|secret|password|authorization|cookie)(_|-|$)/i,Et=Symbol("request-debug-json-parse-fallback");let kt=null,It=!1,At=!1;const jt=e.customFetch.fetch.bind(e.customFetch),Rt=e=>"[object Object]"===Object.prototype.toString.call(e),zt=e=>{try{return JSON.stringify(e)}catch(t){return JSON.stringify(String(e))}},Ut=e=>{if("string"!=typeof e)return"***";const t=e.trim(),i=Pt([/^bearer\s+/i,"access",e=>e.exec,"call",e=>e(t),"optionalAccess",e=>e[0]]);return i?`${i}***`:"***"},Lt=(e,t)=>t&&Tt.test(t)?Ut(e):Array.isArray(e)?e.map((e=>Lt(e))):Rt(e)?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,Lt(t,e)]))):e,Ot=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(Array.from(e.entries()).map((([e,t])=>[e.toLowerCase(),t])));if(Array.isArray(e))return Object.fromEntries(e.map((([e,t])=>[e.toLowerCase(),String(t)])));const t=e;return"function"==typeof t.toJSON?Ot(t.toJSON()):"function"==typeof t.entries?Object.fromEntries(Array.from(t.entries()).map((([e,t])=>[e.toLowerCase(),t]))):Object.fromEntries(Object.entries(e).map((([e,t])=>[e.toLowerCase(),Array.isArray(t)?t.map((e=>String(e))).join(", "):String(t)])))},xt=(e,t)=>e[t.toLowerCase()],Bt=(e,t,i="binary")=>{const o=(e=>"string"==typeof e?a.Buffer.byteLength(e):a.Buffer.isBuffer(e)?e.length:e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:"undefined"!=typeof Blob&&e instanceof Blob?e.size:void 0)(e),s=[i];return t&&s.push(t),"number"==typeof o&&s.push(`${o} bytes`),`[${s.join("; ")}]`},qt=(t,i)=>{if(null==t||""===t)return"<empty>";const o=Pt([xt,"call",e=>e(i,"content-type"),"optionalAccess",e=>e.toLowerCase,"call",e=>e()]);if(Pt([o,"optionalAccess",e=>e.includes,"call",e=>e("multipart/form-data")]))return Bt(t,o,"multipart");if(t instanceof URLSearchParams)return zt(Lt(Object.fromEntries(Array.from(t.entries()))));if(a.Buffer.isBuffer(t)||t instanceof Uint8Array||t instanceof ArrayBuffer||"undefined"!=typeof Blob&&t instanceof Blob)return Bt(t,o);if("string"==typeof t){const i=(t=>{const i=e.safeJsonParse(t,Et);if(i!==Et)return i})(t);return void 0!==i?zt(Lt(i)):JSON.stringify(t)}return Array.isArray(t)||Rt(t)?zt(Lt(t)):Bt(t,o,typeof t)},Dt=(e,t)=>{try{return new URL(e,t).toString()}catch(i){return t?`${t}${e}`:e}},Mt=e=>{const t=Ot(e);return t["x-tt-logid"]||t["x-tt-log-id"]||t.logid||""},Nt=e=>(e||"GET").toUpperCase(),Gt=e=>{It&&kt&&(kt instanceof St?kt.debugFileOnly(e):kt.debug(e))},$t=({method:e,url:t,headers:i,body:o})=>{const s=Ot(i);Gt(`[DBG][HTTP][REQ] ${e} ${t}\nheaders: ${zt((e=>Object.fromEntries(Object.entries(e).map((([e,t])=>[e,Ct.has(e)?Ut(t):t]))))(s))}\nbody: ${qt(o,s)}`)},Ft=({method:e,url:t,status:i,logId:o})=>{Gt(`[DBG][HTTP][RES] ${e} ${t} status=${i} logid=${o||"-"}`)},Vt=({method:e,url:t,status:i,logId:o,message:s})=>{const n=(a=()=>"ERR",null!=(r=i)?r:a());var r,a;const c=s?` error=${JSON.stringify(s)}`:"";Gt(`[DBG][HTTP][ERR] ${e} ${t} status=${n} logid=${o||"-"}${c}`)},Wt=(e,t)=>t&&"body"in t?t.body:"object"==typeof e&&e&&"body"in e&&null!==e.body?"[request body stream]":void 0,Ht=()=>{e.axiosInstance.interceptors.request.use((e=>((e=>{const t=Nt(e.method),i=Dt(e.url||"",e.baseURL),o=Ot(e.headers);$t({method:t,url:i,headers:o,body:e.data})})(e),e))),e.axiosInstance.interceptors.response.use((e=>((e=>{const t=Nt(Pt([e,"access",e=>e.config,"optionalAccess",e=>e.method])),i=Dt(Pt([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",Pt([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Ft({method:t,url:i,status:e.status,logId:Mt(e.headers)})})(e),e)),(e=>((e=>{const t=Nt(Pt([e,"access",e=>e.config,"optionalAccess",e=>e.method])),i=Dt(Pt([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",Pt([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Vt({method:t,url:i,status:Pt([e,"access",e=>e.response,"optionalAccess",e=>e.status]),logId:Mt(Pt([e,"access",e=>e.response,"optionalAccess",e=>e.headers])),message:e.message})})(e),Promise.reject(e))))},Jt=()=>{e.customFetch.fetch=async(t,i)=>{const o=((e,t)=>Pt([t,"optionalAccess",e=>e.method])?Nt(t.method):"object"==typeof e&&e&&"method"in e&&"string"==typeof e.method?Nt(e.method):"GET")(t,i),s=(e=>"string"==typeof e?e:e instanceof URL?e.toString():"object"==typeof e&&e&&"url"in e&&"string"==typeof e.url?e.url:String(e))(t),n=e.customFetch.getRequestHeaders(t,i);$t({method:o,url:s,headers:n,body:Wt(t,i)});try{const e=await jt(t,i);return Ft({method:o,url:s,status:e.status,logId:Mt(e.headers)}),e}catch(e){throw Vt({method:o,url:s,message:e instanceof Error?e.message:String(e)}),e}}};function Kt(e,t){return null!=e?e:t()}function Qt(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 Yt;!function(e){e.AUTHORIZATION_PENDING="authorization_pending";e.SLOW_DOWN="slow_down";e.ACCESS_DENIED="access_denied";e.EXPIRED_TOKEN="expired_token"}(Yt||(Yt={}));const Zt=e=>new Promise((t=>setTimeout(t,e))),Xt=e.createRequestClient({baseURL:"https://api.coze.com",useDefaultPlugins:!0,plugins:[{name:"oauth-error-handler",onError:t=>{if(e.isHttpError(t))throw t;const i=t,o=Kt(Qt([i,"access",e=>e.response,"optionalAccess",e=>e.data]),(()=>({}))),s=o.error_description||o.error||i.message,n={status:Qt([i,"access",e=>e.response,"optionalAccess",e=>e.status]),code:o.error,config:i.config,response:i.response,data:o};throw new e.HttpError(Kt(s,(()=>"OAuth request failed")),n)}}]});async function ei(e){return(await Xt.post("/api/permission/oauth2/token",{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode},{baseURL:e.baseURL})).data}const ti=async(t,i)=>{const o=process.env.HTTP_PROXY||process.env.http_proxy,s=process.env.HTTPS_PROXY||process.env.https_proxy;if(s||o){const i=new p.EnvHttpProxyAgent;e.customFetch.setDispatcher(i);const[{HttpProxyAgent:n},{HttpsProxyAgent:r}]=await Promise.all([import("http-proxy-agent"),import("https-proxy-agent")]);e.axiosInstance$1.defaults.proxy=!1,Xt.defaults.proxy=!1,s&&(e.axiosInstance$1.defaults.httpsAgent=new r(s),Xt.defaults.httpsAgent=new r(s),t.ui.debug(`HTTPS proxy enabled: ${s}`)),o&&(e.axiosInstance$1.defaults.httpAgent=new n(o),Xt.defaults.httpAgent=new n(o),t.ui.debug(`HTTP proxy enabled: ${o}`))}await i()};let ii=()=>{},oi=null;const si=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ni=(e,t)=>{return si(i=e)&&"function"==typeof i.set?(Object.entries(t).forEach((([t,i])=>{e.set(t,i)})),e):{...si(e)?e:{},...t};var i},ri=t=>{ii=t,null===oi&&(oi=e.axiosInstance$1.interceptors.request.use((t=>{const i=s.getCozeAccountHeaders(ii());return 0!==Object.keys(i).length&&s.shouldInjectCozeAccountHeader((t=>{const i=t.url;if(!i)return"";try{return new URL(i,t.baseURL||e.axiosInstance$1.defaults.baseURL).toString()}catch(e){return""}})(t))?(t.headers=ni(t.headers,i),t):t})))};async function ai(t,i){ri((()=>t.config.organizationId)),s.installScopedCozeAccountFetchHeader({getOrganizationId:()=>t.config.organizationId});const o=await t.auth.getValidAccessToken();e.axiosInstance$1.defaults.baseURL=t.config.apiBaseUrl;const n=`Bearer ${o}`;e.axiosInstance$1.defaults.headers.Authorization=n,e.axiosInstance$1.defaults.headers["x-request-from-coze-cli"]="1",e.customFetch.setHeaders({Authorization:n,"x-request-from-coze-cli":"1"}),t.config.xTTEnv&&(e.axiosInstance$1.defaults.headers["x-use-ppe"]="1",e.axiosInstance$1.defaults.headers["x-tt-env"]=t.config.xTTEnv,e.customFetch.setHeaders({"x-use-ppe":"1","x-tt-env":t.config.xTTEnv})),await i()}function ci(e){if(!Array.isArray(e))throw new TypeError("Middleware stack must be an array!");for(const t of e)if("function"!=typeof t)throw new TypeError("Middleware must be composed of functions!");return function(t,i){let o=-1;return function s(n){if(n<=o)return Promise.reject(new Error("next() called multiple times"));o=n;let r=e[n];n===e.length&&(r=i);if(!r)return Promise.resolve();try{return Promise.resolve(r(t,s.bind(null,n+1)))}catch(e){return Promise.reject(e)}}(0)}}var di,li,pi,ui,_i,hi,mi,gi,fi,yi,vi,wi,bi,Si,Pi,Ci,Ti,Ei,ki,Ii,Ai,ji,Ri,zi,Ui,Li,Oi,xi,Bi,qi,Di,Mi,Ni,Gi,$i,Fi,Vi,Wi,Hi,Ji,Ki,Qi,Yi,Zi,Xi,eo,to,io,oo,so,no,ro,ao;function co(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.app="app";e.pat="pat"}(di||(di={})),function(e){e.can_apply2="CanApply";e.already_applied2="AlreadyApplied";e.joined4="Joined";e.deny3="Deny"}(li||(li={})),function(e){e.processing="Processing";e.approved="Approved";e.rejected="Rejected";e.auto_approved="AutoApproved"}(pi||(pi={})),function(e){e.normal="Normal";e.connector="Connector";e.privilege="Privilege"}(ui||(ui={})),function(e){e.auth_app="AuthApp";e.on_behalf_of_user="OnBehalfOfUser"}(_i||(_i={})),function(e){e.password="Password";e.sms="Sms";e.email="Email";e.unknown3="Unknown"}(hi||(hi={})),function(e){e.authorized="authorized";e.unauthorized="unauthorized";e.expired4="expired"}(mi||(mi={})),function(e){e.api_key="api_key";e.wechat_official="wechat_official";e.oauth_2="oauth2"}(gi||(gi={})),function(e){e.noncertificated="Noncertificated";e.certificated="Certificated"}(fi||(fi={})),function(e){e.uncertified="Uncertified";e.personal_certification="PersonalCertification";e.enterprise_certification="EnterpriseCertification"}(yi||(yi={})),function(e){e.obo="Obo";e.app_auth="AppAuth";e.personal_access_token="PersonalAccessToken"}(vi||(vi={})),function(e){e.legacy="Legacy";e.web_backend="WebBackend";e.single_page_or_native="SinglePageOrNative";e.terminal="Terminal";e.service="Service"}(wi||(wi={})),function(e){e.bot_editor="BotEditor";e.bot_developer="BotDeveloper";e.bot_operator="BotOperator"}(bi||(bi={})),function(e){e.workspace="Workspace";e.o_auth_app="OAuthApp";e.authorized_o_auth_app="AuthorizedOAuthApp";e.service_access_token="ServiceAccessToken";e.personal_access_token2="PersonalAccessToken";e.connector2="Connector";e.normal_api_app="NormalApiApp";e.connector_api_app="ConnectorApiApp"}(Si||(Si={})),function(e){e.visitors_prohibited="VisitorsProhibited";e.guest_prohibited_by_invited_user_enterprise2="GuestProhibitedByInvitedUserEnterprise";e.prohibited_by_custom_people_management="ProhibitedByCustomPeopleManagement"}(Pi||(Pi={})),function(e){e.dev2="DEV";e.prod2="PROD"}(Ci||(Ci={})),function(e){e._1="1";e._30="30";e._90="90";e._180="180";e._365="365";e.customize="customize";e.permanent="permanent"}(Ti||(Ti={})),function(e){e._12="1";e._302="30";e._902="90";e._1802="180";e._3652="365";e.customize2="customize";e.permanent2="permanent"}(Ei||(Ei={})),function(e){e.aes_256_gcm="AES-256-GCM"}(ki||(ki={})),function(e){e.conversation="Conversation";e.unknown="Unknown"}(Ii||(Ii={})),function(e){e.active3="Active";e.inactive="Inactive"}(Ai||(Ai={})),function(e){e.cloud_kms="CloudKMS",e.default="Default";e.unknown2="Unknown"}(ji||(ji={})),function(e){e.user_custom2="user_custom";e.consumer3="consumer"}(Ri||(Ri={})),function(e){e.super_admin="SuperAdmin";e.admin="Admin";e.member="Member";e.guest="Guest"}(zi||(zi={})),function(e){e.join_enterprise_share_link_expiration_time="JoinEnterpriseShareLinkExpirationTime";e.sso="SSO";e.forbid_guest_join_enterprise="ForbidGuestJoinEnterprise";e.forbid_member_join_other_enterprise="ForbidMemberJoinOtherEnterprise";e.replace_enterprise_logo="ReplaceEnterpriseLogo";e.forbid_custom_people_management="ForbidCustomPeopleManagement";e.forbid_coze_store_plugin_access="ForbidCozeStorePluginAccess";e.enterprise_member_listing_skill_coze_store="EnterpriseMemberListingSkillCozeStore";e.listing_skill_enterprise_store_audit="ListingSkillEnterpriseStoreAudit"}(Ui||(Ui={})),function(e){e.string="String";e.boolean="Boolean";e.integer="Integer";e.string_list="StringList"}(Li||(Li={})),function(e){e.must_handle="MustHandle";e.no_need_handle="NoNeedHandle"}(Oi||(Oi={})),function(e){e.pending_review_app_auth="pending_review_app_auth";e.pending_review_app_obo="pending_review_app_obo";e.approved_app_auth="approved_app_auth";e.approved_app_obo="approved_app_obo"}(xi||(xi={})),function(e){e.no_permission="NoPermission";e.guest_prohibited_by_enterprise2="GuestProhibitedByEnterprise";e.guest_prohibited_by_invited_user_enterprise3="GuestProhibitedByInvitedUserEnterprise";e.guest_prohibited_by_custom_people_management="GuestProhibitedByCustomPeopleManagement"}(Bi||(Bi={})),function(e){e.confirming2="Confirming";e.joined3="Joined";e.rejected3="Rejected";e.revoked2="Revoked";e.expired3="Expired";e.deny2="Deny"}(qi||(qi={})),function(e){e.confirming="Confirming";e.joined2="Joined";e.rejected2="Rejected";e.revoked="Revoked";e.expired2="Expired"}(Di||(Di={})),function(e){e.can_join="CanJoin";e.guest_prohibited_by_enterprise="GuestProhibitedByEnterprise";e.guest_prohibited_by_invited_user_enterprise="GuestProhibitedByInvitedUserEnterprise"}(Mi||(Mi={})),function(e){e.can_apply="CanApply";e.already_applied="AlreadyApplied";e.joined="Joined";e.expired="Expired";e.deny="Deny"}(Ni||(Ni={})),function(e){e.free="Free";e.premium_lite="PremiumLite";e.premium="Premium";e.premium_plus="PremiumPlus";e.v_1_pro_instance="V1ProInstance";e.pro_personal="ProPersonal";e.coze_personal_plus="CozePersonalPlus";e.coze_personal_advanced="CozePersonalAdvanced";e.coze_personal_pro="CozePersonalPro";e.team="Team";e.enterprise_basic="EnterpriseBasic";e.enterprise="Enterprise";e.enterprise_pro="EnterprisePro"}(Gi||(Gi={})),function(e){e.user_custom_only="user_custom_only";e.all2="all"}($i||($i={})),function(e){e.system="system";e.custom="custom"}(Fi||(Fi={})),function(e){e.not_in_enterprise="NotInEnterprise";e.prohibited_by_custom_people_management2="ProhibitedByCustomPeopleManagement"}(Vi||(Vi={})),function(e){e.can_apply3="CanApply";e.already_applied3="AlreadyApplied";e.joined5="Joined";e.deny4="Deny"}(Wi||(Wi={})),function(e){e.super_admin2="SuperAdmin";e.admin2="Admin";e.member2="Member";e.guest2="Guest"}(Hi||(Hi={})),function(e){e.member_joining_auto_approved="MemberJoiningAutoApproved"}(Ji||(Ji={})),function(e){e.string2="String";e.boolean2="Boolean";e.integer2="Integer";e.string_list2="StringList"}(Ki||(Ki={})),function(e){e.developer="developer";e.consumer2="consumer"}(Qi||(Qi={})),function(e){e.all="all";e.owned="owned";e.others="others"}(Yi||(Yi={})),function(e){e.enterprise_member="EnterpriseMember";e.enterprise_guest="EnterpriseGuest"}(Zi||(Zi={})),function(e){e.not_created="NotCreated";e.enabled="Enabled";e.disabled="Disabled"}(Xi||(Xi={})),function(e){e.production="Production";e.development="Development"}(eo||(eo={})),(to||(to={})).skill="skill",function(e){e.dev="dev";e.prod="prod"}(io||(io={})),function(e){e.user_custom="user_custom";e.coze_default="coze_default";e.consumer="consumer"}(oo||(oo={})),function(e){e.active2="Active";e.deactive="Deactive"}(so||(so={})),function(e){e.active="active";e.deactivated="deactivated";e.offboarded="offboarded"}(no||(no={})),function(e){e.studio_space_selector="studio_space_selector";e.studio_create_project_btn="studio_create_project_btn";e.studio_home_page="studio_home_page";e.studio_develop="studio_develop";e.studio_library="studio_library";e.studio_tasks="studio_tasks";e.studio_evaluate="studio_evaluate";e.studio_space_manage="studio_space_manage";e.studio_templates_store="studio_templates_store";e.studio_plugins_store="studio_plugins_store";e.studio_agents_store="studio_agents_store";e.studio_playground="studio_playground";e.studio_docs="studio_docs";e.studio_enterprise_agents_store="studio_enterprise_agents_store";e.studio_enterprise_plugins_store="studio_enterprise_plugins_store";e.studio_organization_manage="studio_organization_manage";e.studio_enterprise_card="studio_enterprise_card";e.studio_subscription_card="studio_subscription_card";e.studio_personal_menu="studio_personal_menu";e.studio_more_products="studio_more_products";e.studio_notice="studio_notice";e.studio_migration_banner="studio_migration_banner";e.coding_space_selector="coding_space_selector";e.coding_create_project="coding_create_project";e.coding_project_manage="coding_project_manage";e.coding_integrations="coding_integrations";e.coding_library="coding_library";e.coding_tasks="coding_tasks";e.coding_playground="coding_playground";e.coding_evaluate="coding_evaluate";e.coding_coze_redirect="coding_coze_redirect";e.coding_docs="coding_docs";e.coding_community="coding_community";e.coding_enterprise_card="coding_enterprise_card";e.coding_subscription_card="coding_subscription_card";e.coding_personal_menu="coding_personal_menu";e.coding_notice="coding_notice";e.admin_organization_manage="admin_organization_manage";e.admin_member_manage="admin_member_manage";e.admin_enterprise_config="admin_enterprise_config"}(ro||(ro={})),function(e){e.root_user="RootUser";e.basic_user="BasicUser"}(ao||(ao={}));class lo{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){lo.prototype.__init.call(this),lo.prototype.__init2.call(this),this.request=co([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=co([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}CreatePersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/create_personal_access_token_and_permission"),s={name:i.name,expire_at:i.expire_at,duration_day:i.duration_day,organization_id:i.organization_id,workspace_permission:i.workspace_permission,account_permission:i.account_permission,workspace_permission_v2:i.workspace_permission_v2,enterprise_permission:i.enterprise_permission},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}UpdatePersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/update_personal_access_token_and_permission"),s={workspace_permission:i.workspace_permission,account_permission:i.account_permission,workspace_permission_v2:i.workspace_permission_v2,enterprise_permission:i.enterprise_permission,id:i.id,name:i.name},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}DeletePersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/delete_personal_access_token_and_permission"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}ListPersonalAccessTokens(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/pat/list_personal_access_tokens"),s={organization_id:i.organization_id,page:i.page,size:i.size,search_option:i.search_option};return this.request({url:o,method:"GET",params:s},t)}GetPersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/get_personal_access_token_and_permission"),s={id:i.id};return this.request({url:o,method:"GET",params:s},t)}ListPersonalAccessTokenSupportPermissions(e,t){const i=this.genBaseURL("/api/permission_api/pat/list_personal_access_token_support_permissions");return this.request({url:i,method:"GET"},t)}CheckPersonalAccessTokenInWorkspace(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/check_personal_access_token_in_workspace"),s={workspace_id:i.workspace_id};return this.request({url:o,method:"GET",params:s},t)}AddCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/add_collaborator"),s={collaborator_types:i.collaborator_types,principal:i.principal,resource:i.resource};return this.request({url:o,method:"POST",data:s},t)}RemoveCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/remove_collaborator"),s={principal:i.principal,resource:i.resource};return this.request({url:o,method:"POST",data:s},t)}CreateAppMeta(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/create_app_meta"),s={app_type:i.app_type,client_type:i.client_type,name:i.name,description:i.description,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListAppMeta(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/list_app_meta"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}GetAppMeta(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_app_meta"),s={appid:i.appid},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}UpdateAppMeta(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/update_app_meta"),s={status:i.status,oauth2_configuration:i.oauth2_configuration,appid:i.appid,name:i.name,description:i.description,declared_permission:i.declared_permission,declared_permission_v2:i.declared_permission_v2},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}UploadPublicKey(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/upload_public_key"),s={appid:i.appid,public_key_pem:i.public_key_pem};return this.request({url:o,method:"POST",data:s},t)}DeletePublicKey(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/delete_public_key"),s={fingerprint:i.fingerprint};return this.request({url:o,method:"POST",data:s},t)}CreateClientSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/create_client_secret"),s={appid:i.appid};return this.request({url:o,method:"POST",data:s},t)}DeleteClientSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/delete_client_secret"),s={appid:i.appid,client_secret_id:i.client_secret_id};return this.request({url:o,method:"POST",data:s},t)}PutOAuth2Configuration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/put_oauth2_configuration"),s={oauth2_configuration:i.oauth2_configuration,appid:i.appid};return this.request({url:o,method:"POST",data:s},t)}AuthorizeAppWithDeclaredPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/authorize_app_with_declared_permission"),s={appid:i.appid,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListAuthorizedApps(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/list_authorized_apps"),s={page:i.page,size:i.size},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}GetAppAuthorizationRequestInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_app_authorization_request_info"),s={authorize_key:i.authorize_key},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}RevokeAppAuthorizedPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/revoke_app_authorized_permission"),s={authorization_type:i.authorization_type,appid:i.appid,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}DeleteApp(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/delete_app"),s={appid:i.appid};return this.request({url:o,method:"POST",data:s},t)}ModifyCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/modify_collaborator"),s={principal:i.principal,resource:i.resource,collaborator_types:i.collaborator_types};return this.request({url:o,method:"POST",data:s},t)}BatchAddCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/batch_add_collaborator"),s={principal_type:i.principal_type,resource:i.resource,principal_ids:i.principal_ids,collaborator_types:i.collaborator_types};return this.request({url:o,method:"POST",data:s},t)}GetAppInstallationRequestInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_app_installation_request_info"),s={appid:i.appid},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}AppInstallationConsent(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/app_installation_consent"),s={appid:i.appid,installation_account_hint:i.installation_account_hint};return this.request({url:o,method:"POST",data:s},t)}ImpersonateCozeUser(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/coze_web_app/impersonate_coze_user"),s={duration_seconds:i.duration_seconds,scope:i.scope,connector_info:i.connector_info};return this.request({url:o,method:"POST",data:s},t)}GetVolcanoConnectInfoWithInsName(e,t){const i=this.genBaseURL("/api/permission_api/volcano/get_volcano_connect_info_with_ins_name");return this.request({url:i,method:"GET"},t)}GetVolcanoMaskedMobile(e,t){const i=this.genBaseURL("/api/permission_api/volcano/get_volcano_masked_mobile");return this.request({url:i,method:"GET"},t)}BindVolcano(e,t){const i=this.genBaseURL("/api/permission_api/volcano/bind_volcano");return this.request({url:i,method:"POST"},t)}AuthorizeAppWithSpecifiedWorkspace(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/authorize_app_with_specified_permission"),s={appid:i.appid,workspace_list:i.workspace_list,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}GetUserProfile(e,t){const i=this.genBaseURL("/v1/users/me");return this.request({url:i,method:"GET"},t)}ListAppAuthorizations(e,t){const i=e,o=this.genBaseURL(`/v1/oauth-apps/${i.appid}/authorizations`),s={page_num:i.page_num,page_size:i.page_size},n={authorization:i.authorization};return this.request({url:o,method:"GET",params:s,headers:n},t)}GetCertificationInfo(e,t){const i=this.genBaseURL("/api/permission_api/enterprise/get_certification_info");return this.request({url:i,method:"GET"},t)}NeedCreateEnterprise(e,t){const i=this.genBaseURL("/api/permission_api/enterprise/need_create_enterprise");return this.request({url:i,method:"GET"},t)}CreateEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_enterprise"),s={name:i.name,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}ListEnterprise(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/enterprise/list_enterprises"),s={contain_enterprise_of_user:i.contain_enterprise_of_user,contain_organization_of_user:i.contain_organization_of_user,contain_guest_enterprise_of_user:i.contain_guest_enterprise_of_user,is_space:i.is_space};return this.request({url:o,method:"GET",params:s},t)}GetEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_enterprise"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"GET",params:s},t)}UpdateEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_enterprise"),s={enterprise_id:i.enterprise_id,name:i.name,icon_uri:i.icon_uri,replace_logo:i.replace_logo};return this.request({url:o,method:"POST",data:s},t)}UpdateEnterpriseSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_settings"),s={enterprise_id:i.enterprise_id,enterprise_settings:i.enterprise_settings};return this.request({url:o,method:"POST",data:s},t)}BatchAddEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_add_enterprise_people"),s={enterprise_id:i.enterprise_id,enterprise_people:i.enterprise_people,need_check_people_valid:i.need_check_people_valid};return this.request({url:o,method:"POST",data:s},t)}RemoveEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/remove_enterprise_people"),s={enterprise_id:i.enterprise_id,user_id:i.user_id,receiver:i.receiver,sync_default_organization:i.sync_default_organization};return this.request({url:o,method:"POST",data:s},t)}UpdateEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_people"),s={enterprise_id:i.enterprise_id,user_id:i.user_id,enterprise_role_type_list:i.enterprise_role_type_list,sync_default_organization:i.sync_default_organization};return this.request({url:o,method:"POST",data:s},t)}CreateEnterpriseInviteLink(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_enterprise_invite_link"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}CreateJoinApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_join_application"),s={key:i.key,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}GetInviteInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_invite_info"),s={invite_key:i.invite_key};return this.request({url:o,method:"GET",params:s},t)}UpdateJoinApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_join_application"),s={application_status:i.application_status,enterprise_id:i.enterprise_id,join_application_id_list:i.join_application_id_list};return this.request({url:o,method:"POST",data:s},t)}ListPersonalAccessTokensByCreator(e,t){const i=e,o=this.genBaseURL("/api/permission_api/permission/list_personal_access_tokens_by_creator"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}ListAppInstallations(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/list_app_installations"),s={enterprise_id:i.enterprise_id,organization_id:i.organization_id},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}GetEnterpriseSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_enterprise_settings"),s={enterprise_id:i.enterprise_id,enterprise_setting_key_list:i.enterprise_setting_key_list};return this.request({url:o,method:"POST",data:s},t)}SearchCanAddEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_can_add_enterprise_people"),s={people_type:i.people_type,enterprise_id:i.enterprise_id,search_key:i.search_key};return this.request({url:o,method:"POST",data:s},t)}SearchEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_enterprise_people"),s={people_type:i.people_type,enterprise_id:i.enterprise_id,search_key:i.search_key,enterprise_role_type_list:i.enterprise_role_type_list,need_volcano_user_info:i.need_volcano_user_info,need_people_number:i.need_people_number,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}ListJoinApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/list_join_application"),s={application_status:i.application_status,enterprise_id:i.enterprise_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}PostAdapterMpV1Code2Session(e,t){const i=e||{},o=this.genBaseURL("/adapter/mp/v1/code2session"),s={bot_id:i.bot_id,app_id:i.app_id,connector_id:i.connector_id,code:i.code,with_userinfo:i.with_userinfo,execute_mode:i.execute_mode,agent_type:i.agent_type,agent_version:i.agent_version};return this.request({url:o,method:"POST",data:s},t)}SubmitAppOboInstallationReview(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/submit_app_obo_installation_review"),s={appid:i.appid,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}InstallAppObo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/install_app_obo"),s={appid:i.appid,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}UninstallAppObo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/uninstall_app_obo"),s={appid:i.appid,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}GetChecklistForWorkspaceMigration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_checklist_for_workspace_migration"),s={workspace_id_list:i.workspace_id_list};return this.request({url:o,method:"POST",data:s},t)}CheckEnterpriseExist(e,t){const i=this.genBaseURL("/api/permission_api/enterprise/check_enterprise_exist");return this.request({url:i,method:"GET"},t)}GetSSOSetting(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_sso_setting"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}BatchMigrateAuthorization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/batch_migrate_authorization"),s={authorization_list:i.authorization_list,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/list_join_invitation"),s={invitation_status:i.invitation_status,enterprise_id:i.enterprise_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}RevokeJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/revoke_join_invitation"),s={enterprise_id:i.enterprise_id,join_invitation_id:i.join_invitation_id};return this.request({url:o,method:"POST",data:s},t)}UpdateJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_join_invitation"),s={enterprise_id:i.enterprise_id,join_invitation_id:i.join_invitation_id,joined:i.joined};return this.request({url:o,method:"POST",data:s},t)}GetJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_join_invitation"),s={join_invitation_id:i.join_invitation_id};return this.request({url:o,method:"POST",data:s},t)}SearchPeopleInOtherEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_people_in_other_enterprise"),s={enterprise_id:i.enterprise_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}CreateApplicationForEnterpriseMember(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_application_for_enterprise_member"),s={enterprise_id:i.enterprise_id,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}GetApplicationForEnterpriseMember(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_application_for_enterprise_member"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}AuthorizeAppsAndPersonalaccesstokenListWithPersonalAccountPermission(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/authorize_apps_and_patlist_with_personalaccountpermission"),s={crossaccount_authinfo_list:i.crossaccount_authinfo_list};return this.request({url:o,method:"POST",data:s},t)}RevokeAppAndPersonalaccesstokenPersonalAccountPermission(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/revoke_app_and_pat_personalaccountpermission"),s={crossaccount_authinfo:i.crossaccount_authinfo};return this.request({url:o,method:"POST",data:s},t)}GetAppsAndPersonalAccessTokenListForPersonalAccountPermissionAuthorization(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/get_apps_and_patlist_for_personalaccountpermission_authorization"),s={page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}create_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/create_service_identity"),s={name:i.name,organization_id:i.organization_id,expire_at:i.expire_at,duration_day:i.duration_day,permission:i.permission},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}get_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/get_service_identity"),s={id:i.id};return this.request({url:o,method:"GET",params:s},t)}update_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/update_service_identity"),s={permission:i.permission,id:i.id,name:i.name,expire_at:i.expire_at,duration_day:i.duration_day},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}delete_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/delete_service_identity"),s={id:i.id};return this.request({url:o,method:"POST",params:s},t)}list_service_identities(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/service/list_service_identities"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}ListEncryptionConfiguration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterpise/list_encryption_configuration"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}UpdateEncryptionConfiguration(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/enterpise/update_encryption_configuration"),s={encryption_configuration:i.encryption_configuration};return this.request({url:o,method:"POST",data:s},t)}SearchOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_organization"),s={enterprise_id:i.enterprise_id,search_key:i.search_key,joined:i.joined,need_people_number:i.need_people_number,need_workspace_number:i.need_workspace_number,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}CreateOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_organization"),s={enterprise_id:i.enterprise_id,name:i.name,icon_uri:i.icon_uri,description:i.description};return this.request({url:o,method:"POST",data:s},t)}GetOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_organization"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}UpdateOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_organization"),s={organization_id:i.organization_id,name:i.name,icon_uri:i.icon_uri,description:i.description};return this.request({url:o,method:"POST",data:s},t)}SearchCanAddOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_can_add_organization_people"),s={organization_id:i.organization_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}SearchOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_organization_people"),s={organization_role_type:i.organization_role_type,people_type:i.people_type,organization_id:i.organization_id,search_key:i.search_key,page:i.page,page_size:i.page_size,organization_role_type_list:i.organization_role_type_list};return this.request({url:o,method:"POST",data:s},t)}CreateJoinOrganizationApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_join_organization_application"),s={organization_id:i.organization_id,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}ListJoinOrganizationApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/list_join_organization_application"),s={application_status:i.application_status,organization_id:i.organization_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}UpdateJoinOrganizationApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_join_organization_application"),s={application_status:i.application_status,organization_id:i.organization_id,join_application_id_list:i.join_application_id_list};return this.request({url:o,method:"POST",data:s},t)}GetOrganizationApplicationForEnterpriseMember(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_organization_application_for_enterprise_member"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}CanCustomEncryptionConfiguration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterpise/can_custom_encryption_configuration"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"GET",params:s},t)}BatchAddOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_add_organization_people"),s={organization_id:i.organization_id,organization_people:i.organization_people};return this.request({url:o,method:"POST",data:s},t)}RemoveOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/remove_organization_people"),s={organization_id:i.organization_id,user_id:i.user_id,receiver:i.receiver};return this.request({url:o,method:"POST",data:s},t)}UpdateOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_organization_people"),s={organization_role_type:i.organization_role_type,organization_id:i.organization_id,user_id:i.user_id};return this.request({url:o,method:"POST",data:s},t)}DownloadRemoteAttestationEvidence(e,t){const i=e,o=this.genBaseURL("/api/permission_api/aicc/download_remote_attestation_evidence"),s={component_name:i.component_name};return this.request({url:o,method:"GET",params:s},t)}GetAgentAiccInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/aicc/get_agent_aicc_info"),s={agent_id:i.agent_id};return this.request({url:o,method:"GET",params:s},t)}CheckDeleteOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/check_delete_organization"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}DeleteOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/delete_organization"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListProjectUsers(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/list_project_users"),s={project_id:i.project_id,page_size:i.page_size,page_number:i.page_number,environment:i.environment,filter:i.filter};return this.request({url:o,method:"POST",data:s},t)}DeleteProjectUser(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user"),s={environment:i.environment,project_id:i.project_id,user_id:i.user_id};return this.request({url:o,method:"POST",data:s},t)}GetProjectAuthConfig(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}UpdateProjectAuthConfig(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config"),s={project_id:i.project_id,configuration:i.configuration};return this.request({url:o,method:"POST",data:s},t)}ListProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/list_project_secret"),s={env:i.env,project_id:i.project_id,with_providers:i.with_providers,deploy_id:i.deploy_id,option:i.option};return this.request({url:o,method:"POST",data:s},t)}UpdateProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/update_project_secret"),s={project_id:i.project_id,update_secrets:i.update_secrets,update_cred_provider:i.update_cred_provider};return this.request({url:o,method:"POST",data:s},t)}DeleteProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/delete_project_secret"),s={project_id:i.project_id,keys:i.keys,cred_provider_ids:i.cred_provider_ids};return this.request({url:o,method:"POST",data:s},t)}EncryptProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/encrypt_project_secret"),s={project_id:i.project_id,project_type:i.project_type,encrypt_secrets:i.encrypt_secrets};return this.request({url:o,method:"POST",data:s},t)}InsertProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/insert_project_secret"),s={project_id:i.project_id,insert_secrets:i.insert_secrets};return this.request({url:o,method:"POST",data:s},t)}OutboundAuthCallback(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/outbound_auth/callback"),s={session_id:i.session_id,error:i.error};return this.request({url:o,method:"GET",params:s},t)}CreateAgentAccessToken(e,t){const i=e,o=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:i.project_id,deployment_env:i.deployment_env};return this.request({url:o,method:"POST",data:s},t)}ListAgentAccessTokens(e,t){const i=e,o=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}DeleteAgentAccessToken(e,t){const i=e,o=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={token_id:i.token_id,project_id:i.project_id};return this.request({url:o,method:"DELETE",data:s},t)}GenerateInviteCode(e,t){const i=this.genBaseURL("/api/permission_api/coze_user/generate_invite_code");return this.request({url:i,method:"POST"},t)}GetInviteCodeInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/coze_user/get_invite_code_info"),s={invite_code:i.invite_code};return this.request({url:o,method:"GET",params:s},t)}AuthorizeCredProvider(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/authorize"),s={provider_id:i.provider_id};return this.request({url:o,method:"GET",params:s},t)}ProjectSecretAuthCallback(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/project_secret/callback"),s={code:i.code,state:i.state,error:i.error};return this.request({url:o,method:"GET",params:s},t)}ListAuthInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/list_auth_info"),s={credential_ids:i.credential_ids};return this.request({url:o,method:"POST",data:s},t)}RevokeAuthorization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/revoke"),s={credential_id:i.credential_id};return this.request({url:o,method:"POST",data:s},t)}VisibilityConfig(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/visibility_config"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}GetVolcanoLoginMaskedMobile(e,t){const i=this.genBaseURL("/api/permission_api/volcano/get_volcano_login_masked_mobile");return this.request({url:i,method:"GET"},t)}BatchGetPeopleJoinedOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_get_people_joined_organization"),s={enterprise_id:i.enterprise_id,user_ids:i.user_ids};return this.request({url:o,method:"POST",data:s},t)}BatchRemoveOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_remove_organization_people"),s={enterprise_id:i.enterprise_id,remove_user_list:i.remove_user_list};return this.request({url:o,method:"POST",data:s},t)}BatchRemoveEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_remove_enterprise_people"),s={enterprise_id:i.enterprise_id,remove_user_list:i.remove_user_list};return this.request({url:o,method:"POST",data:s},t)}GetOrganizationSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_organization_settings"),s={organization_id:i.organization_id,organization_setting_key_list:i.organization_setting_key_list};return this.request({url:o,method:"POST",data:s},t)}UpdateOrganizationSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_organization_settings"),s={organization_id:i.organization_id,organization_settings:i.organization_settings};return this.request({url:o,method:"POST",data:s},t)}GithubAuthCallback(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/github_auth/callback"),s={code:i.code,state:i.state,error:i.error};return this.request({url:o,method:"GET",params:s},t)}}const po=new lo({});function uo(e,t){return null!=e?e:t()}const _o=1e3,ho=Math.floor(new Date("2000-01-01T00:00:00.000Z").getTime()/_o),mo=e=>e instanceof Error?e.message:String(e);class go{constructor(e){this.ctx=e,this.config=e.config}getOAuthConfig(){return{baseURL:uo(this.config.openApiBaseUrl,(()=>s.DEFAULT_CONFIG.openApiBaseUrl)),clientId:uo(this.config.clientId,(()=>s.DEFAULT_CONFIG.clientId))}}async clearUserContext(){this.config.organizationId=void 0,this.config.enterpriseId=void 0,this.config.spaceId=void 0,await s.saveConfig({organizationId:void 0,enterpriseId:void 0,spaceId:void 0})}openInBrowser(e){const t="darwin"===process.platform?"open":"win32"===process.platform?"cmd":"xdg-open",i="win32"===process.platform?["/c","start",'""',e]:[e],s="Failed to open browser automatically. Please open the URL manually.";try{const e=o.spawn(t,i,{detached:!0,stdio:"ignore"});e.on("error",(()=>{this.ctx.ui.verbose(s)})),e.unref()}catch(e){this.ctx.ui.verbose(`${s} ${e instanceof Error?e.message:String(e)}`)}}async clearAuthData(){this.config.accessToken=void 0,this.config.refreshToken=void 0,this.config.tokenExpiresAt=void 0,await s.saveConfig({accessToken:void 0,refreshToken:void 0,tokenExpiresAt:void 0})}async login(t){if(this.ctx.ui.verbose("Initiating login process..."),t.token)return this.ctx.ui.info("Using Personal Access Token (PAT)..."),this.config.accessToken=t.token,await s.saveConfig({accessToken:t.token,refreshToken:void 0,tokenExpiresAt:void 0}),await this.clearUserContext(),this.ctx.ui.info("Authentication successful. Credentials saved."),void("json"===this.ctx.format&&this.ctx.response.print({success:!0,method:"PAT"}));try{this.ctx.ui.info("Starting OAuth flow...");const{baseURL:t,clientId:o}=this.getOAuthConfig();this.ctx.ui.verbose("Starting OAuth device flow...");const s=await async function(e){const t=e.workspaceId?`/api/permission/oauth2/workspace_id/${e.workspaceId}/device/code`:"/api/permission/oauth2/device/code";return(await Xt.post(t,{client_id:e.clientId},{baseURL:e.baseURL})).data}({baseURL:t,clientId:o}),n=`${s.verification_uri}?user_code=${s.user_code}`;this.ctx.ui.info(`Please visit ${i.underline(n)} and authorize the application.\n\nPrivacy Policy: ${i.underline("https://docs.coze.cn/guides/privacy")}\nTerms of Service: ${i.underline("https://docs.coze.cn/guides/terms-of-service")}\n\nIf you are an agent using Coze CLI, please share the authorization link,\nPrivacy Policy, and Terms of Service with your users.\n `),this.openInBrowser(n);const r=await async function(t,i){if(!t.poll)return ei(t);let o=5e3;for(i.ui.debug("Start Polling for device token..."),i.ui.debug(`Polling interval: ${o}ms`),i.ui.debug("Polling timeout: 30000ms");;)try{i.ui.debug(`Polling for device token..., ${JSON.stringify(t)}`);const e=await ei(t);return i.ui.debug(`Polling for device token success: ${JSON.stringify(e)}`),e}catch(t){if(e.isHttpError(t)){const e=t;i.ui.debug(`Polling for device token error, the error is a HttpError.\n logid: ${Qt([e,"access",e=>e.response,"optionalAccess",e=>e.headers,"access",e=>e["x-tt-logid"]])}`),i.ui.debug(`Polling for device token error: ${JSON.stringify(Kt(Qt([e,"access",e=>e.toJSON,"optionalCall",e=>e()]),(()=>e)))}`);const s=e.data;if(Qt([s,"optionalAccess",e=>e.error])===Yt.AUTHORIZATION_PENDING){i.ui.debug("Polling for device token: user has not completed authorization yet."),await Zt(o);continue}if(Qt([s,"optionalAccess",e=>e.error])===Yt.SLOW_DOWN){o<3e4&&(o+=5e3),i.ui.debug(`Polling for device token: client is polling too frequently. Increasing interval to ${o}ms`),await Zt(o);continue}}const s=t;throw i.ui.debug(`Polling for device token error, the error is: ${s.message}\n ${s.stack}\n `),t}}({baseURL:t,clientId:o,deviceCode:s.device_code,poll:!0},this.ctx);this.ctx.ui.debug(`Polling for device token success: ${JSON.stringify(r)}`),await this.saveOAuthToken(r),this.ctx.ui.debug("Saving OAuth token successfully."),await this.clearUserContext(),this.ctx.ui.info("Authentication successful. Credentials saved."),"json"===this.ctx.format&&this.ctx.response.print({success:!0,method:"OAuth"})}catch(e){throw this.ctx.ui.error(`OAuth login failed: ${mo(e)}`),e}}async logout(){await this.clearAuthData(),await this.clearUserContext(),this.ctx.ui.info("You have been logged out. Credentials cleared."),"json"===this.ctx.format&&this.ctx.response.print({success:!0,logged_out:!0})}async whoami(){if(!await this.getValidAccessToken())return void this.ctx.response.print({logged_in:!1});this.ctx.ui.info("Fetching user information...");this.ctx.response.print({logged_in:!0,user:"mock-user@coze.io",org:"mock-org",profile:"default"})}async status(){const e=await this.getValidAccessToken();if(this.ctx.ui.info("Checking authentication status..."),!e)return void this.ctx.response.print({logged_in:!1});const t=this.config.tokenExpiresAt,i=!!this.config.refreshToken,{data:o}=await po.GetUserProfile({},{baseURL:this.config.openApiBaseUrl}),s={logged_in:!0,user:o,token_expires_at:t?new Date(t).toISOString():i?void 0:"Never (PAT)"};this.ctx.response.print(s)}async getValidAccessToken(){const{accessToken:e,refreshToken:t,tokenExpiresAt:i}=this.config;if(e){if(!t)return e;if((e=>{if(!e)return!1;const t=Date.now();return!(e-t>316224e5)&&t<e-3e5})(i))return e;this.ctx.ui.verbose("Access token is expired or expiring soon, refreshing...");try{const{baseURL:e,clientId:i}=this.getOAuthConfig(),o=await async function(e){const t={};return e.clientSecret&&(t.Authorization=`Bearer ${e.clientSecret}`),(await Xt.post("/api/permission/oauth2/token",{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken},{baseURL:e.baseURL,headers:t})).data}({baseURL:e,clientId:i,refreshToken:t});return await this.saveOAuthToken(o),this.ctx.ui.verbose("Token refreshed successfully."),o.access_token}catch(e){return this.ctx.ui.error(`Failed to refresh token: ${mo(e)}`),void await this.clearAuthData()}}}async saveOAuthToken(e){const t=(i=e.expires_in)>=ho?i*_o:Date.now()+i*_o;var i;this.config.accessToken=e.access_token,this.config.refreshToken=e.refresh_token,this.config.tokenExpiresAt=t,await s.saveConfig({accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:t})}}const fo="",yo="",vo="",wo="",bo="",So="",Po="",Co="",To="[PROC]",Eo="[INFO]",ko="[WARN]",Io="[ERR]",Ao="[DONE]",jo="[DBG]",Ro={debug:0,verbose:1,info:2,success:3,warn:4,error:5};function zo(e){return`${vo}${yo}${e}${fo}`}class Uo{constructor(e,t,i="info"){var o,s;this.log=e,this.silent="json"===t,this.useColor=this.detectColorSupport(),this.level=i,this.levelPriority=(s=()=>2,null!=(o=Ro[i])?o:s())}detectColorSupport(){return!0===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}([process,"access",e=>e.stderr,"optionalAccess",e=>e.isTTY])&&void 0===process.env.NO_COLOR}paint(e,t){return this.useColor?`${e}${t}${fo}`:t}shouldOutput(e){return!this.silent&&Ro[e]>=this.levelPriority}verbose(e,...t){this.log.verbose(e,...t),this.shouldOutput("verbose")&&process.stderr.write(`${zo(To)} ${this.paint(Po,e)}\n`)}info(e,...t){this.log.info(e,...t),this.shouldOutput("info")&&process.stderr.write(`${zo(Eo)} ${this.paint(fo,e)}\n`)}warn(e,...t){this.log.warn(e,...t),this.shouldOutput("warn")&&process.stderr.write(`${zo(ko)} ${this.paint(So,e)}\n`)}error(e,...t){this.log.error(e,...t),this.shouldOutput("error")&&process.stderr.write(`${zo(Io)} ${this.paint(wo,e)}\n`)}success(e,...t){this.log.success(e,...t),this.shouldOutput("success")&&process.stderr.write(`${zo(Ao)} ${this.paint(bo,e)}\n`)}debug(e,...t){this.log.debug(e,...t),this.shouldOutput("debug")&&process.stderr.write(`${zo(jo)} ${this.paint(Co,e)}\n`)}}class Lo{constructor(e){const{format:t}=e;this.formatter=function(e){return"text"===e?new x:new P}(t)}print(e){const t=this.formatter.format(e);process.stdout.write(t)}eprint(e){const t=this.formatter.formatError(e);process.stderr.write(t)}}function Oo(e,t){return null!=e?e:t()}async function xo(e,t){const i=Date.now();e.ui.verbose(`[Logger] CLI start: ${e.argv.join(" ")}`);try{await t()}finally{const t=Date.now()-i;e.ui.verbose(`[Logger] CLI end (took ${t}ms)`)}}var Bo,qo,Do,Mo,No,Go,$o,Fo,Vo,Wo,Ho,Jo,Ko,Qo,Yo,Zo,Xo,es,ts,is,os,ss,ns,rs,as,cs,ds,ls,ps,us,_s,hs,ms,gs,fs,ys,vs,ws,bs,Ss,Ps,Cs,Ts,Es,ks,Is,As,js,Rs,zs,Us,Ls,Os,xs,Bs,qs,Ds,Ms,Ns,Gs,$s,Fs,Vs,Ws,Hs,Js,Ks,Qs,Ys,Zs,Xs,en,tn,on,sn,nn,rn,an,cn,dn,ln,pn,un,_n,hn,mn,gn,fn,yn,vn,wn,bn,Sn,Pn,Cn,Tn,En,kn,In,An,jn,Rn,zn,Un,Ln,On,xn,Bn,qn,Dn,Mn,Nn,Gn,$n,Fn,Vn,Wn,Hn,Jn,Kn,Qn,Yn,Zn,Xn,er,tr,ir,or,sr,nr,rr;function ar(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[e.Start_Agent=0]="Start_Agent";e[e.LLM_Agent=1]="LLM_Agent";e[e.Task_Agent=2]="Task_Agent";e[e.Global_Agent=3]="Global_Agent";e[e.Bot_Agent=4]="Bot_Agent"}(Bo||(Bo={})),function(e){e[e.OldVersion=0]="OldVersion";e[e.MiddleVersion=1]="MiddleVersion";e[e.NewVersion=2]="NewVersion";e[e.MiddleVersionNotPrompt=3]="MiddleVersionNotPrompt"}(qo||(qo={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(Do||(Do={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(Mo||(Mo={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(No||(No={})),function(e){e[e.Current=1]="Current";e[e.Previous=2]="Previous";e[e.Start=3]="Start";e[e.MostSuitable=4]="MostSuitable"}(Go||(Go={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}($o||($o={})),function(e){e[e.Default=0]="Default";e[e.Function=1]="Function"}(Fo||(Fo={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned"}(Vo||(Vo={})),function(e){e[e.LimitedReadWrite=1]="LimitedReadWrite";e[e.ReadOnly=2]="ReadOnly";e[e.UnlimitedReadWrite=3]="UnlimitedReadWrite";e[e.RWModeMax=4]="RWModeMax"}(Wo||(Wo={})),function(e){e[e.Default=0]="Default";e[e.DouyinAvatar=1]="DouyinAvatar"}(Ho||(Ho={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(Jo||(Jo={})),function(e){e[e.Chat=0]="Chat";e[e.FunctionCall_1=1]="FunctionCall_1";e[e.FunctionCall_2=2]="FunctionCall_2";e[e.FunctionCall_3=3]="FunctionCall_3"}(Ko||(Ko={})),function(e){e[e.NotSet=0]="NotSet";e[e.Text=1]="Text";e[e.Voice=2]="Voice";e[e.Call=3]="Call";e[e.VideoCall=4]="VideoCall"}(Qo||(Qo={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Yo||(Yo={})),function(e){e[e.Text=1]="Text";e[e.Number=2]="Number";e[e.Date=3]="Date";e[e.Float=4]="Float";e[e.Boolean=5]="Boolean"}(Zo||(Zo={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Xo||(Xo={})),function(e){e[e.SLM=0]="SLM";e[e.LLM=1]="LLM"}(es||(es={})),function(e){e[e.Pre=1]="Pre";e[e.Post=2]="Post";e[e.PreAndPost=3]="PreAndPost"}(ts||(ts={})),function(e){e[e.Default=0]="Default";e[e.CustomizePrompt=1]="CustomizePrompt"}(is||(is={})),function(e){e[e.ReplyBottom=0]="ReplyBottom";e[e.CardList=1]="CardList"}(os||(os={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(ss||(ss={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(ns||(ns={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(rs||(rs={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Trigger=4]="Trigger";e[e.KnowledgeText=5]="KnowledgeText";e[e.KnowledgeTable=6]="KnowledgeTable";e[e.KnowledgeAutoCall=7]="KnowledgeAutoCall";e[e.KnowledgeOnDemandCall=8]="KnowledgeOnDemandCall";e[e.Variable=9]="Variable";e[e.Database=10]="Database";e[e.LongTermMemory=11]="LongTermMemory";e[e.FileBox=12]="FileBox";e[e.Onboarding=13]="Onboarding";e[e.Suggestion=14]="Suggestion";e[e.ShortcutCommand=15]="ShortcutCommand";e[e.BackGroundImage=16]="BackGroundImage";e[e.TTS=17]="TTS";e[e.MultiAgentRecognize=18]="MultiAgentRecognize";e[e.KnowledgePhoto=19]="KnowledgePhoto";e[e.HookInfo=20]="HookInfo";e[e.KnowledgeValcanoUnstructured=21]="KnowledgeValcanoUnstructured";e[e.KnowledgeValcanoStructured=22]="KnowledgeValcanoStructured";e[e.Model=23]="Model";e[e.KnowledgeThirdPartyUnstructured=24]="KnowledgeThirdPartyUnstructured";e[e.KnowledgeThirdPartyStructured=25]="KnowledgeThirdPartyStructured"}(as||(as={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(cs||(cs={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(ds||(ds={})),function(e){e[e.Curve=0]="Curve";e[e.Straight=1]="Straight"}(ls||(ls={})),function(e){e[e.Flow=1]="Flow";e[e.Host=2]="Host"}(ps||(ps={})),function(e){e[e.NO_NEED=1]="NO_NEED";e[e.USE_MANUAL=2]="USE_MANUAL";e[e.USE_LLM=3]="USE_LLM"}(us||(us={})),function(e){e[e.EQUAL=1]="EQUAL";e[e.NOT_EQUAL=2]="NOT_EQUAL";e[e.GREATER_THAN=3]="GREATER_THAN";e[e.LESS_THAN=4]="LESS_THAN";e[e.GREATER_EQUAL=5]="GREATER_EQUAL";e[e.LESS_EQUAL=6]="LESS_EQUAL";e[e.IN=7]="IN";e[e.NOT_IN=8]="NOT_IN";e[e.IS_NULL=9]="IS_NULL";e[e.IS_NOT_NULL=10]="IS_NOT_NULL";e[e.LIKE=11]="LIKE";e[e.NOT_LIKE=12]="NOT_LIKE"}(_s||(_s={})),function(e){e[e.Input=0]="Input";e[e.Variable=1]="Variable"}(hs||(hs={})),function(e){e[e.Default=0]="Default";e[e.FromSaas=1]="FromSaas"}(ms||(ms={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(gs||(gs={})),function(e){e[e.FunctionCall=1]="FunctionCall";e[e.Independent=2]="Independent"}(fs||(fs={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(ys||(ys={})),function(e){e[e.ManualUpdate=1]="ManualUpdate";e[e.AutoUpdate=2]="AutoUpdate"}(vs||(vs={})),function(e){e[e.SemanticSearch=0]="SemanticSearch";e[e.HybirdSearch=1]="HybirdSearch";e[e.FullTextSearch=20]="FullTextSearch"}(ws||(ws={})),function(e){e[e.Public=1]="Public";e[e.Anonymous=2]="Anonymous";e[e.Custom=3]="Custom"}(bs||(bs={})),function(e){e[e.Random=0]="Random";e[e.All=1]="All"}(Ss||(Ss={})),function(e){e[e.System=0]="System";e[e.Custom=1]="Custom";e[e.Disable=2]="Disable";e[e.OriBot=3]="OriBot"}(Ps||(Ps={})),function(e){e[e.ListString=1]="ListString";e[e.String=2]="String";e[e.Integer=3]="Integer";e[e.Float=4]="Float";e[e.Boolean=5]="Boolean"}(Cs||(Cs={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Ts||(Ts={})),function(e){e[e.CozeOldTimeCapsule=0]="CozeOldTimeCapsule";e[e.VolcanoTimeCapsule=1]="VolcanoTimeCapsule"}(Es||(Es={})),function(e){e[e.Workflow=0]="Workflow";e[e.Imageflow=1]="Imageflow";e[e.SceneFlow=2]="SceneFlow";e[e.ChatFlow=3]="ChatFlow";e[e.All=100]="All"}(ks||(ks={})),function(e){e[e.BotQuery=1]="BotQuery";e[e.Plugin=2]="Plugin";e[e.Workflow=3]="Workflow"}(Is||(Is={})),function(e){e[e.Unknown=0]="Unknown";e[e.Webhook=1]="Webhook"}(As||(As={})),function(e){e[e.Unknown=0]="Unknown";e[e.Time=1]="Time";e[e.Event=2]="Event"}(js||(js={})),function(e){e[e.NoHistory=0]="NoHistory";e[e.NeedHistory=1]="NeedHistory"}(Rs||(Rs={})),function(e){e[e.NoTriggered=0]="NoTriggered";e[e.Triggered=1]="Triggered";e[e.DoAction=2]="DoAction";e[e.WaitToPush=3]="WaitToPush";e[e.PushSuccess=4]="PushSuccess";e[e.PushFail=5]="PushFail"}(zs||(zs={})),function(e){e[e.Init=0]="Init";e[e.Activated=1]="Activated";e[e.Deactivated=2]="Deactivated";e[e.Suspended=3]="Suspended"}(Us||(Us={})),function(e){e[e.Preset=1]="Preset";e[e.UserTask=2]="UserTask";e[e.PluginRunTask=3]="PluginRunTask"}(Ls||(Ls={})),function(e){e[e.Deploying=0]="Deploying";e[e.Successful=1]="Successful";e[e.Failed=2]="Failed"}(Os||(Os={})),function(e){e[e.All=0]="All";e[e.Bind=1]="Bind";e[e.UnBind=2]="UnBind"}(xs||(xs={})),function(e){e[e.CreateTime=0]="CreateTime";e[e.UpdateTime=1]="UpdateTime"}(Bs||(Bs={})),function(e){e[e.EventMeta=1]="EventMeta";e[e.ProfileMeta=2]="ProfileMeta"}(qs||(qs={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Ds||(Ds={})),function(e){e[e.GPT=1]="GPT";e[e.SEED=2]="SEED";e[e.Claude=3]="Claude";e[e.MiniMax=4]="MiniMax";e[e.Plugin=5]="Plugin";e[e.StableDiffusion=6]="StableDiffusion";e[e.ByteArtist=7]="ByteArtist";e[e.Maas=9]="Maas";e[e.QianFan=10]="QianFan";e[e.Gemini=11]="Gemini";e[e.Moonshot=12]="Moonshot";e[e.GLM=13]="GLM";e[e.MaaSAutoSync=14]="MaaSAutoSync";e[e.QWen=15]="QWen";e[e.Cohere=16]="Cohere";e[e.Baichuan=17]="Baichuan";e[e.Ernie=18]="Ernie";e[e.DeekSeek=19]="DeekSeek";e[e.Llama=20]="Llama";e[e.StepFun=23]="StepFun";e[e.Custom=24]="Custom";e[e.Other=999]="Other"}(Ms||(Ms={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(Ns||(Ns={})),function(e){e[e.ModelType=1]="ModelType";e[e.ModelUserRight=2]="ModelUserRight";e[e.ModelFeature=3]="ModelFeature";e[e.ModelFunction=4]="ModelFunction";e[e.ModelPaid=15]="ModelPaid";e[e.ModelAbility=16]="ModelAbility";e[e.ModelStatus=17]="ModelStatus";e[e.Custom=20]="Custom";e[e.Others=100]="Others"}(Gs||(Gs={})),function(e){e[e.Flagship=1]="Flagship";e[e.HighSpeed=2]="HighSpeed";e[e.ToolInvocation=3]="ToolInvocation";e[e.RolePlaying=4]="RolePlaying";e[e.LongText=5]="LongText";e[e.ImageUnderstanding=6]="ImageUnderstanding";e[e.Reasoning=7]="Reasoning";e[e.VideoUnderstanding=8]="VideoUnderstanding";e[e.CostPerformance=9]="CostPerformance";e[e.CodeSpecialization=10]="CodeSpecialization";e[e.AudioUnderstanding=11]="AudioUnderstanding"}($s||($s={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(Fs||(Fs={})),function(e){e[e.Start_Agent=0]="Start_Agent";e[e.LLM_Agent=1]="LLM_Agent";e[e.Task_Agent=2]="Task_Agent";e[e.Global_Agent=3]="Global_Agent";e[e.Bot_Agent=4]="Bot_Agent"}(Vs||(Vs={})),function(e){e[e.Upgrade=1]="Upgrade";e[e.BrowseOldNoPrompt=2]="BrowseOldNoPrompt"}(Ws||(Ws={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(Hs||(Hs={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(Js||(Js={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(Ks||(Ks={})),function(e){e[e.Visit=1]="Visit";e[e.Edit=2]="Edit"}(Qs||(Qs={})),function(e){e[e.Online=1]="Online";e[e.Offline=2]="Offline"}(Ys||(Ys={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online"}(Zs||(Zs={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Xs||(Xs={})),function(e){e[e.AutoGenBeforePublish=1]="AutoGenBeforePublish"}(en||(en={})),function(e){e[e.CozeHome=1]="CozeHome";e[e.Space=2]="Space"}(tn||(tn={})),function(e){e[e.Undefined=0]="Undefined";e[e.PersonalDraft=1]="PersonalDraft";e[e.Base=2]="Base";e[e.Publish=3]="Publish"}(on||(on={})),function(e){e[e.Undefined=0]="Undefined";e[e.Committed=1]="Committed";e[e.Behind=2]="Behind";e[e.NoDraftReplica=3]="NoDraftReplica"}(sn||(sn={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(nn||(nn={})),function(e){e[e.USER_RES=0]="USER_RES";e[e.USER_LLM_RES=1]="USER_LLM_RES";e[e.USER_LLM_APILEN_RES=2]="USER_LLM_APILEN_RES";e[e.USER_LLM_API_RES=3]="USER_LLM_API_RES"}(rn||(rn={})),function(e){e[e.Personal=1]="Personal";e[e.Organization=2]="Organization"}(an||(an={})),function(e){e[e.Agent=1]="Agent";e[e.Project=2]="Project";e[e.Knowledge=3]="Knowledge";e[e.Dataset=4]="Dataset";e[e.Plugin=5]="Plugin";e[e.Memorybase=6]="Memorybase"}(cn||(cn={})),function(e){e[e.Text=0]="Text";e[e.Table=1]="Table";e[e.Image=2]="Image";e[e.VolcanoStructured=4]="VolcanoStructured";e[e.VolcanoUnstructured=5]="VolcanoUnstructured";e[e.ThirdPartyStructured=7]="ThirdPartyStructured";e[e.ThirdPartyUnstructured=8]="ThirdPartyUnstructured"}(dn||(dn={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned";e[e.MoveFail=3]="MoveFail"}(ln||(ln={})),function(e){e[e.ByteTree=1]="ByteTree";e[e.GPTAK=2]="GPTAK";e[e.MaasAK=3]="MaasAK"}(pn||(pn={})),function(e){e[e.Init=0]="Init";e[e.Generating=1]="Generating";e[e.Success=2]="Success";e[e.Fail=3]="Fail";e[e.Cancel=4]="Cancel"}(un||(un={})),function(e){e[e.BotStore=1]="BotStore"}(_n||(_n={})),function(e){e[e.shorcutIcon=1]="shorcutIcon"}(hn||(hn={})),function(e){e[e.Onboarding=0]="Onboarding";e[e.BackgroundImage=1]="BackgroundImage"}(mn||(mn={})),function(e){e[e.BasicUser=1]="BasicUser";e[e.ExternalUser=2]="ExternalUser";e[e.RootUser=3]="RootUser"}(gn||(gn={})),function(e){e[e.GetInfo=1]="GetInfo"}(fn||(fn={})),function(e){e[e.Normal=1]="Normal";e[e.Invalid=2]="Invalid";e[e.Expired=3]="Expired";e[e.Rejected=4]="Rejected";e[e.Applying=5]="Applying"}(yn||(yn={})),function(e){e[e.Apply=1]="Apply";e[e.Invite=2]="Invite";e[e.EnterpriseApply=3]="EnterpriseApply"}(vn||(vn={})),function(e){e[e.GPT=1]="GPT";e[e.Claude=3]="Claude";e[e.Gemini=11]="Gemini";e[e.Moonshot=12]="Moonshot";e[e.GLM=13]="GLM";e[e.QWen=15]="QWen";e[e.DeekSeek=19]="DeekSeek";e[e.StepFun=23]="StepFun"}(wn||(wn={})),function(e){e[e.Douyin=1]="Douyin"}(bn||(bn={})),function(e){e[e.GPTOpenAPI=1]="GPTOpenAPI";e[e.Maas=2]="Maas";e[e.LLMFlow=3]="LLMFlow";e[e.Merlin=4]="Merlin"}(Sn||(Sn={})),function(e){e[e.Move=0]="Move";e[e.ForcedMove=1]="ForcedMove";e[e.RetryMove=2]="RetryMove";e[e.Preview=3]="Preview";e[e.ViewTask=4]="ViewTask";e[e.CancelTask=5]="CancelTask"}(Pn||(Pn={})),function(e){e[e.All=0]="All";e[e.Unread=1]="Unread"}(Cn||(Cn={})),function(e){e[e.Bot=1]="Bot"}(Tn||(Tn={})),function(e){e[e.CharactersAnime=1]="CharactersAnime";e[e.CharactersRealistic=2]="CharactersRealistic";e[e.CharactersCGThickPainting=3]="CharactersCGThickPainting";e[e.CharactersJapaneseShowa=4]="CharactersJapaneseShowa";e[e.CharactersAmericanComics=5]="CharactersAmericanComics";e[e.CharactersChineseWatercolor=6]="CharactersChineseWatercolor";e[e.ScenesScienceFiction=7]="ScenesScienceFiction";e[e.ScenesRealistic=8]="ScenesRealistic";e[e.ScenesChinesePainting=9]="ScenesChinesePainting";e[e.ScenesCartoonIllustrations=10]="ScenesCartoonIllustrations";e[e.ScenesCartoon3D=11]="ScenesCartoon3D"}(En||(En={})),function(e){e[e.IconStatic=1]="IconStatic";e[e.IconGif=2]="IconGif";e[e.BackgroundStatic=3]="BackgroundStatic";e[e.BackgroundGif=4]="BackgroundGif";e[e.PicPrompt=5]="PicPrompt"}(kn||(kn={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ShortcutCommand=3]="ShortcutCommand";e[e.Task=4]="Task"}(In||(In={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Knowledge=4]="Knowledge"}(An||(An={})),function(e){e[e.NoPublish=0]="NoPublish";e[e.HadPublished=1]="HadPublished"}(jn||(jn={})),function(e){e[e.Success=1]="Success";e[e.Failed=2]="Failed";e[e.InReview=3]="InReview"}(Rn||(Rn={})),function(e){e[e.Unread=1]="Unread";e[e.Read=2]="Read"}(zn||(zn={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(Un||(Un={})),function(e){e[e.UnLimit=1]="UnLimit";e[e.Forbidden=2]="Forbidden"}(Ln||(Ln={})),function(e){e[e.Plugin=1]="Plugin";e[e.NewBotIDEGuide=2]="NewBotIDEGuide";e[e.NewBeginnerGuide=3]="NewBeginnerGuide"}(On||(On={})),function(e){e[e.Default=0]="Default";e[e.Explore=1]="Explore";e[e.BotStore=2]="BotStore";e[e.CozeHome=3]="CozeHome";e[e.Playground=4]="Playground";e[e.Evaluation=5]="Evaluation";e[e.AgentApp=6]="AgentApp";e[e.GenerateAgentInfo=8]="GenerateAgentInfo";e[e.Template=9]="Template";e[e.EnterpriseStore=10]="EnterpriseStore"}(xn||(xn={})),function(e){e[e.All=0]="All";e[e.Self=1]="Self"}(Bn||(Bn={})),function(e){e[e.All=0]="All";e[e.Joined=1]="Joined";e[e.Confirming=2]="Confirming";e[e.Rejected=3]="Rejected";e[e.AutoApproved=4]="AutoApproved"}(qn||(qn={})),function(e){e[e.All=0]="All";e[e.Joined=1]="Joined";e[e.Confirming=2]="Confirming";e[e.Rejected=3]="Rejected";e[e.Revoked=4]="Revoked";e[e.Expired=5]="Expired"}(Dn||(Dn={})),function(e){e[e.EnterpriseUser=1]="EnterpriseUser";e[e.ExternalUser=2]="ExternalUser"}(Mn||(Mn={})),function(e){e[e.Normal=0]="Normal";e[e.DevMode=1]="DevMode"}(Nn||(Nn={})),function(e){e[e.DraftBot=1]="DraftBot";e[e.Project=2]="Project";e[e.Space=3]="Space";e[e.DouyinAvatarBot=4]="DouyinAvatarBot"}(Gn||(Gn={})),function(e){e[e.Default=0]="Default";e[e.Owner=1]="Owner";e[e.Admin=2]="Admin";e[e.Member=3]="Member";e[e.Guest=4]="Guest"}($n||($n={})),function(e){e[e.Professional=1]="Professional"}(Fn||(Fn={})),function(e){e[e.Personal=1]="Personal";e[e.Team=2]="Team"}(Vn||(Vn={})),function(e){e[e.Dark=1]="Dark";e[e.Light=2]="Light"}(Wn||(Wn={})),function(e){e[e.AlwaysOn=0]="AlwaysOn";e[e.AlwaysOff=1]="AlwaysOff"}(Hn||(Hn={})),function(e){e[e.CozeAssistantGuide=1]="CozeAssistantGuide"}(Jn||(Jn={})),function(e){e[e.Normal=1]="Normal";e[e.Banned=2]="Banned";e[e.Canceled=3]="Canceled"}(Kn||(Kn={})),function(e){e[e.External=0]="External";e[e.Internal=1]="Internal"}(Qn||(Qn={})),function(e){e[e.Invisible=0]="Invisible";e[e.Visible=1]="Visible";e[e.SocietyInvisible=2]="SocietyInvisible"}(Yn||(Yn={})),function(e){e[e.SingleAgent=1]="SingleAgent";e[e.MultiAgent=2]="MultiAgent";e[e.WorkflowAsAgent=3]="WorkflowAsAgent"}(Zn||(Zn={})),function(e){e[e.Preset=1]="Preset";e[e.Library=2]="Library"}(Xn||(Xn={})),function(e){e[e.DatasetServiceValid=0]="DatasetServiceValid";e[e.DatasetServiceInvalid=1]="DatasetServiceInvalid"}(er||(er={})),function(e){e[e.DatasetValid=0]="DatasetValid";e[e.DatasetInvalid=1]="DatasetInvalid"}(tr||(tr={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(ir||(ir={})),function(e){e[e.Workflow=0]="Workflow";e[e.Imageflow=1]="Imageflow";e[e.SceneFlow=2]="SceneFlow";e[e.ChatFlow=3]="ChatFlow";e[e.All=100]="All"}(or||(or={})),function(e){e[e.TextInput=0]="TextInput";e[e.Select=1]="Select";e[e.UploadImage=2]="UploadImage";e[e.UploadDoc=3]="UploadDoc";e[e.UploadTable=4]="UploadTable";e[e.UploadAudio=5]="UploadAudio";e[e.MixUpload=6]="MixUpload";e[e.VIDEO=7]="VIDEO";e[e.ARCHIVE=8]="ARCHIVE";e[e.CODE=9]="CODE";e[e.TXT=10]="TXT";e[e.PPT=11]="PPT"}(sr||(sr={})),function(e){e[e.SendTypeQuery=0]="SendTypeQuery";e[e.SendTypePanel=1]="SendTypePanel"}(nr||(nr={})),function(e){e[e.ToolTypeWorkFlow=1]="ToolTypeWorkFlow";e[e.ToolTypePlugin=2]="ToolTypePlugin"}(rr||(rr={}));class cr{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){cr.prototype.__init.call(this),cr.prototype.__init2.call(this),this.request=ar([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=ar([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}GetSpaceInfoV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/info"),s={space_id:i.space_id,join_space_type:i.join_space_type};return this.request({url:o,method:"POST",data:s},t)}DeleteSpaceV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/delete"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}SaveSpaceV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/save"),s={space_id:i.space_id,name:i.name,description:i.description,icon_uri:i.icon_uri,space_type:i.space_type,space_mode:i.space_mode,space_config:i.space_config,enterprise_id:i.enterprise_id,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}GetSpaceListV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/list"),s={search_word:i.search_word,enterprise_id:i.enterprise_id,organization_id:i.organization_id,scope_type:i.scope_type,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}UpdateAgent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/update_agent"),s={id:i.id,reference_id:i.reference_id,current_version:i.current_version,space_id:i.space_id,bot_id:i.bot_id,base_commit_version:i.base_commit_version,name:i.name,description:i.description,position:i.position,icon_uri:i.icon_uri,intents:i.intents,work_info:i.work_info,is_delete:i.is_delete};return this.request({url:o,method:"POST",data:s},t)}BatchCreateAgent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/batch_create_agent"),s={space_id:i.space_id,bot_id:i.bot_id,agent_type:i.agent_type,position:i.position,references:i.references,agent_cnt:i.agent_cnt,base_commit_version:i.base_commit_version,version_compat:i.version_compat};return this.request({url:o,method:"POST",data:s},t)}GetPublishBotList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_publish_bot_list"),s={space_id:i.space_id,bot_mode:i.bot_mode,page_num:i.page_num,page_size:i.page_size,name:i.name,login_user_create:i.login_user_create,bot_id:i.bot_id};return this.request({url:o,method:"GET",params:s},t)}MGetBotByVersion(e,t){const i=e,o=this.genBaseURL("/api/playground_api/mget_bot_by_version"),s={bot_versions:i.bot_versions,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}BotLastPublishInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bot_last_publish_info"),s={space_id:i.space_id,bot_id:i.bot_id,bot_mode:i.bot_mode};return this.request({url:o,method:"GET",params:s},t)}ProduceBot(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/produce/create_bot"),s={space_id:i.space_id,name:i.name,description:i.description,icon_url:i.icon_url,icon_uri:i.icon_uri,prompt:i.prompt,plugin_apis:i.plugin_apis,prologue:i.prologue,suggested_questions:i.suggested_questions,bot_source:i.bot_source};return this.request({url:o,method:"POST",data:s},t)}UpdateProducedBot(e,t){const i=e,o=this.genBaseURL("/api/playground_api/produce/update_bot"),s={bot_id:i.bot_id,name:i.name,description:i.description,icon_url:i.icon_url,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}GetPublishedBotList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bot_version/get_published_bot_list"),s={space_id_list:i.space_id_list,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}GetBotVersionInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bot_version/get_bot_version_info"),s={bot_id:i.bot_id,version:i.version,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}DuplicateBotVersionToSpace(e,t){const i=e,o=this.genBaseURL("/api/playground_api/dup_bot_version"),s={target_space_id:i.target_space_id,bot_id:i.bot_id,version:i.version,name:i.name,dup_society_host:i.dup_society_host};return this.request({url:o,method:"POST",data:s},t)}UpdateUserRiskAlertInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/update_user_risk_alert_info"),s={risk_alert_type:i.risk_alert_type,switch_info:i.switch_info};return this.request({url:o,method:"POST",data:s},t)}GetUserRiskAlertInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_user_risk_alert_info"),s={risk_alert_type_list:i.risk_alert_type_list,switch_type_list:i.switch_type_list},n={Cookie:i.Cookie};return this.request({url:o,method:"POST",data:s,headers:n},t)}DraftBotCollaboration(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/collaboration"),s={space_id:i.space_id,bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}BotInfoAudit(e,t){const i=e,o=this.genBaseURL("/api/playground_api/audit/bot_info"),s={bot_id:i.bot_id,bot_audit_info:i.bot_audit_info,space_id:i.space_id,bot_mode:i.bot_mode};return this.request({url:o,method:"POST",data:s},t)}TimeCapsuleInvokeEvent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/timecapsule_invoke_event"),s={bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}InviteMemberLinkV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/invite"),s={space_id:i.space_id,team_invite_link_status:i.team_invite_link_status,func:i.func};return this.request({url:o,method:"POST",data:s},t)}SpaceMemberDetailV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/detail"),s={space_id:i.space_id,search_word:i.search_word,space_role_type:i.space_role_type,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}JoinSpaceV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/join"),s={space_id:i.space_id,join_space_type:i.join_space_type,is_reject:i.is_reject};return this.request({url:o,method:"POST",data:s},t)}UpdateSpaceMemberV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/update"),s={space_id:i.space_id,user_id:i.user_id,space_role_type:i.space_role_type};return this.request({url:o,method:"POST",data:s},t)}TransferSpaceV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/transfer"),s={space_id:i.space_id,transfer_user_id:i.transfer_user_id};return this.request({url:o,method:"POST",data:s},t)}RemoveSpaceMemberV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/remove"),s={space_id:i.space_id,remove_user_id:i.remove_user_id,transfer_user_id:i.transfer_user_id};return this.request({url:o,method:"POST",data:s},t)}SearchMemberV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/member/search"),s={search_list:i.search_list,space_id:i.space_id,search_volcano_account_list:i.search_volcano_account_list,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}AddBotSpaceMemberV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/member/add"),s={member_info_list:i.member_info_list,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}ExitSpaceV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/exit"),s={space_id:i.space_id,transfer_user_id:i.transfer_user_id};return this.request({url:o,method:"POST",data:s},t)}GetBotPopupInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/operate/get_bot_popup_info"),s={bot_popup_types:i.bot_popup_types,bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}UpdateBotPopupInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/operate/update_bot_popup_info"),s={bot_popup_type:i.bot_popup_type,bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}GenerateDescription(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/generate_description"),s={bot_name:i.bot_name,prompt:i.prompt};return this.request({url:o,method:"POST",data:s},t)}DraftBotPublishHistoryDetail(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/publish_history_detail"),s={bot_id:i.bot_id,space_id:i.space_id,publish_id:i.publish_id,version:i.version};return this.request({url:o,method:"POST",data:s},t)}GenerateStoreCategory(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/generate_store_category"),s={bot_name:i.bot_name,bot_description:i.bot_description,prompt:i.prompt};return this.request({url:o,method:"POST",data:s},t)}UpdateMultiAgent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/update_multi_agent"),s={space_id:i.space_id,bot_id:i.bot_id,session_type:i.session_type,base_commit_version:i.base_commit_version,connector_type:i.connector_type};return this.request({url:o,method:"POST",data:s},t)}SwitchAgentVersion(e,t){const i=e,o=this.genBaseURL("/api/playground_api/switch_agent_version"),s={bot_id:i.bot_id,space_id:i.space_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}LangDetect(e,t){const i=e,o=this.genBaseURL("/api/playground_api/audio/lang/detect"),s={detect_text_list:i.detect_text_list};return this.request({url:o,method:"POST",data:s},t)}GetImagexShortUrl(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_imagex_url"),s={uris:i.uris,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetPlatformCommonConfig(e,t){const i=this.genBaseURL("/api/playground_api/get_platform_common_config");return this.request({url:i,method:"GET"},t)}CreateShortcutCommand(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/create_shortcut_command"),s={object_id:i.object_id,shortcuts:i.shortcuts};return this.request({url:o,method:"POST",data:s},t)}MGetUserBasicInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/mget_user_info"),s={user_ids:i.user_ids,need_user_status:i.need_user_status,need_enterprise_identity:i.need_enterprise_identity,need_volcano_user_name:i.need_volcano_user_name};return this.request({url:o,method:"POST",data:s},t)}BindVolcanoTrn(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/bind_volcano_trn"),s={space_id:i.space_id,trn:i.trn,account_name:i.account_name};return this.request({url:o,method:"POST",data:s},t)}UnbindVolcanoTrn(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/unbind_volcano_trn"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}RetrieveFileOpen(e,t){const i=e,o=this.genBaseURL("/v1/files/retrieve"),s={file_id:i.file_id};return this.request({url:o,method:"GET",params:s},t)}RetrieveFileContentOpen(e,t){const i=e,o=this.genBaseURL("/v1/files/content/retrieve"),s={file_id:i.file_id};return this.request({url:o,method:"GET",params:s},t)}UploadFileOpen(e,t){const i=e,o=this.genBaseURL("/v1/files/upload"),s={Data:i.Data},n={"Content-Type":i["Content-Type"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}BotInfoCheck(e,t){const i=e,o=this.genBaseURL("/api/playground_api/check/bot_info_check"),s={bot_id:i.bot_id,space_id:i.space_id,bot_audit_info:i.bot_audit_info};return this.request({url:o,method:"POST",data:s},t)}SupportVoiceCall(e,t){const i=e,o=this.genBaseURL("/api/playground_api/support_voice_call"),s={voice_id_list:i.voice_id_list};return this.request({url:o,method:"POST",data:s},t)}CreateUpdateShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/playground_api/create_update_shortcut_command"),s={object_id:i.object_id,space_id:i.space_id,shortcuts:i.shortcuts};return this.request({url:o,method:"POST",data:s},t)}MoveDraftBot(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/move_draft_bot"),s={bot_id:i.bot_id,target_spaceId:i.target_spaceId,from_spaceId:i.from_spaceId,move_action:i.move_action};return this.request({url:o,method:"POST",data:s},t)}GetShortcutAvailNodes(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_shortcut_avail_nodes"),s={bot_id:i.bot_id,space_id:i.space_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}MarkReadNotice(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gen_img/mark_read_notice"),s={bot_id:i.bot_id,pic_type:i.pic_type};return this.request({url:o,method:"POST",data:s},t)}CancelGenerateGif(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gen_img/cancel_generate_gif"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}GetPicTask(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gen_img/get_pic_task"),s={bot_id:i.bot_id,pic_type:i.pic_type};return this.request({url:o,method:"POST",data:s},t)}GeneratePic(e,t){const i=e,o=this.genBaseURL("/api/playground_api/gen_img/generate_pic"),s={gen_prompt:i.gen_prompt,image_url:i.image_url,image_uri:i.image_uri,bot_id:i.bot_id,pic_type:i.pic_type,device_id:i.device_id,bot_name:i.bot_name,bot_desc:i.bot_desc};return this.request({url:o,method:"POST",data:s},t)}GetGenPicTimes(e,t){const i=this.genBaseURL("/api/playground_api/gen_img/get_gen_pic_times");return this.request({url:i,method:"POST"},t)}ListStyle(e,t){const i=this.genBaseURL("/api/playground_api/gen_img/list_style");return this.request({url:i,method:"POST"},t)}GetFileUrls(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_file_list"),s={scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetDraftBotInfoAgw(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/get_draft_bot_info"),s={bot_id:i.bot_id,version:i.version,commit_version:i.commit_version};return this.request({url:o,method:"POST",data:s},t)}CommitDraftBotInfoAgw(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/commit_draft_bot_info"),s={bot_id:i.bot_id,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}UpdateDraftBotInfoAgw(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/draftbot/update_draft_bot_info"),s={bot_info:i.bot_info,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}GetUserQueryCollectOption(e,t){const i=this.genBaseURL("/api/playground_api/draftbot/get_user_query_collect_option");return this.request({url:i,method:"GET"},t)}GenerateUserQueryCollectPolicy(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/draftbot/generate_user_query_collect_policy"),s={bot_id:i.bot_id,developer_name:i.developer_name,contact_information:i.contact_information};return this.request({url:o,method:"POST",data:s},t)}GetCozeProRights(e,t){const i=this.genBaseURL("/api/playground_api/get_coze_pro_rights");return this.request({url:i,method:"POST"},t)}GetPolicyContent(e,t){const i=e,o=this.genBaseURL(`/api/playground_api/private_policy/${i.secret}`);return this.request({url:o,method:"GET"},t)}UpdateAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/update_agent_v2"),s={id:i.id,reference_id:i.reference_id,current_version:i.current_version,space_id:i.space_id,bot_id:i.bot_id,base_commit_version:i.base_commit_version,name:i.name,description:i.description,position:i.position,icon_uri:i.icon_uri,intents:i.intents,is_delete:i.is_delete,prompt_info:i.prompt_info,model_info:i.model_info,plugin_info_list:i.plugin_info_list,knowledge:i.knowledge,workflow_info_list:i.workflow_info_list,jump_config:i.jump_config,suggest_reply_info:i.suggest_reply_info,hook_info:i.hook_info};return this.request({url:o,method:"POST",data:s},t)}CopyAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/copy_agent_v2"),s={bot_id:i.bot_id,agent_id:i.agent_id,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}CreateAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/create_agent_v2"),s={bot_id:i.bot_id,agent_type:i.agent_type,position:i.position,references:i.references,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}BatchCreateAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/batch_create_agent_v2"),s={bot_id:i.bot_id,agent_type:i.agent_type,position:i.position,references:i.references,agent_cnt:i.agent_cnt,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}CozeProCopyGetLinkMetaInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/get_link_meta_info"),s={auth_code:i.auth_code};return this.request({url:o,method:"POST",data:s},t)}CozeProCopyTaskConfirm(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/copy_task_confirm"),s={auth_code:i.auth_code};return this.request({url:o,method:"POST",data:s},t)}CozeProCopyGenerateAuthLink(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/generate_auth_link"),s={copy_user_id:i.copy_user_id,target_space_id:i.target_space_id};return this.request({url:o,method:"POST",data:s},t)}GetOpVoiceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_op_voice_list"),s={voice_ids:i.voice_ids,name:i.name,style_id:i.style_id,language_code:i.language_code,status:i.status,page_index:i.page_index,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetSupportLanguage(e,t){const i=this.genBaseURL("/api/playground_api/get_support_language");return this.request({url:i,method:"GET"},t)}SynchronizeVoiceList(e,t){const i=this.genBaseURL("/api/playground_api/synchronize_voice_list");return this.request({url:i,method:"GET"},t)}CheckBotAllModelPluginIds(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/check_bot_all_model_plugin_ids"),s={bot_id:i.bot_id,commit_version:i.commit_version};return this.request({url:o,method:"POST",data:s},t)}GetBotCollaborationQuota(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/collaboration_quota"),s={bot_id:i.bot_id,only_config_item:i.only_config_item,account_type:i.account_type};return this.request({url:o,method:"POST",data:s},t)}OpenCreateSpace(e,t){const i=e||{},o=this.genBaseURL("/v1/workspaces"),s={name:i.name,description:i.description,icon_file_id:i.icon_file_id,coze_account_id:i.coze_account_id,owner_uid:i.owner_uid};return this.request({url:o,method:"POST",data:s},t)}NoticeMarkRead(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/notice/mark_read"),s={notice_ids:i.notice_ids,mark_all:i.mark_all};return this.request({url:o,method:"POST",data:s},t)}GetNoticeList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/notice/get_list"),s={cursor:i.cursor,count:i.count,notice_rank_type:i.notice_rank_type};return this.request({url:o,method:"POST",data:s},t)}GetNoticeUnreadCount(e,t){const i=this.genBaseURL("/api/playground_api/notice/get_unread_count");return this.request({url:i,method:"POST"},t)}OpenSpaceList(e,t){const i=e||{},o=this.genBaseURL("/v1/workspaces"),s={page_num:i.page_num,page_size:i.page_size,enterprise_id:i.enterprise_id,user_id:i.user_id,coze_account_id:i.coze_account_id,scope:i.scope};return this.request({url:o,method:"GET",params:s},t)}ReportUserBehavior(e,t){const i=e,o=this.genBaseURL("/api/playground_api/report_user_behavior"),s={resource_id:i.resource_id,resource_type:i.resource_type,behavior_type:i.behavior_type,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetUserConfig(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_user_config"),s={risk_alert_type_list:i.risk_alert_type_list,switch_type_list:i.switch_type_list},n={Cookie:i.Cookie};return this.request({url:o,method:"POST",data:s,headers:n},t)}UpdateUserConfig(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/update_user_config"),s={risk_alert_type:i.risk_alert_type,switch_info:i.switch_info};return this.request({url:o,method:"POST",data:s},t)}GetRecentDraftBotList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/get_recent_draft_bot"),s={behavior_type:i.behavior_type,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}GetPromptResourceInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_prompt_resource_info"),s={prompt_resource_id:i.prompt_resource_id};return this.request({url:o,method:"GET",params:s},t)}UpsertPromptResource(e,t){const i=e,o=this.genBaseURL("/api/playground_api/upsert_prompt_resource"),s={prompt:i.prompt};return this.request({url:o,method:"POST",data:s},t)}DeletePromptResource(e,t){const i=e,o=this.genBaseURL("/api/playground_api/delete_prompt_resource"),s={prompt_resource_id:i.prompt_resource_id};return this.request({url:o,method:"POST",data:s},t)}GetPromptReferenceInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_prompt_reference_info"),s={space_id:i.space_id,reference_id:i.reference_id,reference_type:i.reference_type,api_id:i.api_id,project_id:i.project_id,avatar_bot_id:i.avatar_bot_id};return this.request({url:o,method:"POST",data:s},t)}GetOfficialPromptResourceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_official_prompt_list"),s={keyword:i.keyword};return this.request({url:o,method:"POST",data:s},t)}GetByteTreeByName(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/search_byte_tree"),s={name:i.name},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}CreatePrivateModel(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/create_private_model"),s={space_id:i.space_id,model_vendor:i.model_vendor,model_show_name:i.model_show_name,model_arch:i.model_arch,ak:i.ak,token_limit:i.token_limit,upper_limit_of_max_token:i.upper_limit_of_max_token,function_call:i.function_call,multimodal:i.multimodal,multimodal_types:i.multimodal_types,form_detail:i.form_detail,record_id:i.record_id,maas_model_name:i.maas_model_name,maas_model_version:i.maas_model_version,maas_model_customer_id:i.maas_model_customer_id,model_family:i.model_family,space_id_i18n:i.space_id_i18n,operator:i.operator,email:i.email,employee_id:i.employee_id,presence_penalty_config:i.presence_penalty_config,frequency_penalty_config:i.frequency_penalty_config,temperature_config:i.temperature_config,top_p_config:i.top_p_config},n={"x-inner-auth":i["x-inner-auth"],"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}CheckExemptFormInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/check_exempt_form_info"),s={exempt_form_type:i.exempt_form_type,space_id:i.space_id},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}SetByteTreeForSpace(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/set_byte_tree_for_space"),s={space_id:i.space_id,byte_tree_node_id:i.byte_tree_node_id,byte_tree_node_name:i.byte_tree_node_name,form_detail:i.form_detail,record_id:i.record_id},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}GetModelCapability(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bpm/get_model_capability"),s={vendor:i.vendor,model_arch:i.model_arch,maas_model_name:i.maas_model_name,maas_model_version:i.maas_model_version,maas_customer_id:i.maas_customer_id},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}GetSpaceDetail(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/detail"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}RevocateSpaceInvite(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/revocate_invite"),s={space_id:i.space_id,invite_user_id:i.invite_user_id};return this.request({url:o,method:"GET",params:s},t)}SaveVolcanoUserManageInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/save_volcano_user_manage_info"),s={volcano_basic_user_config:i.volcano_basic_user_config};return this.request({url:o,method:"POST",data:s},t)}GetVolcanoUserManageInfo(e,t){const i=this.genBaseURL("/api/playground_api/coze_pro/get_volcano_user_manage_info");return this.request({url:i,method:"POST"},t)}GetSpaceInviteManageList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/invite_manage_list"),s={space_id:i.space_id,space_invite_status:i.space_invite_status,search_word:i.search_word,page:i.page,size:i.size};return this.request({url:o,method:"GET",params:s},t)}DebugDouYin(e,t){const i=e,o=this.genBaseURL("/api/playground_api/douyin/debug"),s={bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}GetDouYinAuthCode(e,t){const i=this.genBaseURL("/api/playground_api/douyin/get_auth_qr_code");return this.request({url:i,method:"GET"},t)}GetDouyinAvatarInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/douyin/v1/get_avatar_info"),s={is_draft:i.is_draft,body:i.body},n={"Open-Platform-App-ID":i["Open-Platform-App-ID"],"Byte-Signature":i["Byte-Signature"],"Byte-Timestamp":i["Byte-Timestamp"],"Byte-Nonce-Str":i["Byte-Nonce-Str"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}DouYinAuthUserList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/douyin/auth_user_list"),s={page_index:i.page_index,page_size:i.page_size,bind_status:i.bind_status,order_by:i.order_by};return this.request({url:o,method:"POST",data:s},t)}GetDebugDouYinStatus(e,t){const i=e,o=this.genBaseURL("/api/playground_api/douyin/get_debug_status"),s={bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}CanUserApplyClose(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/coze_pro/can_user_apply_close"),s={AccountId:i.AccountId,EventName:i.EventName,Action:i.Action,Version:i.Version},n={"X-Tt-Logid":i["X-Tt-Logid"],"X-Top-Service":i["X-Top-Service"],"X-Top-Region":i["X-Top-Region"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}CreateRoom(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/create_room"),s={bot_id:i.bot_id,conversation_id:i.conversation_id,scene:i.scene,voice_id:i.voice_id,video_config:i.video_config};return this.request({url:o,method:"POST",data:s},t)}GetVoiceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_voice_list"),s={page_index:i.page_index,page_size:i.page_size,language_code:i.language_code};return this.request({url:o,method:"POST",data:s},t)}GetVoiceByIds(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_voice_by_ids"),s={voice_id_map:i.voice_id_map,voice_type:i.voice_type,space_id:i.space_id,emotion_config:i.emotion_config,voice_biz_scene:i.voice_biz_scene};return this.request({url:o,method:"POST",data:s},t)}GrayVoice(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gray_voice"),s={bot_id:i.bot_id,language_to_voice_id:i.language_to_voice_id};return this.request({url:o,method:"POST",data:s},t)}GetSpaceApplyManageList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/apply_manage_list"),s={space_id:i.space_id,space_apply_status:i.space_apply_status,search_word:i.search_word,page:i.page,size:i.size};return this.request({url:o,method:"GET",params:s},t)}DraftBotCrossSpaceCopy(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/draftbot/crossspace_copy"),s={bot_id:i.bot_id,to_space_id:i.to_space_id};return this.request({url:o,method:"POST",data:s},t)}RemovePublishMember(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/remove_publish_member"),s={space_id:i.space_id,member_list:i.member_list};return this.request({url:o,method:"POST",data:s},t)}AddPublishMember(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/add_publish_member"),s={space_id:i.space_id,member_list:i.member_list};return this.request({url:o,method:"POST",data:s},t)}SearchAddablePublishMember(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/search_addable_publish_member"),s={space_id:i.space_id,search_word:i.search_word,cursor_id:i.cursor_id,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}PublishMemberList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/publish_member_list"),s={space_id:i.space_id,search_word:i.search_word,cursor_id:i.cursor_id,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}OperateSpaceApply(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/operate_apply"),s={space_id:i.space_id,enterprise_id:i.enterprise_id,organization_id:i.organization_id,apply_id_list:i.apply_id_list,space_apply_status:i.space_apply_status};return this.request({url:o,method:"POST",data:s},t)}ImportSpaceConfirm(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/import/confirm"),s={space_id_list:i.space_id_list,enterprise_id:i.enterprise_id,organization_id:i.organization_id,personal_space_new_name:i.personal_space_new_name,user_id_list:i.user_id_list};return this.request({url:o,method:"POST",data:s},t)}ImportSpaceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/import/list"),s={enterprise_id:i.enterprise_id,organization_id:i.organization_id,search_word:i.search_word};return this.request({url:o,method:"GET",params:s},t)}ImportSpaceUserList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/import/user_list"),s={space_id_list:i.space_id_list,enterprise_id:i.enterprise_id,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}GetDouYinInfo(e,t){const i=this.genBaseURL("/api/playground_api/douyin/get_douyin_info");return this.request({url:i,method:"POST"},t)}LongTermMemoryList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/list"),s={bot_id:i.bot_id,connector_id:i.connector_id,offset:i.offset,limit:i.limit,time_capsule_item_type:i.time_capsule_item_type};return this.request({url:o,method:"GET",params:s},t)}LongTermMemoryUpdate(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/update"),s={bot_id:i.bot_id,connector_id:i.connector_id,biz_id:i.biz_id,new_content:i.new_content,event_ms:i.event_ms,ext:i.ext,tags:i.tags,time_capsule_item_type:i.time_capsule_item_type,iid:i.iid,meta_type:i.meta_type,memory_type:i.memory_type};return this.request({url:o,method:"POST",data:s},t)}LongTermMemoryClearAll(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/clear_all"),s={bot_id:i.bot_id,connector_id:i.connector_id,time_capsule_item_type:i.time_capsule_item_type};return this.request({url:o,method:"POST",data:s},t)}LongTermMemoryDelete(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/delete"),s={bot_id:i.bot_id,connector_id:i.connector_id,biz_ids:i.biz_ids,time_capsule_item_type:i.time_capsule_item_type,iids:i.iids,memory_meta_type_map:i.memory_meta_type_map};return this.request({url:o,method:"POST",data:s},t)}LongTermMemoryVersion(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/version"),s={bot_id:i.bot_id};return this.request({url:o,method:"GET",params:s},t)}GetVoiceListV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_voice_list_v2"),s={language_code:i.language_code,space_id:i.space_id,voice_type:i.voice_type,page_size:i.page_size,next_cursor:i.next_cursor};return this.request({url:o,method:"POST",data:s},t)}GetUserUpdateProfileTag(e,t){const i=this.genBaseURL("/api/playground_api/get_user_update_profile_tag");return this.request({url:i,method:"GET"},t)}OpenRemoveSpaceMember(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members`),s={user_ids:i.user_ids};return this.request({url:o,method:"DELETE",data:s},t)}OpenSpaceMemberList(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members`),s={page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}OpenAddSpaceMember(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members`),s={users:i.users};return this.request({url:o,method:"POST",data:s},t)}OpenGetBotInfo(e,t){const i=e||{},o=this.genBaseURL(`/v1/bots/${i.bot_id}`),s={is_published:i.is_published,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}OpenApplyJoinSpace(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members/apply`),s={user_ids:i.user_ids};return this.request({url:o,method:"POST",data:s},t)}OpenRemoveSpace(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}`);return this.request({url:o,method:"DELETE"},t)}GetTypeList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_type_list"),s={model:i.model,voice:i.voice,raw_model:i.raw_model,space_id:i.space_id,cur_model_id:i.cur_model_id,cur_model_ids:i.cur_model_ids,model_scene:i.model_scene,tag_filters:i.tag_filters};return this.request({url:o,method:"POST",data:s},t)}GetCozeLaneInfo(e,t){const i=this.genBaseURL("/api/playground_api/get_coze_lane_info");return this.request({url:i,method:"POST"},t)}OpenUpdateSpaceMember(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members/${i.user_id}`),s={role_type:i.role_type};return this.request({url:o,method:"PUT",data:s},t)}OpenListBotVersions(e,t){const i=e||{},o=this.genBaseURL(`/v1/bots/${i.bot_id}/versions`),s={page_num:i.page_num,page_size:i.page_size,publish_status:i.publish_status,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}OpenSwitchBotDevelopMode(e,t){const i=e||{},o=this.genBaseURL(`/v1/bots/${i.bot_id}/collaboration_mode`),s={collaboration_mode:i.collaboration_mode};return this.request({url:o,method:"POST",data:s},t)}OpenUpdateSpace(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}`),s={name:i.name,description:i.description};return this.request({url:o,method:"PUT",data:s},t)}}const dr=new cr({});function lr(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}async function pr(t,o){if(lr([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipAuth]))return void await o();if(!t.config.accessToken)throw new e.CozeError(e.ErrorCode.E2001,"No API token found. Please authenticate first.",void 0,{fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"});if(lr([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipOrgCheck]))return void await o();const s=await async function(t){let o=t.config.organizationId,{enterpriseId:s}=t.config,n=!1;const{data:r}=await po.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0}),a=r.enterprise_info_list||[],c=r.personal_account_info;if(o){if(!a.some((e=>lr([e,"access",e=>e.organization_info_list,"optionalAccess",e=>e.some,"call",e=>e((e=>e.organization_id===o))]))))throw new e.CozeError(e.ErrorCode.E1000,`Organization ID ${o} is invalid or not found`,void 0,{fix:"Run `coze organization list` and select a valid organization",example:"coze organization use <organization_id>"})}else{if(c.available)return!1;let r;t.ui.info(i.gray("[Context] Organization ID not found. Attempting to auto-initialize..."));for(const e of a)if(e.organization_info_list&&e.organization_info_list.length>0){const t=e.organization_info_list[0];r={id:t.organization_id,name:t.organization_name,entId:e.enterprise_id};break}if(!r)throw new e.CozeError(e.ErrorCode.E3000,"No organizations found",void 0,{fix:"Create an organization or join an existing one",example:"coze organization list"});o=r.id,s=r.entId,t.config.organizationId=o,t.config.enterpriseId=s,n=!0,t.ui.info(`[Context] Auto-selected Organization: ${r.name} (${r.id})`)}return n}(t);if(lr([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipSpaceCheck]))return s&&await ur(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId}),void await o();const n=await async function(t){const i=t.config.organizationId,{enterpriseId:o}=t.config;let{spaceId:s}=t.config,n=!1;try{if(s){const{data:t}=await dr.GetSpaceListV2({organization_id:i,enterprise_id:o}),n=lr([t,"optionalAccess",e=>e.bot_space_list])||[];if(!n.some((e=>e.id===s))){const t=i?`[Context] Space ID ${s} is invalid or not found in organization ${i}.`:`[Context] Space ID ${s} is invalid or not found.`;throw new e.CozeError(e.ErrorCode.E1000,t,void 0,{fix:"Run `coze space list` and select a valid space",example:"coze space use <space_id>"})}}else{t.ui.info("[Context] Space ID not found. Attempting to auto-initialize...");const{data:r}=await dr.GetSpaceListV2({organization_id:i,enterprise_id:o,page:1,size:1}),a=lr([r,"optionalAccess",e=>e.bot_space_list,"optionalAccess",e=>e[0]]);if(!a){const t=i?`[Context] No spaces found in organization ${i}. Please create one.`:"[Context] No spaces found. Please create one.";throw new e.CozeError(e.ErrorCode.E3000,t,void 0,{fix:"Create a space in the current organization",example:"coze space list"})}s=a.id,t.config.spaceId=s,n=!0,t.ui.success(`[Context] Auto-selected Space: ${a.name} (${a.id})`)}}catch(t){const i=t instanceof e.CozeError?t:new e.CozeError(e.ErrorCode.E5000,t.message,t instanceof Error?t.stack:t);throw i.fix??="Switch organization or space using `coze organization use <organization_id>` or `coze space use <space_id>`",i.example??="coze organization list",i}return n}(t);await _r(t),(s||n)&&await ur(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId,spaceId:t.config.spaceId,billingProjectId:t.config.billingProjectId}),await o()}async function ur(e,t){try{await s.saveConfig(t)}catch(t){e.ui.warn(`Failed to save auto-initialized context: ${t}`)}}const _r=async i=>{const{spaceId:o}=i.config;try{const{data:s}=await t.IdeApi.GetOrCreateBillingProject({space_id:o});if(!lr([s,"optionalAccess",e=>e.project_id]))throw new e.CozeError(e.ErrorCode.E5002,"[Context] Failed to get billing project ID from response.",s);i.config.billingProjectId=s.project_id,i.ui.success(`[Context] Billing Project: ${s.project_id} (space: ${o})`)}catch(e){const t=[`Failed to get billing project, ${e.message}. please check your space context:`," coze space list"," coze space use <space_id>"];throw e.message=`${t.join("\n")}`,e}};function hr(e,t){return null!=e?e:t()}function mr(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 gr=t=>{const i=t.command("space").config({skipSpaceCheck:!0,help:{brief:"Workspace (Space) context management commands",description:"Provides workspace viewing and switching functionality, used to set the default Space ID for subsequent commands",examples:[{desc:"List all available workspaces",cmd:"coze space list"},{desc:"Set default space",cmd:"coze space use 123456789"}],seeAlso:["coze organization"]}}).description("Manage workspace (Space) context");i.command("list").description("List all spaces").config({help:{brief:"List all workspaces under the current organization",description:"Retrieve and display a list of all available Spaces under the currently configured Organization or Enterprise. Defaults to fetching up to the first 100.",examples:[{desc:"List space list",cmd:"coze space list",tags:["[RECOMMENDED]"]},{desc:"List in JSON format",cmd:"coze space list --format json"}],schema:{output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Space ID"},name:{type:"string",description:"Space name"},org_id:{type:"string",description:"Belonging Organization ID"}}}}}}}).action((async(e,t)=>{const i=t.getContext(),o=e.orgId||mr([i,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),s=mr([i,"optionalAccess",e=>e.config,"access",e=>e.enterpriseId]);mr([i,"optionalAccess",e=>e.ui,"access",e=>e.verbose,"call",e=>e(`Fetching spaces for organization '${o}'...`)]);const n=await async function(e){const{data:t}=await dr.GetSpaceListV2({organization_id:e.orgId,enterprise_id:e.enterpriseId,page:1,size:100});return hr(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}([t,"optionalAccess",e=>e.bot_space_list]),(()=>[])).map((t=>({id:hr(t.id,(()=>"")),name:hr(t.name,(()=>"")),org_id:hr(e.orgId,(()=>""))})))}({orgId:o,enterpriseId:s});mr([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Spaces:")]),mr([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)]);const r=["Please use the following command to switch space:"," coze space use <space_id>"];mr([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(r.join("\n"))])})),i.command("use").description("Set the default workspace context").argument("<space_id>","Space ID to set as default context").config({help:{brief:"Switch current default Space",description:"Save the specified space_id to the local configuration as the default workspace for subsequent commands.",examples:[{desc:"Switch space",cmd:"coze space use 7349123847123",tags:["[RECOMMENDED]"]}],schema:{input:{space_id:{type:"string",required:!0,description:"Space ID to switch to"}},output:{status:{type:"string"},message:{type:"string"}}}}}).action((async(t,i,o)=>{const n=o.getContext();mr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to space '${t}'...`)]),await async function(t){try{await s.saveConfig({spaceId:t})}catch(i){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set default space to '${t}': ${i.message}`,i.stack)}}(t),mr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default space set to '${t}' successfully.`)]),"json"===mr([n,"optionalAccess",e=>e.format])&&mr([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default space set to '${t}'.`})])}))};function fr(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 yr=async t=>{fr([t,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switching to personal account...")]);const{available:i}=await async function(){const[e,{data:t}]=await Promise.all([s.loadConfig(),po.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);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}([t.personal_account_info,"optionalAccess",e=>e.available]))return{available:!1};const i=!!e.organizationId;return await s.saveConfig({organizationId:void 0,enterpriseId:void 0,...i?{spaceId:void 0}:{}}),{available:!0}}();if(!i)throw new e.CozeError(e.ErrorCode.E1000,"Personal account is not available for the current user.");fr([t,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switched to personal account successfully.")]),"json"===fr([t,"optionalAccess",e=>e.format])&&fr([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:"Switched to personal account."})])},vr=t=>{const i=t.command("organization").config({skipOrgCheck:!0,help:{brief:"Manage organization context",description:"Provides viewing and switching functions for organizations, used to set the default Organization ID for subsequent commands. Supports switching to personal account by omitting the org_id.",examples:[{desc:"List all accessible organizations",cmd:"coze organization list"},{desc:"Set default organization",cmd:"coze organization use 123456"},{desc:"Switch to personal account",cmd:"coze organization use"},{desc:"List organizations (alias)",cmd:"coze org list"},{desc:"Set default organization (alias)",cmd:"coze org use 123456"}],seeAlso:["coze space"]}}).alias("org").description("Manage organization context");i.command("list").description("List all accessible organizations").config({help:{brief:"List all accessible organizations",description:"Retrieve and display all organizations (Teams) and their corresponding enterprises accessible to the current logged-in user.",examples:[{desc:"List organizations",cmd:"coze organization list",tags:["[RECOMMENDED]"]},{desc:"Output in JSON format",cmd:"coze organization list --format json"}],schema:{output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Organization ID"},name:{type:"string",description:"Organization name"},enterprise_id:{type:"string",description:"Belonging Enterprise ID"},enterprise_name:{type:"string",description:"Belonging Enterprise name"}}}}}}}).action((async(e,t)=>{const i=t.getContext();fr([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching organizations...")]);const o=await async function(){const{data:e}=await po.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0});return e.enterprise_info_list.flatMap((e=>(e.organization_info_list||[]).map((t=>({id:t.organization_id,name:t.organization_name,enterprise_id:e.enterprise_id,enterprise_name:e.name})))))}();fr([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Organizations (Teams):")]),fr([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(o)]);const s=["Please use the following command to switch organization:"," coze organization use <organization_id>","Please use the following command to switch space:"," coze space list"," coze space use <space_id>"];fr([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])})),i.command("use").description("Set the default organization context").argument("[org_id]","Organization ID to set as default context (empty to switch to personal account)").config({help:{brief:"Set default organization or switch to personal account",description:"Save the specified org_id to the local configuration as the default organization for subsequent commands. The command will automatically retrieve and save the corresponding Enterprise ID. If the org_id is not found in the user's enterprise list, the command will fail without modifying the configuration. When switching to a different organization, the saved spaceId will be cleared. Omit org_id to switch to personal account mode (requires personal account to be available).",examples:[{desc:"Switch organization",cmd:"coze organization use 12345678",tags:["[RECOMMENDED]"]},{desc:"Switch to personal account",cmd:"coze organization use"},{desc:"Switch to personal account (explicit empty string)",cmd:'coze organization use ""'}],errors:[{code:e.ErrorCode.E3001,name:"RESOURCE_NOT_FOUND",desc:"Organization not found",fix:"Run `coze organization list` to see available organizations."},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Personal account not available",fix:"Your account does not have personal account access. Use `coze organization use <org_id>` to switch to an organization instead."}],schema:{input:{org_id:{type:"string",required:!1,description:"Organization ID to switch to. Empty or omitted to switch to personal account."}},output:{status:{type:"string",description:"Operation result status"},message:{type:"string",description:"Human-readable result message"},enterprise_id:{type:"string",description:"Enterprise ID of the selected organization (empty for personal account)"},organization_id:{type:"string",description:"Organization ID that was set (empty for personal account)"}}}}}).action((async(t,i,o)=>{const n=o.getContext();if(!t)return void await yr(n);fr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to organization '${t}'...`)]);const{enterpriseId:r}=await async function(t){const[i,{data:o}]=await Promise.all([s.loadConfig(),po.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);let n="",r=!1;for(const e of o.enterprise_info_list)if((e.organization_info_list||[]).find((e=>e.organization_id===t))){n=e.enterprise_id,r=!0;break}if(!r)throw new e.CozeError(e.ErrorCode.E3000,`Organization '${t}' not found in current user's enterprises.`);const a=i.organizationId!==t;return await s.saveConfig({organizationId:t,enterpriseId:n,...a?{spaceId:void 0}:{}}),{enterpriseId:n}}(t);fr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Organization '${t}' found in enterprise '${r}'. Config saved.`)]),fr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default organization set to '${t}' successfully.`)]),"json"===fr([n,"optionalAccess",e=>e.format])&&fr([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default organization set to '${t}'.`,enterprise_id:r,organization_id:t})])}))};function wr(e,t){return null!=e?e:t()}const br=async(e={})=>{const t=wr(e.stdin,(()=>process.stdin));return!0===wr(e.isTTY,(()=>t.isTTY))?null:await(async e=>{let t="";e.setEncoding("utf-8");for await(const i of e)t+=i;return t})(t)},Sr=e=>{process.stdout.write(e.endsWith("\n")?e:`${e}\n`)},Pr=e=>{Sr(JSON.stringify(e))},Cr=async(e,t)=>{const i=c.resolve(e),o=c.dirname(i);if(await u.mkdir(o,{recursive:!0}),t instanceof Blob){const e=Buffer.from(await t.arrayBuffer());await u.writeFile(i,e)}else Buffer.isBuffer(t)?await u.writeFile(i,t):t instanceof ArrayBuffer?await u.writeFile(i,Buffer.from(t)):await u.writeFile(i,String(t));return i};const Tr=e=>"object"==typeof e&&null!==e,Er=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},kr=e=>Tr(e)&&"data"in e&&void 0!==e.data?e.data:e,Ir=(e,t)=>{try{const{pathname:i}=new URL(e);return c.extname(i)||t}catch(e){return t}},Ar=()=>{const e=new Date;return`${e.getFullYear()}${String(e.getMonth()+1).padStart(2,"0")}${String(e.getDate()).padStart(2,"0")}_${String(e.getHours()).padStart(2,"0")}${String(e.getMinutes()).padStart(2,"0")}${String(e.getSeconds()).padStart(2,"0")}`},jr=e=>{const{outputPath:t,type:i,index:o,ext:s,timestamp:n}=e,r=`${i}_${n}_${o}${s}`;return c.join(t,r)},Rr=async(t,i={})=>{let o=null;i.stdin&&(o=await br());const s=Er(t),n=Er(o),r=(c=()=>n,null!=(a=s)?a:c());var a,c;if(!r)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin with piped content");return r},zr="720p",Ur="16:9",Lr=!1,Or=!1;function xr(e,t){return null!=e?e:t()}function Br(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 qr=(e,t)=>{if(null==e)return 5;const i=Number(e);if(!Number.isFinite(i))return Br([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --duration '${String(e)}', falling back to 5`)]),5;const o=Math.floor(i);return o<4||o>12?(Br([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`--duration '${String(e)}' out of bounds (4..12), falling back to -1 as per documentation (letting the model decide)`)]),-1):o},Dr=(e,t)=>{if(null==e)return;const i=Number(e);if(Number.isSafeInteger(i)&&i>=0)return i;Br([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --seed '${String(e)}', this parameter will be ignored`)])},Mr=e=>{const{content:t,options:i,ctx:o}=e,s=(e=>{if("string"!=typeof e)return null;const t=e.trim(),i=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(t);if(!i)return null;const o=Number(i[1]),s=Number(i[2]);if(!Number.isFinite(o)||!Number.isFinite(s)||o<=0)return null;const n=((e,t)=>{let i=Math.abs(e),o=Math.abs(t);for(;0!==o;){const e=i%o;i=o,o=e}return i})(o,s)||1,r=`${Math.round(o/n)}:${Math.round(s/n)}`,a=Math.max(o,s);return{ratio:r,resolution:a<=854?"480p":a<=1280?"720p":"1080p"}})(i.size),n=((e,t)=>"480p"===e||"720p"===e||"1080p"===e?e:(void 0!==e&&Br([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --resolution '${String(e)}', falling back to '${zr}'`)]),zr))(xr(i.resolution,(()=>Br([s,"optionalAccess",e=>e.resolution]))),o),r=((e,t)=>{if("string"==typeof e){const t=e.trim();if(t.length>0)return t}return void 0!==e&&Br([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --ratio '${String(e)}', falling back to '${Ur}'`)]),Ur})(xr(i.ratio,(()=>Br([s,"optionalAccess",e=>e.ratio]))),o);return{model:"doubao-seedance-1-5-pro-251215",content:t,callback_url:xr(Er(i.callbackUrl),(()=>{})),return_last_frame:"boolean"==typeof i.returnLastFrame?i.returnLastFrame:Or,resolution:n,ratio:r,duration:qr(i.duration,o),watermark:"boolean"!=typeof i.watermark||i.watermark,seed:Dr(i.seed,o),camerafixed:"boolean"==typeof i.camerafixed?i.camerafixed:Lr,generate_audio:"boolean"!=typeof i.generateAudio||i.generateAudio}},Nr=async t=>{const i=await e.customFetch.fetch(t);if(!i.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download generated resource: ${i.status} ${i.statusText}`,{url:t});return Buffer.from(await i.arrayBuffer())},Gr=async e=>{const{outputPath:t,videoUrl:i,lastFrameUrl:o,shouldSaveLastFrame:s}=e,n=Ir(i,".mp4"),r=Ar(),a=jr({outputPath:t,type:"video",index:0,ext:n,timestamp:r}),d=await Nr(i),l=[await Cr(a,d)];if(s&&"string"==typeof o&&o.length>0){const e=(e=>{const{outputPath:t,ext:i,timestamp:o}=e,s=`last_frame_${o}_0${i}`;return c.join(t,s)})({outputPath:t,ext:Ir(o,".png"),timestamp:r}),i=await Nr(o),s=await Cr(e,i);l.push(s)}return l};var $r,Fr,Vr,Wr,Hr,Jr,Kr,Qr,Yr,Zr,Xr,ea,ta,ia,oa,sa,na,ra,aa;function ca(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[e.TotalTokens=1]="TotalTokens";e[e.TotalInputTokens=2]="TotalInputTokens";e[e.TotalOutputTokens=3]="TotalOutputTokens"}($r||($r={})),function(e){e[e.ASC=1]="ASC";e[e.DESC=2]="DESC"}(Fr||(Fr={})),function(e){e[e.None=0]="None";e[e.APIKey=1]="APIKey";e[e.Oauth3LO=2]="Oauth3LO";e[e.Oauth2LO=3]="Oauth2LO";e[e.SAT=4]="SAT"}(Vr||(Vr={})),function(e){e[e.Free=1]="Free";e[e.Trial=2]="Trial";e[e.Paid=3]="Paid"}(Wr||(Wr={})),function(e){e[e.Inactive=1]="Inactive";e[e.Active=2]="Active"}(Hr||(Hr={})),function(e){e[e.CNY=1]="CNY";e[e.ResourcePoint=2]="ResourcePoint"}(Jr||(Jr={})),function(e){e[e.Cancellable=0]="Cancellable";e[e.NoCancellable=1]="NoCancellable";e[e.AlwaysDefault=2]="AlwaysDefault"}(Kr||(Kr={})),function(e){e[e.LLMModel=1]="LLMModel";e[e.ImageModel=2]="ImageModel";e[e.VideoModel=3]="VideoModel";e[e.AudioModel=4]="AudioModel";e[e.Database=5]="Database";e[e.Storage=6]="Storage";e[e.WebSearch=7]="WebSearch";e[e.EmbeddingModel=8]="EmbeddingModel";e[e.ContentProcessing=9]="ContentProcessing"}(Qr||(Qr={})),function(e){e[e.Internal=1]="Internal";e[e.External=2]="External";e[e.Infra=3]="Infra"}(Yr||(Yr={})),function(e){e[e.Text=1]="Text";e[e.Image=2]="Image";e[e.Video=3]="Video";e[e.Audio=4]="Audio"}(Zr||(Zr={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String";e[e.JsonInput=5]="JsonInput"}(Xr||(Xr={})),function(e){e[e.Seed=1]="Seed";e[e.DeepSeek=2]="DeepSeek";e[e.Kimi=3]="Kimi";e[e.GLM=4]="GLM";e[e.MiniMax=5]="MiniMax";e[e.Qwen=6]="Qwen";e[e.StepFun=7]="StepFun";e[e.GPT=8]="GPT";e[e.Others=100]="Others"}(ea||(ea={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online";e[e.GradualRollout=2]="GradualRollout";e[e.ReadyToOffline=3]="ReadyToOffline"}(ta||(ta={})),function(e){e[e.None=0]="None";e[e.InProgress=1]="InProgress";e[e.Success=2]="Success";e[e.Fail=3]="Fail";e[e.RollingBack=4]="RollingBack"}(ia||(ia={})),function(e){e[e.Install=1]="Install";e[e.Uninstall=2]="Uninstall"}(oa||(oa={})),function(e){e[e.Default=0]="Default";e[e.Agent=1]="Agent";e[e.Workflow=2]="Workflow";e[e.App=4]="App";e[e.Skill=5]="Skill";e[e.Web=6]="Web";e[e.WechatMiniProgram=7]="WechatMiniProgram";e[e.AssistantAgent=8]="AssistantAgent";e[e.General=9]="General";e[e.Design=100]="Design";e[e.Integration=101]="Integration";e[e.Dev=102]="Dev"}(sa||(sa={})),function(e){e[e.Scene=1]="Scene";e[e.Type=2]="Type"}(na||(na={})),function(e){e[e.Official=1]="Official";e[e.Community=2]="Community"}(ra||(ra={})),function(e){e[e.Agent=1]="Agent";e[e.Automation=2]="Automation";e[e.WebApp=3]="WebApp";e[e.App=4]="App";e[e.Skill=5]="Skill";e[e.GeneralWeb=6]="GeneralWeb";e[e.WechatMiniProgram=7]="WechatMiniProgram";e[e.AssistantAgent=8]="AssistantAgent";e[e.General=9]="General";e[e.CLIBilling=101]="CLIBilling"}(aa||(aa={}));class da{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){da.prototype.__init.call(this),da.prototype.__init2.call(this),this.request=ca([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=ca([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}ListIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/list"),s={space_id:i.space_id,project_id:i.project_id,integration_type:i.integration_type,integration_id:i.integration_id,filter_installed:i.filter_installed,org_id:i.org_id,search_words:i.search_words,page_num:i.page_num,page_size:i.page_size,project_type:i.project_type};return this.request({url:o,method:"POST",data:s},t)}SetIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/update"),s={integration_id:i.integration_id,space_id:i.space_id,auth_schema_value:i.auth_schema_value};return this.request({url:o,method:"POST",data:s},t)}DeleteIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/delete"),s={integration_id:i.integration_id,space_id:i.space_id,project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}AuthIntegrationStatus(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/auth/status"),s={integration_id:i.integration_id,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}ManageSpaceIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/space/manage"),s={space_ids:i.space_ids,integration_ids:i.integration_ids,op_type:i.op_type};return this.request({url:o,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/api/v3/contents/generations/tasks"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}FlashASR(e,t){const i=e||{},o=this.genBaseURL("/api/v3/auc/bigmodel/recognize/flash"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}ListModel(e,t){const i=e||{},o=this.genBaseURL("/v1/model/list"),s={model_type:i.model_type,current_model_ids:i.current_model_ids,integration_ids:i.integration_ids,need_model_config_param:i.need_model_config_param,page_size:i.page_size,offset:i.offset};return this.request({url:o,method:"POST",data:s},t)}ChatCompletions(e,t){const i=e||{},o=this.genBaseURL("/api/v3/chat/completions"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CreateResponses(e,t){const i=e||{},o=this.genBaseURL("/api/v3/responses"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}GenerateImages(e,t){const i=e||{},o=this.genBaseURL("/api/v3/images/generations"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const i=e||{},o=this.genBaseURL("/api/v3/tts/unidirectional"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}GetIntegrationOauthConfig(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/auth/oauth_config"),s={integration_id:i.integration_id,space_id:i.space_id,project_id:i.project_id,session_id:i.session_id};return this.request({url:o,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/api/v3/contents/generations/tasks/:id"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"GET",data:s,params:n},t)}WebSearch(e,t){const i=e||{},o=this.genBaseURL("/api/search_api/web_search"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}WebSearch(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/search_api/web_search"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CreateResponses(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/responses"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks/:id"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"GET",data:s,params:n},t)}FlashASR(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/auc/bigmodel/recognize/flash"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}GenerateImages(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/images/generations"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/tts/unidirectional"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}ChatCompletions(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/chat/completions"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CancelIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/cancel"),s={integration_id:i.integration_id,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}Embeddings(e,t){const i=e||{},o=this.genBaseURL("/api/v3/embeddings/multimodal"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}Embeddings(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/embeddings/multimodal"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}VideoEditingUtils(e,t){const i=e||{},o=this.genBaseURL("/api/v1/integration/video_editing_utils"),s={Body:i.Body},n={tool_name:i.tool_name};return this.request({url:o,method:"POST",data:s,params:n},t)}GetProjectDefaultSkill(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/default"),s={project_type:i.project_type,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetSkillByIDs(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/by_ids"),s={project_type:i.project_type,skill_ids:i.skill_ids,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetSkillCategoryList(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/category/list"),s={project_type:i.project_type};return this.request({url:o,method:"POST",data:s},t)}UploadSkill(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/upload"),s={data:i.data},n={"Content-Type":i["Content-Type"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}GetUserSkillList(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/user/list"),s={page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}DeleteSkill(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/delete"),s={skill_id:i.skill_id};return this.request({url:o,method:"POST",data:s},t)}GetSkillList(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/list"),s={project_type:i.project_type,category_type_list:i.category_type_list,space_id:i.space_id,source_list:i.source_list};return this.request({url:o,method:"POST",data:s},t)}UploadSkillConfirm(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/upload/confirm"),s={preview_skill_key:i.preview_skill_key};return this.request({url:o,method:"POST",data:s},t)}FetchTool(e,t){const i=e||{},o=this.genBaseURL("/api/v1/integration/fetch_tool"),s={url:i.url};return this.request({url:o,method:"POST",data:s},t)}GetModelSwitchStatus(e,t){const i=e||{},o=this.genBaseURL("/v1/model/switch/status"),s={model_id:i.model_id,project_ids:i.project_ids,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}StartSwitchModel(e,t){const i=e||{},o=this.genBaseURL("/v1/model/switch/start"),s={space_id:i.space_id,project_ids:i.project_ids,current_model:i.current_model,target_model:i.target_model};return this.request({url:o,method:"POST",data:s},t)}GetModelUsageList(e,t){const i=e||{},o=this.genBaseURL("/v1/model/usage/list"),s={space_id:i.space_id,model_id:i.model_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp,order_by_field:i.order_by_field,order_by_type:i.order_by_type,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetModelDetails(e,t){const i=e||{},o=this.genBaseURL("/v1/model/details"),s={model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}GetModelUsageDetail(e,t){const i=e||{},o=this.genBaseURL("/v1/model/usage/details"),s={space_id:i.space_id,model_id:i.model_id,project_id:i.project_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp};return this.request({url:o,method:"POST",data:s},t)}RollbackSwitchModel(e,t){const i=e||{},o=this.genBaseURL("/v1/model/switch/rollback"),s={space_id:i.space_id,project_ids:i.project_ids,current_model:i.current_model};return this.request({url:o,method:"POST",data:s},t)}TextEmbeddings(e,t){const i=e||{},o=this.genBaseURL("/api/v3/embeddings"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}TextEmbeddings(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/embeddings"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CheckModelReadyToOffline(e,t){const i=e||{},o=this.genBaseURL("/v1/model/ready_to_offline/check"),s={model_type:i.model_type};return this.request({url:o,method:"POST",data:s},t)}Audit(e,t){const i=e||{},o=this.genBaseURL("/api/v1/integration/audit"),s={content:i.content};return this.request({url:o,method:"POST",data:s},t)}}da.prototype.UploadSkill=function(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/upload"),s=i.body;return this.request({url:o,method:"POST",data:s},t)},da.prototype.GenerateImages=function(e,t){const i=e||{},o=this.genBaseURL("/api/v3/images/generations"),s=i.Body;return this.request({url:o,method:"POST",data:s},t)},da.prototype.SubmitVideoGenerationsTasks=function(e,t){const i=e||{},o=this.genBaseURL("/api/v3/contents/generations/tasks"),s=i;return this.request({url:o,method:"POST",data:s},t)},da.prototype.GetVideoGenerationsTasks=function(e,t){const i=e||{},o=this.genBaseURL(`/api/v3/contents/generations/tasks/${i.id}`);return this.request({url:o,method:"GET"},t)};const la=new da({});const pa=async e=>await new Promise((t=>setTimeout(t,e))),ua=async e=>{const{taskId:t,baseURL:i,accessToken:o,projectId:s}=e,n=await la.GetVideoGenerationsTasks({id:t},{baseURL:i,headers:{Authorization:`Bearer ${o}`},params:{project_id:s}});return kr(n)};function _a(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 ha=e=>`coze generate video status ${e}`,ma=e=>{const{ctx:t,response:i}=e;"json"!==_a([t,"optionalAccess",e=>e.format])?Sr((e=>{const t=[e.status],i=_a([e,"access",e=>e.content,"optionalAccess",e=>e.video_url]),o=_a([e,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);return"succeeded"===e.status?("string"==typeof i&&i.length>0&&t.push(i),"string"==typeof o&&o.length>0&&t.push(o),t.join("\n")):("string"==typeof e.error_message&&e.error_message&&t.push(e.error_message),t.join("\n"))})(i)):Pr(i)},ga=t=>{const i=t.getContext(),{outputPath:o}=t.optsWithGlobals(),n=(r=_a([i,"optionalAccess",e=>e.config,"optionalAccess",e=>e.integrationApiBaseUrl]),a=()=>s.DEFAULT_CONFIG.integrationApiBaseUrl,null!=r?r:a());var r,a;const c=_a([i,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]);if(!c)throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login --oauth` or `coze auth login --token <token>` first");return{accessToken:c,ctx:i,integrationApiBaseUrl:n,outputPath:o}},fa=async(t,i,o)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:r,outputPath:a}=ga(o);let c=null;i.stdin&&(c=await br());const{content:d}=(t=>{const{prompt:i,stdinPrompt:o,options:s}=t,n=xr(Er(i),(()=>Er(o))),r=Er(s.firstFrame),a=Er(s.lastFrame),c=Boolean(r)||Boolean(a);if(!n&&!c)throw new e.CozeError(e.ErrorCode.E1000,"Missing input: Please provide PROMPT/stdin text, or provide images (--first-frame/--last-frame/--reference-image)");const d=[];return n&&d.push({type:"text",text:n}),r&&d.push({type:"image_url",image_url:{url:r},role:"first_frame"}),a&&d.push({type:"image_url",image_url:{url:a},role:"last_frame"}),{content:d}})({prompt:t,stdinPrompt:c,options:i}),l=Mr({content:d,options:i,ctx:n}),p=n.format,u=_a([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!u)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const{createResp:_,taskId:h}=await(async t=>{const{requestBody:i,baseURL:o,accessToken:s,projectId:n}=t,r=await la.SubmitVideoGenerationsTasks(i,{baseURL:o,headers:{Authorization:`Bearer ${s}`},params:{project_id:n}}),a=kr(r),c=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,"optionalAccess",e=>e.id]);if(!c||"string"!=typeof c)throw new e.CozeError(e.ErrorCode.E5002,"Video generation task created successfully but no valid task_id was returned",a);return{taskId:c,createResp:a}})({requestBody:l,baseURL:r,accessToken:s,projectId:u});if(!i.wait)return"json"===p?void Pr({query_command:ha(h),response:_,task_id:h}):void Sr((e=>["Video generation task created successfully.",`taskId: ${e}`,`Use \`${ha(e)}\` to query status.`].join("\n"))(h));const m=await(async t=>{const{taskId:i,baseURL:o,accessToken:s,pollIntervalMs:n,pollTimeoutMs:r,projectId:a}=t,c=Date.now();for(;;){const t=await ua({taskId:i,baseURL:o,accessToken:s,projectId:a});if("succeeded"===t.status)return t;if("failed"===t.status||"cancelled"===t.status)throw new e.CozeError(e.ErrorCode.E5002,`Video generation failed (status=${t.status}): ${d=t.error_message,l=()=>"unknown",null!=d?d:l()}`,t);if(Date.now()-c>r)throw new e.CozeError(e.ErrorCode.E5003,[`Video generation timed out after ${r}ms.`,`taskId: ${i}`,`Use \`coze generate video status ${i}\` to query status.`].join("\n"),{task_id:i,last_status:t.status});await pa(n)}var d,l})({taskId:h,baseURL:r,accessToken:s,pollIntervalMs:2e3,pollTimeoutMs:3e5,projectId:u}),g=_a([m,"access",e=>e.content,"optionalAccess",e=>e.video_url]),f=_a([m,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);if(!g||"string"!=typeof g)throw new e.CozeError(e.ErrorCode.E5002,"Video generated successfully but video_url was not returned");if(a){const e=await Gr({outputPath:a,videoUrl:g,lastFrameUrl:f,shouldSaveLastFrame:!0===i.returnLastFrame});return"json"===p?void Pr({task_id:h,request:l,response:m,saved_paths:e}):void Sr(e.join("\n"))}if("json"===p)return void Pr({task_id:h,request:l,response:m});const y=[g];!0===i.returnLastFrame&&"string"==typeof f&&f.length>0&&y.push(f),Sr(y.join("\n"))},ya=(e,t)=>{const i=t.getContext();V(e,i)},va=t=>{var i;i=t.command("create [prompt]").description("Create a video generation task").config({help:{brief:"Create video generation task",description:"Create a video generation task from text prompts or images. By default the command returns taskId immediately; use `--wait` to poll until completion.",examples:[{desc:"Create video from text",cmd:'coze generate video create "A dancing kitten"'},{desc:"Create task and wait for completion",cmd:'coze generate video create "A dancing kitten" --wait'},{desc:"Save result to file",cmd:'coze generate video create "A dancing kitten" --wait --output-path ./video.mp4'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --first-frame/--last-frame) with -h."},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid access token",fix:"Run `coze auth login --oauth` or set COZE_API_TOKEN/related credentials first"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server returned an error or response parsing failed",fix:"Please retry later. Use --debug for more details"},{code:e.ErrorCode.E5003,name:"TIMEOUT",desc:"Video generation request timed out",fix:"Please retry later or use `coze generate video status <taskId>` to query task status"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text prompt (can also be passed via stdin)"}},output:{type:"object",properties:{query_command:{type:"string"},task_id:{type:"string"},request:{type:"object"},response:{type:"object"},saved_paths:{type:"array",items:{type:"string"}}}}}}}).action((async(e,t,i)=>{try{await fa(e,t,i)}catch(e){ya(e,i)}})),i.option("--callback-url <url>","Callback URL for task status changes").option("--return-last-frame","Return last frame URL (default: disabled)",Or).option("--resolution <res>","Resolution: 480p|720p|1080p",zr).option("--ratio <ratio>",`Aspect ratio (default: ${Ur})`,Ur).option("--size <size>","Derive ratio/resolution from WIDTHxHEIGHT (lower priority than explicit parameters)").option("--duration <seconds>","Duration (seconds, 4..12; out-of-bounds fallback -1), default: 5",String(5)).option("--no-watermark","Disable watermark (default: enabled)").option("--seed <seed>","Random seed (safe integer)").option("--camerafixed","Fixed camera position (default: disabled)",Lr).option("--no-generate-audio","Do not generate accompanying audio (default: generate)").option("--first-frame <url>","First frame image URL").option("--last-frame <url>","Last frame image URL").option("--stdin","Read prompt from stdin (pipe input)").option("--wait","Wait for task completion by polling; by default the command returns taskId immediately")},wa=t=>{t.command("status <taskId>").description("Query video generation task status by task ID").option("--output <format>","Output format: text|json").config({help:{brief:"Query video task status",description:"Query the latest status of a video generation task by task ID. This command does not create a new task.",examples:[{desc:"Query task status",cmd:"coze generate video status task_123"},{desc:"Output full response as JSON",cmd:"coze generate video status task_123 --output json"}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid task ID or request parameters",fix:"Please confirm <taskId> is correct and try again",example:"coze generate video status task_123"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server returned an error or response parsing failed",fix:"Please retry later. Use --debug for more details"},{code:e.ErrorCode.E5003,name:"TIMEOUT",desc:"Request timed out",fix:"Please retry later"}],schema:{input:{taskId:{type:"string",required:!0,description:"Video generation task ID"}},output:{type:"object",properties:{id:{type:"string"},status:{type:"string"},model:{type:"string"},content:{type:"object"},error_message:{type:"string"}}}}}}).action((async(t,i,o)=>{try{await(async(t,i,o)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:r}=ga(o),a=_a([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!a)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const c=await ua({taskId:t,baseURL:r,accessToken:s,projectId:a});ma({ctx:n,response:c})})(t,0,o)}catch(e){ya(e,o)}}))};function ba(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 Sa="2K",Pa="url",Ca="standard",Ta="disabled",Ea=3686400,ka=16777216,Ia=e=>"object"==typeof e&&null!==e,Aa=e=>{if("string"==typeof e){const t=e.trim();return t.length?t:Ca}return Ca},ja=e=>{if(null==e)return;const t=(Array.isArray(e)?e:[e]).filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return 0!==t.length?1===t.length?t[0]:t:void 0},Ra=t=>{t.command("image [prompt]").description("Generate images from text prompts").config({help:{brief:"Generate images from text",description:"Generate images based on text prompts. Supports setting size, watermark, and multiple images.",examples:[{desc:"Generate image",cmd:'coze generate image "A futuristic city"'},{desc:"Save to file",cmd:'coze generate image "A cat" --output-path ./cat.png'},{desc:"Specify size",cmd:'coze generate image "A dog" --size 1024x1024'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --size/--max-images) with -h."},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Please configure billing project ID and retry"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"API response parsing failed or server returned an error",fix:"Please retry later. Use --debug for more details"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text prompt (can also be passed via stdin)"}},output:{type:"object",properties:{model:{type:"string"},created:{type:"number"},image_0:{type:"object"},saved_paths:{type:"array",items:{type:"string"}}}}}}}).option("--size <size>","Image size: 2K|4K or WIDTHxHEIGHT (local validation)",Sa).option("--no-watermark","Disable watermark (default: enabled)").option("--image <url>","Reference image URL (can be used multiple times)",((e,t)=>[...t,e]),[]).option("--response-format <format>","Response format: url|b64_json",Pa).option("--optimize-prompt-mode <mode>",`Prompt optimization mode (default: ${Ca})`,Ca).option("--sequential <mode>","Group image generation mode: auto|disabled",Ta).option("--max-images <n>","Maximum number of group images (1-15)",String(15)).option("--stdin","Read prompt from stdin (pipe input)").action((async(t,i,o)=>{const n=o.getContext(),{outputPath:r}=o.optsWithGlobals(),a=await Rr(t,{stdin:i.stdin}),c=ba([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const d=((e,t)=>{if(null==e)return{value:Sa};if("string"!=typeof e)return ba([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --size '${String(e)}', falling back to '${Sa}'`)]),{value:Sa};const i=e.trim();if("2K"===i||"4K"===i)return{value:i};const o=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(i);if(!o)return{value:Sa,warning:`Invalid --size '${i}', falling back to '${Sa}'. Expected 2K/4K or WIDTHxHEIGHT`};const s=Number(o[1]),n=Number(o[2]),r=s*n,a=s/n;return Number.isFinite(s)&&Number.isFinite(n)&&s>0&&n>0&&r>=Ea&&r<=ka&&a>=.0625&&a<=16?{value:`${s}x${n}`}:{value:Sa,warning:`Invalid --size '${i}', falling back to '${Sa}'. Total pixels must be in [3686400, 16777216], aspect ratio must be in [1:16, 16:1].`}})(i.size,n),l="url"===(p=i.responseFormat)||"b64_json"===p?{value:p}:void 0!==p?{value:Pa,warning:`Invalid --response-format '${String(p)}', falling back to '${Pa}'`}:{value:Pa};var p;const u=(e=>"auto"===e||"disabled"===e?{value:e}:void 0!==e?{value:Ta,warning:`Invalid --sequential '${String(e)}', falling back to '${Ta}'`}:{value:Ta})(i.sequential),_=(e=>{if(null==e)return{value:15};const t=Number(e);if(Number.isFinite(t)){const e=Math.floor(t);if(e>=1&&e<=15)return{value:e}}return{value:15,warning:`Invalid --max-images '${String(e)}', falling back to '15'`}})(i.maxImages);d.warning&&ba([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(d.warning)]),l.warning&&ba([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(l.warning)]),u.warning&&ba([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(u.warning)]),_.warning&&ba([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(_.warning)]);const h={model:"doubao-seedream-4-5-251128",prompt:a,size:d.value,watermark:"boolean"!=typeof i.watermark||i.watermark,image:ja(i.image),response_format:l.value,optimize_prompt_options:{mode:Aa(i.optimizePromptMode)},sequential_image_generation:u.value,sequential_image_generation_options:{max_images:_.value}},m=(t=>{const i=Ia(t)&&"data"in t?t.data:t;if(Ia(o=i)&&"string"==typeof o.model&&"number"==typeof o.created&&Array.isArray(o.data))return i;var o;throw new e.CozeError(e.ErrorCode.E5002,"Image generation API returned an unexpected response format",t)})(await la.GenerateImages({Body:h},{baseURL:s.DEFAULT_CONFIG.integrationApiBaseUrl,params:{project_id:c}}));if(m.error)throw new e.CozeError(e.ErrorCode.E5002,"Image generation failed (top-level error)",m.error);const g=(y=()=>Pa,null!=(f=h.response_format)?f:y());var f,y;const v=m.data.filter((e=>!e.error&&("url"===g?"string"==typeof e.url&&e.url.length>0:"string"==typeof e.b64_json&&e.b64_json.length>0)));if(0===v.length)throw new e.CozeError(e.ErrorCode.E5002,"Image generation succeeded but no valid image data was returned",m);if(r){const t=[],i=Ar();for(const[o,s]of v.entries()){const n="url"===g&&s.url?Ir(s.url,".png"):".png",a=jr({outputPath:r,type:"image",index:o,ext:n,timestamp:i});let c;if("url"===g){const t=await e.customFetch.fetch(s.url);if(!t.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download generated image: ${t.status} ${t.statusText}`);c=Buffer.from(await t.arrayBuffer())}else c=Buffer.from(s.b64_json,"base64");const d=await Cr(a,c);t.push(d)}const{model:o,usage:s,HttpHeader:a,...c}=(e=>{const{data:t,...i}=e,o=Object.fromEntries(t.map(((e,t)=>[`image_${t}`,e])));return{...i,...o}})(m);ba([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...c,saved_paths:t})])}else ba([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(m.data)])}))};function za(e,t){return null!=e?e:t()}function Ua(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 La="cli_user",Oa="zh_female_xiaohe_uranus_bigtts",xa="mp3",Ba=24e3,qa=(e,t)=>"pcm"===e||"mp3"===e||"ogg_opus"===e?e:(void 0!==e&&Ua([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --audio-format '${String(e)}', falling back to '${xa}'`)]),xa),Da=(e,t,i,o)=>{if(null==e)return t;const s=Number(e);return Number.isFinite(s)?Math.floor(s):(Ua([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",o=>o(`Invalid --${i} '${String(e)}', falling back to ${t}`)]),t)},Ma=t=>{const i=t.trim();if(0===i.length)return null;const o=i.startsWith("data:")?i.slice(5).trim():i;if(0===o.length)return null;const s=o[0];if("{"!==s&&"["!==s)return null;const n=e.safeJsonParse(o,void 0,{onError:t=>{const o=t instanceof Error?t.message:String(t);throw new e.CozeError(e.ErrorCode.E5002,`Failed to parse response: ${o}`,{line:i})}});return void 0===n?null:Tr(n)&&"number"==typeof n.code?n:null},Na=t=>{const i=t.command("generate").description("Media generation commands (API TBD)").config({help:{brief:"Media generation commands",description:"Generate media such as audio, image, and video using Coze APIs.",examples:[{desc:"Generate image",cmd:'coze generate image "A cat"'},{desc:"Generate audio",cmd:'coze generate audio "Hello world"'},{desc:"Generate video",cmd:'coze generate video create "A dancing dog"'}],seeAlso:["coze auth"]}}).option("--output-path <path>","Directory path to save the generated media files");Ra(i),(t=>{t.command("audio [prompt]").description("Synthesize speech from text or SSML (streaming)").config({help:{brief:"Generate audio from text",description:"Synthesize speech from text or SSML. Supports streaming output and configurable audio encodings.",examples:[{desc:"Basic text to speech",cmd:'coze generate audio "Hello world"'},{desc:"Save to file",cmd:'coze generate audio "Hello" --output-path ./audio.mp3'},{desc:"Use SSML",cmd:'echo "<speak>Hello</speak>" | coze generate audio --ssml'},{desc:"Specify audio encoding",cmd:'coze generate audio "Hello" --audio-format ogg_opus'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --speaker/--audio-format) with -h."},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Configure billing project ID and retry",example:'coze generate audio "Hello"'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid access token",fix:"Run `coze auth login --oauth` or `coze auth login --token <token>` first"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"API response parsing failed or server returned an error",fix:"Please retry later. Use --debug for more details"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text or SSML prompt (can also be passed via stdin)"}},output:{type:"object",properties:{request:{type:"object"},url:{type:"string",description:"Audio download URL"},saved_path:{type:"string",description:"Local path if saved"}}}}}}).option("--output <format>","Output format: text|json").option("--uid <uid>",`User UID (default: ${La})`,La).option("--speaker <speaker>",`Speaker (default: ${Oa})`,Oa).option("--audio-format <format>","Audio encoding: pcm|mp3|ogg_opus",xa).option("--sample-rate <n>","Sample rate (default: 24000)",String(Ba)).option("--speech-rate <n>","Speech rate (-50..100, default: 0)",String(0)).option("--loudness-rate <n>","Loudness (-50..100, default: 0)",String(0)).option("--ssml","Treat input as SSML (defaults to plain text)",!1).option("--stdin","Read prompt from stdin (pipe input)").action((async(t,i,o)=>{const s=o.getContext();try{const{outputPath:n}=o.optsWithGlobals(),r=Ua([s,"optionalAccess",e=>e.config,"access",e=>e.integrationApiBaseUrl]);if(!Ua([s,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]))throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login --oauth` or `coze auth login --token <token>` first");const a=await Rr(t,{stdin:i.stdin}),c=Ua([s,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const d={user:{uid:za(Er(i.uid),(()=>La))},req_params:{speaker:za(Er(i.speaker),(()=>Oa)),audio_params:{format:qa(i.audioFormat,s),sample_rate:Da(i.sampleRate,Ba,"sample-rate",s),speech_rate:Da(i.speechRate,0,"speech-rate",s),loudness_rate:Da(i.loudnessRate,0,"loudness-rate",s)}}};i.ssml?d.req_params={...d.req_params,ssml:a}:d.req_params={...d.req_params,text:a};const l=new URL("/api/v3/tts/unidirectional",r);l.searchParams.append("project_id",c);const p=await e.customFetch.fetch(l.toString(),{method:"POST",body:JSON.stringify(d)});if(!p.ok)throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis request failed: ${p.status} ${p.statusText}`,{status:p.status,statusText:p.statusText});if(!p.body)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis response is empty (no streaming body returned)");const u=new TextDecoder("utf-8"),_=p.body.getReader(),h=[];let m;const g=t=>{if(0===t.code)return n&&"string"==typeof t.data&&h.push(Buffer.from(t.data,"base64")),!1;if(2e7===t.code)return"string"==typeof t.url&&t.url.length>0&&(m=t.url),!0;throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis failed (code=${t.code}): ${za(t.message,(()=>"unknown"))}`,t)};let f="";for(;;){const{done:e,value:t}=await _.read();if(e)break;f+=u.decode(t,{stream:!0});const i=f.split(/\r?\n/);f=za(i.pop(),(()=>""));for(const e of i){const t=Ma(e);if(t&&g(t)){await _.cancel();break}}if(m)break}if(!m){f+=u.decode();const e=f.split(/\r?\n/);f="";for(const t of e){const e=Ma(t);if(e&&g(e))break}}if(n){const t=za(Ua([d,"access",e=>e.req_params,"optionalAccess",e=>e.audio_params,"optionalAccess",e=>e.format]),(()=>xa)),i="pcm"===t?".pcm":"ogg_opus"===t?".ogg":".mp3",o=Ar(),r=jr({outputPath:n,type:"audio",index:0,ext:i,timestamp:o});let a=null;if(h.length>0)a=await Cr(r,Buffer.concat(h));else if(m){const t=await e.customFetch.fetch(m);if(!t.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download synthesized speech: ${t.status} ${t.statusText}`,{status:t.status,statusText:t.statusText});const s=Buffer.from(await t.arrayBuffer()),r=Ir(m,i),c=jr({outputPath:n,type:"audio",index:0,ext:r,timestamp:o});a=await Cr(c,s)}if(!a)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis completed but no savable audio data was obtained (neither chunks nor download URL)",{url:m});return"json"===Ua([s,"optionalAccess",e=>e.format])?void Pr({request:d,url:m,saved_path:a}):void Sr(a)}if("json"===Ua([s,"optionalAccess",e=>e.format]))return void Pr({request:d,url:m});if(m)return void Sr(m);Sr("Speech synthesis completed, but no audio download URL was returned; you can use --output json to view details.")}catch(e){V(e,s)}}))})(i),(e=>{const t=(e=>e.command("video").description("Create videos or query video generation task status").config({help:{brief:"Generate videos",description:"Use explicit subcommands to create video generation tasks or query task status by task ID.",examples:[{desc:"Create video from text",cmd:'coze generate video create "A dancing kitten"'},{desc:"Query task status",cmd:"coze generate video status task_123"}],seeAlso:["coze generate image","coze generate audio"]}}))(e);va(t),wa(t)})(i)};function Ga(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 $a=i=>{(i=>{i.command("upload <path>").description("Upload a local file").config({help:{brief:"Upload a local file",description:"Upload a local file to Coze. The file can be used as an attachment or context in projects.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf",tags:["[RECOMMENDED]"]}],errors:[{code:e.ErrorCode.E3000,name:"RESOURCE_NOT_FOUND",desc:"Local file not found or not readable",fix:"Please confirm the file path exists and you have read permission"}],schema:{input:{path:{type:"string",required:!0,description:"Local file path to upload"}},output:{type:"string",description:"Uploaded file URL"}}}}).action((async(i,o,s)=>{let n;try{n=s.getContext();try{await h.access(i)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${i}`,{filePath:i})}const o=_.basename(i),r=_.extname(i),a=r?o.slice(0,-r.length):o,c=r.slice(1),d=new g;d.append("file_name",a),d.append("file_extension",c),d.append("file_content",m.createReadStream(i)),d.append("biz_type","cli_attachment");const l=await t.IdeApi.UploadFile({data:d},{headers:{...d.getHeaders()}});"json"===Ga([n,"optionalAccess",e=>e.format])?Ga([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(l.data)]):Ga([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(Ga([l,"access",e=>e.data,"optionalAccess",e=>e.file_url]))])}catch(e){V(e,n)}}))})(i.command("file").description("General file operations").config({help:{brief:"File upload and management",description:"Manage file operations for Coze projects. Currently supports uploading local files to Coze for use as attachments or context.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf"}],seeAlso:["coze code message send"]}}))};function Fa(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 Va(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 Wa(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 Ha(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 Ja=t=>{const i=t.command("config").description("Manage Coze CLI configuration").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Manage local configuration",description:"Provides read, set, list, and delete operations for the CLI local configuration file (`~/.cozerc.json`).",examples:[{desc:"List all configurations",cmd:"coze config list"},{desc:"Set configuration value",cmd:"coze config set base_url https://api.coze.cn"}]}});(e=>{e.command("get <keys...>").description("Get configuration values and their sources").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Get configuration values",description:"Read and output the value of the specified configuration keys from `~/.cozerc.json`. If a key does not exist, prompts that it was not found.",examples:[{desc:"Get BaseURL configuration",cmd:"coze config get baseUrl"},{desc:"Get default Space ID",cmd:"coze config get spaceId"},{desc:"Get multiple configurations",cmd:"coze config get baseUrl spaceId"}],schema:{input:{keys:{type:"array",required:!0,description:"Configuration key names"}},output:{value:{type:"any",description:"Configuration value"}}}}}).action((async(e,t,i)=>{const o=i.getContext(),n=await s.listConfigs();for(const t of e){const e=n.find((e=>e.key===t));Fa(e?[o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)]:[o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Configuration '${t}' not found.`)])}}))})(i),(t=>{t.command("set <key> <value>").description("Set a configuration value").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Set a single configuration value",description:"Update or add the specified local configuration key-value pair. The configuration will be persistently saved in `~/.cozerc.json`.",examples:[{desc:"Modify default workspace",cmd:"coze config set spaceId 123456789"},{desc:"Modify BaseURL",cmd:"coze config set baseUrl https://api.coze.cn"}],errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to set configuration value",fix:"Please check the key/value and retry. Use --debug for more details."}],schema:{input:{key:{type:"string",required:!0,description:"Configuration key name"},value:{type:"string",required:!0,description:"New configuration value"}}}}}).action((async(t,i,o,n)=>{const r=n.getContext();try{const e={};e[t]=i;const o="global";await s.saveConfig(e,o);const n={key:t,value:i,scope:o,status:"updated",message:`Configuration '${t}' updated successfully in ${o} scope.`};if(Va([r,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(n.message)]),"json"===Va([r,"optionalAccess",e=>e.format]))return void Va([r,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)])}catch(o){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set '${t}' to '${i}': ${o.message}`,o.stack)}}))})(i),(t=>{t.command("delete <keys...>").description("Delete a configuration value").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Delete configuration values",description:"Remove the specified configuration values from the local configuration file `~/.cozerc.json`.",examples:[{desc:"Delete a specific configuration key",cmd:"coze config delete spaceId"},{desc:"Delete multiple configuration keys",cmd:"coze config delete spaceId baseUrl"}],errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to delete configuration value",fix:"Please check the configuration key and retry. Use --debug for more details."}],schema:{input:{keys:{type:"array",required:!0,description:"Configuration key names"}}}}}).action((async(t,i,o)=>{const n=o.getContext();for(const i of t)try{await s.deleteConfig(i);const e={key:i,status:"deleted",message:`Configuration '${i}' has been removed.`};Wa([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleted ${i} from configuration file successfully.`)]),"json"===Wa([n,"optionalAccess",e=>e.format])&&Wa([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)])}catch(t){const o=t;throw new e.CozeError(e.ErrorCode.E5000,`Failed to delete config '${i}': ${o.message}`,o.stack)}}))})(i),(e=>{e.command("list").description("List all configuration values and their sources").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"List all local configuration values",description:"Print all configuration content stored in `~/.cozerc.json` in JSON format.",examples:[{desc:"List configurations",cmd:"coze config list"}],schema:{output:{type:"object",additionalProperties:!0,description:"Configuration key-value pairs"}}}}).action((async(e,t)=>{const i=t.getContext(),o=(await s.listConfigs()).map((({key:e,value:t,source:i})=>({key:e,value:t,source:i})));Ha([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Configurations found:")]),Ha([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(o)])}))})(i)},Ka="__COZE_FILE_COMP__";function Qa(){const e=process.env.SHELL;if(e){if(e.includes("bash"))return"bash";if(e.includes("zsh"))return"zsh";if(e.includes("fish"))return"fish"}if(process.env.PSModulePath)return"powershell"}function Ya(e){const t=d.homedir();switch(e){case"bash":return c.join(t,"darwin"===process.platform?".bash_profile":".bashrc");case"zsh":return c.join(t,".zshrc");case"fish":return c.join(t,".config/fish/config.fish");case"powershell":return function(){const e=["pwsh","powershell"];for(const t of e)try{const e=o.execSync(`${t} -NoProfile -NoLogo -Command "echo $PROFILE"`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim();if(e)return e}catch(e){continue}return}();default:return}}function Za(){return["### coze completion - begin. generated by coze cli ###","if type compdef &>/dev/null; then"," _coze_completion() {"," local completions",' completions=("${(@f)$(coze --compzsh --compgen "${CURRENT}" "${words[CURRENT-1]}" "${BUFFER}")}")',` if [[ "\${completions[1]}" == "${Ka}" ]]; then`," _files"," else"," compadd -- $completions"," fi"," }"," compdef _coze_completion coze","elif type complete &>/dev/null; then"," _coze_completion() {"," local cur prev nb_colon"," _get_comp_words_by_ref -n : cur prev",' nb_colon=$(grep -o ":" <<< "$COMP_LINE" | wc -l)'," local completions",' completions=$(coze --compbash --compgen "$((COMP_CWORD - (nb_colon * 2)))" "$prev" "${COMP_LINE}")',` if [[ "$completions" == "${Ka}" ]]; then`," COMPREPLY=()"," return"," fi",' COMPREPLY=( $(compgen -W "$completions" -- "$cur") )',' __ltrim_colon_completions "$cur"'," }"," complete -o default -o bashdefault -F _coze_completion coze","elif type compctl &>/dev/null; then"," _coze_completion() {"," local cword line point si"," read -Ac words"," read -cn cword"," read -l line",' si="$IFS"',' if ! IFS=$\'\\n\' reply=($(coze --compzsh --compgen "${cword}" "${words[cword-1]}" "${line}")); then'," local ret=$?",' IFS="$si"'," return $ret"," fi",' IFS="$si"'," }"," compctl -K _coze_completion coze","fi","### coze completion - end ###"].join(d.EOL)}function Xa(e){switch(e){case"bash":return`\n# begin coze completion\nsource ${c.join(d.homedir(),".coze","completion.sh")}\n# end coze completion\n`;case"zsh":return"\n# begin coze completion\n. <(coze --completion)\n# end coze completion\n";case"fish":return"\n# begin coze completion\ncoze --completion-fish | source\n# end coze completion\n";case"powershell":return`\n# begin coze completion\nRegister-ArgumentCompleter -Native -CommandName coze -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n $tokens = $commandAst.ToString().Split(" ", [StringSplitOptions]::RemoveEmptyEntries)\n $allArgs = @("--comppwsh")\n if ($tokens.Count -gt 1) {\n $allArgs += $tokens[1..($tokens.Count - 1)]\n }\n $result = & coze $allArgs 2>$null\n if ($result -and $result[0] -ne '${Ka}') {\n $result -split '\\n' | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n } else {\n Get-ChildItem -Path "$wordToComplete*" -ErrorAction SilentlyContinue | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_.Name, $_.Name, 'ProviderItem', $_.FullName)\n }\n }\n}\n# end coze completion\n`;default:return}}function ec(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}let tc,ic,oc=!1,sc=!1;function nc(e){const t=(i=e._args,o=()=>[],null!=i?i:o());var i,o;if(0===t.length)return!1;const s=/path|file|dir|folder/i;return t.some((e=>s.test(e._name)))}function rc(e){ic=e,function(){const e=process.argv.indexOf("--completion");e>-1&&(oc=!0,process.argv.splice(e,1));const t=process.argv.indexOf("--completion-fish");t>-1&&(sc=!0,process.argv.splice(t,1))}(),tc=f("coze"),tc.on("complete",((t,i)=>{const o=i.line.trimStart().split(/\s+/);o.length>0&&(o[0].endsWith("coze")||o[0].endsWith("bin/main"))&&o.shift();let s="";i.line.endsWith(" ")?(s="",""===o[o.length-1]&&o.pop()):s=o.pop()||"";const n=function(e,t,i){let o=e;for(const e of t){const t=o.commands.find((t=>t.name()===e||t.alias()===e));if(t)o=t;else if(!e.startsWith("-"))return nc(o)?[Ka]:[]}const s=[];o.commands.length>0&&o.commands.forEach((e=>{s.push(e.name())})),o.options.forEach((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))})),o!==e&&e.options.forEach((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}));const n=Array.from(new Set(s)).filter((e=>e.startsWith(i)));return 0===n.length&&nc(o)?[Ka]:n}(e,o,s);i.reply(n)})),e.command("completion").description("Setup shell auto-completion").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Configure terminal auto-completion",description:"Install or remove the auto-completion script for the current terminal environment (supports bash/zsh/fish/powershell).",examples:[{desc:"Install completion script",cmd:"coze completion --setup"},{desc:"Remove completion script",cmd:"coze completion --cleanup"}]}}).option("--setup","Install shell completion into your startup script (.zshrc / .bashrc / $PROFILE)").option("--cleanup","Remove shell completion from your startup script").action((async e=>{if(e.cleanup)!function(){const e=Qa();if(!e)return;const t=Ya(e);if(!t||!l.existsSync(t))return;const i=Xa(e);if(i){const e=l.readFileSync(t,"utf8").replace(new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"");l.writeFileSync(t,e)}if("bash"===e){const e=c.join(d.homedir(),".coze"),t=c.join(e,"completion.sh");l.existsSync(t)&&l.unlinkSync(t),l.existsSync(e)&&0===l.readdirSync(e).length&&l.rmdirSync(e)}}(),await s.saveConfig({completionInstalled:!1}),console.log("Shell completion removed! Please restart your terminal.");else{const e=Qa();if(!e)return console.error("Could not detect your shell type. Supported shells: bash, zsh, fish, powershell."),void(process.exitCode=1);const t=function(){const e=Qa();if(!e)return!1;const t=Ya(e);if(!t)return!1;if("bash"===e){const e=c.join(d.homedir(),".coze"),t=c.join(e,"completion.sh");l.existsSync(e)||l.mkdirSync(e,{recursive:!0}),l.writeFileSync(t,Za())}const i=c.dirname(t);l.existsSync(i)||l.mkdirSync(i,{recursive:!0});const o=Xa(e);return!!o&&(l.appendFileSync(t,o),!0)}();t?(await s.saveConfig({completionInstalled:!0}),console.log(`Shell completion (${e}) setup successful! Please restart your terminal or source your config file.`)):(console.error(`Failed to setup shell completion for ${e}.`),process.exitCode=1)}}))}function ac(){return oc?(console.log(Za()),void process.exit()):sc?(console.log(["### coze completion - begin. generated by coze cli ###","function _coze_completion"," set -l completions (coze --compfish --compgen (count (commandline -poc)) (commandline -pt) (commandline -pb))",` if test (count $completions) -eq 1 -a "$completions[1]" = "${Ka}"`," return"," end"," for c in $completions"," echo $c"," end","end","complete -c coze -a '(_coze_completion)' -n '_coze_completion'","### coze completion - end ###"].join(d.EOL)),void process.exit()):void(process.argv.includes("--comppwsh")?function(){if(!ic)return void process.exit();const e=process.argv.indexOf("--comppwsh"),t=process.argv.slice(e+1);let i=ic;const o=[];for(const e of t){const t=ec([i,"access",e=>e.commands,"optionalAccess",e=>e.find,"call",t=>t((t=>t.name()===e||t.alias()===e))]);t?i=t:o.push(e)}const s=[];ec([i,"access",e=>e.commands,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{s.push(e.name())}))]),ec([i,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}))]),i!==ic&&ec([ic,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}))]);const n=o[o.length-1]||"",r=Array.from(new Set(s)).filter((e=>e.startsWith(n)));0===r.length&&nc(i)?console.log(Ka):r.length>0&&console.log(r.join("\n")),process.exit()}():tc&&tc.init())}function cc(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 dc(i){i.command("remove <skillId>").description("Remove skills from the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Remove skill from project",description:"Remove a configured skill from the specified project.",examples:[{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID to remove"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},removed_skill_ids:{type:"array",items:{type:"string"},description:"Removed skill IDs"},message:{type:"string",description:"Result message"}}}}},errors:[{code:e.ErrorCode.E3004,name:"SKILL_NOT_INSTALLED",desc:"The specified skill is not installed in the project",fix:"Please use `skill list` to confirm installed skills"}]}}).action((async function(e,i,o){const s=o.getContext(),{projectId:n}=i,r=new Set([e]),a=cc([(await t.IdeApi.GetVibeProject({project_id:n})).data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]);var c;const d=(c=cc([a,"optionalAccess",e=>e.skills]),Array.isArray(c)?c.map((e=>{return{skill_id:String((t=cc([e,"optionalAccess",e=>e.skill_id]),i=()=>"",null!=t?t:i())),is_preload:cc([e,"optionalAccess",e=>e.is_preload])};var t,i})).filter((e=>Boolean(e.skill_id))):[]).filter((e=>!r.has(e.skill_id))),l={filter_types:cc([a,"optionalAccess",e=>e.filter_types]),skills:d};await t.IdeApi.UpdateVibeProject({project_id:n,project_settings:{skill_setting:l}}),cc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill removed.")]),cc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,removed_skill_ids:Array.from(r),message:"removed Skills successfully."})])}))}function lc(e,t){return null!=e?e:t()}function pc(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 uc(i){i.command("list").description("List available skills for the project").requiredOption("-p, --project-id <projectId>","Project ID").option("--space-id <spaceId>","Space ID (optional, reads from config)").config({help:{brief:"List available skills for the project",description:"Retrieve a list of all available skills for the specified project type, with installation status indicating which skills are already added.",examples:[{desc:"List project skills",cmd:"coze code skill list --project-id <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{type:"array",items:{type:"object",properties:{description:{type:"string",description:"Skill description"},skill_id:{type:"string",description:"Skill ID"},name:{type:"string",description:"Skill name"},icon:{type:"string",description:"Skill icon URL"},is_installed:{type:"boolean",description:"Whether the skill is installed"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}]}}).action((async function(i,o){const s=o.getContext(),{projectId:n}=i,r=lc(lc(i.spaceId,(()=>pc([s,"optionalAccess",e=>e.config,"access",e=>e.spaceId]))),(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing spaceId: pass --space-id <spaceId> or set config.spaceId");const a=await t.IdeApi.GetVibeProject({project_id:n}),c=function(e){const t=[],i=pc([e,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_settings]);pc([i,"optionalAccess",e=>e.skill_setting,"optionalAccess",e=>e.skills])&&t.push(...i.skill_setting.skills);const o=t.map((e=>pc([e,"optionalAccess",e=>e.skill_id]))).filter(Boolean);return new Set(o)}(a.data||{}),d=pc([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),l=await la.GetSkillList({project_type:d,space_id:r,category_type_list:[d]});pc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${pc([l,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} skills.`)]),pc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(pc([l,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({description:pc([e,"optionalAccess",e=>e.description]),skill_id:pc([e,"optionalAccess",e=>e.skill_id]),name:pc([e,"optionalAccess",e=>e.name]),icon:pc([e,"optionalAccess",e=>e.icon]),is_installed:c.has(e.skill_id||"")})))]))])}))}function _c(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 hc(i){i.command("add <skillId>").description("Add skills to the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add skill to project",description:"Add a specified skill to the project. Skills can extend project capabilities, such as adding search, code execution, etc.",examples:[{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},added_skill_ids:{type:"array",items:{type:"string"},description:"Added skill IDs"},message:{type:"string",description:"Result message"}}}}},errors:[{code:e.ErrorCode.E3002,name:"SKILL_NOT_FOUND",desc:"The specified skill does not exist",fix:"Please use `skill list` to confirm available skills"}]}}).action((async function(e,i,o){const s=o.getContext(),{projectId:n}=i,r=[e],a=(await t.IdeApi.GetVibeProject({project_id:n})).data||{},c=_c([a,"access",e=>e.project_info,"optionalAccess",e=>e.project_type]),d=_c([a,"access",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]),l=function(e){const t=new Map;for(const i of e){const e=_c([i,"optionalAccess",e=>e.skill_id])?String(i.skill_id):"";e&&(t.has(e)||t.set(e,{skill_id:e,is_preload:i.is_preload}))}return Array.from(t.values())}([...Array.isArray(_c([d,"optionalAccess",e=>e.skills]))?d.skills:[],...r.map((e=>({skill_id:String(e),is_preload:!0})))]),p={filter_types:_c([d,"optionalAccess",e=>e.filter_types])&&d.filter_types.length>0?d.filter_types:[c],skills:l};await t.IdeApi.UpdateVibeProject({project_id:n,project_settings:{skill_setting:p}}),_c([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skills added successfully.")]),_c([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,added_skill_ids:r,message:"added Skills successfully."})])}))}var mc,gc,fc,yc,vc,wc,bc,Sc,Pc,Cc,Tc,Ec,kc,Ic,Ac,jc,Rc,zc,Uc,Lc,Oc,xc,Bc,qc,Dc,Mc,Nc,Gc,$c,Fc,Vc,Wc,Hc,Jc,Kc,Qc,Yc,Zc,Xc,ed,td,id,od,sd,nd,rd,ad,cd,dd,ld,pd,ud,_d,hd,md,gd,fd,yd,vd,wd,bd,Sd,Pd,Cd,Td,Ed,kd,Id,Ad,jd,Rd,zd,Ud,Ld,Od,xd,Bd;function qd(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[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(mc||(mc={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(gc||(gc={})),function(e){e[e.Chat=0]="Chat";e[e.FunctionCall_1=1]="FunctionCall_1";e[e.FunctionCall_2=2]="FunctionCall_2";e[e.FunctionCall_3=3]="FunctionCall_3"}(fc||(fc={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(yc||(yc={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Trigger=4]="Trigger";e[e.KnowledgeText=5]="KnowledgeText";e[e.KnowledgeTable=6]="KnowledgeTable";e[e.KnowledgeAutoCall=7]="KnowledgeAutoCall";e[e.KnowledgeOnDemandCall=8]="KnowledgeOnDemandCall";e[e.Variable=9]="Variable";e[e.Database=10]="Database";e[e.LongTermMemory=11]="LongTermMemory";e[e.FileBox=12]="FileBox";e[e.Onboarding=13]="Onboarding";e[e.Suggestion=14]="Suggestion";e[e.ShortcutCommand=15]="ShortcutCommand";e[e.BackGroundImage=16]="BackGroundImage";e[e.TTS=17]="TTS";e[e.MultiAgentRecognize=18]="MultiAgentRecognize";e[e.KnowledgePhoto=19]="KnowledgePhoto";e[e.HookInfo=20]="HookInfo";e[e.KnowledgeValcanoUnstructured=21]="KnowledgeValcanoUnstructured";e[e.KnowledgeValcanoStructured=22]="KnowledgeValcanoStructured";e[e.Model=23]="Model";e[e.KnowledgeThirdPartyUnstructured=24]="KnowledgeThirdPartyUnstructured";e[e.KnowledgeThirdPartyStructured=25]="KnowledgeThirdPartyStructured"}(vc||(vc={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(wc||(wc={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(bc||(bc={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(Sc||(Sc={})),function(e){e[e.Official=1]="Official";e[e.Public=2]="Public";e[e.Custom=3]="Custom";e[e.Others=101]="Others"}(Pc||(Pc={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(Cc||(Cc={})),function(e){e[e.App=1]="App";e[e.Resource=2]="Resource"}(Tc||(Tc={})),function(e){e[e.CozeModel=1]="CozeModel";e[e.VolcAccount=2]="VolcAccount";e[e.SelfAccount=3]="SelfAccount";e[e.SelfModel=4]="SelfModel"}(Ec||(Ec={})),function(e){e[e.Asc=1]="Asc";e[e.Desc=2]="Desc"}(kc||(kc={})),function(e){e[e.NoDetail=1]="NoDetail";e[e.Detail=2]="Detail";e[e.Operate=3]="Operate"}(Ic||(Ic={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(Ac||(Ac={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.Imageflow=3]="Imageflow";e[e.Knowledge=4]="Knowledge";e[e.UI=5]="UI";e[e.Prompt=6]="Prompt";e[e.Database=7]="Database";e[e.Variable=8]="Variable"}(jc||(jc={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi";e[e.MessagesApi=2]="MessagesApi"}(Rc||(Rc={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(zc||(zc={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(Uc||(Uc={})),function(e){e[e.Provider=1]="Provider";e[e.Custom=2]="Custom"}(Lc||(Lc={})),function(e){e[e.CozeAccountTypeUnknown=0]="CozeAccountTypeUnknown";e[e.CozeAccountTypePersonal=1]="CozeAccountTypePersonal";e[e.CozeAccountTypeOrganization=2]="CozeAccountTypeOrganization"}(Oc||(Oc={})),function(e){e[e.Intelligence=1]="Intelligence";e[e.App=2]="App";e[e.Plugin=3]="Plugin";e[e.Workflow=4]="Workflow";e[e.Knowledge=5]="Knowledge";e[e.Card=6]="Card";e[e.Prompt=7]="Prompt";e[e.Database=8]="Database";e[e.Voice=9]="Voice";e[e.VibeProjectAgent=11]="VibeProjectAgent";e[e.VibeProjectAutomation=12]="VibeProjectAutomation";e[e.VibeProjectWebApp=13]="VibeProjectWebApp";e[e.VibeProjectApp=14]="VibeProjectApp";e[e.VibeProjectSkill=15]="VibeProjectSkill";e[e.VibeProjectGeneralWeb=16]="VibeProjectGeneralWeb";e[e.VibeProjectWechatMiniProgram=17]="VibeProjectWechatMiniProgram";e[e.VibeProjectAssistantAgent=18]="VibeProjectAssistantAgent";e[e.VibeProjectGeneral=19]="VibeProjectGeneral"}(xc||(xc={})),function(e){e[e.Mobile=1]="Mobile";e[e.Web=2]="Web"}(Bc||(Bc={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(qc||(qc={})),function(e){e[e.Using=1]="Using";e[e.Deleted=2]="Deleted";e[e.Banned=3]="Banned";e[e.MoveFailed=4]="MoveFailed";e[e.Copying=5]="Copying";e[e.CopyFailed=6]="CopyFailed"}(Dc||(Dc={})),function(e){e[e.Bot=1]="Bot";e[e.Project=2]="Project";e[e.DouyinAvatarBot=3]="DouyinAvatarBot";e[e.VibeProjectAgent=11]="VibeProjectAgent";e[e.VibeProjectAutomation=12]="VibeProjectAutomation";e[e.VibeProjectWebApp=13]="VibeProjectWebApp";e[e.VibeProjectApp=14]="VibeProjectApp";e[e.VibeProjectSkill=15]="VibeProjectSkill";e[e.VibeProjectGeneralWeb=16]="VibeProjectGeneralWeb";e[e.VibeProjectWechatMiniProgram=17]="VibeProjectWechatMiniProgram";e[e.VibeProjectAssistantAgent=18]="VibeProjectAssistantAgent";e[e.VibeProjectGeneral=19]="VibeProjectGeneral"}(Mc||(Mc={})),function(e){e[e.DEFAULT=0]="DEFAULT";e[e.Chux=1]="Chux"}(Nc||(Nc={})),function(e){e[e.ProjectOwner=1]="ProjectOwner";e[e.ProjectEditor=2]="ProjectEditor";e[e.BotEditor=3]="BotEditor";e[e.BotDeveloper=4]="BotDeveloper";e[e.BotOperator=5]="BotOperator";e[e.BotOwner=6]="BotOwner"}(Gc||(Gc={})),function(e){e[e.PromptDiff=1]="PromptDiff";e[e.ModelDiff=2]="ModelDiff"}($c||($c={})),function(e){e[e.DraftBot=1]="DraftBot"}(Fc||(Fc={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(Vc||(Vc={})),function(e){e[e.Archive=1]="Archive";e[e.Rollback=2]="Rollback"}(Wc||(Wc={})),function(e){e[e.ProjectCopyCancel=1]="ProjectCopyCancel";e[e.ProjectCopyRetry=2]="ProjectCopyRetry"}(Hc||(Hc={})),function(e){e[e.ProjectCopy=1]="ProjectCopy";e[e.BotCopy=2]="BotCopy";e[e.VibeProjectCopy=3]="VibeProjectCopy"}(Jc||(Jc={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Kc||(Kc={})),function(e){e[e.Bot=1]="Bot";e[e.Workflow=2]="Workflow";e[e.Application=3]="Application"}(Qc||(Qc={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(Yc||(Yc={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(Zc||(Zc={})),function(e){e[e.BatchSize=1]="BatchSize";e[e.LearningRate=2]="LearningRate";e[e.Epochs=3]="Epochs"}(Xc||(Xc={})),function(e){e[e.GPT=1]="GPT";e[e.SEED=2]="SEED";e[e.Claude=3]="Claude";e[e.MiniMax=4]="MiniMax";e[e.Plugin=5]="Plugin";e[e.StableDiffusion=6]="StableDiffusion";e[e.ByteArtist=7]="ByteArtist";e[e.Maas=9]="Maas";e[e.QianFan=10]="QianFan";e[e.Gemini=11]="Gemini";e[e.Moonshot=12]="Moonshot";e[e.GLM=13]="GLM";e[e.MaaSAutoSync=14]="MaaSAutoSync";e[e.QWen=15]="QWen";e[e.Cohere=16]="Cohere";e[e.Baichuan=17]="Baichuan";e[e.Ernie=18]="Ernie";e[e.DeekSeek=19]="DeekSeek";e[e.Llama=20]="Llama";e[e.StepFun=23]="StepFun";e[e.Custom=24]="Custom";e[e.Other=999]="Other"}(ed||(ed={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(td||(td={})),function(e){e[e.Douyin=1]="Douyin"}(id||(id={})),function(e){e[e.Terminating=1]="Terminating";e[e.Terminated=2]="Terminated"}(od||(od={})),function(e){e[e.Online=1]="Online";e[e.Offline=2]="Offline";e[e.Deleted=3]="Deleted";e[e.FineTuneInQueue=4]="FineTuneInQueue";e[e.FineTuneRunning=5]="FineTuneRunning";e[e.FineTuneFailed=6]="FineTuneFailed";e[e.FineTuneTeminated=7]="FineTuneTeminated"}(sd||(sd={})),function(e){e[e.ModelType=1]="ModelType";e[e.ModelUserRight=2]="ModelUserRight";e[e.ModelFeature=3]="ModelFeature";e[e.ModelFunction=4]="ModelFunction";e[e.ModelScenario=5]="ModelScenario";e[e.ModelPayment=15]="ModelPayment";e[e.ModelAbility=16]="ModelAbility";e[e.ModelStatus=17]="ModelStatus";e[e.Custom=20]="Custom";e[e.Others=100]="Others"}(nd||(nd={})),function(e){e[e.Flagship=1]="Flagship";e[e.HighSpeed=2]="HighSpeed";e[e.ToolInvocation=3]="ToolInvocation";e[e.RolePlaying=4]="RolePlaying";e[e.LongText=5]="LongText";e[e.ImageUnderstanding=6]="ImageUnderstanding";e[e.Reasoning=7]="Reasoning";e[e.VideoUnderstanding=8]="VideoUnderstanding";e[e.CostPerformance=9]="CostPerformance";e[e.CodeSpecialization=10]="CodeSpecialization";e[e.AudioUnderstanding=11]="AudioUnderstanding"}(rd||(rd={})),function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInput=2]="TotalInput";e[e.TotalOutput=3]="TotalOutput"}(ad||(ad={})),function(e){e[e.stop=1]="stop";e[e.resume=2]="resume",e[e.delete=3]="delete"}(cd||(cd={})),function(e){e[e.Recommend=1]="Recommend"}(dd||(dd={})),function(e){e[e.Default=0]="Default";e[e.Terminate=1]="Terminate"}(ld||(ld={})),function(e){e[e.All=0]="All";e[e.WithBenefit=1]="WithBenefit"}(pd||(pd={})),function(e){e[e.upload=1]="upload";e[e.TrainingSetSplit=2]="TrainingSetSplit"}(ud||(ud={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(_d||(_d={})),function(e){e[e.Using=1]="Using";e[e.Deleted=2]="Deleted"}(hd||(hd={})),function(e){e[e.Publish=0]="Publish";e[e.Archive=1]="Archive"}(md||(md={})),function(e){e[e.User=0]="User";e[e.NL2App=1]="NL2App"}(gd||(gd={})),function(e){e[e.NoBindRequired=1]="NoBindRequired";e[e.AuthBind=2]="AuthBind";e[e.KvBind=3]="KvBind";e[e.KvAuthBind=4]="KvAuthBind";e[e.ApiBind=5]="ApiBind";e[e.WebSDKBind=6]="WebSDKBind";e[e.StoreBind=7]="StoreBind";e[e.AuthAndConfig=8]="AuthAndConfig";e[e.ConnectorCustom=9]="ConnectorCustom"}(fd||(fd={})),function(e){e[e.APIOrSDK=1]="APIOrSDK";e[e.SocialPlatform=2]="SocialPlatform";e[e.Coze=3]="Coze";e[e.MiniProgram=4]="MiniProgram";e[e.CozeSpaceExtensionLibrary=5]="CozeSpaceExtensionLibrary"}(yd||(yd={})),function(e){e[e.Configured=1]="Configured";e[e.NotConfigured=2]="NotConfigured";e[e.Disconnected=3]="Disconnected";e[e.Configuring=4]="Configuring";e[e.NeedReconfiguring=5]="NeedReconfiguring"}(vd||(vd={})),function(e){e[e.Default=0]="Default";e[e.Auditing=1]="Auditing";e[e.Success=2]="Success";e[e.Failed=3]="Failed";e[e.Disable=4]="Disable"}(wd||(wd={})),function(e){e[e.Normal=0]="Normal";e[e.InReview=1]="InReview";e[e.Offline=2]="Offline"}(bd||(bd={})),function(e){e[e.Packing=0]="Packing";e[e.PackFailed=1]="PackFailed";e[e.Auditing=2]="Auditing";e[e.AuditNotPass=3]="AuditNotPass";e[e.ConnectorPublishing=4]="ConnectorPublishing";e[e.PublishDone=5]="PublishDone"}(Sd||(Sd={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Authorizing=3]="Authorizing"}(Pd||(Pd={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.Imageflow=3]="Imageflow";e[e.Knowledge=4]="Knowledge";e[e.UI=5]="UI";e[e.Prompt=6]="Prompt";e[e.Database=7]="Database";e[e.Variable=8]="Variable";e[e.Voice=9]="Voice";e[e.Memorybase=10]="Memorybase";e[e.MCP=11]="MCP"}(Cd||(Cd={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Td||(Td={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.Name=2]="Name"}(Ed||(Ed={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime"}(kd||(kd={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.PublishTime=2]="PublishTime";e[e.OpenTime=3]="OpenTime"}(Id||(Id={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(Ad||(Ad={})),function(e){e[e.All=0]="All";e[e.CreateByMe=1]="CreateByMe";e[e.AllWithCollaborator=2]="AllWithCollaborator";e[e.CanImportToSpace=3]="CanImportToSpace"}(jd||(jd={})),function(e){e[e.Desc=0]="Desc";e[e.Asc=1]="Asc"}(Rd||(Rd={})),function(e){e[e.Copy=1]="Copy";e[e.Move=2]="Move";e[e.Publish=3]="Publish";e[e.ImportExport=4]="ImportExport"}(zd||(zd={})),function(e){e[e.Project=1]="Project";e[e.Space=2]="Space";e[e.Online=3]="Online";e[e.Template=4]="Template";e[e.Agent=5]="Agent"}(Ud||(Ud={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.Imageflow=3]="Imageflow";e[e.Knowledge=4]="Knowledge";e[e.UI=5]="UI";e[e.Project=6]="Project";e[e.Database=7]="Database";e[e.Variable=8]="Variable";e[e.Trigger=9]="Trigger";e[e.Agent=10]="Agent";e[e.Prompt=11]="Prompt";e[e.Shortcut=12]="Shortcut";e[e.Chux=13]="Chux";e[e.Memorybase=14]="Memorybase";e[e.VibeProjectAgent=15]="VibeProjectAgent";e[e.VibeProjectAutomation=16]="VibeProjectAutomation";e[e.VibeProjectWebApp=17]="VibeProjectWebApp";e[e.VibeProjectApp=18]="VibeProjectApp";e[e.VibeProjectSkill=19]="VibeProjectSkill";e[e.VibeProjectGeneralWeb=20]="VibeProjectGeneralWeb";e[e.VibeProjectWechatMiniProgram=21]="VibeProjectWechatMiniProgram";e[e.VibeProjectAssistantAgent=22]="VibeProjectAssistantAgent";e[e.VibeProjectGeneral=23]="VibeProjectGeneral"}(Ld||(Ld={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(Od||(Od={})),function(e){e[e.CopyResourceInProject=1]="CopyResourceInProject";e[e.CopyProjectResourceToLibrary=2]="CopyProjectResourceToLibrary";e[e.MoveProjectResourceToLibrary=3]="MoveProjectResourceToLibrary";e[e.CopyLibraryResourceToProject=4]="CopyLibraryResourceToProject";e[e.CopyProject=5]="CopyProject";e[e.PublishProject=6]="PublishProject";e[e.CopyTemplateToProject=7]="CopyTemplateToProject";e[e.PublishProjectTemplate=8]="PublishProjectTemplate";e[e.LaunchProjectTemplate=9]="LaunchProjectTemplate";e[e.ArchiveProject=10]="ArchiveProject";e[e.RollbackProject=11]="RollbackProject";e[e.CrossSpaceCopy=12]="CrossSpaceCopy";e[e.CrossSpaceCopyProject=13]="CrossSpaceCopyProject";e[e.Export=14]="Export";e[e.Import=15]="Import";e[e.PublishChuxProject=16]="PublishChuxProject";e[e.CopyResource=17]="CopyResource";e[e.CopyVibeProject=18]="CopyVibeProject"}(xd||(xd={})),function(e){e[e.Packing=0]="Packing";e[e.PackSuccess=1]="PackSuccess";e[e.PackFail=2]="PackFail"}(Bd||(Bd={}));class Dd{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Dd.prototype.__init.call(this),Dd.prototype.__init2.call(this),this.request=qd([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=qd([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}Ping(e,t){const i=this.genBaseURL("/api/intelligence_api/ping");return this.request({url:i,method:"POST"},t)}DraftProjectCreate(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/draft_project/create"),s={space_id:i.space_id,name:i.name,description:i.description,icon_uri:i.icon_uri,monetization_conf:i.monetization_conf,create_from:i.create_from,folder_id:i.folder_id,type:i.type};return this.request({url:o,method:"POST",data:s},t)}GetDraftIntelligenceList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_list"),s={space_id:i.space_id,name:i.name,has_published:i.has_published,status:i.status,types:i.types,search_scope:i.search_scope,folder_id:i.folder_id,folder_include_children:i.folder_include_children,order_type:i.order_type,project_type:i.project_type,is_fav_filter:i.is_fav_filter,is_collaborator_filter:i.is_collaborator_filter,organization_id:i.organization_id,is_fav:i.is_fav,recently_open:i.recently_open,option:i.option,order_by:i.order_by,cursor_id:i.cursor_id,size:i.size};return this.request({url:o,method:"POST",data:s},t)}DraftProjectUpdate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/update"),s={project_id:i.project_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}GetDraftIntelligenceInfo(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_info"),s={intelligence_id:i.intelligence_id,intelligence_type:i.intelligence_type,version:i.version};return this.request({url:o,method:"POST",data:s},t)}GetUserRecentlyEditIntelligence(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/search/get_recently_edit_intelligence"),s={size:i.size,types:i.types,enterprise_id:i.enterprise_id,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}DraftProjectCopy(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/draft_project/copy"),s={project_id:i.project_id,to_space_id:i.to_space_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}ProcessEntityTask(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/entity_task/process"),s={entity_id:i.entity_id,action:i.action,task_id_list:i.task_id_list};return this.request({url:o,method:"POST",data:s},t)}DraftProjectDelete(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/delete"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}EntityTaskSearch(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/entity_task/search"),s={task_list:i.task_list};return this.request({url:o,method:"POST",data:s},t)}ListIntelligenceCollaboration(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/collaboration/list"),s={intelligence_id:i.intelligence_id,intelligence_type:i.intelligence_type};return this.request({url:o,method:"POST",data:s},t)}OceanProjectCreate(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/ocean_project/create"),s={space_id:i.space_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}OceanProjectUpdate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/ocean_project/update"),s={project_id:i.project_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}GetOceanProjectList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_list"),s={space_id:i.space_id,status:i.status,search_scope:i.search_scope,order_by:i.order_by,page_index:i.page_index,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}PublishProject(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_project"),s={project_id:i.project_id,version_number:i.version_number,description:i.description,connectors:i.connectors,connector_publish_config:i.connector_publish_config};return this.request({url:o,method:"POST",data:s},t)}GetPublishRecordDetail(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_record_detail"),s={project_id:i.project_id,publish_record_id:i.publish_record_id};return this.request({url:o,method:"POST",data:s},t)}GetPublishRecordList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_record_list"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}PublishConnectorList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/connector_list"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}CheckProjectVersionNumber(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/check_version_number"),s={project_id:i.project_id,version_number:i.version_number};return this.request({url:o,method:"POST",data:s},t)}DraftProjectInnerTaskList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/inner_task_list"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}GetOceanProjectInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_info"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}GetModelListFilterParams(e,t){const i=this.genBaseURL("/api/intelligence_api/model/get_model_list_filter_params");return this.request({url:i,method:"POST"},t)}StartEstimatedTrainingCost(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/start_estimated_training_cost"),s={base_model_id:i.base_model_id,space_id:i.space_id,training_dataset_id:i.training_dataset_id,epochs:i.epochs};return this.request({url:o,method:"POST",data:s},t)}GetModelList(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_list"),s={space_id:i.space_id,name:i.name,tag_filters:i.tag_filters,context_len_min:i.context_len_min,context_len_max:i.context_len_max,model_cost_min:i.model_cost_min,model_cost_max:i.model_cost_max,model_vendor:i.model_vendor,statusList:i.statusList,model_show_family_id:i.model_show_family_id,model_source:i.model_source,order_by:i.order_by,cursor_id:i.cursor_id,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}GetFinetuneTemplateDataset(e,t){const i=this.genBaseURL("/api/intelligence_api/model/get_finetune_template_dataset");return this.request({url:i,method:"POST"},t)}GetModelUsageData(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_usage_data"),s={space_id:i.space_id,model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}GetEstimatedTrainingCost(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_estimated_training_cost"),s={task_id:i.task_id,space_id:i.space_id,base_model_id:i.base_model_id,epochs:i.epochs};return this.request({url:o,method:"POST",data:s},t)}CreateFinetuneTask(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/create_finetune_task"),s={space_id:i.space_id,base_model_id:i.base_model_id,training_dataset_id:i.training_dataset_id,validating_dataset:i.validating_dataset,finetune_configuration:i.finetune_configuration,description:i.description,name:i.name};return this.request({url:o,method:"POST",data:s},t)}UploadFinetuneDataset(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/upload_finetune_dataset"),s={space_id:i.space_id,fileType:i.fileType,fileName:i.fileName,data:i.data,testing_data:i.testing_data};return this.request({url:o,method:"POST",data:s},t)}GetModelInfo(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_info"),s={space_id:i.space_id,model_id:i.model_id,is_finetuning:i.is_finetuning};return this.request({url:o,method:"POST",data:s},t)}GetFinetuneTrainingInfo(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_finetune_training_info"),s={space_id:i.space_id,model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}GetModelPerformanceData(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_performance_data"),s={space_id:i.space_id,model_id:i.model_id,get_pct:i.get_pct};return this.request({url:o,method:"POST",data:s},t)}OperateFinetuneTask(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/operate_finetune_task"),s={id:i.id,action:i.action};return this.request({url:o,method:"POST",data:s},t)}DeleteFinetuneModel(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/delete_finetune_model"),s={model_id:i.model_id,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetUserCompleteProfileRecord(e,t){const i=this.genBaseURL("/api/intelligence_api/user_profile/get_user_complete_profile_record");return this.request({url:i,method:"POST"},t)}DownloadUserProfile(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/user_profile/download_user_profile"),s={Cookie:i.Cookie};return this.request({url:o,method:"POST",headers:s},t)}GetProjectPublishedConnector(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/get_published_connector"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}PublishIntelligenceUnList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_intelligence_unlist"),s={intelligence_id:i.intelligence_id,connector_ids:i.connector_ids,intelligence_type:i.intelligence_type};return this.request({url:o,method:"POST",data:s},t)}PublishIntelligenceList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_publish_intelligence_list"),s={intelligence_type:i.intelligence_type,space_id:i.space_id,owner_id:i.owner_id,name:i.name,order_last_publish_time:i.order_last_publish_time,order_total_token:i.order_total_token,size:i.size,cursor_id:i.cursor_id,intelligence_ids:i.intelligence_ids};return this.request({url:o,method:"POST",data:s},t)}UpdateDiffModeInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/diff_mode/update_diff_mode_info"),s={target_type:i.target_type,target_id:i.target_id,diff_mode_info:i.diff_mode_info,exit_and_save:i.exit_and_save,exit_and_discard:i.exit_and_discard};return this.request({url:o,method:"POST",data:s},t)}GetDiffModeInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/diff_mode/get_diff_mode_info"),s={target_type:i.target_type,target_id:i.target_id};return this.request({url:o,method:"POST",data:s},t)}GetProjectPublishSummary(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_project_publish_summary"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}DraftProjectCrossSpaceCopy(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/draft_project/crossspace_copy"),s={project_id:i.project_id,to_space_id:i.to_space_id};return this.request({url:o,method:"POST",data:s},t)}EntityTaskList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/entity_task/list"),s={space_id:i.space_id,task_id_list:i.task_id_list};return this.request({url:o,method:"POST",data:s},t)}ExpansionTpm(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/expansion_tpm"),s={model_id:i.model_id,enterprise_id:i.enterprise_id,organization_id:i.organization_id,tpm_input_expansion:i.tpm_input_expansion,tpm_output_expansion:i.tpm_output_expansion,start_time:i.start_time,end_time:i.end_time};return this.request({url:o,method:"POST",data:s},t)}GetEstimatedTpmExpansionCost(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion_cost"),s={model_id:i.model_id,enterprise_id:i.enterprise_id,input_tpm:i.input_tpm,output_tpm:i.output_tpm};return this.request({url:o,method:"POST",data:s},t)}GetEstimatedTpmExpansion(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion"),s={model_id:i.model_id,enterprise_id:i.enterprise_id,estimated_rpm:i.estimated_rpm,StartTime:i.StartTime,EndTime:i.EndTime};return this.request({url:o,method:"POST",data:s},t)}FolderUpdate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/update"),s={folder_id:i.folder_id,name:i.name,description:i.description};return this.request({url:o,method:"POST",data:s},t)}GetFolderList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_folder_list"),s={space_id:i.space_id,type:i.type,name:i.name,search_scope:i.search_scope,parent_folder_id:i.parent_folder_id,parent_include_children:i.parent_include_children,order_by:i.order_by,order_type:i.order_type,size:i.size,page_num:i.page_num};return this.request({url:o,method:"POST",data:s},t)}FolderMove(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/move"),s={folder_id:i.folder_id,parent_folder_id:i.parent_folder_id};return this.request({url:o,method:"POST",data:s},t)}FolderDelete(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/delete"),s={folder_id:i.folder_id};return this.request({url:o,method:"POST",data:s},t)}FolderCreate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/create"),s={space_id:i.space_id,type:i.type,name:i.name,description:i.description,parent_folder_id:i.parent_folder_id};return this.request({url:o,method:"POST",data:s},t)}ArchiveProject(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/archive"),s={project_id:i.project_id,description:i.description,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetIntelligenceTaskInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/entity_task/task_info"),s={task_id:i.task_id};return this.request({url:o,method:"GET",params:s},t)}ProjectHistoryList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/history_list"),s={project_id:i.project_id,history_type:i.history_type,cursor:i.cursor,size:i.size};return this.request({url:o,method:"POST",data:s},t)}RollbackProject(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/rollback"),s={project_id:i.project_id,rollback_version:i.rollback_version,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetModelConcurrencyPerformanceData(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_concurrency_performance_data"),s={space_id:i.space_id,model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}UpdateModelConfigType(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/update_model_config_type"),s={space_id:i.space_id,model_id:i.model_id,config_type:i.config_type};return this.request({url:o,method:"POST",data:s},t)}GetSpaceModelUserConfig(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_space_model_user_config"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}OpenGetProjectList(e,t){const i=e||{},o=this.genBaseURL("/v1/apps"),s={workspace_id:i.workspace_id,publish_status:i.publish_status,connector_id:i.connector_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}OpenGetBotList(e,t){const i=e||{},o=this.genBaseURL("/v1/bots"),s={workspace_id:i.workspace_id,publish_status:i.publish_status,connector_id:i.connector_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}GetFolderTree(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/tree"),s={space_id:i.space_id,type:i.type};return this.request({url:o,method:"POST",data:s},t)}OpenGetSpaceFolder(e,t){const i=e||{},o=this.genBaseURL("/v1/folders"),s={workspace_id:i.workspace_id,folder_type:i.folder_type,parent_folder_id:i.parent_folder_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}MoveObjectToFolder(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/move_object"),s={dest_folder_id:i.dest_folder_id,folder_space_id:i.folder_space_id,move_objects:i.move_objects};return this.request({url:o,method:"POST",data:s},t)}GetFolderInfoByIds(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/folder/get_by_ids"),s={space_id:i.space_id,folder_ids:i.folder_ids,get_path_info:i.get_path_info};return this.request({url:o,method:"POST",data:s},t)}OpenGetFolderInfo(e,t){const i=e||{},o=this.genBaseURL(`/v1/folders/${i.folder_id}`);return this.request({url:o,method:"GET"},t)}ExportPreCheck(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/export_pre_check"),s={res_type:i.res_type,id:i.id,commit_id:i.commit_id};return this.request({url:o,method:"POST",data:s},t)}ImportPreCheck(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/import_pre_check"),s={package_uri:i.package_uri};return this.request({url:o,method:"POST",data:s},t)}GetUploadAuthToken(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/upload/auth_token"),s={scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}MarkProjectHistory(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/history_list/read"),s={project_id:i.project_id,version:i.version};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelDetail(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_detail"),s={model_id:i.model_id,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_list"),s={search_key:i.search_key,sort_field:i.sort_field,org_id:i.org_id,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetProjectHistoryNotice(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/history_list/notice"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}BindCustomModelSpace(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/bind_custom_model_space"),s={model_id:i.model_id,space_id_list:i.space_id_list,status:i.status,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelSpaceList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_space_list"),s={model_id:i.model_id,search_key:i.search_key,org_id:i.org_id,cursor_id:i.cursor_id,limit:i.limit,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelParameterTemplate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_parameter_template"),s={org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}OpenCopyTaskInfo(e,t){const i=e||{},o=this.genBaseURL(`/v1/entities/copy_tasks/${i.task_id}`);return this.request({url:o,method:"GET"},t)}OpenDuplicateDraftEntity(e,t){const i=e||{},o=this.genBaseURL("/v1/entities/copy_tasks"),s={entity_id:i.entity_id,entity_type:i.entity_type,to_workspace_id:i.to_workspace_id};return this.request({url:o,method:"POST",data:s},t)}ConvertCustomModelParameter(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/convert_custom_model_parameter"),s={parameters:i.parameters,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}CreateCustomModel(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/create_custom_model"),s={model_name:i.model_name,model_icon_uri:i.model_icon_uri,model_arch:i.model_arch,model_desc:i.model_desc,base_url:i.base_url,secret_name:i.secret_name,model_runtime_tag:i.model_runtime_tag,inputLength:i.inputLength,parameters:i.parameters,api_agreement:i.api_agreement,safety_guardrails:i.safety_guardrails,auth:i.auth,api_mode:i.api_mode,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}TerminateCustomModel(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/terminate_custom_model"),s={model_id:i.model_id,terminate_time:i.terminate_time,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCustomModel(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/update_custom_model"),s={model_name:i.model_name,model_icon_uri:i.model_icon_uri,model_arch:i.model_arch,model_desc:i.model_desc,base_url:i.base_url,secret_name:i.secret_name,model_runtime_tag:i.model_runtime_tag,inputLength:i.inputLength,parameters:i.parameters,model_id:i.model_id,api_agreement:i.api_agreement,safety_guardrails:i.safety_guardrails,auth:i.auth,api_mode:i.api_mode,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}GetModelUsageRecord(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_usage_record"),s={space_id:i.space_id,model_id:i.model_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp,order_by_type:i.order_by_type,order_by_field:i.order_by_field,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetEntityModelUsage(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_entity_model_usage"),s={space_id:i.space_id,model_id:i.model_id,entity_id:i.entity_id,entity_type:i.entity_type,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp};return this.request({url:o,method:"POST",data:s},t)}GetTypeList(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/get_type_list"),s={model:i.model,voice:i.voice,raw_model:i.raw_model,space_id:i.space_id,cur_model_id:i.cur_model_id,cur_model_ids:i.cur_model_ids,model_scene:i.model_scene,tag_filters:i.tag_filters,user_benefit_filter:i.user_benefit_filter};return this.request({url:o,method:"POST",data:s},t)}SaveModelReplacement(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/save_replacement"),s={space_id:i.space_id,old_model_id:i.old_model_id,new_model_id:i.new_model_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp};return this.request({url:o,method:"POST",data:s},t)}GetModelReplacement(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_replacement"),s={space_id:i.space_id,entity_type:i.entity_type,entity_id:i.entity_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCustomModelV2(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/update"),s={model_id:i.model_id,display_name:i.display_name,model_name:i.model_name,base_url:i.base_url,api_mode:i.api_mode,auth:i.auth,support_image_understanding:i.support_image_understanding,max_tokens:i.max_tokens};return this.request({url:o,method:"POST",data:s},t)}ListProviderModels(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/list_provider_models"),s={provider:i.provider,auth:i.auth,base_url:i.base_url,search_key:i.search_key};return this.request({url:o,method:"POST",data:s},t)}ListCustomModelV2(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/list"),s={account_type:i.account_type,coze_account_id:i.coze_account_id,enterprise_id:i.enterprise_id,search_key:i.search_key,provider:i.provider,source_type:i.source_type,sort_field:i.sort_field,sort_order:i.sort_order,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}ToggleCustomModelMemberVisibility(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/toggle_member_visibility"),s={model_id:i.model_id,member_visible:i.member_visible};return this.request({url:o,method:"POST",data:s},t)}DeleteCustomModelV2(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/delete"),s={model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}ListProviders(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/custom_model/list_providers"),s={only_enabled:i.only_enabled};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelDetailV2(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/detail"),s={model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}CreateCustomModelV2(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/create"),s={source_type:i.source_type,provider:i.provider,display_name:i.display_name,model_name:i.model_name,base_url:i.base_url,api_mode:i.api_mode,auth:i.auth,support_image_understanding:i.support_image_understanding,max_tokens:i.max_tokens,account_type:i.account_type,coze_account_id:i.coze_account_id,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}}const Md=new Dd({}),Nd={agent:Mc.VibeProjectAgent,workflow:Mc.VibeProjectAutomation,webapp:Mc.VibeProjectWebApp,app:Mc.VibeProjectApp,skill:Mc.VibeProjectSkill,web:Mc.VibeProjectGeneralWeb,miniprogram:Mc.VibeProjectWechatMiniProgram,assistant:Mc.VibeProjectAssistantAgent},Gd={[Mc.VibeProjectAgent]:"agent",[Mc.VibeProjectAutomation]:"workflow",[Mc.VibeProjectWebApp]:"webapp",[Mc.VibeProjectApp]:"app",[Mc.VibeProjectSkill]:"skill",[Mc.VibeProjectGeneralWeb]:"web",[Mc.VibeProjectWechatMiniProgram]:"miniprogram",[Mc.VibeProjectAssistantAgent]:"assistant"};function $d(e){if(!e)return;const t=String(e).trim();if(!t)return;const i=t.toLowerCase();return Nd[i]}const Fd=e=>Gd[e],Vd=[Mc.VibeProjectAgent,Mc.VibeProjectAutomation,Mc.VibeProjectWebApp,Mc.VibeProjectApp,Mc.VibeProjectSkill,Mc.VibeProjectGeneralWeb,Mc.VibeProjectWechatMiniProgram,Mc.VibeProjectAssistantAgent].map(Fd).filter(Boolean);function Wd(e,t){return null!=e?e:t()}function Hd(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 Jd={agent:t.VibeProjectType.Agent,workflow:t.VibeProjectType.Automation,webapp:t.VibeProjectType.WebApp,app:t.VibeProjectType.App,skill:t.VibeProjectType.Skill,web:t.VibeProjectType.GeneralWeb,miniprogram:t.VibeProjectType.WechatMiniProgram,assistant:t.VibeProjectType.AssistantAgent},Kd={[t.VibeProjectType.Agent]:"agent",[t.VibeProjectType.Automation]:"workflow",[t.VibeProjectType.WebApp]:"webapp",[t.VibeProjectType.App]:"app",[t.VibeProjectType.Skill]:"skill",[t.VibeProjectType.GeneralWeb]:"web",[t.VibeProjectType.WechatMiniProgram]:"miniprogram",[t.VibeProjectType.AssistantAgent]:"assistant"};const Qd=e=>Kd[e],Yd=[t.VibeProjectType.GeneralWeb,t.VibeProjectType.App],Zd=Yd.map(Qd);function Xd(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 el(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 tl{static getInstance(){return tl.INSTANCE||(tl.INSTANCE=new tl),tl.INSTANCE}sendMessageRunTask(e){const t=[_.resolve(__dirname,"./send-message.worker.js")],i=process.execPath;v.spawn(i,[...t,JSON.stringify(e)],{detached:!0,stdio:"ignore"}).unref()}async sendMessage(e){return await t.sendProjectChatMessage(e)}isValidType(e){return Yd.includes(e)}}const il=tl.getInstance();function ol(e,t){return null!=e?e:t()}function sl(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 nl(i){i.command("create").description("Create a new project").requiredOption("--message <message>","Description/requirements for creating the project").requiredOption("--type <type>","Project type: agent | workflow | app | skill | web | miniprogram | assistant").option("--org-id <orgId>","Organization ID (optional, will read from context automatically)").option("--space-id <spaceId>","Space ID (optional, will read from context automatically)").option("--wait","Wait for project creation to complete").config({help:{brief:"Create a new Coze Coding project",description:"Create a new Coze Coding project via natural language description. The system will automatically generate project structure and configuration based on the description, supporting multiple project types.",examples:[{desc:"Create an Agent project",cmd:'coze code project create --message "Create an intelligent customer service robot" --type agent',tags:["[RECOMMENDED]"]},{desc:"Create a Workflow project",cmd:'coze code project create --message "Create a data processing workflow" --type workflow'}],schema:{input:{message:{type:"string",required:!0,description:"Project description/requirements (natural language)"},type:{type:"string",required:!0,enum:Zd,description:"Project type"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{project_id:{type:"string",description:"Created project ID"},type:{type:"string",description:"Project type"}}},enums:{type:Zd.reduce(((e,t)=>(e[t]=`${t.toUpperCase()} project`,e)),{})},errors:[{code:e.ErrorCode.E1005,name:"INVALID_PROJECT_TYPE",desc:"Invalid project type",fix:"Please use a valid project type: agent | workflow | app | skill | web | miniprogram | assistant"},{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Missing Space ID",fix:"Please use the --space-id parameter or run `coze space use <spaceId>` first"},{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Project type is not supported for creation",fix:"Please choose a supported project type and try again"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized or project tool config is missing",fix:"Please retry and run with --debug if the issue persists"}]}}).action((async(i,o)=>{const s=o.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=ol(ol(i.spaceId,(()=>sl([s,"optionalAccess",e=>e.config,"access",e=>e.spaceId]))),(()=>"")),{message:r,type:a,wait:c}=i;sl([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e(`Resolving project type '${a}'...`)]);const d=function(e){if(!e)return;const t=String(e).trim();if(!t)return;const i=t.toLowerCase();return Jd[i]}(a);if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!d)throw new e.CozeError(e.ErrorCode.E1005,`Unknown project type: ${a}`,{type:a});if(!il.isValidType(d))throw new e.CozeError(e.ErrorCode.E1006,`Project type ${a} is not supported for creation`,{type:a,projectType:d});sl([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching agent tools configuration...")]);const l=sl([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===d)),"optionalAccess",e=>e.tools]);if(!l||0===l.length)throw new e.CozeError(e.ErrorCode.E5000,`No tools config for projectType: ${String(a)}`,{type:a,projectType:d});const p={};l.forEach((e=>{sl([e,"optionalAccess",e=>e.name])&&(p[e.name]=Boolean(e.enabled))})),sl([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching project default skills...")]);const u={skills:ol(sl([await la.GetProjectDefaultSkill({project_type:d,space_id:String(n)}),"access",e=>e.data,"optionalAccess",e=>e.skill_list]),(()=>[])).map((e=>({skill_id:e.skill_id,is_preload:e.is_preload}))),filter_types:[d]},_={space_id:String(n),user_query:r,project_type:d,agent_tools:p,project_settings:{model_setting:{model_name:""},skill_setting:u}};sl([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating project...")]);const h=ol((await t.IdeApi.ChatCreateVibeProject(_)).data,(()=>({}))).project_id,m=await sl([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!m)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(s.ui.success('Project created successfully, please use "coze code message status" to check the status.'),sl([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:h,type:a})]),c){const e=await il.sendMessage({projectId:ol(h,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:m,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${h}`});s.response.print(e.lastAnswerMessage)}else il.sendMessageRunTask({projectId:ol(h,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:m,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${h}`})}))}const rl=i=>{const o=i.command("project").alias("proj").config({help:{brief:"Manage Coze Coding projects",description:"Manage Coze Coding projects (Vibe Project). Supports creating, viewing, listing, and deleting projects, covering various project types like Agent, Workflow, Skill, Web apps, Mini-programs, etc.",examples:[{desc:"Create project",cmd:'coze code project create --message "Create a chatbot" --type web'},{desc:"List projects",cmd:"coze code project list"},{desc:"View project details",cmd:"coze code project get <projectId>"},{desc:"Delete project",cmd:"coze code project delete <projectId>"}],seeAlso:["coze code deploy","coze code skill"],schema:{input:{},output:{}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).description("Manage Coze Coding projects");nl(o),function(t){t.command("list").description("List all projects").config({help:{brief:"List all projects in the current space",description:"Get the list of projects in the current space. Supports filtering by type, name, publish status, and supports pagination.",examples:[{desc:"List projects",cmd:"coze code project list",tags:["[RECOMMENDED]"]},{desc:"Filter by type",cmd:"coze code project list --type agent --type workflow"},{desc:"Search by name",cmd:'coze code project list --name "customer service"'}],schema:{input:{size:{type:"number",required:!1,description:"Number of projects to return (default: 10)"},cursorId:{type:"string",required:!1,description:"Cursor for pagination"},type:{type:"array",required:!1,description:"Project type filter (can be passed multiple times)"},name:{type:"string",required:!1,description:"Filter by project name"},hasPublished:{type:"boolean",required:!1,description:"Filter by publish status"},searchScope:{type:"number",required:!1,description:"Created by (All = 0, CreateByMe = 1)"},folderId:{type:"string",required:!1,description:"Folder ID"},orderType:{type:"number",required:!1,description:"Sort type (0 for descending, 1 for ascending)"},isFavFilter:{type:"boolean",required:!1,description:"Filter by favorite status"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Project ID"},name:{type:"string",description:"Project name"},type:{type:"string",description:"Project type"},description:{type:"string",description:"Project description"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}],enums:{type:Vd.reduce(((e,t)=>(e[t]=`${t.toUpperCase()} project`,e)),{}),"search-scope":{0:"All",1:"CreateByMe"},"order-type":{0:"Descending",1:"Ascending"},"order-by":{0:"updated_at",1:"created_at"}}}}).option("--size <size>","Number of projects to return",parseInt).option("--cursor-id <cursorId>","Cursor for pagination").option("--type <type>","Project type filter (can be passed multiple times): agent | workflow | webapp | app | web | miniprogram | assistant",((e,t=[])=>[...t,e]),[]).option("--name <name>","Filter by project name").option("--has-published","Filter by publish status").option("--search-scope <searchScope>","Created by (All = 0, CreateByMe = 1, AllWithCollaborator = 2)").option("--folder-id <folderId>","Folder ID").option("--order-type <orderType>","Sort type (0 for descending, 1 for ascending)").option("--order-by <orderBy>","Order by (0 for updated_at, 1 for created_at)").option("--is-fav-filter","Filter by favorite status (true | false)").action((async function(e,t){const i=t.getContext(),o=Wd(Hd([e,"optionalAccess",e=>e.size]),(()=>10)),s=Wd(Hd([e,"optionalAccess",e=>e.cursorId]),(()=>{})),n=Hd([e,"optionalAccess",e=>e.type,"optionalAccess",e=>e.map,"call",e=>e($d),"access",e=>e.filter,"call",e=>e(Boolean)]),r=Hd([e,"optionalAccess",e=>e.name]),a=Hd([e,"optionalAccess",e=>e.hasPublished])?Boolean(Hd([e,"optionalAccess",e=>e.hasPublished])):void 0,c=Number(Wd(Hd([e,"optionalAccess",e=>e.searchScope]),(()=>jd.All))),d=Wd(Hd([e,"optionalAccess",e=>e.folderId]),(()=>"0")),l=Number(Wd(Hd([e,"optionalAccess",e=>e.orderType]),(()=>Rd.Desc))),p=Boolean(Hd([e,"optionalAccess",e=>e.isFavFilter])),u=Number(Wd(Hd([e,"optionalAccess",e=>e.orderBy]),(()=>Id.UpdateTime)));let _=[];Hd([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching project list...")]);const h=await Md.GetDraftIntelligenceList({space_id:Wd(Hd([i,"optionalAccess",e=>e.config,"access",e=>e.spaceId]),(()=>"")),size:o,cursor_id:s,types:n,name:r,has_published:a,search_scope:c,folder_id:d,order_type:l,order_by:u,is_fav_filter:p,status:[Dc.Using,Dc.Banned,Dc.MoveFailed]});_=Hd([h,"access",e=>e.data,"optionalAccess",e=>e.intelligences])||[],Hd([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetched ${_.length} projects.`)]),Hd([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(_.map((e=>({id:Hd([e,"access",e=>e.basic_info,"optionalAccess",e=>e.id]),name:Hd([e,"access",e=>e.basic_info,"optionalAccess",e=>e.name]),type:Fd(e.type),description:Hd([e,"access",e=>e.basic_info,"optionalAccess",e=>e.description])}))))])}))}(o),function(i){i.command("get <projectId>").description("View project details").config({help:{brief:"Get project details",description:"Get the detailed configuration of the specified project, including project type, settings, skill configurations, etc.",examples:[{desc:"View project details",cmd:"coze code project get <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},project_name:{type:"string",description:"Project name"},project_type:{type:"string",description:"Project type"},skills:{type:"object",description:"Project skill configurations",properties:{skills:{type:"array",items:{type:"object",properties:{skill_id:{type:"string",description:"Skill ID"},is_preload:{type:"boolean",description:"Is preloaded"}}}}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project does not exist",fix:"Please confirm if the project ID is correct, use `project list` to view available projects"}]}}).action((async function(i,o,s){const n=s.getContext();Xd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetching project details for '${i}'...`)]);const r=Xd([await t.IdeApi.GetVibeProject({project_id:i}),"access",e=>e.data,"optionalAccess",e=>e.project_info]);if(!r)throw new e.CozeError(e.ErrorCode.E3001,`Project ${i} not found`,{projectId:i});Xd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Project details for '${i}':`)]),Xd([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...y.omit(r,["project_settings"]),skills:y.pick(Xd([r,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]),["skills"]),project_type:Qd(Xd([r,"optionalAccess",e=>e.project_type]))})])}))}(o),function(i){i.command("delete <projectId>").description("Delete a project").config({help:{brief:"Delete project",description:"Delete the specified Coze Coding project. This operation cannot be undone, please use with caution.",examples:[{desc:"Delete project",cmd:"coze code project delete <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID to delete"}},output:{project_id:{type:"string",description:"Deleted project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E3005,name:"DELETE_FAILED",desc:"Failed to delete project",fix:"Please confirm if the project ID is correct and check if you have sufficient permissions"}]}}).action((async function(e,i,o){const s=o.getContext();el([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",t=>t(`Deleting project '${e}'...`)]),await t.IdeApi.DeleteVibeProject({project_id:e}),el([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Project '${e}' deleted successfully.`)]),el([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({project_id:e,message:`Project '${e}' deleted successfully.`})])}))}(o)};var al,cl,dl,ll,pl,ul,_l,hl,ml,gl,fl,yl,vl,wl,bl,Sl,Pl,Cl,Tl,El,kl,Il,Al,jl,Rl,zl,Ul,Ll,Ol,xl,Bl,ql,Dl,Ml,Nl,Gl,$l,Fl,Vl,Wl,Hl,Jl,Kl,Ql,Yl,Zl,Xl,ep,tp,ip,op,sp,np,rp,ap,cp,dp,lp,pp,up,_p,hp,mp,gp,fp,yp,vp;function wp(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[e.Example=0]="Example";e[e.Template=1]="Template"}(al||(al={})),function(e){e[e.SpaceEvent=1]="SpaceEvent"}(cl||(cl={})),function(e){e[e.Interest=1]="Interest"}(dl||(dl={})),function(e){e[e.General=0]="General";e[e.PPT=1]="PPT";e[e.Podcast=2]="Podcast";e[e.WEB=3]="WEB";e[e.ImageDoc=4]="ImageDoc";e[e.Poster=5]="Poster";e[e.Excel=6]="Excel";e[e.DesignTemplate=7]="DesignTemplate";e[e.PPTTemplate=8]="PPTTemplate";e[e.Chart=9]="Chart";e[e.Video=10]="Video";e[e.ImagePPTTemplate=11]="ImagePPTTemplate";e[e.VideoTemplate=12]="VideoTemplate"}(ll||(ll={})),function(e){e[e.Chat=1]="Chat";e[e.Fill=2]="Fill"}(pl||(pl={})),function(e){e[e.Delete=0]="Delete";e[e.Running=1]="Running";e[e.Pause=2]="Pause";e[e.TaskFinish=3]="TaskFinish";e[e.Init=4]="Init";e[e.Stop=5]="Stop";e[e.Interrupt=6]="Interrupt";e[e.IllegalContent=7]="IllegalContent";e[e.AbnormalInterrupt=8]="AbnormalInterrupt";e[e.Sleep=9]="Sleep"}(ul||(ul={})),function(e){e[e.Favorite=1]="Favorite";e[e.Template=2]="Template";e[e.TemplateCover=3]="TemplateCover";e[e.PlanTemplate=4]="PlanTemplate";e[e.Article=5]="Article"}(_l||(_l={})),function(e){e[e.General=0]="General";e[e.Product=1]="Product"}(hl||(hl={})),function(e){e[e.Unknown=0]="Unknown";e[e.Pending=1]="Pending";e[e.Running=2]="Running";e[e.Completed=3]="Completed";e[e.Failed=4]="Failed";e[e.Cancelled=5]="Cancelled"}(ml||(ml={})),function(e){e[e.HandsOff=0]="HandsOff";e[e.Cooperative=1]="Cooperative";e[e.Auto=2]="Auto"}(gl||(gl={})),function(e){e[e.Modify=1]="Modify";e[e.Clear=2]="Clear";e[e.RemoveBackground=3]="RemoveBackground";e[e.Inpainting=4]="Inpainting";e[e.TextReplacement=5]="TextReplacement"}(fl||(fl={})),function(e){e[e.Unactivated=1]="Unactivated";e[e.Activated=2]="Activated"}(yl||(yl={})),function(e){e[e.hot_city=1]="hot_city";e[e.city=2]="city"}(vl||(vl={})),function(e){e[e.PDF=1]="PDF";e[e.PPT=2]="PPT";e[e.ImageEditablePpt=3]="ImageEditablePpt"}(wl||(wl={})),function(e){e[e.Chinese=0]="Chinese";e[e.English=1]="English"}(bl||(bl={})),function(e){e[e.Review=1]="Review";e[e.Draft=2]="Draft";e[e.LawQA=3]="LawQA"}(Sl||(Sl={})),function(e){e[e.Pin=1]="Pin";e[e.UnPin=2]="UnPin";e[e.Use=3]="Use"}(Pl||(Pl={})),function(e){e[e.Init=1]="Init";e[e.Stock=2]="Stock";e[e.Sector=3]="Sector"}(Cl||(Cl={})),function(e){e[e.GeneralChat=1]="GeneralChat";e[e.Scheduled=2]="Scheduled"}(Tl||(Tl={})),function(e){e[e.FieldAnalysis=1]="FieldAnalysis";e[e.Upload=2]="Upload"}(El||(El={})),function(e){e[e.Running=1]="Running";e[e.Pause=2]="Pause";e[e.TaskFinish=3]="TaskFinish";e[e.Init=4]="Init";e[e.Stop=5]="Stop";e[e.Interrupt=6]="Interrupt";e[e.IllegalContent=7]="IllegalContent";e[e.AbnormalInterrupt=8]="AbnormalInterrupt";e[e.Sleep=9]="Sleep"}(kl||(kl={})),function(e){e[e.UNKNOWN=0]="UNKNOWN";e[e.HTML=1]="HTML";e[e.WORD=2]="WORD";e[e.PPT=3]="PPT";e[e.EXCEL=4]="EXCEL";e[e.PDF=5]="PDF";e[e.NOTE=6]="NOTE";e[e.IMAGE=7]="IMAGE";e[e.PODCAST=8]="PODCAST"}(Il||(Il={})),function(e){e[e.FavoritePage=1]="FavoritePage";e[e.TASK=2]="TASK"}(Al||(Al={})),function(e){e[e.UserUpload=1]="UserUpload";e[e.Explore=2]="Explore";e[e.TASK=3]="TASK"}(jl||(jl={})),function(e){e[e.PPT=1]="PPT"}(Rl||(Rl={})),function(e){e[e.Favorite=1]="Favorite";e[e.MultiDocImage=2]="MultiDocImage"}(zl||(zl={})),function(e){e[e.Upload=1]="Upload";e[e.Search=2]="Search";e[e.Generate=3]="Generate"}(Ul||(Ul={})),function(e){e[e.PNG=1]="PNG";e[e.JPG=2]="JPG";e[e.MP4=3]="MP4"}(Ll||(Ll={})),function(e){e[e.Modify=1]="Modify";e[e.Clear=2]="Clear";e[e.RemoveBackground=3]="RemoveBackground";e[e.Generate=4]="Generate";e[e.Search=5]="Search";e[e.Blur=6]="Blur"}(Ol||(Ol={})),function(e){e[e.Image=1]="Image";e[e.Html=2]="Html";e[e.Livephoto=3]="Livephoto"}(xl||(xl={})),function(e){e[e.Chat=1]="Chat";e[e.ApiTemplate=2]="ApiTemplate"}(Bl||(Bl={})),function(e){e[e.Suggest=1]="Suggest"}(ql||(ql={})),function(e){e[e.Unknown=0]="Unknown";e[e.Clarifying=1]="Clarifying";e[e.PendingActivation=2]="PendingActivation";e[e.Running=3]="Running";e[e.PendingConfirm=4]="PendingConfirm";e[e.Terminated=5]="Terminated"}(Dl||(Dl={})),function(e){e[e.Unknown=0]="Unknown";e[e.SystemError=1]="SystemError";e[e.InsufficientBalance=2]="InsufficientBalance";e[e.UserManual=3]="UserManual";e[e.Timeout=4]="Timeout"}(Ml||(Ml={})),function(e){e[e.DiggTypeDigg=1]="DiggTypeDigg";e[e.DiggTypeBury=2]="DiggTypeBury"}(Nl||(Nl={})),function(e){e[e.Query=1]="Query";e[e.Answer=2]="Answer";e[e.Resume=3]="Resume"}(Gl||(Gl={})),function(e){e[e.Unknown=0]="Unknown";e[e.ActivatePlan=1]="ActivatePlan";e[e.ResumePlan=2]="ResumePlan"}($l||($l={})),function(e){e[e.DocMultiImage=1]="DocMultiImage"}(Fl||(Fl={})),function(e){e[e.PDF=1]="PDF";e[e.DOCX=2]="DOCX"}(Vl||(Vl={})),function(e){e[e.DeleteCookie=1]="DeleteCookie"}(Wl||(Wl={})),function(e){e[e.POSITION=0]="POSITION";e[e.ELEMENT=1]="ELEMENT"}(Hl||(Hl={})),function(e){e[e.DiamondMatrix=1]="DiamondMatrix";e[e.BulletPoints=2]="BulletPoints";e[e.StaggeredProcessDiagram=3]="StaggeredProcessDiagram";e[e.ArrowRingDiagram=4]="ArrowRingDiagram";e[e.VerticalTimeline=5]="VerticalTimeline"}(Jl||(Jl={})),function(e){e[e.Init=1]="Init";e[e.Enabled=2]="Enabled";e[e.Disabled=3]="Disabled"}(Kl||(Kl={})),function(e){e[e.Pending=1]="Pending";e[e.Success=2]="Success";e[e.Avoid=3]="Avoid";e[e.Failed=4]="Failed"}(Ql||(Ql={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Expired=3]="Expired"}(Yl||(Yl={})),function(e){e[e.Query=1]="Query";e[e.Template=2]="Template"}(Zl||(Zl={})),function(e){e[e.Pause=1]="Pause";e[e.Resume=2]="Resume";e[e.Pin=3]="Pin";e[e.Unpin=4]="Unpin";e[e.DoNotDisturb=5]="DoNotDisturb";e[e.CancelDoNotDisturb=6]="CancelDoNotDisturb";e[e.Stop=7]="Stop";e[e.Read=8]="Read"}(Xl||(Xl={})),function(e){e[e.Init=0]="Init";e[e.Enable=1]="Enable";e[e.Disable=2]="Disable"}(ep||(ep={})),function(e){e[e.Open=1]="Open";e[e.Close=2]="Close"}(tp||(tp={})),function(e){e[e.Open=1]="Open";e[e.Close=2]="Close"}(ip||(ip={})),function(e){e[e.Online=1]="Online";e[e.Debug=2]="Debug"}(op||(op={})),function(e){e[e.UserCreate=0]="UserCreate";e[e.Example=1]="Example"}(sp||(sp={})),function(e){e[e.Init=0]="Init";e[e.List=1]="List";e[e.Unlist=2]="Unlist"}(np||(np={})),function(e){e[e.Good=1]="Good";e[e.Bad=2]="Bad"}(rp||(rp={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(ap||(ap={})),function(e){e[e.Pending=1]="Pending";e[e.Running=2]="Running";e[e.Success=3]="Success";e[e.Failed=4]="Failed";e[e.Cancel=5]="Cancel"}(cp||(cp={})),function(e){e[e.Video=1]="Video";e[e.Voice=2]="Voice";e[e.Music=3]="Music"}(dp||(dp={})),function(e){e[e.Update=1]="Update";e[e.UpdateAndAdd=2]="UpdateAndAdd";e[e.UpdateAndSync=3]="UpdateAndSync"}(lp||(lp={})),function(e){e[e.ChatQuery=1]="ChatQuery";e[e.VideoEdit=2]="VideoEdit"}(pp||(pp={})),function(e){e[e.Pin=1]="Pin";e[e.Unpin=2]="Unpin"}(up||(up={})),function(e){e[e.Valid=1]="Valid";e[e.Deleted=2]="Deleted"}(_p||(_p={})),function(e){e[e.Narration=1]="Narration";e[e.Music=2]="Music";e[e.Other=3]="Other"}(hp||(hp={})),function(e){e[e.Video=1]="Video";e[e.Image=2]="Image";e[e.Audio=3]="Audio";e[e.Combination=4]="Combination";e[e.Document=5]="Document"}(mp||(mp={})),function(e){e[e.Local=1]="Local";e[e.AiGenerated=2]="AiGenerated";e[e.Asset=3]="Asset";e[e.Search=4]="Search"}(gp||(gp={})),function(e){e[e.Role=1]="Role";e[e.Item=2]="Item";e[e.Scene=3]="Scene";e[e.Other=4]="Other"}(fp||(fp={})),function(e){e[e.VoiceSelection=1]="VoiceSelection";e[e.VoiceDescription=2]="VoiceDescription";e[e.None=3]="None"}(yp||(yp={})),function(e){e[e.NotUploaded=1]="NotUploaded";e[e.Active=2]="Active";e[e.Processing=3]="Processing";e[e.Failed=4]="Failed"}(vp||(vp={}));class bp{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){bp.prototype.__init.call(this),bp.prototype.__init2.call(this),this.request=wp([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=wp([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}CreateTaskReplay(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/create_task_replay"),s={task_id:i.task_id,need_qr_code:i.need_qr_code,file_list:i.file_list,doc_multi_img_zip_uri:i.doc_multi_img_zip_uri};return this.request({url:o,method:"POST",data:s},t)}GetTaskReplay(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_replay"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}DeleteCozeSpaceTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/delete_task"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCozeSpaceTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/update_task"),s={task_id:i.task_id,task_name:i.task_name,mcp_tool_list:i.mcp_tool_list,expert_agent_config:i.expert_agent_config,scheduled_task_setting:i.scheduled_task_setting};return this.request({url:o,method:"POST",data:s},t)}CreateCozeSpaceTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/create_task"),s={task_name:i.task_name,task_type:i.task_type,file_uri_list:i.file_uri_list,mcp_tool_list:i.mcp_tool_list,agent_ids:i.agent_ids,scheduled_task_setting:i.scheduled_task_setting,source_from:i.source_from,is_debug:i.is_debug,expert_agent_config:i.expert_agent_config};return this.request({url:o,method:"POST",data:s},t)}CozeSpaceChat(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/chat"),s={task_id:i.task_id,query:i.query,files:i.files,mcp_list:i.mcp_list,chat_type:i.chat_type,pause_reason:i.pause_reason,task_run_mode:i.task_run_mode,expert_agent_run_config:i.expert_agent_run_config,scheduled_task_config:i.scheduled_task_config,disable_team_mode:i.disable_team_mode,resume_data:i.resume_data,ability_type:i.ability_type,all_authorized_mcp:i.all_authorized_mcp,reference_template_list:i.reference_template_list,agent_ids:i.agent_ids,router_control:i.router_control,favorites:i.favorites,extra_info:i.extra_info,reference_content:i.reference_content,guiding_id:i.guiding_id,skill_id_list:i.skill_id_list,is_skill_debug:i.is_skill_debug,thinking:i.thinking,reference_items:i.reference_items,plan_template_id:i.plan_template_id,action:i.action,assets:i.assets};return this.request({url:o,method:"POST",data:s},t)}PollStepList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/poll_step_list"),s={task_id:i.task_id,answer_id:i.answer_id,next_key:i.next_key};return this.request({url:o,method:"POST",data:s},t)}OperateTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_task"),s={task_id:i.task_id,operate_type:i.operate_type,pause_reason:i.pause_reason,browser:i.browser,read_progress:i.read_progress,has_unread:i.has_unread};return this.request({url:o,method:"POST",data:s},t)}GetCozeSpaceTaskList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_list"),s={cursor:i.cursor,size:i.size,long_term:i.long_term};return this.request({url:o,method:"POST",data:s},t)}GetMessageList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_message_list"),s={task_id:i.task_id,cursor:i.cursor,size:i.size,asc_mode:i.asc_mode};return this.request({url:o,method:"POST",data:s},t)}UpdateTaskPlan(e,t){const i=e,o=this.genBaseURL("/api/coze_space/update_task_plan"),s={task_id:i.task_id,action_id:i.action_id,task_plan:i.task_plan};return this.request({url:o,method:"POST",data:s},t)}GetTaskReplayById(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_replay_by_id"),s={task_share_id:i.task_share_id,secret:i.secret};return this.request({url:o,method:"POST",data:s},t)}OperateTaskReplay(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_task_replay"),s={task_id:i.task_id,task_share_id:i.task_share_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}UploadTaskFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/upload_task_file"),s={task_id:i.task_id,file_name:i.file_name,file_content:i.file_content};return this.request({url:o,method:"POST",data:s},t)}UploadUserResearchFile(e,t){const i=e,o=this.genBaseURL("/api/coze_space/upload_user_research_file"),s={task_id:i.task_id,action:i.action,file_type:i.file_type,file_name:i.file_name,file_content:i.file_content,desc:i.desc,fields:i.fields};return this.request({url:o,method:"POST",data:s},t)}LandingPageEmailSubscribe(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/landing_page/email_subscribe"),s={email:i.email};return this.request({url:o,method:"POST",data:s},t)}GetUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_url"),s={uri:i.uri,expire_seconds:i.expire_seconds,is_short_url:i.is_short_url,uri_list:i.uri_list};return this.request({url:o,method:"POST",data:s},t)}LandingPage(e,t){const i=this.genBaseURL("/api/coze_space/landing_page");return this.request({url:i,method:"POST"},t)}ExpertProductDetails(e,t){const i=e,o=this.genBaseURL("/api/coze_space/expert_product_details"),s={agent_id:i.agent_id};return this.request({url:o,method:"POST",data:s},t)}Digg(e,t){const i=e,o=this.genBaseURL("/api/coze_space/digg"),s={agent_id:i.agent_id,action_type:i.action_type,is_cancel:i.is_cancel};return this.request({url:o,method:"POST",data:s},t)}SearchStock(e,t){const i=e,o=this.genBaseURL("/api/coze_space/search_stock"),s={search_type:i.search_type,stock_search_word:i.stock_search_word,sector_search_word:i.sector_search_word};return this.request({url:o,method:"POST",data:s},t)}Text2Image(e,t){const i=e,o=this.genBaseURL("/api/coze_space/text2image"),s={prompt:i.prompt,width:i.width,height:i.height};return this.request({url:o,method:"GET",params:s},t)}GetInviteInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_invite_info");return this.request({url:i,method:"POST"},t)}CheckInviteCode(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/check_invite_code"),s={code:i.code};return this.request({url:o,method:"POST",data:s},t)}ExpertProductList(e,t){const i=this.genBaseURL("/api/coze_space/expert_product_list");return this.request({url:i,method:"POST"},t)}CheckInWaitList(e,t){const i=this.genBaseURL("/api/coze_space/check_in_wait_list");return this.request({url:i,method:"POST"},t)}JoinWaitList(e,t){const i=this.genBaseURL("/api/coze_space/join_wait_list");return this.request({url:i,method:"POST"},t)}GetSandboxToken(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_sandbox_token"),s={task_id:i.task_id,action_url_code:i.action_url_code};return this.request({url:o,method:"POST",data:s},t)}GetUserScheduledTasks(e,t){const i=this.genBaseURL("/api/coze_space/get_user_scheduled_tasks");return this.request({url:i,method:"POST"},t)}GenerateRelatedWords(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/generate_related_words"),s={original_word:i.original_word,describe:i.describe};return this.request({url:o,method:"POST",data:s},t)}CodeRepair(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/code_repair"),s={uri:i.uri,error_msg:i.error_msg};return this.request({url:o,method:"POST",data:s},t)}AuthorizedChannelMatch(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/authorized_channel_match"),s={web_rul:i.web_rul};return this.request({url:o,method:"POST",data:s},t)}UpdateTaskStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_task_status"),s={agent_id:i.agent_id,sk:i.sk,task_id:i.task_id,task_status:i.task_status,result:i.result};return this.request({url:o,method:"POST",data:s},t)}GetWebUrl(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_web_url"),s={original_url:i.original_url,exchange_for_short_url:i.exchange_for_short_url,exchange_for_qr_code:i.exchange_for_qr_code,exchange_for_long_url:i.exchange_for_long_url};return this.request({url:o,method:"POST",data:s},t)}OperateSandbox(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_sandbox"),s={task_id:i.task_id,action:i.action,delete_cookie_info:i.delete_cookie_info};return this.request({url:o,method:"POST",data:s},t)}UpdateTaskName(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_task_name"),s={agent_id:i.agent_id,sk:i.sk,task_id:i.task_id,task_name:i.task_name};return this.request({url:o,method:"POST",data:s},t)}GenDoc(e,t){const i=e,o=this.genBaseURL("/api/coze_space/gen_doc"),s={task_id:i.task_id,target_file_type:i.target_file_type,original_file_uri:i.original_file_uri,original_file_name:i.original_file_name,file_content:i.file_content};return this.request({url:o,method:"POST",data:s},t)}PreGetContractInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/pre_get_contract_info"),s={file_content:i.file_content,task_id:i.task_id,file_name:i.file_name};return this.request({url:o,method:"POST",data:s},t)}GetContractCaseInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_contract_case_info"),s={case_no:i.case_no};return this.request({url:o,method:"POST",data:s},t)}GetContractLawInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_contract_law_info"),s={law:i.law,num:i.num};return this.request({url:o,method:"POST",data:s},t)}GetCozeSpaceUserInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_user_info"),s={need_volcano_info:i.need_volcano_info,need_user_job_info:i.need_user_job_info,need_turn_off_user_data_management:i.need_turn_off_user_data_management,need_user_scenes:i.need_user_scenes,need_user_active_time:i.need_user_active_time,need_turn_off_ai_watermark:i.need_turn_off_ai_watermark,need_dnu_user:i.need_dnu_user,need_close_video_demo_project:i.need_close_video_demo_project,need_video_demo_project_account:i.need_video_demo_project_account};return this.request({url:o,method:"POST",data:s},t)}SearchCityInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/search_city_info"),s={search_type:i.search_type,keyword:i.keyword};return this.request({url:o,method:"POST",data:s},t)}UpdateScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/update_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id,task_type:i.task_type,status:i.status,scheduled_task_name:i.scheduled_task_name,trigger:i.trigger,mcp_tool_list:i.mcp_tool_list,expert_agent_config:i.expert_agent_config,task_plan:i.task_plan,is_need_try_run:i.is_need_try_run,description:i.description,task_id:i.task_id,daily_executed_at:i.daily_executed_at,task_plan_v2:i.task_plan_v2};return this.request({url:o,method:"POST",data:s},t)}GetScheduledTasks(e,t){const i=this.genBaseURL("/api/coze_space/get_scheduled_tasks");return this.request({url:i,method:"POST"},t)}TryRunScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/try_run_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id};return this.request({url:o,method:"POST",data:s},t)}DeleteScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/delete_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id};return this.request({url:o,method:"POST",data:s},t)}CreateScheduledTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/create_scheduled_task"),s={is_need_try_run:i.is_need_try_run,scheduled_task_name:i.scheduled_task_name,trigger:i.trigger,source_task_id:i.source_task_id,task_plan:i.task_plan,description:i.description,daily_executed_at:i.daily_executed_at,task_plan_v2:i.task_plan_v2};return this.request({url:o,method:"POST",data:s},t)}UpdateTeamInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_team_info"),s={switch:i.switch};return this.request({url:o,method:"POST",data:s},t)}GetTeamInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_team_info");return this.request({url:i,method:"POST"},t)}GetTaskInfo(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_task_info"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}FeelGood(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/feel_good"),s={task_id:i.task_id,answer_id:i.answer_id,feel:i.feel,content:i.content};return this.request({url:o,method:"POST",data:s},t)}GetUserScheduledTaskQuota(e,t){const i=this.genBaseURL("/api/coze_space/get_scheduled_task_quota");return this.request({url:i,method:"POST"},t)}GetSingleScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_single_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id};return this.request({url:o,method:"POST",data:s},t)}DeleteUserAuthorization(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/delete_user_authorization"),s={url:i.url,clear_arg:i.clear_arg};return this.request({url:o,method:"POST",data:s},t)}GetUserAuthorizationList(e,t){const i=this.genBaseURL("/api/coze_space/get_user_authorization_list");return this.request({url:i,method:"POST"},t)}AddUserAuthorization(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/add_user_authorization"),s={task_id:i.task_id,url:i.url,clear_arg:i.clear_arg,add_arg:i.add_arg};return this.request({url:o,method:"POST",data:s},t)}SearchFeelGood(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/search_feel_good"),s={task_id:i.task_id,answer_id:i.answer_id};return this.request({url:o,method:"POST",data:s},t)}GetAuthorizedChannelList(e,t){const i=this.genBaseURL("/api/coze_space/get_authorized_channel_list");return this.request({url:i,method:"GET"},t)}GetTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_task_example"),s={task_example_id:i.task_example_id};return this.request({url:o,method:"POST",data:s},t)}AdminListTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/list_task_example"),s={size:i.size,page:i.page,task_ids:i.task_ids,category_id:i.category_id,ability_type:i.ability_type,status:i.status};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_task_example"),s={example_id:i.example_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCozeSpaceUserInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_user_info"),s={job_id:i.job_id,turn_off_user_data_management:i.turn_off_user_data_management,scene_ids:i.scene_ids,turn_off_ai_watermark:i.turn_off_ai_watermark,close_video_demo_project:i.close_video_demo_project,video_demo_project_account:i.video_demo_project_account};return this.request({url:o,method:"POST",data:s},t)}GetTaskExampleList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_example_list"),s={category_id:i.category_id,page_size:i.page_size,page:i.page,ability_type:i.ability_type,scene_ids:i.scene_ids};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_task_example"),s={task_id:i.task_id,example_name:i.example_name,example_description:i.example_description,icon_uri:i.icon_uri,index:i.index,category_id:i.category_id,user_query:i.user_query,share_id:i.share_id,ability_type:i.ability_type,open_app_use:i.open_app_use,app_title:i.app_title,official_recommend:i.official_recommend,file_type:i.file_type,type:i.type,close_make_same:i.close_make_same,product_info:i.product_info,api_template_type:i.api_template_type,attachment_files:i.attachment_files};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_task_example"),s={example_id:i.example_id,example_name:i.example_name,example_description:i.example_description,icon_uri:i.icon_uri,index:i.index,category_id:i.category_id,user_query:i.user_query,status:i.status,ability_type:i.ability_type,open_app_use:i.open_app_use,app_title:i.app_title,official_recommend:i.official_recommend,type:i.type,close_make_same:i.close_make_same,product_info:i.product_info,file_type:i.file_type,api_template_type:i.api_template_type,attachment_files:i.attachment_files};return this.request({url:o,method:"POST",data:s},t)}GetTaskExampleCategory(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_example_category"),s={ability_type:i.ability_type};return this.request({url:o,method:"GET",params:s},t)}GetUserJobList(e,t){const i=this.genBaseURL("/api/coze_space/get_user_job_list");return this.request({url:i,method:"GET"},t)}AdminParseTaskShareURL(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/parse_task_share_url"),s={share_url:i.share_url};return this.request({url:o,method:"POST",data:s},t)}GetAppInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_app_info");return this.request({url:i,method:"GET"},t)}AdminGetTaskExampleCategory(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/get_task_example_category"),s={ability_type:i.ability_type};return this.request({url:o,method:"GET",params:s},t)}AdminUploadFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/upload_task_file"),s={file_name:i.file_name,file_content:i.file_content,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}UpdateFileContent(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_file_content"),s={task_id:i.task_id,file_uri:i.file_uri,file_content:i.file_content};return this.request({url:o,method:"POST",data:s},t)}ExportPPTAgentFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/export_ppt_agent_file"),s={source_uri:i.source_uri,task_id:i.task_id,export_type:i.export_type};return this.request({url:o,method:"POST",data:s},t)}RestoreExampleFile(e,t){const i=e,o=this.genBaseURL("/api/coze_space/restore_example_file"),s={task_id:i.task_id,example_id:i.example_id,product:i.product};return this.request({url:o,method:"POST",data:s},t)}GetHtmlHeightFix(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_html_height_fix"),s={code:i.code};return this.request({url:o,method:"POST",data:s},t)}PollMessages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/poll_messages"),s={start_next_key:i.start_next_key};return this.request({url:o,method:"GET",params:s},t)}OperatePausedTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_paused_task"),s={task_id:i.task_id,pause_reason:i.pause_reason};return this.request({url:o,method:"POST",data:s},t)}GetFrontierKey(e,t){const i=this.genBaseURL("/api/coze_space/get_frontier_key");return this.request({url:i,method:"GET"},t)}SearchImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/search_image"),s={query:i.query,count:i.count};return this.request({url:o,method:"POST",data:s},t)}GetUserExpertList(e,t){const i=this.genBaseURL("/api/coze_space/get_user_expert_list");return this.request({url:i,method:"POST"},t)}OperateUserExpert(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_user_expert"),s={agent_id:i.agent_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}GetHotQuery(e,t){const i=this.genBaseURL("/api/coze_space/get_hot_query");return this.request({url:i,method:"POST"},t)}ImageDownload(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/download_image"),s={image_infos:i.image_infos,download_type:i.download_type};return this.request({url:o,method:"POST",data:s},t)}ImageEdit(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/edit_image"),s={edit_type:i.edit_type,image_url:i.image_url,query:i.query,count:i.count,task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}CreateImageCopy(e,t){const i=e,o=this.genBaseURL("/api/coze_space/create_image_copy"),s={task_id:i.task_id,image_path:i.image_path,source_image_url:i.source_image_url};return this.request({url:o,method:"POST",data:s},t)}GetLatestImagesWithID(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_latest_images_with_id"),s={task_id:i.task_id,image_paths:i.image_paths};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTaskExampleCategory(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_task_example_category"),s={name:i.name,ability_type:i.ability_type,index:i.index,job_ids:i.job_ids,scene_ids:i.scene_ids};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteTaskExampleCategory(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_task_example_category"),s={category_id:i.category_id};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTaskExampleCategory(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_task_example_category"),s={category_id:i.category_id,name:i.name,index:i.index,job_ids:i.job_ids,scene_ids:i.scene_ids};return this.request({url:o,method:"POST",data:s},t)}BatchHtmlToImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_html_to_image"),s={task_id:i.task_id,html_uri:i.html_uri,device_info:i.device_info,screenshot_info:i.screenshot_info};return this.request({url:o,method:"POST",data:s},t)}GetAppTaskExampleList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_app_task_example_list"),s={ability_type:i.ability_type,need_official_recommended:i.need_official_recommended};return this.request({url:o,method:"POST",data:s},t)}GenCover(e,t){const i=e,o=this.genBaseURL("/api/coze_space/gen_cover"),s={task_id:i.task_id,original_file_uri:i.original_file_uri,resolution:i.resolution,mode:i.mode,selector_str:i.selector_str,task_share_url:i.task_share_url};return this.request({url:o,method:"POST",data:s},t)}CopyResource(e,t){const i=e,o=this.genBaseURL("/api/coze_space/copy_resource"),s={new_task_id:i.new_task_id,uri_list:i.uri_list};return this.request({url:o,method:"POST",data:s},t)}BatchUpdateImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_update_image"),s={task_id:i.task_id,image_info_list:i.image_info_list};return this.request({url:o,method:"POST",data:s},t)}Text2Json(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/text2json"),s={text:i.text,type:i.type};return this.request({url:o,method:"POST",data:s},t)}EditImageWithMsg(e,t){const i=e,o=this.genBaseURL("/api/coze_space/edit_image_with_msg"),s={task_id:i.task_id,source_image_info:i.source_image_info,edit_type:i.edit_type,query:i.query,edit_info:i.edit_info};return this.request({url:o,method:"POST",data:s},t)}GetASRToken(e,t){const i=this.genBaseURL("/api/coze_space/get_asr_token");return this.request({url:i,method:"GET"},t)}QueryRewriting(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/query_rewriting"),s={query:i.query};return this.request({url:o,method:"POST",data:s},t)}GetShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_shortcut_command"),s={ability_type:i.ability_type,need_general_data:i.need_general_data};return this.request({url:o,method:"POST",data:s},t)}ClickPopup(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/click_popup"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}GetPopupInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_popup_info"),s={ability_type:i.ability_type};return this.request({url:o,method:"POST",data:s},t)}AdminCreateExampleDatabaseData(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_example_database_data"),s={data:i.data};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_shortcut_command"),s={id:i.id,title:i.title,app_title:i.app_title,query:i.query,action_type:i.action_type,open_pc:i.open_pc,open_app:i.open_app,job_id:i.job_id,open_time:i.open_time,expire_time:i.expire_time};return this.request({url:o,method:"POST",data:s},t)}AdminCreateShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_shortcut_command"),s={ability_type:i.ability_type,title:i.title,app_title:i.app_title,query:i.query,action_type:i.action_type,open_pc:i.open_pc,open_app:i.open_app,job_id:i.job_id,expire_time:i.expire_time};return this.request({url:o,method:"POST",data:s},t)}AdminGetShortcutCommandList(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/get_shortcut_command_list"),s={size:i.size,ability_type:i.ability_type,page:i.page,open_pc:i.open_pc,open_app:i.open_app,job_id:i.job_id};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_shortcut_command"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}AdminSyncCrawl(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/sync_crawl"),s={req:i.req,upload:i.upload};return this.request({url:o,method:"POST",data:s},t)}AdminGetUserJobList(e,t){const i=this.genBaseURL("/api/coze_space/admin/get_user_job_list");return this.request({url:i,method:"GET"},t)}AdminListTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/list_template"),s={size:i.size,page:i.page,template_ids:i.template_ids,category_ids:i.category_ids,ability_type:i.ability_type,template_name:i.template_name};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_template"),s={ability_type:i.ability_type,category_id:i.category_id,web_template_conf:i.web_template_conf,template_labels:i.template_labels,original_query:i.original_query,query_template:i.query_template,template_words:i.template_words,open_app_use:i.open_app_use,app_template_conf:i.app_template_conf,template_files:i.template_files,reference_info:i.reference_info,api_template_type:i.api_template_type,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_template"),s={template_id:i.template_id,ability_type:i.ability_type,category_id:i.category_id,web_template_conf:i.web_template_conf,template_labels:i.template_labels,original_query:i.original_query,query_template:i.query_template,template_words:i.template_words,open_app_use:i.open_app_use,app_template_conf:i.app_template_conf,index:i.index,is_selected:i.is_selected,template_files:i.template_files,reference_info:i.reference_info,api_template_type:i.api_template_type,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_template"),s={template_id:i.template_id};return this.request({url:o,method:"POST",data:s},t)}GetTemplateList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_template_list"),s={category_id:i.category_id,page_size:i.page_size,page:i.page,ability_type:i.ability_type};return this.request({url:o,method:"POST",data:s},t)}GetAppTemplateList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_app_template_list"),s={ability_type:i.ability_type};return this.request({url:o,method:"POST",data:s},t)}GetTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_template_info"),s={template_id:i.template_id};return this.request({url:o,method:"POST",data:s},t)}GetActivityInfo(e,t){const i=this.genBaseURL("/api/coze_space/activity/info");return this.request({url:i,method:"GET"},t)}BindRelation(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/activity/bind"),s={code:i.code};return this.request({url:o,method:"POST",data:s},t)}GetInviteCode(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/activity/invite_code"),s={activity_id:i.activity_id};return this.request({url:o,method:"POST",data:s},t)}GetInviteRecords(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/activity/invite_records"),s={activity_id:i.activity_id};return this.request({url:o,method:"POST",data:s},t)}RollbackFileVersion(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/rollback_file_version"),s={task_id:i.task_id,file_name:i.file_name,target_version:i.target_version};return this.request({url:o,method:"POST",data:s},t)}GetFileVersionInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_file_version_info"),s={task_id:i.task_id,file_name:i.file_name,long_term_plan:i.long_term_plan};return this.request({url:o,method:"POST",data:s},t)}AdminMDelUri(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdel_uri"),s={uris:i.uris,urls:i.urls};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_sem_url"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}AdminCreateSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_sem_url"),s={experiment_url:i.experiment_url,compare_url:i.compare_url,description:i.description};return this.request({url:o,method:"POST",data:s},t)}AdminListSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/list_sem_url"),s={size:i.size,page:i.page};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_sem_url"),s={id:i.id,experiment_url:i.experiment_url,compare_url:i.compare_url,description:i.description};return this.request({url:o,method:"POST",data:s},t)}GetSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_sem_url"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}ClickCompetitionLikes(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/click_competition_likes"),s={competition_task_id:i.competition_task_id,is_like:i.is_like};return this.request({url:o,method:"POST",data:s},t)}SubmitCompetitionTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/submit_competition_task"),s={task_id:i.task_id,product_url:i.product_url,title:i.title,cover_uri:i.cover_uri,competition_id:i.competition_id};return this.request({url:o,method:"POST",data:s},t)}GetCompetitionInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_competition_info");return this.request({url:i,method:"POST"},t)}GetCompetitionTaskList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_competition_task_list"),s={page_size:i.page_size,cursor:i.cursor,is_create_sorted:i.is_create_sorted,search_title:i.search_title,competition_id:i.competition_id};return this.request({url:o,method:"POST",data:s},t)}FavoriteList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/list"),s={tag_ids:i.tag_ids,name:i.name,need_untagged:i.need_untagged,size:i.size,cursor:i.cursor,exclude_content_types:i.exclude_content_types};return this.request({url:o,method:"POST",data:s},t)}DeleteTags(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/delete_tags"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}DeleteFavorites(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/delete"),s={ids:i.ids,related_uris:i.related_uris};return this.request({url:o,method:"POST",data:s},t)}BatchGetFavoriteInfo(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/batch_get_info"),s={favorite_ids:i.favorite_ids};return this.request({url:o,method:"POST",data:s},t)}UpdateFavoriteInfo(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/update"),s={id:i.id,tag_ids:i.tag_ids};return this.request({url:o,method:"POST",data:s},t)}GetTagList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/get_tag_list"),s={tag_ids:i.tag_ids,tag_name:i.tag_name};return this.request({url:o,method:"POST",data:s},t)}CreateTags(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/create_tag"),s={tag_name:i.tag_name,tag_desc:i.tag_desc,favorite_info_list:i.favorite_info_list};return this.request({url:o,method:"POST",data:s},t)}AddFavorite(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/add"),s={title:i.title,content_uri:i.content_uri,content_text:i.content_text,tag_ids:i.tag_ids,source:i.source,scene:i.scene,product_type:i.product_type};return this.request({url:o,method:"POST",data:s},t)}UpdateTags(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/update_tag"),s={tag_id:i.tag_id,tag_name:i.tag_name,tag_desc:i.tag_desc};return this.request({url:o,method:"POST",data:s},t)}GetMyCompetitionTaskList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_my_competition_task_list"),s={page_size:i.page_size,cursor:i.cursor,competition_id:i.competition_id};return this.request({url:o,method:"POST",data:s},t)}AdminGetUserScenes(e,t){const i=this.genBaseURL("/api/coze_space/admin/get_user_scenes");return this.request({url:i,method:"GET"},t)}GetUserScenes(e,t){const i=this.genBaseURL("/api/coze_space/get_user_scenes");return this.request({url:i,method:"GET"},t)}GetDeepWritingConf(e,t){const i=this.genBaseURL("/api/coze_space/get_deep_writing_conf");return this.request({url:i,method:"GET"},t)}GetCompetitionTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_competition_task"),s={competition_task_id:i.competition_task_id};return this.request({url:o,method:"POST",data:s},t)}GetUnreadCount(e,t){const i=this.genBaseURL("/api/coze_space/get_unread_count");return this.request({url:i,method:"POST"},t)}BatchHtmlCodeToImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_html_code_to_image"),s={task_id:i.task_id,html_code:i.html_code,device_info:i.device_info,screenshot_info:i.screenshot_info,zip:i.zip};return this.request({url:o,method:"POST",data:s},t)}GenDocMultiImageMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/gen_doc_multi_image_material"),s={task_id:i.task_id,file_uri:i.file_uri};return this.request({url:o,method:"POST",data:s},t)}GetDerivedProduct(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_derived_product"),s={task_id:i.task_id,derived_product_type:i.derived_product_type};return this.request({url:o,method:"POST",data:s},t)}SaveDerivedProduct(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/save_derived_product"),s={task_id:i.task_id,derived_product:i.derived_product};return this.request({url:o,method:"POST",data:s},t)}TagFavorites(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/tag_favorites"),s={tag_name:i.tag_name,tag_desc:i.tag_desc};return this.request({url:o,method:"POST",data:s},t)}SuggestQuery(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/suggest_query"),s={query:i.query,image_urls:i.image_urls};return this.request({url:o,method:"POST",data:s},t)}BatchGetUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_get_url"),s={uri_list:i.uri_list,expire_seconds:i.expire_seconds,is_short_url:i.is_short_url};return this.request({url:o,method:"POST",data:s},t)}UploadFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/upload_file"),s={file_name:i.file_name,file_content:i.file_content,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}BatchGetFavorite(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/get_count"),s={file_uris:i.file_uris};return this.request({url:o,method:"POST",data:s},t)}GetEarliestQuery(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_earliest_query"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}GetMappingUri(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_mapping_uri"),s={uri:i.uri};return this.request({url:o,method:"POST",data:s},t)}ApiTemplate(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/api_template"),s={prompt:i.prompt,files:i.files,type:i.type,task_id:i.task_id,template_id:i.template_id};return this.request({url:o,method:"POST",data:s},t)}BatchGetMultiMedia(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/batch_get_multimedia"),s={media_uris:i.media_uris};return this.request({url:o,method:"POST",data:s},t)}AdminBatchGetMultiMedia(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/batch_get_multimedia"),s={media_uris:i.media_uris};return this.request({url:o,method:"POST",data:s},t)}AdminCreateMultiMedia(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_multimedia"),s={task_id:i.task_id,media_path:i.media_path,media_uri:i.media_uri,media_url:i.media_url,image_type:i.image_type,media_ext:i.media_ext};return this.request({url:o,method:"POST",data:s},t)}GetPodcastConfig(e,t){const i=this.genBaseURL("/api/coze_space/get_podcast_config");return this.request({url:i,method:"POST"},t)}IntentRecognition(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/intent_recognition"),s={task_id:i.task_id,files:i.files,ability_type:i.ability_type,query:i.query};return this.request({url:o,method:"POST",data:s},t)}ListTemplate(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/list_template"),s={size:i.size,cursor:i.cursor,tags:i.tags,ability_type:i.ability_type,api_template_type:i.api_template_type};return this.request({url:o,method:"POST",data:s},t)}AdminGetTagsByImages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/get_tags_by_images"),s={images:i.images,query:i.query,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetTagsByImages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_tags_by_images"),s={images:i.images,query:i.query,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_template_image"),s={image:i.image,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}ReportSubmit(e,t){const i=e,o=this.genBaseURL("/api/coze_space/report_submit"),s={object_type:i.object_type,object_id:i.object_id,report_detail:i.report_detail};return this.request({url:o,method:"POST",data:s},t)}ListBotChatMessages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/list_bot_chat_message"),s={bot_chat_type:i.bot_chat_type,cursor:i.cursor,size:i.size};return this.request({url:o,method:"POST",data:s},t)}BotChatWithType(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/bot_chat_with_type"),s={bot_chat_type:i.bot_chat_type,query:i.query};return this.request({url:o,method:"POST",data:s},t)}GenImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/gen_image"),s={task_id:i.task_id,project_id:i.project_id,prompt:i.prompt,count:i.count,video_project_uri:i.video_project_uri,image_url:i.image_url,base_image_urls:i.base_image_urls,skip_save_material:i.skip_save_material,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}UploadVideoResource(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/upload_video_resource"),s={task_id:i.task_id,project_id:i.project_id,file_name:i.file_name,file_content:i.file_content,video_project_uri:i.video_project_uri,skip_save_material:i.skip_save_material,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}GetVideoConfig(e,t){const i=this.genBaseURL("/api/coze_space/video/get_video_config");return this.request({url:i,method:"POST"},t)}GetCozeSpaceDeviceInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_device_info");return this.request({url:i,method:"POST"},t)}AdminMDeleteReferenceImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdelete_reference_image"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}AdminMDeleteTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdelete_template_image"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}AdminListReferenceImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_reference_image"),s={size:i.size,cursor:i.cursor,tag:i.tag};return this.request({url:o,method:"POST",data:s},t)}AdminListRewriteImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_rewrite_image"),s={size:i.size,cursor:i.cursor,tag:i.tag};return this.request({url:o,method:"POST",data:s},t)}AdminCreateReferenceImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_reference_image"),s={tag:i.tag,image:i.image};return this.request({url:o,method:"POST",data:s},t)}AdminTemplateRewrite(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/template_rewrite"),s={template_image_ids:i.template_image_ids,rewrite_image_id:i.rewrite_image_id};return this.request({url:o,method:"POST",data:s},t)}AdminMDeleteRewriteImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdelete_rewrite_image"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}AdminListTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_template_image"),s={size:i.size,cursor:i.cursor,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateRewriteImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/update_rewrite_image"),s={id:i.id,rewrite_result:i.rewrite_result};return this.request({url:o,method:"POST",data:s},t)}GetGuidingMessage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_guiding_message"),s={guiding_id:i.guiding_id};return this.request({url:o,method:"POST",data:s},t)}AdminListImageTag(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_image_tag"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}UpdateProject(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/update_project"),s={GroupId:i.GroupId,ProjectId:i.ProjectId,LatestEditParam:i.LatestEditParam,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}DescribeProject(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/describe_project"),s={GroupId:i.GroupId,ProjectId:i.ProjectId,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}SubmitEditTaskAsync(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/submit_edit_task_async"),s={GroupId:i.GroupId,ProjectId:i.ProjectId,ProjectType:i.ProjectType,EditParam:i.EditParam,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,ignore_edit_param:i.ignore_edit_param,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}BatchGetVideoPlayInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/batch_get_video_play_info"),s={vids:i.vids,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri};return this.request({url:o,method:"POST",data:s},t)}GetDirectEditProgress(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/get_direct_edit_progress"),s={ReqId:i.ReqId,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}SearchEditMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/search_edit_material"),s={ProjectId:i.ProjectId,EditMids:i.EditMids,Space:i.Space,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}ListSnapshots(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/list_snapshots"),s={ProjectId:i.ProjectId,Vid:i.Vid,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/update_reference_image"),s={id:i.id,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}VolcVodCallback(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/volc_vod_callback"),s={RequestId:i.RequestId,Version:i.Version,EventType:i.EventType,EventTime:i.EventTime};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/delete_video_text_style"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}AdminListVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_video_text_style"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}AdminSaveVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/save_video_text_style"),s={video_text_style:i.video_text_style};return this.request({url:o,method:"POST",data:s},t)}GetMusicList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/get_music_list"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}ListVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/list_video_text_style"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}GetMessageMeta(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_message_meta"),s={task_id:i.task_id};return this.request({url:o,method:"GET",params:s},t)}AdminRunWorkflow(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/run_workflow"),s={id:i.id,input:i.input};return this.request({url:o,method:"POST",data:s},t)}QueryGenResourceStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/query_gen_resource_status"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,gen_resource_task_id:i.gen_resource_task_id,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}GenResourceAsync(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/gen_resource_async"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,gen_resource_type:i.gen_resource_type,gen_video_req_payload:i.gen_video_req_payload,gen_voice_audio_req_payload:i.gen_voice_audio_req_payload,gen_music_req_payload:i.gen_music_req_payload,skip_save_material:i.skip_save_material,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}GetTaskItemList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_item_list"),s={task_id:i.task_id,item_ids:i.item_ids,start_time:i.start_time,end_time:i.end_time};return this.request({url:o,method:"POST",data:s},t)}CancelGenResourceTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/cancel_gen_resource_task"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,gen_resource_task_id:i.gen_resource_task_id,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTemplateTagsFromCSV(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/update_template_tags_from_csv"),s={is_run_wf:i.is_run_wf,is_update:i.is_update,tos_path:i.tos_path};return this.request({url:o,method:"POST",data:s},t)}GetPlanTemplates(e,t){const i=this.genBaseURL("/api/coze_space/get_plan_templates");return this.request({url:i,method:"POST"},t)}DeleteTaskFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/delete_task_file"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}ListTaskFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/list_task_file"),s={task_id:i.task_id,size:i.size,cursor:i.cursor,plan_file:i.plan_file};return this.request({url:o,method:"POST",data:s},t)}GenPodcastStream(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/gen_podcast"),s={cache_key:i.cache_key};return this.request({url:o,method:"POST",data:s},t)}AdminTemplateTypeIntentBG(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/template_type_intent_bg"),s={files:i.files};return this.request({url:o,method:"POST",data:s},t)}ExportImagePPT(e,t){const i=e,o=this.genBaseURL("/api/coze_space/export_image_ppt_agent_file"),s={task_id:i.task_id,title:i.title,pages:i.pages,export_type:i.export_type};return this.request({url:o,method:"POST",data:s},t)}ExportProject(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/export_project"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}GetModelConfig(e,t){const i=this.genBaseURL("/api/coze_space/get_model_config");return this.request({url:i,method:"POST"},t)}ConfirmPlan(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/confirm_plan"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}GetUserSkillAuthorizationInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/skill/get_user_skill_authorization_info"),s={credential_id:i.credential_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCozeUserNickname(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_user_nickname"),s={nickname:i.nickname};return this.request({url:o,method:"POST",data:s},t)}CreateCozeUserJobName(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/create_user_job_name"),s={job_name:i.job_name};return this.request({url:o,method:"POST",data:s},t)}EnterpriseCustomer(e,t){const i=this.genBaseURL("/api/coze_space/enterprise_customer");return this.request({url:i,method:"POST"},t)}CreateVideoAsset(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/create_video_asset"),s={base_info:i.base_info,details:i.details};return this.request({url:o,method:"POST",data:s},t)}UpdateVideoAsset(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/update_video_asset"),s={asset_id:i.asset_id,base_info:i.base_info,details:i.details};return this.request({url:o,method:"POST",data:s},t)}DeleteVideoAsset(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/asset/delete_video_asset"),s={asset_id:i.asset_id};return this.request({url:o,method:"POST",data:s},t)}UpdateVideoProduction(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/production/update_video_production"),s={video_production:i.video_production,ratio:i.ratio};return this.request({url:o,method:"POST",data:s},t)}CreateVideoProduction(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/production/create_video_production"),s={video_production:i.video_production,ratio:i.ratio};return this.request({url:o,method:"POST",data:s},t)}VideoProductionMaterialList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/video_material_list"),s={production_id:i.production_id,tag_category:i.tag_category,type_category:i.type_category,page:i.page,size:i.size,need_detail_url:i.need_detail_url,session_id:i.session_id,conversation_id:i.conversation_id,search_word:i.search_word,not_need_cvs_or_cvp:i.not_need_cvs_or_cvp};return this.request({url:o,method:"POST",data:s},t)}VideoAssetDetail(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/video_asset_detail"),s={asset_id:i.asset_id};return this.request({url:o,method:"POST",data:s},t)}VideoProductionMaterialDetail(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/video_material_detail"),s={material_id:i.material_id};return this.request({url:o,method:"POST",data:s},t)}DeleteVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/delete_video_material"),s={material_id:i.material_id};return this.request({url:o,method:"POST",data:s},t)}CreateVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/create_video_material"),s={production_id:i.production_id,base_info:i.base_info,details:i.details,asset_id:i.asset_id,session_id:i.session_id,conversation_id:i.conversation_id};return this.request({url:o,method:"POST",data:s},t)}UpdateVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/update_video_material"),s={material_id:i.material_id,material_update_type:i.material_update_type,base_info:i.base_info,details:i.details};return this.request({url:o,method:"POST",data:s},t)}DeleteVideoProduction(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/production/delete_video_production"),s={production_id:i.production_id};return this.request({url:o,method:"POST",data:s},t)}VideoAssetList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/video_asset_list"),s={tag_category:i.tag_category,type_category:i.type_category,page:i.page,size:i.size,search_word:i.search_word,need_detail_url:i.need_detail_url};return this.request({url:o,method:"POST",data:s},t)}VideoProductionList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/production/video_production_list"),s={page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}OperateVideoProduction(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/production/operate_video_production"),s={production_id:i.production_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}OperateVideoAsset(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/asset/operate_video_asset"),s={asset_id:i.asset_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}BatchParseVideoAsset(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/asset/batch_parse_video_asset"),s={vids:i.vids};return this.request({url:o,method:"POST",data:s},t)}GetFileLock(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/file_lock/get"),s={project_id:i.project_id,file_path:i.file_path};return this.request({url:o,method:"GET",params:s},t)}ReleaseFileLock(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/file_lock/release"),s={project_id:i.project_id,file_path:i.file_path,session_id:i.session_id};return this.request({url:o,method:"POST",data:s},t)}AcquireFileLock(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/file_lock/acquire"),s={project_id:i.project_id,file_path:i.file_path,session_id:i.session_id,file_name:i.file_name};return this.request({url:o,method:"POST",data:s},t)}GetOutputVideo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/get_output_video"),s={video_project_uri:i.video_project_uri};return this.request({url:o,method:"POST",data:s},t)}CloneToVideoAsset(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/clone_to_video_asset"),s={material_id:i.material_id};return this.request({url:o,method:"POST",data:s},t)}CloneToVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/clone_to_video_material"),s={asset_id:i.asset_id,production_id:i.production_id,session_id:i.session_id,conversation_id:i.conversation_id};return this.request({url:o,method:"POST",data:s},t)}}const Sp=new bp({});var Pp,Cp,Tp,Ep,kp,Ip,Ap,jp,Rp,zp,Up,Lp,Op,xp,Bp,qp,Dp,Mp,Np,Gp,$p,Fp,Vp,Wp,Hp,Jp,Kp,Qp,Yp,Zp,Xp;function eu(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[e.Image=1]="Image";e[e.Android=2]="Android";e[e.IOS=3]="IOS";e[e.GitCode=4]="GitCode";e[e.FaasRuntimePkg=5]="FaasRuntimePkg";e[e.SkillPkg=6]="SkillPkg";e[e.H5=7]="H5"}(Pp||(Pp={})),function(e){e[e.Unknown=0]="Unknown";e[e.FreeCertificate=1]="FreeCertificate"}(Cp||(Cp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Normal=1]="Normal"}(Tp||(Tp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Existing=1]="Existing";e[e.Free=2]="Free"}(Ep||(Ep={})),function(e){e[e.AuditPass=1]="AuditPass";e[e.AuditUnPass=2]="AuditUnPass";e[e.Auditing=3]="Auditing";e[e.Released=11]="Released";e[e.ReleaseFailed=12]="ReleaseFailed";e[e.Running=21]="Running"}(kp||(kp={})),function(e){e[e.Passed=1]="Passed";e[e.UnPassed=2]="UnPassed";e[e.Auditing=3]="Auditing"}(Ip||(Ip={})),function(e){e[e.Official=1]="Official"}(Ap||(Ap={})),function(e){e[e.Prepare=1]="Prepare";e[e.Package=2]="Package";e[e.Build=3]="Build";e[e.Deploy=4]="Deploy";e[e.Audit=5]="Audit"}(jp||(jp={})),function(e){e[e.Pending=1]="Pending";e[e.Running=2]="Running";e[e.Succeeded=3]="Succeeded";e[e.Failed=4]="Failed";e[e.Canceled=5]="Canceled";e[e.Interrupted=6]="Interrupted"}(Rp||(Rp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Success=1]="Success";e[e.Pending=2]="Pending";e[e.Failed=3]="Failed"}(zp||(zp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Default=1]="Default";e[e.Custom=2]="Custom"}(Up||(Up={})),function(e){e[e.Unknown=0]="Unknown";e[e.Active=1]="Active";e[e.Disabled=2]="Disabled";e[e.Redirected=3]="Redirected";e[e.Primary=4]="Primary"}(Lp||(Lp={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(Op||(Op={})),function(e){e[e.Agent=1]="Agent";e[e.Automation=2]="Automation";e[e.WebApp=3]="WebApp";e[e.App=4]="App";e[e.Skill=5]="Skill";e[e.GeneralWeb=6]="GeneralWeb";e[e.WechatMiniProgram=7]="WechatMiniProgram";e[e.General=9]="General"}(xp||(xp={})),function(e){e[e.Created=1]="Created";e[e.Ready=3]="Ready";e[e.Stopped=4]="Stopped";e[e.Banned=5]="Banned";e[e.Paused=6]="Paused"}(Bp||(Bp={})),function(e){e[e.Unknown=0]="Unknown";e[e.VefaasFunction=1]="VefaasFunction"}(qp||(qp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Dev=1]="Dev";e[e.Prod=2]="Prod";e[e.Audit=3]="Audit"}(Dp||(Dp={})),function(e){e[e.A=1]="A";e[e.CNAME=2]="CNAME"}(Mp||(Mp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Single=1]="Single";e[e.Wildcard=2]="Wildcard";e[e.Multi=3]="Multi"}(Np||(Np={})),function(e){e[e.Unknown=0]="Unknown";e[e.DV=1]="DV";e[e.OV=2]="OV";e[e.EV=3]="EV"}(Gp||(Gp={})),function(e){e[e.Unknown=0]="Unknown";e[e.NotSubmitted=1]="NotSubmitted";e[e.Pending=2]="Pending";e[e.Issued=3]="Issued";e[e.Cancelling=4]="Cancelling";e[e.Canceled=5]="Canceled";e[e.Revoking=6]="Revoking";e[e.Revoked=7]="Revoked";e[e.Failed=8]="Failed";e[e.Expired=9]="Expired"}($p||($p={})),function(e){e[e.Unknown=0]="Unknown";e[e.Free=1]="Free";e[e.Test=2]="Test";e[e.Paid=3]="Paid";e[e.Imported=4]="Imported"}(Fp||(Fp={})),function(e){e[e.NeedAuthorize=1]="NeedAuthorize";e[e.BindSuccess=2]="BindSuccess";e[e.BoundToOtherProject=3]="BoundToOtherProject";e[e.BoundToOtherUser=4]="BoundToOtherUser"}(Vp||(Vp={})),function(e){e[e.BoundToSelf=1]="BoundToSelf";e[e.BoundToOtherUser=2]="BoundToOtherUser";e[e.NotAuthorized=3]="NotAuthorized"}(Wp||(Wp={})),function(e){e[e.Line=1]="Line"}(Hp||(Hp={})),function(e){e[e.Default=0]="Default";e[e.WechatMini=1]="WechatMini";e[e.DouyinMini=2]="DouyinMini"}(Jp||(Jp={})),function(e){e[e.Day=1]="Day";e[e.Week=2]="Week";e[e.Month=3]="Month";e[e.Yesterday=4]="Yesterday";e[e.ThreeDays=5]="ThreeDays"}(Kp||(Kp={})),function(e){e[e.InvokeQPS=1]="InvokeQPS";e[e.ErrorQPS=2]="ErrorQPS";e[e.Latency=3]="Latency";e[e.DAU=4]="DAU";e[e.DNU=5]="DNU";e[e.ActiveRetention=6]="ActiveRetention";e[e.NewUserRetention=7]="NewUserRetention"}(Qp||(Qp={})),function(e){e[e.Recorded=1]="Recorded"}(Yp||(Yp={})),function(e){e[e.Sum=1]="Sum";e[e.Avg=2]="Avg"}(Zp||(Zp={})),function(e){e[e.Next=1]="Next";e[e.Third=3]="Third";e[e.Seventh=7]="Seventh"}(Xp||(Xp={}));class tu{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){tu.prototype.__init.call(this),tu.prototype.__init2.call(this),this.request=eu([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=eu([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}PublicCreateDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/create"),s={project_id:i.project_id,is_sync_db_to_prod:i.is_sync_db_to_prod,encrypt_env_variable:i.encrypt_env_variable,table_sync_configs:i.table_sync_configs,encrypt_deploy:i.encrypt_deploy,commit_hash:i.commit_hash,connector_configs:i.connector_configs};return this.request({url:o,method:"POST",data:s},t)}PublicRollbackDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/rollback"),s={project_id:i.project_id,target_deploy_history_id:i.target_deploy_history_id,rollback_database:i.rollback_database};return this.request({url:o,method:"POST",data:s},t)}PublicCancelDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/cancel"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"POST",data:s},t)}PublicGetDeployConfig(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_config/get"),s={project_id:i.project_id,commit_hash:i.commit_hash};return this.request({url:o,method:"GET",params:s},t)}PublicListDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/list"),s={project_id:i.project_id,page_token:i.page_token,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}PublicSearchRuntimeLog(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/runtime_log/search"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id,start_time:i.start_time,end_time:i.end_time,limit:i.limit,cursor:i.cursor,query:i.query,level:i.level};return this.request({url:o,method:"GET",params:s},t)}PublicGetDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/get"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"GET",params:s},t)}PublicBindCertificate(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/bind"),s={project_id:i.project_id,certificate_id:i.certificate_id,domain:i.domain};return this.request({url:o,method:"POST",data:s},t)}PublicApplyFreeCertificate(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/apply_free"),s={project_id:i.project_id,domain:i.domain,auto_renew_free_cert:i.auto_renew_free_cert};return this.request({url:o,method:"POST",data:s},t)}PublicListDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/list"),s={project_id:i.project_id,unit_type:i.unit_type};return this.request({url:o,method:"GET",params:s},t)}PublicDeleteDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/delete"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"POST",data:s},t)}PublicCreateDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/create"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"POST",data:s},t)}PublicGetDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/get"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetCertificateDetail(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/get"),s={project_id:i.project_id,certificate_id:i.certificate_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/get"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"GET",params:s},t)}PublicListVolcanoDomain(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/volcano_domain/list"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicListVolcanoCertificate(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/list_volcano"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"GET",params:s},t)}PublicListProjectTraces(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/traces/list"),s={project_id:i.project_id,start_time:i.start_time,end_time:i.end_time,filter:i.filter,page_token:i.page_token,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}PublicDownloadProjectTraces(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/traces/download"),s={project_id:i.project_id,start_time:i.start_time,end_time:i.end_time,filter:i.filter};return this.request({url:o,method:"POST",data:s},t)}PublicGetProjectMetrics(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/metrics/get"),s={project_id:i.project_id,time_range:i.time_range,retention_days:i.retention_days};return this.request({url:o,method:"GET",params:s},t)}PublicDeleteDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/delete"),s={project_id:i.project_id,deploy_unit_id:i.deploy_unit_id};return this.request({url:o,method:"POST",data:s},t)}PublicGetHelpCenterLink(e,t){const i=this.genBaseURL("/api/coding/deployment/help_center/link");return this.request({url:i,method:"GET"},t)}PublicCheckRollbackDatabase(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/check_rollback_database"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetMiniProgramPreview(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/mini_program/preview"),s={project_id:i.project_id,app_id:i.app_id,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}PublicSubmitAuthCode(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/submit_code"),s={project_id:i.project_id,connector_id:i.connector_id,code:i.code,verify_state:i.verify_state,auth_params:i.auth_params};return this.request({url:o,method:"POST",data:s},t)}PublicGetAuthStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/status"),s={project_id:i.project_id,connector_id:i.connector_id,redirect_url:i.redirect_url};return this.request({url:o,method:"POST",data:s},t)}PublicBindAuth(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/bind"),s={project_id:i.project_id,connector_id:i.connector_id,redirect_url:i.redirect_url,auth_params:i.auth_params,override:i.override};return this.request({url:o,method:"POST",data:s},t)}PublicUnbindAuth(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/unbind"),s={project_id:i.project_id,connector_id:i.connector_id};return this.request({url:o,method:"POST",data:s},t)}PublicGetBoundProject(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/get_bound_project"),s={connector_id:i.connector_id,related_id:i.related_id};return this.request({url:o,method:"GET",params:s},t)}PublicUpdateDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/update"),s={project_id:i.project_id,domain:i.domain,auto_renew_free_cert:i.auto_renew_free_cert,visit_status:i.visit_status,next_primary_domain:i.next_primary_domain};return this.request({url:o,method:"POST",data:s},t)}PublicGetCertificateQuota(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/quota"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicListDomainCertificates(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/list"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"GET",params:s},t)}PublicUnpublishConnector(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/unpublish_project"),s={project_id:i.project_id,connector_ids:i.connector_ids};return this.request({url:o,method:"POST",data:s},t)}PublicListConnector(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/list"),s={project_id:i.project_id,project_publish_status:i.project_publish_status};return this.request({url:o,method:"GET",params:s},t)}PublicPublishConnector(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/publish_project"),s={project_id:i.project_id,connector_configs:i.connector_configs};return this.request({url:o,method:"POST",data:s},t)}PublicGetDeployCount(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/get_count"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}GetRuntimeLogCount(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/runtime_log/count"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicExchangeFeishuAuthCode(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/feishu/auth/exchange_code"),s={project_id:i.project_id,code:i.code,verify_state:i.verify_state};return this.request({url:o,method:"POST",data:s},t)}PublicRevokeFeishuAuth(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/feishu/auth/revoke"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}PublicUpdateDefaultDomainPrefix(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/update_default_prefix"),s={project_id:i.project_id,prefix:i.prefix};return this.request({url:o,method:"POST",data:s},t)}PublicFeishuWebhookEvent(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/feishu/webhook/event"),s={body:i.body};return this.request({url:o,method:"POST",data:s},t)}PublicCheckCreateDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/check_create"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetHostedUsageMonthly(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/hosted_usage/monthly"),s={project_id:i.project_id,bill_month:i.bill_month};return this.request({url:o,method:"GET",params:s},t)}PublicGetEstimateHostedCost(e,t){const i=this.genBaseURL("/api/coding/deployment/hosted_usage/estimate_cost");return this.request({url:i,method:"GET"},t)}PublicGetDeployHistoryLog(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/log"),s={deploy_history_id:i.deploy_history_id,key:i.key};return this.request({url:o,method:"GET",params:s},t)}PublicGetMPICPStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/mini_program/icp_status"),s={project_id:i.project_id,app_id:i.app_id,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetOnlineDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/get_online"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetUserAnalyticsMetrics(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/metrics/user_analytics/get"),s={project_id:i.project_id,time_range:i.time_range};return this.request({url:o,method:"GET",params:s},t)}PublicPauseDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/pause"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"POST",data:s},t)}PublicStopDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/stop"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"POST",data:s},t)}PublicResumeDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/resume"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"POST",data:s},t)}PublicReportUserAnalytics(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/analytics/report"),s={events:i.events},n={project_id:i.project_id,did:i.did};return this.request({url:o,method:"POST",data:s,params:n},t)}PublicCreateDefaultDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/create_default"),s={project_id:i.project_id,prefix:i.prefix};return this.request({url:o,method:"POST",data:s},t)}PublicGetProtectionConfig(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/protection_config/get"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicUpdateProtectionConfig(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/protection_config/update"),s={project_id:i.project_id,config:i.config};return this.request({url:o,method:"POST",data:s},t)}}const iu=new tu({}),ou={[Rp.Pending]:"Pending",[Rp.Running]:"Running",[Rp.Succeeded]:"Succeeded",[Rp.Failed]:"Failed",[Rp.Canceled]:"Canceled",[Rp.Interrupted]:"Interrupted"},su=[Rp.Succeeded,Rp.Failed,Rp.Canceled],nu=e=>e&&ou[e]||"Unknown";function ru(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 au{static __initStatic(){this.INSTANCE=new au}static getInstance(){return au.INSTANCE||(au.INSTANCE=new au),this.INSTANCE}async pollDeployStatus(t){const{projectId:i,deployHistoryId:o,onBeforePoll:s,onStatusChange:n}=t;let r;for(;;){ru([s,"optionalCall",e=>e()]);const t=ru([await iu.PublicGetDeployHistory({project_id:i,deploy_history_id:o}),"optionalAccess",e=>e.data]);if(!t)throw new e.CozeError(e.ErrorCode.E5000,"Failed to get deploy history data during polling");const a=t.status;if(a!==r&&(r=a,ru([n,"optionalCall",e=>e(t)])),su.includes(a))return t;await new Promise((e=>setTimeout(e,3e3)))}}async getLatestDeployHistoryId(e){const{projectId:t}=e;return ru([await iu.PublicListDeployHistory({page_size:1,project_id:t}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list,"optionalAccess",e=>e[0],"optionalAccess",e=>e.deploy_history_id])}async getDeployHistory(t){const{projectId:i,deployHistoryId:o}=t,s=await iu.PublicGetDeployHistory({project_id:i,deploy_history_id:o});if(!ru([s,"optionalAccess",e=>e.data]))throw new e.CozeError(e.ErrorCode.E5000,"Failed to get deploy history data");return s.data}canDeploy(e){return[t.VibeProjectType.AssistantAgent,t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.Skill,t.VibeProjectType.Agent,t.VibeProjectType.Automation].includes(e)}async getCommitList({projectId:i}){const o=await t.IdeApi.ProxySandboxMessage({ProjectID:i,Method:"repo_version.commit.list",Params:JSON.stringify({project_id:i})});return e.safeJsonParse(o.data,{commits:[]}).commits||[]}}au.__initStatic();const cu=au.getInstance();function du(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 lu(e,t){return null!=e?e:t()}function pu(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 uu(e,t){return null!=e?e:t()}function _u(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 hu=e=>{if(null==e)return null;return 0===e.trim().length?null:e},mu=i=>{i.command("send [message]").description("Send a prompt message to Coze Coding project chat").option("--wait","Wait for the chat response before returning").option("--stdin","Read additional context from stdin (pipe input)").config({help:{brief:"Send a message to project chat",description:"Send a prompt message to the specified Coze Coding project chat. The message can be provided as a positional argument. Use --stdin to pipe additional context. Use @<path> to mention and upload local files as context.",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug in auth module" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Send and wait for the response",cmd:'coze code message send "Fix the bug in auth module" -p 123456 --wait'},{desc:"Mention a file with @",cmd:'coze code message send "Refactor @src/utils.ts to use async/await" -p 123456'},{desc:"Mention multiple files",cmd:'coze code message send "Compare @src/old.ts and @src/new.ts, list the differences" -p 123456'},{desc:"Send message with stdin context",cmd:'cat error.log | coze code message send "Analyze this error" --stdin -p 123456'},{desc:"Use environment variable for project",cmd:'export COZE_PROJECT_ID=123456 && coze code message send "Hello"'}],errors:[{code:e.ErrorCode.E1000,name:"MISSING_MESSAGE",desc:"No message content provided",fix:"Provide MESSAGE argument or use --stdin with piped content",example:'coze code message send "Your question" -p 123456 # or: echo "context" | coze code message send --stdin "question" -p 123456'},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{message:{type:"string",required:!1,description:"The prompt message to send to the project chat"},wait:{type:"boolean",required:!1,description:"Wait for the chat response before returning. Without this flag, the message is sent in the background."},stdin:{type:"boolean",required:!1,description:"Read additional context from stdin (pipe input)."}},output:{type:"object",properties:{content:{type:"string",description:"The chat response content"}}}}}}).action((async(i,o,s)=>{const n=s.getContext();try{if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const r=_u([s,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),a=uu(_u([r,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!a)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");const c=await _u([n,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!c)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const{wait:d,stdin:l}=o;let p=null;l&&(p=await br());const u=hu(i),_=hu(p);if(!u&&!_)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin");const h=u&&_?`${u}\n\n${_}`:uu(uu(u,(()=>_)),(()=>"")),m=new Set,g=await t.sendProjectChatMessage({projectId:a,prompt:h,apiBaseUrl:n.config.apiBaseUrl,accessToken:c,xTTEnv:n.config.xTTEnv,key:`coze-coding-cli:message:${a}`,onWarn:e=>n.ui.warn(e),waitForResponse:!!d,onMessageItem:e=>{if(d&&"json"===n.format&&e.finish){const t=(e=>{const t=uu(e.msg_id,(()=>"")),i=uu(e.sequence_id,(()=>""));return`${e.type}:${t}:${String(i)}`})(e);m.has(t)||(m.add(t),n.response.print({content:e.content,role:e.role,finish:e.finish,type:e.type}))}}});if(d)"text"===n.format&&n.response.print(uu(_u([g,"access",e=>e.lastAnswerMessage,"optionalAccess",e=>e.content,"access",e=>e.answer]),(()=>"")));else{const e=`Message sent. Use \`coze code message status -p ${a}\` to check the result.`;"json"===n.format?n.response.print({status:"sent",project_id:a,message:e}):n.response.print(e),process.exit(0)}}catch(e){V(e,n)}}))};function gu(e,t){return null!=e?e:t()}function fu(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 yu(e,t){return null!=e?e:t()}function vu(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 wu=async(i,o)=>{const s=o.getContext();try{if(!s)throw new e.CozeError("E5000","CLI context is not initialized");const n=vu([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=yu(vu([n,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!r)throw new e.CozeError("E1001","Missing required option: --project-id (or env COZE_PROJECT_ID)");if(!await vu([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]))throw new e.CozeError("E2001","Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(i.after&&i.before)throw new e.CozeError("E1000","--after and --before cannot be used together. Use only one cursor at a time.");s.ui.verbose(`Fetching conversation history for project ${r}...`);const a=t.createChatCore({key:`coze-coding-cli:history:${r}`,apiBaseUrl:s.config.apiBaseUrl});try{const e=i.after?"loadNext":"loadPrev",t="loadNext"===e?"11":"10",o=await a.getHistoryMessage({limit:t,project_id:r,after:i.after,before:i.before}),n=[],c=new Map,d=new Map;o.histories.forEach((e=>{if(e.user){const t=e.user.msg_id;c.has(t)||n.push(t);const i=(e=>{const t=vu([e,"optionalAccess",e=>e.content]);return yu(yu(vu([t,"optionalAccess",e=>e.query,"optionalAccess",e=>e.prompt]),(()=>vu([t,"optionalAccess",e=>e.retry,"optionalAccess",e=>e.prompt]))),(()=>vu([t,"optionalAccess",e=>e.edit,"optionalAccess",e=>e.prompt])))})(e.user.message);c.set(t,i?(e=>e.map((e=>"text"===e.type?e.content.text:"file"===e.type?`${fu([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.path])} ${gu(fu([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.from,"optionalAccess",e=>e[0]]),(()=>""))} ${gu(fu([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.to,"optionalAccess",e=>e[0]]),(()=>""))} `:"console"===e.type?fu([e,"access",e=>e.content,"access",e=>e.console,"optionalAccess",e=>e.content]):"node"===e.type?fu([e,"access",e=>e.content,"access",e=>e.node,"optionalAccess",e=>e.node_title]):"upload_file"===e.type?fu([e,"access",e=>e.content,"access",e=>e.upload_file,"optionalAccess",e=>e.file_name]):"page"===e.type?fu([e,"access",e=>e.content,"access",e=>e.page,"optionalAccess",e=>e.page_title]):"page_elements"===e.type?fu([e,"access",e=>e.content,"access",e=>e.page_elements,"optionalAccess",e=>e[0],"optionalAccess",e=>e.path,"optionalAccess",e=>e[0],"optionalAccess",e=>e.node_name]):"wf_canvas_change"===e.type?fu([e,"access",e=>e.content,"access",e=>e.wf_canvas_change,"optionalAccess",e=>e.query]):"")).join(" "))(i):"")}if(e.assistant){const t=e.assistant.messages.find((e=>"answer"===e.type&&e.content.answer));if(!t)return;const i=t.query_msg_id,o=t.content.answer;"string"==typeof i&&"string"==typeof o&&d.set(i,o)}}));const l=n[0],p=n[n.length-1],u=n.reverse().filter((e=>d.has(e))).map((e=>({userMessage:yu(c.get(e),(()=>"")),answer:yu(d.get(e),(()=>""))}))),_={histories:u,cursor:{after:l,before:p,has_more:o.has_more,loadDirection:e}};if("json"===s.format)s.response.print(_);else{if(0===u.length)return void s.response.print("No conversation history found.");u.forEach(((e,t)=>{s.response.print(`--- #${t+1} ---\nQ: ${e.userMessage}\nA: ${e.answer}\n`)})),s.response.print(`\n[cursor] after=${l}, before=${p}, has_more=${o.has_more}, loadDirection=${e}`)}}finally{a.destroy()}}catch(e){V(e,s)}};function bu(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 Su=i=>{const o=i.command("message");o.description("Manage project chat messages").config({help:{brief:"Manage project chat messages",description:"Manage Coze Coding project chat messages.\n\nThis command group provides:\n- send: Send a new message to the project chat\n- status: Query the status of current chat message (auto-fetch result when completed)\n- cancel: Cancel an ongoing chat message\n- history: View conversation history",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Check message status",cmd:"coze code message status -p 123456"},{desc:"Cancel ongoing message",cmd:"coze code message cancel -p 123456"},{desc:"View conversation history",cmd:"coze code message history -p 123456"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID (can also be set via COZE_PROJECT_ID env)"}}},seeAlso:["coze code project list","coze code project create"]}}).option("-p, --project-id <id>","Coze project id (or env COZE_PROJECT_ID)"),mu(o),(i=>{i.command("status").description("Query current project chat message status and get result when completed").config({help:{brief:"Query chat message status",description:"Get the current status of the chat message for the specified project. Returns status information such as running, completed, or error. When the chat is completed, automatically fetches and returns the result.",examples:[{desc:"Check message status (auto-fetch result when completed)",cmd:"coze code message status -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message status"},{desc:"Output as JSON",cmd:"coze code message status -p 123456 --format json"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Message status (running/completed/error)"},message:{type:"string",description:"Status message or error details"},answer:{type:"string",description:"The chat answer content (only when completed)"}}}}}}).action((async(i,o)=>{const s=o.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const i=pu([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),n=lu(pu([i,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!n)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");s.ui.verbose(`Fetching chat status for project ${n}...`);const{code:r,msg:a,reply_id:c,...d}=await t.BuildAgentApi.GetChatCLIMessageStatus({project_id:n});if("done"===d.status){s.ui.verbose(`Chat completed, fetching result for project ${n}...`);const e=await t.BuildAgentApi.GetChatCLIMessageResultContent({project_id:n}),i="data"in e?e.data:e;"json"===s.format?s.response.print({...d,answer:i.answer}):s.response.print(`status: [${d.status}]\nanswer: ${lu(i.answer,(()=>""))}`)}else"json"===s.format?s.response.print(d):s.response.print(d.status)}catch(e){V(e,s)}}))})(o),function(i){i.command("cancel").description("Cancel current project chat message").config({help:{brief:"Cancel ongoing chat message",description:"Cancel the currently running chat message for the specified project. Useful for stopping long-running or stuck message generation.",examples:[{desc:"Cancel current message",cmd:"coze code message cancel -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message cancel"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Cancel operation status"},message:{type:"string",description:"Result message"}}}}}}).action((async(i,o)=>{const s=o.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const i=bu([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=null!=(n=bu([i,"optionalAccess",e=>e.projectId]))?n:(()=>process.env.COZE_PROJECT_ID)();if(!r)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");const{accessToken:a}=s.config;if(!a)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");s.ui.verbose(`Canceling chat message for project ${r}...`);const{message:c}=await t.BuildAgentApi.CancelChatCLIMessage({project_id:r});"json"===s.format?s.response.print({message:c}):s.response.print(c)}catch(e){V(e,s)}var n}))}(o),(e=>{e.command("history").description("View conversation history of the project chat").option("--after <msg_id>","Cursor for fetching newer messages (smaller index)").option("--before <msg_id>","Cursor for fetching older messages (larger index)").config({help:{brief:"View conversation history",description:"Retrieve and display the conversation history for the specified Coze Coding project. Shows each round of user messages and LLM responses. By default, returns the latest 10 rounds of conversation. Use --after or --before cursors for pagination.",examples:[{desc:"View latest 10 rounds of conversation history",cmd:"coze code message history -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message history"},{desc:"Output as JSON with cursor info",cmd:"coze code message history -p 123456 --format json"},{desc:"Fetch newer messages after a cursor",cmd:"coze code message history -p 123456 --after msg_xxx"},{desc:"Fetch older messages before a cursor",cmd:"coze code message history -p 123456 --before msg_yyy"}],errors:[{code:"E1000",name:"INVALID_ARGUMENT",desc:"--after and --before cannot be used together",fix:"Use only one cursor option at a time for pagination"},{code:"E1001",name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:"E2001",name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"},after:{type:"string",description:'Cursor (message ID) for fetching newer messages. Newer messages have smaller index. Use the "after" value from previous output as this parameter.'},before:{type:"string",description:'Cursor (message ID) for fetching older messages. Older messages have larger index. Use the "before" value from previous output as this parameter.'}},output:{type:"object",properties:{histories:{type:"array",items:{type:"object",properties:{userMessage:{type:"string",description:"User's message in this round"},answer:{type:"string",description:"LLM's last answer with content"}}}},cursor:{type:"object",description:"Pagination cursor info for next/prev page requests",properties:{after:{type:"string",description:"Message ID of the newest result, use as --after to fetch newer messages (loadNext)"},before:{type:"string",description:"Message ID of the oldest result, use as --before to fetch older messages (loadPrev)"},has_more:{type:"boolean",description:"Whether there are more messages available"},loadDirection:{type:"string",enum:["loadNext","loadPrev"],description:"Load direction of current request. Defaults to 'loadPrev' (load older messages). 'loadNext' when --after is used, 'loadPrev' when --before is used or on initial request."}}}}}}}}).action(wu)})(o)};function Pu(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 Cu(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 Tu(i){i.command("list").description("List project environment variables").option("--env <scope>","Environment scope: dev | prod","dev").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List project environment variables",description:"Retrieve the list of environment variables for the specified project. Supports filtering by environment (dev/prod) and displays all configured sensitive information key names.",examples:[{desc:"List dev environment variables",cmd:"coze code env list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List prod environment variables",cmd:"coze code env list -p <projectId> --env prod"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},env:{type:"string",required:!1,enum:["dev","prod"],description:"Environment scope (default: dev)"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},project_type:{type:"string",description:"Project type"},env:{type:"string",description:"Environment scope"},secrets:{type:"array",description:"Environment variable list"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action((async function(e,i){const o=i.getContext(),{projectId:s}=e,n=Cu([await t.IdeApi.GetVibeProject({project_id:s}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=(a=e.env,"prod"===String(a||"dev").toLowerCase()?io.prod:io.dev);var a;const c=Cu([await po.ListProjectSecret({env:r,project_id:s,...n===t.VibeProjectType.Skill?{with_providers:!0}:{}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[];Cu([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secrets listed successfully.")]),Cu([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(c.map((e=>({secret_key:e.secret_key,secret_id:e.secret_id,secret_val:e.secret_val,secret_type:e.secret_type}))))])}))}function Eu(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 ku=i=>{const o=i.command("env").config({help:{brief:"Manage project environment variables",description:"Manage project environment variables (Secrets). Supports setting, viewing, and deleting sensitive configuration information such as API keys and database connection strings in development and production environments.",examples:[{desc:"List environment variables",cmd:"coze code env list -p <projectId>"},{desc:"Set environment variable",cmd:"coze code env set KEY VALUE -p <projectId>"},{desc:"Delete environment variable",cmd:"coze code env delete KEY -p <projectId>"}],seeAlso:["coze code deploy","coze code project"]}}).description("Manage project environment variables");Tu(o),o.command("set <key> <value>").description("Set a project environment variable").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Set project environment variable",description:"Add or update environment variables for the project. Environment variables are securely stored and used for sensitive information like API keys, passwords, etc.",examples:[{desc:"Set environment variable",cmd:"coze code env set <KEY> <VALUE> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{key:{type:"string",required:!0,description:"Environment variable key"},value:{type:"string",required:!0,description:"Environment variable value"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},key:{type:"string",description:"Set key name"},value:{type:"string",description:"Set value"}}}}},errors:[{code:e.ErrorCode.E3008,name:"SKILL_PROJECT_NOT_SUPPORTED",desc:"Skill project secret_type logic to be supplemented",fix:"This feature is not yet supported for Skill projects"}]}}).action((async function(i,o,s,n){const r=n.getContext(),{projectId:a}=s,c=Pu([await t.IdeApi.GetVibeProject({project_id:a}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(c===t.VibeProjectType.Skill)throw new e.CozeError(e.ErrorCode.E3008,"Skill project secret_type logic to be supplemented",{projectId:a,projectType:c});await po.InsertProjectSecret({project_id:a,insert_secrets:{secrets:[{secret_key:i,secret_val:o}]}}),Pu([r,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secret set successfully")]),Pu([r,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:a,key:i,value:o})])})),function(t){t.command("delete <key>").description("Delete a project environment variable").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete project environment variable",description:"Delete specified environment variables from the project. Supports deleting multiple variables simultaneously by passing the --key parameter multiple times.",examples:[{desc:"Delete a single environment variable",cmd:"coze code env delete <KEY> -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Delete multiple environment variables",cmd:"coze code env delete <KEY> -p <projectId>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},key:{type:"string",required:!0,description:"Environment variable key name to delete"}},output:{message:{type:"string",description:"Result message"},key:{type:"string",description:"Deleted key"}}},errors:[{code:e.ErrorCode.E3003,name:"SECRET_NOT_FOUND",desc:"The specified environment variable does not exist",fix:"Please use `env list` first to confirm if the variable name is correct"}]}}).action((async function(t,i,o){const s=o.getContext(),{projectId:n}=i,r=[t],a=Eu([await po.ListProjectSecret({env:io.dev,project_id:n}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],c=new Set(r.map((e=>String(e)))),d=a.filter((e=>c.has(String(e.secret_key||"")))).map((e=>e.secret_id)).filter(Boolean);if(0===d.length)throw new e.CozeError(e.ErrorCode.E3003,`No matched secrets by keys: ${r.join(", ")}`,{projectId:n,keys:r});await po.DeleteProjectSecret({project_id:n,keys:d}),Eu([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env has been delete successfully")]),Eu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({message:"env has been delete successfully",key:t,project_id:n,keys:r,secret_ids:d})])}))}(o)};function Iu(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 Au(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 ju(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 Ru=t=>{const i=t.command("domain").config({help:{brief:"Manage custom domains for the project",description:"Manage custom domains for deployed projects. Supports adding, listing, and removing domains associated with a project, used to access deployed applications.",examples:[{desc:"List project domains",cmd:"coze code domain list <projectId>"},{desc:"Add custom domain",cmd:"coze code domain add example.com -p <projectId>"},{desc:"Delete domain",cmd:"coze code domain remove example.com -p <projectId>"}],seeAlso:["coze code deploy"]}}).description("Manage custom domains for the project");i.command("list").description("List custom domains of the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List all domains bound to the project",description:"Retrieve a list of all custom domains bound to the specified project.",examples:[{desc:"List domains",cmd:"coze code domain list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Output in JSON format",cmd:"coze code domain list -p <projectId> --format json"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Domain ID"},domain_host:{type:"string",description:"Domain host"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action((async function(e,t){const i=t.getContext(),{projectId:o}=e,s=Au([await iu.PublicListDomainRelated({project_id:o}),"access",e=>e.data,"optionalAccess",e=>e.items])||[];Au([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Fetched domains List successfully")]),Au([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(s.map((e=>({id:e.id,domain_host:e.domain_host}))))])})),function(t){t.command("add <domain>").description("Add a custom domain to the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add custom domain to project",description:"Bind a custom domain to a specified project. The domain must follow standard format (e.g., example.com). Once bound, the deployed application can be accessed via this domain.",examples:[{desc:"Add domain",cmd:"coze code domain add <domain> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to add (e.g., example.com)"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},domain:{type:"string",description:"Added domain"}}}}},errors:[{code:e.ErrorCode.E1004,name:"INVALID_DOMAIN",desc:"Incorrect domain format",fix:"Please use a standard domain format, e.g., example.com"}]}}).action((async function(t,i,o){const s=o.getContext(),{projectId:n}=i;if(!/^[a-zA-Z0-9][a-zA-Z0-9-]*\.[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(t))throw new e.CozeError(e.ErrorCode.E1004,"Invalid domain",{domain:t});await iu.PublicCreateDomainRelated({project_id:n,domain:t}),ju([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Domain '${t}' added.`)]),ju([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,domain:t})])}))}(i),function(t){t.command("remove <domain>").description("Remove a custom domain from the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete custom domain of the project",description:"Remove a bound custom domain from the specified project.",examples:[{desc:"Delete domain",cmd:"coze code domain remove example.com -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to delete"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},domain:{type:"string",description:"Deleted domain"}}}}},errors:[{code:e.ErrorCode.E1004,name:"INVALID_DOMAIN",desc:"Incorrect domain format",fix:"Please use a standard domain format, e.g., example.com"},{code:e.ErrorCode.E3005,name:"DELETE_FAILED",desc:"Failed to remove domain",fix:"Please confirm the domain is bound to the project and you have sufficient permissions"}]}}).action((async function(e,t,i){const o=i.getContext(),{projectId:s}=t;await iu.PublicDeleteDomainRelated({project_id:s,domain:e}),Iu([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Domain '${e}' removed.`)]),Iu([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({message:`Domain '${e}' removed.`,domain:e})])}))}(i)};function zu(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 Uu(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 Lu(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 Ou(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 xu(i){const o=i.command("deploy <projectId>").description("Deploy the project to production environment").option("--commit-id <commitId>","Commit ID (optional, queries latest if omitted)").option("--wait","Wait for deployment to complete").config({help:{brief:"Deploy the project to production environment",description:"Deploy the specified project to the production environment. Supports multiple project types (Agent, Workflow, Skill, Web, Mini-program, etc.), automatically fetches the latest commit, and triggers the deployment process.",examples:[{desc:"Deploy latest project",cmd:"coze code deploy <projectId>",tags:["[RECOMMENDED]"]},{desc:"Deploy and wait for completion",cmd:"coze code deploy <projectId> --wait"},{desc:"Deploy a specific commit",cmd:"coze code deploy <projectId> --commit-id <commitId>"},{desc:"View deployment status",cmd:"coze code deploy status <projectId>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.E3007,name:"MISSING_COMMIT_HASH",desc:"No commits found in the project",fix:"Please commit your changes first before deploying"},{code:e.ErrorCode.E2002,name:"MINIPROGRAM_NOT_AUTHORIZED",desc:"Mini-program AppID not configured",fix:"Please complete the Mini-program AppID configuration in the project settings"},{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Project type is not supported for deployment",fix:"Please confirm the project type and try again with a supported project"}]}}).description("Deploy the project to production environment").action((async function(i,o,s){const n=s.getContext(),{wait:r,commitId:a}=o,c=Ou([(await t.IdeApi.GetVibeProject({project_id:i})).data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(!cu.canDeploy(c)){const t=`Project type ${Qd(c)} is not supported for deployment`;throw new e.CozeError(e.ErrorCode.E1006,t,{projectType:c})}if(c===t.VibeProjectType.AssistantAgent){const t=await e.axiosInstance$1.post("/api/sandbox/coze_coding/devbox/open_claw/deploy",{project_id:i},{headers:{"content-type":"application/json"}});return Ou([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying (AssistantAgent)...")]),void Ou([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({command:"deploy",status:"ok",data:{type:c,data:Ou([t,"optionalAccess",e=>e.data])}})])}let d=a;if(!d){Ou([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching latest commit...")]);const e=await cu.getCommitList({projectId:i});d=Ou([e,"optionalAccess",e=>e[0],"optionalAccess",e=>e.id])}if(!d){const t="Missing commitHash: pass --commit-hash <commitHash>";throw new e.CozeError(e.ErrorCode.E3007,t,{projectId:i})}if(c===t.VibeProjectType.WechatMiniProgram){Ou([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking Mini-program authorization...")]);if(!Ou([await iu.PublicGetAuthStatus({project_id:i,connector_id:"10000127"}),"access",e=>e.data,"optionalAccess",e=>e.bound_related_id])){const t="Deployment failed, please complete the Mini-program AppID configuration";throw new e.CozeError(e.ErrorCode.E2002,t)}}Ou([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking deploy config...")]),await iu.PublicGetDeployConfig({project_id:i,commit_hash:d},{__disableErrorToast:!0});let l="";const p=await po.ListProjectSecret({env:io.dev,project_id:i,with_providers:!0}),u=Ou([p,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],_=Ou([p,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_cred_providers])||[];Ou([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Encrypting secrets...")]);l=Ou([await po.EncryptProjectSecret({project_id:i,project_type:c===t.VibeProjectType.Skill?to.skill:void 0,encrypt_secrets:{secrets:u.map((e=>({secret_key:e.secret_key||"",secret_val:e.secret_val||"",secret_id:e.secret_id||"",secret_type:e.secret_type===oo.consumer?Ri.consumer3:Ri.user_custom2}))),...c===t.VibeProjectType.Skill?{cred_providers:_}:{}}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.sealed_secrets])||"",Ou([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying...")]);const h=Ou([await iu.PublicCreateDeployHistory({project_id:i,encrypt_env_variable:l,commit_hash:d}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_id]);Ou([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploy started.")]),r&&h?await cu.pollDeployStatus({projectId:i,deployHistoryId:h,onBeforePoll:()=>{Ou([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const t=nu(e.status);Ou([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",o=>o({projectId:i,status:t,domain:Ou([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:h,commitHash:e.commit_hash})])}}):Ou([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({projectId:i,status:nu(Rp.Pending),domain:"",deployHistoryId:h,commitHash:d})])}));!function(t){t.command("status <projectId>").description("Check deployment status").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest if omitted)").config({help:{brief:"Query project deployment status",description:"Query the deployment status of a specified project. If no deployment history ID is specified, it automatically queries the latest deployment record. Supports viewing deployment progress, results, and error messages.",examples:[{desc:"Query latest deployment status",cmd:"coze code deploy status <projectId>",tags:["[RECOMMENDED]"]},{desc:"Query specific deployment record",cmd:"coze code deploy status <projectId> --deploy-id <deployHistoryId>"},{desc:"Wait for deployment to complete",cmd:"coze code deploy status <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (optional, queries latest if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.E3006,name:"NO_DEPLOYMENT_HISTORY",desc:"No deployment history found for this project",fix:"Please deploy the project first using `coze code deploy <projectId>`"}]}}).action((async function(t,i,o){const s=o.getContext(),{deployId:n}=i,{wait:r}=zu([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=n;if(!a&&(zu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("get latest deployment record...")]),a=await cu.getLatestDeployHistoryId({projectId:t}),!a))throw new e.CozeError(e.ErrorCode.E3006,"No deployment history found for this project");if(r)await cu.pollDeployStatus({projectId:t,deployHistoryId:a,onBeforePoll:()=>{zu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const i=nu(e.status);zu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",o=>o({projectId:t,status:i,domain:zu([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:a,commitHash:e.commit_hash})])}});else{zu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Querying deployment status...")]);const e=await cu.getDeployHistory({projectId:t,deployHistoryId:a}),i=nu(e.status),o=e.domain_list||[];zu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",s=>s({projectId:t,status:i,domain:o[0],deployHistoryId:a,commitHash:e.commit_hash})])}}))}(o),function(e){e.command("list <projectId>").description("List deployment history for a project").option("--page-size <pageSize>","Number of records per page","10").option("--page-token <pageToken>","Page token for pagination").config({help:{brief:"List project deployment history",description:"List the deployment history of a specified project. Supports pagination to browse historical deployment records including status, commit hash, domains and timestamps.",examples:[{desc:"List deployment history",cmd:"coze code deploy list <projectId>",tags:["[RECOMMENDED]"]},{desc:"List with custom page size",cmd:"coze code deploy list <projectId> --page-size 20"},{desc:"List next page",cmd:"coze code deploy list <projectId> --page-token <token>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},pageSize:{type:"number",required:!1,description:"Number of records per page (default: 10)"},pageToken:{type:"string",required:!1,description:"Page token for pagination"}},output:{type:"array",items:{deploy_history_id:{type:"string",description:"Deployment history ID"},status:{type:"string",description:"Deployment status"},commit_hash:{type:"string",description:"Commit hash"},domain_list:{type:"array",description:"Deployed domains"},created_at:{type:"string",description:"Creation timestamp"}}}}}}).action((async function(e,t,i){const o=i.getContext(),s=Number(t.pageSize)||10,n=(Uu([await iu.PublicListDeployHistory({project_id:e,page_size:s,page_token:t.pageToken}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list])||[]).map((e=>({deploy_history_id:e.deploy_history_id,project_id:e.project_id,status:nu(e.status),commit_hash:e.commit_hash_short||e.commit_hash,domain_list:e.domain_list,created_at:e.created_at,can_rollback:e.can_rollback})));Uu([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)])}))}(o),function(t){t.command("fix <projectId>").description("Fix a failed deployment by sending deploy logs to AI").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest failed if omitted)").option("--wait","Wait for fix message response").config({help:{brief:"Fix a failed deployment",description:"Diagnose and fix a failed deployment. Retrieves deploy logs and sends them to AI for analysis and automatic fix. Only works when the deployment status is Failed.",examples:[{desc:"Fix latest failed deployment",cmd:"coze code deploy fix -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Fix a specific deployment",cmd:"coze code deploy fix <projectId> --deploy-id <deployId>"},{desc:"Fix and wait for result",cmd:"coze code deploy fix <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (queries latest failed if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for fix message response"}},output:{type:"object",properties:{deploy_history_id:{type:"string"},status:{type:"string"},message:{type:"string"}}}}}}).action((async function(t,i,o){const s=o.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const{deployId:n}=i,{wait:r}=Lu([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=n;if(n||(a=await cu.getLatestDeployHistoryId({projectId:t})),!a)throw new e.CozeError(e.ErrorCode.E5002,`No deploy history found for project ${t}`,{project_id:t});const c=Lu([await iu.PublicGetDeployHistory({project_id:t,deploy_history_id:a}),"optionalAccess",e=>e.data]);if(Lu([c,"optionalAccess",e=>e.status])!==Rp.Failed){const t=nu(Lu([c,"optionalAccess",e=>e.status]));throw new e.CozeError(e.ErrorCode.E3009,`Deployment ${a} is not in Failed status (current: ${t}). Only failed deployments can be fixed.`,{deploy_history_id:a,status:Lu([c,"optionalAccess",e=>e.status])})}const d=c.deploy_log_url;if(!d)throw new e.CozeError(e.ErrorCode.E5002,`No deploy log URL found for deployment ${a}`,{deploy_history_id:a});const l=await e.customFetch.fetch(d,{method:"GET"}),p=await l.text();if(!p)throw new e.CozeError(e.ErrorCode.E5002,`Deploy log is empty for deployment ${a}`,{deploy_history_id:a,deploy_log_url:d});const u=`修复以下部署错误:\n${p}`,_=await Lu([s,"access",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!_)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(r){const e=await il.sendMessage({projectId:t,prompt:u,apiBaseUrl:s.config.apiBaseUrl,accessToken:_,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${t}`});Lu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({deploy_history_id:a,status:"fix_sent",message:e.lastAnswerMessage})])}else il.sendMessageRunTask({projectId:t,prompt:u,apiBaseUrl:s.config.apiBaseUrl,accessToken:_,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${t}`})}))}(o)}function Bu(i){const o=i.command("code").description("Coze Coding CLI utilities").config({help:{brief:"Coze Coding project management",description:"Manage Coze Coding projects, including project creation, messaging, deployment, environment variables, domains, skills, and previews.",examples:[{desc:"Create a new project",cmd:'coze code project create --message "Create a chatbot" --type web'},{desc:"Send a message",cmd:'coze code message send "Fix the bug" -p <projectId>'},{desc:"Deploy project",cmd:"coze code deploy <projectId>"},{desc:"Preview project",cmd:"coze code preview <projectId>"}],seeAlso:["coze auth","coze space","coze organization"]}});Su(o),xu(o),rl(o),ku(o),Ru(o),(e=>{const t=e.command("skill").config({help:{brief:"Manage project skills",description:"Manage skills associated with a project. Skills are important components to extend project capabilities, supporting adding, viewing, and removing project skills.",examples:[{desc:"List project skills",cmd:"coze code skill list -p <projectId>"},{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>"},{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>"}],seeAlso:["coze code project"]}}).description("Manage project skills");uc(t),hc(t),dc(t)})(o),function(i){i.command("preview <projectId>").description("Get deployment preview info for the project").config({help:{brief:"Get project preview URL",description:"Get the sandbox preview URL for the project. Supports AssistantAgent and GeneralWeb project types, returning an accessible preview URL. Sandbox initialization takes 1-3 minutes.",examples:[{desc:"Get preview URL",cmd:"coze code preview <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:{type:"string",description:"Project type"},preview_url:{type:"string",description:"Preview URL"}}},errors:[{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Unsupported project type",fix:"Preview feature only supports AssistantAgent and GeneralWeb project types"},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Missing required argument: projectId",fix:"Pass <projectId> as the first argument: `coze code preview <projectId>`",example:"coze code preview 123456"}]}}).action((async function(i,o,s){const n=s.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E1000,"Missing projectId: pass <projectId> as argument");const r=await t.IdeApi.GetVibeProject({project_id:i}),a=du([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=du([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.name]),d={type:Qd(a)};if(!il.isValidType(a))throw new e.CozeError(e.ErrorCode.E1006,"Unsupported project type",{projectId:i,type:a});if(a===t.VibeProjectType.Skill){const e=await cu.getCommitList({projectId:i});du([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating preview task...")]);const t=await Sp.CreateCozeSpaceTask({task_name:`${c}-preview-${du([e,"access",e=>e[0],"optionalAccess",e=>e.id])}`,task_type:1,is_debug:!0,source_from:sp.UserCreate,mcp_tool_list:[]});d.preview_url=`https://www.coze.cn/task-m/${t.data.task.task_id}`,du([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Preview task created. Please access the preview URL: ${d.preview_url}`)])}else{const e=await t.IdeApi.InitSandbox({project_id:i});d.preview_url=e.token?`https://${e.project_host}?token=${e.token}`:`https://${e.project_host}`,du([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Sandbox initialization started. Please access the preview URL in 1-3 minutes,preview_url: ${d.preview_url}`)])}du([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(d)])}))}(o)}const qu=async e=>await new Promise((t=>setTimeout(t,e)));function Du(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 Mu=e=>{if(!e)return;const t=e.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);if(Du([t,"optionalAccess",e=>e[1]]))return(e=>{try{return decodeURIComponent(e)}catch(t){return URIError,e}})(t[1]);const i=e.match(/filename\s*=\s*"([^"]+)"/i);if(Du([i,"optionalAccess",e=>e[1]]))return i[1];const o=e.match(/filename\s*=\s*([^;]+)/i);return Du([o,"optionalAccess",e=>e[1]])?o[1].trim():void 0},Nu=async({url:t,outputPath:i,fetchImpl:o=t=>e.customFetch.fetch(t)})=>{const{buffer:s,response:n}=await(async(t,i)=>{const o=await i(t);if(!o.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download session file: ${o.status} ${o.statusText}`);return{buffer:Buffer.from(await o.arrayBuffer()),response:o}})(t,o),r=i||(e=>{const t=Mu((i=e.contentDisposition,o=()=>null,null!=i?i:o()));var i,o;if(t)return t;for(const t of[e.responseUrl,e.requestUrl]){if(!t||!URL.canParse(t))continue;const e=new URL(t),i=c.basename(decodeURIComponent(e.pathname));if(i&&"/"!==i&&"."!==i)return i}return"session-file.bin"})({requestUrl:t,responseUrl:n.url,contentDisposition:n.headers.get("content-disposition")}),a=await Cr(r,s);return{path:a,filename:c.basename(a),size:s.byteLength,url:t}},Gu="1008033";function $u(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 Fu=async({baseUrl:t,headers:i,xTTEnv:o})=>{const n=new URL("/api/coze_claw/resource/get_frontier_key",s.normalizeBaseUrl(t));s.appendSearchParams(n,{aid:Gu});const r={...i,...s.getPpeHeaders(o)},a=await e.customFetch.fetch(n.toString(),{method:"GET",headers:r}),c=await s.parseServiceResponseBody(a,{}),d=s.getServiceResponseLogId(a);if(!a.ok)throw new Error(s.formatServiceErrorWithLogId({fallback:`Failed to get frontier key: ${a.status} ${a.statusText}`,logId:d,message:c.msg}));const l=$u([c,"access",e=>e.data,"optionalAccess",e=>e.access_key]),p=$u([c,"access",e=>e.data,"optionalAccess",e=>e.device_id]);if(!l||!p)throw new Error(s.formatServiceErrorWithLogId({fallback:"Frontier key response is incomplete",logId:d,message:c.msg}));return{accessKey:l,deviceId:p}};function Vu(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 Wu=async({filePaths:t,clawId:i,sessionId:o,accessFile:s=u.access,createFileReadStream:n=l.openAsBlob,uploadFile:r})=>{const a=[];for(const d of t){try{await s(d)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${d}${t instanceof Error?` (${t.message})`:""}`)}const t=c.basename(d),l=await r({fileName:t,fileContent:await n(d),clawId:i,sessionId:o}),p=Vu([l,"access",e=>e.data,"optionalAccess",e=>e.file]);if(!Vu([p,"optionalAccess",e=>e.file_uri])||!Vu([p,"optionalAccess",e=>e.file_url]))throw new e.CozeError(e.ErrorCode.E5002,l.msg||`Failed to upload session file: ${d}`);a.push({file_name:p.file_name||t,file_uri:p.file_uri,file_url:p.file_url})}return a},Hu=async({filePaths:e,sessionId:t,apiBaseUrl:i,sessionApiBaseUrl:o,sessionSpaceWebId:n,xTTEnv:r,service:a,deps:c})=>{if(!e||0===e.length)return[];const d=Vu([c,"optionalAccess",e=>e.store])||s.createSessionConfigStore(),{sessionClawId:l}=await d.get(),p=l||(await a.getStatus()).clawId;if(!p)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const u=o||i,_=await(async({sessionSpaceWebId:e,baseUrl:t,xTTEnv:i})=>{if(e)return e;try{return(await Fu({baseUrl:t,headers:{},xTTEnv:i})).deviceId}catch(e){return}})({sessionSpaceWebId:n,baseUrl:u,xTTEnv:r}),h=(Vu([c,"optionalAccess",e=>e.createApi])||s.createSessionApiClient)({baseUrl:u,webOrigin:u,xSpaceWebId:_,xTTEnv:r}),m=Vu([c,"optionalAccess",e=>e.uploadFiles])||Wu;return await m({filePaths:e,clawId:p,sessionId:t,uploadFile:({fileName:e,fileContent:t,clawId:i,sessionId:o})=>h.uploadFile({fileName:e,fileContent:t,clawId:i,sessionId:o})})};function Ju(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 Ku=1048576,Qu=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,Yu=({absolutePath:e,root:t})=>{const i=c.relative(t,e);return Boolean(i)&&!i.startsWith("..")&&!c.isAbsolute(i)},Zu=async({onWarn:e,shouldWarnInvalidMention:t=()=>!0,statFile:i=u.stat,userInput:o,workTree:s})=>{(e=>{if(e.length>Ku)throw new Error("Message input is too long: max 1048576 characters")})(o);const n=[...o.matchAll(Qu)];if(0===n.length)return[{type:"text",text:o}];const r=[],a=c.resolve(s);let d=0;for(const s of n){const n=s.index,l=s[0],p=s[1];n>d&&r.push({type:"text",text:o.slice(d,n)});const u=c.resolve(a,p);let _=!1;if(Yu({absolutePath:u,root:a}))try{(await i(u)).isFile()?_=!0:t(p)&&Ju([e,"optionalCall",e=>e(`Uploading directories is not supported: ${p}`)])}catch(i){t(p)&&Ju([e,"optionalCall",e=>e(`File not found: ${p}`)])}_?r.push({type:"file",absolutePath:u,rawMention:l,relativePath:p}):r.push({type:"text",text:l}),d=n+l.length}return d<o.length&&r.push({type:"text",text:o.slice(d)}),r};const Xu=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},e_=e=>e.includes("/")||e.includes("\\")||e.includes(".")||e.startsWith("."),t_=async(e,t={})=>{const i=await(async e=>{const t=await br(),i=Xu(e),o=Xu(t);return i||o?i&&o?`${i}\n\n${o}`:(n=()=>o,null!=(s=i)?s:n()):null;var s,n})(e);if(!i)return{content:i,filePaths:[]};const o=await Zu({onWarn:t.onWarn,shouldWarnInvalidMention:e_,userInput:i,workTree:t.cwd||process.cwd()}),s=[];return{content:Xu(o.map((e=>"text"===e.type?e.text:(s.push(e.absolutePath),""))).join("")),filePaths:s}};const i_=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(),"access",e=>e.toLowerCase,"call",e=>e()])||"",o_=async({baseUrl:t,xTTEnv:i,fetchImpl:o=e.customFetch.fetch.bind(e.customFetch)})=>{const s={"content-type":"application/json"};i&&(s["x-use-ppe"]="1",s["x-tt-env"]=i);const n=await o(`${(e=>new URL(e).origin)(t)}/api/coze_space/get_podcast_config`,{method:"POST",headers:s,body:"{}"});if(!n.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to fetch podcast config: ${String(n.status||"")} ${String(n.statusText||"")}`.trim());const r=await n.json();if(0!==r.code&&void 0!==r.code)throw new e.CozeError(e.ErrorCode.E5002,r.msg||"Failed to fetch podcast config");return r.data||{}},s_=({config:t,mode:i,keyword:o})=>{const s=(({config:t,mode:i})=>{if(!i)return;const o=i_(i),s=(t.mode_options||[]).find((e=>i_(e.value)===o||i_(e.label)===o));if(!s)throw new e.CozeError(e.ErrorCode.E1000,`Podcast mode not found: ${i}`);return s})({config:t,mode:i}),n=i_(o);return(s?[s]:t.mode_options||[]).flatMap((e=>(e.voice_options||[]).map((t=>({mode_label:e.label,mode_value:e.value,label:t.label,value:t.value,sample:t.sample,color_code:t.color_code}))).filter((e=>!n||(i_(e.label).includes(n)||i_(e.value).includes(n))))))};
16
+ ***************************************************************************** */var te=function(){return te=Object.assign||function(e){for(var t,i=1,o=arguments.length;i<o;i++)for(var s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},te.apply(this,arguments)};function ie(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var o,s,n=i.call(e),r=[];try{for(;(void 0===t||t-- >0)&&!(o=n.next()).done;)r.push(o.value)}catch(e){s={error:e}}finally{try{o&&!o.done&&(i=n.return)&&i.call(n)}finally{if(s)throw s.error}}return r}function oe(e,t,i){if(2===arguments.length)for(var o,s=0,n=t.length;s<n;s++)!o&&s in t||(o||(o=Array.prototype.slice.call(t,0,s)),o[s]=t[s]);return e.concat(o||Array.prototype.slice.call(t))}var se=function(){return{}};function ne(e){return e}function re(e){return"object"==typeof e&&null!==e}var ae=Object.prototype;function ce(e){return"[object Array]"===ae.toString.call(e)}function de(e){return"number"==typeof e}function le(e){return"string"==typeof e}function pe(e,t){if(!ce(e))return!1;if(0===e.length)return!1;for(var i=0;i<e.length;){if(e[i]===t)return!0;i++}return!1}var ue=function(e,t){if(!ce(e))return e;var i=e.indexOf(t);if(i>=0){var o=e.slice();return o.splice(i,1),o}return e};function _e(e){try{return le(e)?e:JSON.stringify(e)}catch(e){return"[FAILED_TO_STRINGIFY]:"+String(e)}}var he="".padStart?function(e,t){return void 0===t&&(t=8),e.padStart(t," ")}:function(e){return e},me=0,ge=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,oe(["[SDK]",Date.now(),he(""+me++)],ie(e),!1))},fe=0,ye=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,oe(["[SDK]",Date.now(),he(""+fe++)],ie(e),!1))},ve=function(e){return Math.random()<Number(e)},we=function(e,t){return e<Number(t)},be=function(e){return function(t){for(var i=t,o=0;o<e.length&&i;o++)try{i=e[o](i)}catch(e){ge(e)}return i}};function Se(){var e=function(){for(var e=new Array(16),t=0,i=0;i<16;i++)3&i||(t=4294967296*Math.random()),e[i]=t>>>((3&i)<<3)&255;return e}();return e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){for(var t=[],i=0;i<256;++i)t[i]=(i+256).toString(16).substr(1);var o=0,s=t;return[s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]]].join("")}(e)}var Pe=["init","start","config","beforeDestroy","provide","beforeReport","report","beforeBuild","build","beforeSend","send","beforeConfig"];function Ce(e){var t,i,o=e.builder,s=e.createSender,n=e.createDefaultConfig,r=e.createConfigManager,a=e.userConfigNormalizer,c=e.initConfigNormalizer,d=e.validateInitConfig,l={};Pe.forEach((function(e){return l[e]=[]}));var p=!1,u=!1,_=!1,h=[],m=[],g=function(){var e=!1,t={},i=function(e){e.length&&e.forEach((function(e){try{e()}catch(e){}})),e.length=0},o=function(e){t[e]&&t[e].forEach((function(e){i(e[1])})),t[e]=void 0};return{set:function(o,s,n){t[o]?t[o].push([s,n]):t[o]=[[s,n]],e&&i(n)},has:function(e){return!!t[e]},remove:o,removeByEvType:function(e){Object.keys(t).forEach((function(o){t[o]&&t[o].forEach((function(t){t[0]===e&&i(t[1])}))}))},clear:function(){e=!0,Object.keys(t).forEach((function(e){o(e)}))}}}(),f={getBuilder:function(){return o},getSender:function(){return t},getPreStartQueue:function(){return h},init:function(e){if(p)ye("already inited");else{if(!(e&&re(e)&&d(e)))throw new Error("invalid InitConfig, init failed");var o=n(e);if(!o)throw new Error("defaultConfig missing");var a=c(e);if((i=r(o)).setConfig(a),i.onChange((function(){y("config")})),!(t=s(i.getConfig())))throw new Error("sender missing");p=!0,y("init",!0)}},set:function(e){p&&e&&re(e)&&(y("beforeConfig",!1,e),null==i||i.setConfig(e))},config:function(e){if(p)return e&&re(e)&&(y("beforeConfig",!1,e),null==i||i.setConfig(a(e))),null==i?void 0:i.getConfig()},provide:function(e,t){pe(m,e)?ye("cannot provide "+e+", reserved"):(f[e]=t,y("provide",!1,e))},start:function(){p&&(u||null==i||i.onReady((function(){u=!0,y("start",!0),function(e){var t=e.getPreStartQueue();t.forEach((function(t){return e.build(t)})),t.length=0}(f)})))},report:function(e){if(e){var t=be(l.beforeReport)(e);if(t){var i=be(l.report)(t);i&&(u?this.build(i):function(e,t,i){if(t.push(i),!(t.length<500)){var o=t.splice(0,50);e.savePreStartDataToDb&&e.savePreStartDataToDb(o)}}(f,h,i))}}},build:function(e){if(u){var t=be(l.beforeBuild)(e);if(t){var i=o.build(t);if(i){var s=be(l.build)(i);s&&this.send(s)}}}},send:function(e){if(u){var i=be(l.beforeSend)(e);i&&(t.send(i),y("send",!1,i))}},destroy:function(){g.clear(),_=!0,h.length=0,y("beforeDestroy",!0)},on:function(e,t){if("init"===e&&p||"start"===e&&u||"beforeDestroy"===e&&_)try{t()}catch(e){}else l[e]&&l[e].push(t)},off:function(e,t){l[e]&&(l[e]=ue(l[e],t))},destroyAgent:g};return m=Object.keys(f),f;function y(e,t){void 0===t&&(t=!1);for(var i=[],o=2;o<arguments.length;o++)i[o-2]=arguments[o];l[e].forEach((function(e){try{e.apply(void 0,oe([],ie(i),!1))}catch(e){}})),t&&(l[e].length=0)}}var Te=function(e){var t=function(){var e={},t={},i={set:function(o,s){return e[o]=s,t[o]=_e(s),i},merge:function(o){return e=te(te({},e),o),Object.keys(o).forEach((function(e){t[e]=_e(o[e])})),i},delete:function(o){return delete e[o],delete t[o],i},clear:function(){return e={},t={},i},get:function(e){return t[e]},toString:function(){return te({},t)}};return i}();e.provide("context",t),e.on("report",(function(e){return e.extra||(e.extra={}),e.extra.context=t.toString(),e}))};var Ee=function(){return Date.now()};var Ie=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=function(e){if(e)return e.__SLARDAR_REGISTRY__||(e.__SLARDAR_REGISTRY__={Slardar:{plugins:[],errors:[],subject:{}}}),e.__SLARDAR_REGISTRY__.Slardar}(function(){if("object"==typeof window&&re(window))return window}());i&&(i.errors||(i.errors=[]),i.errors.push(e))},ke="custom",Ae=function(e){var t=function(i){var o=function(e){if(e&&re(e)&&e.name&&le(e.name)){var t={name:e.name,type:"event"};if("metrics"in e&&re(e.metrics)){var i=e.metrics,o={};for(var s in i)de(i[s])&&(o[s]=i[s]);t.metrics=o}if("categories"in e&&re(e.categories)){var n=e.categories,r={};for(var s in n)r[s]=_e(n[s]);t.categories=r}return"attached_log"in e&&le(e.attached_log)&&(t.attached_log=e.attached_log),t}}(i);if(o){var s=function(e){var t;if("object"==typeof window&&window.__perfsee__){var i={};return null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,i,e),i.stack}}(t);s&&(o.stacks=s),e.report({ev_type:ke,payload:o,extra:{timestamp:Ee()}})}};e.provide("sendEvent",t),e.provide("sendLog",(function(t){var i=function(e){if(e&&re(e)&&e.content&&le(e.content)){var t={content:_e(e.content),type:"log",level:"info"};if("level"in e&&(t.level=e.level),"extra"in e&&re(e.extra)){var i=e.extra,o={},s={};for(var n in i)de(i[n])?o[n]=i[n]:s[n]=_e(i[n]);t.metrics=o,t.categories=s}return"attached_log"in e&&le(e.attached_log)&&(t.attached_log=e.attached_log),t}}(t);i&&e.report({ev_type:ke,payload:i,extra:{timestamp:Ee()}})}))},je=function(e,t){var i=e.common||{};return i.sample_rate=t,e.common=i,e},Re=function(e,t,i,o,s){return e?(n=s(o,t),function(){return n}):function(){return i(t)};var n},ze=function(e,t,i,o){var s=function(e,t,i){for(var o,s=ie(t.split(".")),n=s[0],r=s.slice(1);e&&r.length>0;)e=e[n],n=(o=ie(r))[0],r=o.slice(1);if(e)return i(e,n)}(e,t,(function(e,t){return e[t]}));return void 0!==s&&function(e,t,i){switch(i){case"eq":return pe(t,e);case"neq":return!pe(t,e);case"gt":return e>t[0];case"gte":return e>=t[0];case"lt":return e<t[0];case"lte":return e<=t[0];case"regex":return Boolean(e.match(new RegExp(t.join("|"))));case"not_regex":return!e.match(new RegExp(t.join("|")));default:return!1}}(s,function(e,t){return e.map((function(e){switch(t){case"number":return Number(e);case"boolean":return"1"===e;default:return String(e)}}))}(o,"boolean"==typeof s?"bool":de(s)?"number":"string"),i)},Le=function(e,t){try{return"rule"===t.type?ze(e,t.field,t.op,t.values):"and"===t.type?t.children.every((function(t){return Le(e,t)})):t.children.some((function(t){return Le(e,t)}))}catch(e){return Ie(e),!1}},Ue=function(e,t,i,o,s){if(!t)return ne;var n=t.sample_rate,r=t.include_users,a=t.sample_granularity,c=t.rules,d=t.r,l=void 0===d?Math.random():d;if(pe(r,e))return function(e){return je(e,1)};var p="session"===a,u=Re(p,n,i,l,o),_=function(e,t,i,o,s,n){var r={};return Object.keys(e).forEach((function(a){var c=e[a],d=c.enable,l=c.sample_rate,p=c.conditional_sample_rules;d?(r[a]={enable:d,sample_rate:l,effectiveSampleRate:l*i,hit:Re(t,l,o,s,n)},p&&(r[a].conditional_hit_rules=p.map((function(e){var r=e.sample_rate,a=e.filter;return{sample_rate:r,hit:Re(t,r,o,s,n),effectiveSampleRate:r*i,filter:a}})))):r[a]={enable:d,hit:function(){return!1},sample_rate:0,effectiveSampleRate:0}})),r}(c,p,n,i,l,o);return function(e){var t;if(!u())return p&&s[0](),!1;if(!(e.ev_type in _))return je(e,n);if(!_[e.ev_type].enable)return p&&s[1](e.ev_type),!1;if(null===(t=e.common)||void 0===t?void 0:t.sample_rate)return e;var i=_[e.ev_type],o=i.conditional_hit_rules;if(o)for(var r=0;r<o.length;r++)if(Le(e,o[r].filter))return!!o[r].hit()&&je(e,o[r].effectiveSampleRate);return i.hit()?je(e,i.effectiveSampleRate):((!o||!o.length)&&p&&s[1](e.ev_type),!1)}},Oe={build:function(e){return{ev_type:e.ev_type,payload:e.payload,common:te(te({},e.extra||{}),e.overrides||{})}}},xe={sample_rate:1,include_users:[],sample_granularity:"session",rules:{}};function Be(e){var t,i;try{for(var o=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],o=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&o>=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(["userId","deviceId","sessionId","env"]),s=o.next();!s.done;s=o.next()){var n=s.value;e[n]||delete e[n]}}catch(e){t={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}return e}function qe(e){return Be(te({},e))}function De(e){return re(e)&&"bid"in e&&"transport"in e}function Me(e){return Be(te({},e))}var Ne=function(e,t){return void 0===t&&(t="/monitor_browser/collect/batch/"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Ge=function(e,t){return void 0===t&&(t="/monitor_web/settings/browser-settings"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},$e=function(e){var t,i,o=e,s={},n=se,r=se;return{getConfig:function(){return o},setConfig:function(e){return s=te(te({},s),e||{}),a(),t||(t=e,o.useLocalConfig||!o.bid?(i={},n()):function(e,t,i,o){if(!e.get)return o({});e.get({withCredentials:!0,url:Ge(t)+"?bid="+i+"&store=1",success:function(e){o(e.data||{})},fail:function(){o({sample:{sample_rate:.001}})}})}(o.transport,o.domain,o.bid,(function(e){i=function(e){if(!e)return{};var t=e.sample,i=e.timestamp,o=e.quota_rate,s=void 0===o?1:o;if(!t)return{};var n=t.sample_rate,r=t.sample_granularity,a=void 0===r?"session":r,c=t.include_users,d=t.rules;return{sample:{include_users:c,sample_rate:n*s,sample_granularity:a,rules:(void 0===d?[]:d).reduce((function(e,t){var i=t.name,o=t.enable,s=t.sample_rate,n=t.conditional_sample_rules;return e[i]={enable:o,sample_rate:s,conditional_sample_rules:n},e}),{})},serverTimestamp:i}}(e),a(),n()}))),o},onChange:function(e){r=e},onReady:function(e){n=e,i&&n()}};function a(){var t=te(te(te({},e),i||{}),s);t.sample=Fe(Fe(e.sample,null==i?void 0:i.sample),s.sample),o=t,r()}};function Fe(e,t){if(!e||!t)return e||t;var i=te(te({},e),t);return i.include_users=oe(oe([],ie(e.include_users||[]),!1),ie(t.include_users||[]),!1),i.rules=oe(oe([],ie(Object.keys(e.rules||{})),!1),ie(Object.keys(t.rules||{})),!1).reduce((function(i,o){var s,n;return o in i||(o in(e.rules||{})&&o in(t.rules||{})?(i[o]=te(te({},e.rules[o]),t.rules[o]),i[o].conditional_sample_rules=oe(oe([],ie(e.rules[o].conditional_sample_rules||[]),!1),ie(t.rules[o].conditional_sample_rules||[]),!1)):i[o]=(null===(s=e.rules)||void 0===s?void 0:s[o])||(null===(n=t.rules)||void 0===n?void 0:n[o])),i}),{}),i}var Ve=function(e){e.on("report",(function(t){return function(e,t){var i=t||{},o=i.version,s=i.name,n={url:"",protocol:"",domain:"",path:"",query:"",timestamp:Date.now(),sdk_version:o||"2.1.8",sdk_name:s||"SDK_BASE"};return te(te({},e),{extra:te(te({},n),e.extra||{})})}(t,e.config())}))},We=function(e){e.on("beforeBuild",(function(t){return function(e,t){var i={};return i.bid=t.bid,i.pid=t.pid,i.view_id=t.viewId,i.user_id=t.userId,i.device_id=t.deviceId,i.session_id=t.sessionId,i.release=t.release,i.env=t.env,te(te({},e),{extra:te(te({},i),e.extra||{})})}(t,e.config())}))};var He=function(e){return{bid:"",pid:"",viewId:(t="_",t+"_"+Date.now()),userId:Se(),deviceId:Se(),sessionId:Se(),domain:"mon.zijieapi.com",release:"",env:"production",sample:xe,plugins:{},transport:{get:se,post:se},useLocalConfig:!1};var t},Je=function(e){var t=void 0===e?{}:e,i=t.createSender,o=void 0===i?function(e){return function(e){return ee(e)}({size:20,endpoint:Ne(e.domain),transport:e.transport})}:i,s=t.builder,n=void 0===s?Oe:s,r=t.createDefaultConfig,a=Ce({validateInitConfig:De,initConfigNormalizer:qe,userConfigNormalizer:Me,createSender:o,builder:n,createDefaultConfig:void 0===r?He:r,createConfigManager:$e});return Te(a),We(a),Ve(a),function(e){e.on("init",(function(){var t=[],i=function(i){i.forEach((function(i){var o=i.name;pe(t,o)||(t.push(o),i.setup(e),e.destroyAgent.set(o,o,[function(){t=ue(t,o),i.tearDown&&i.tearDown()}]))}))};e.provide("applyIntegrations",i);var o=e.config();o&&o.integrations&&i(o.integrations)}))}(a),function(e){try{"object"==typeof window&&re(window)&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__.push(e)}catch(e){}}(a),a},Ke=function(e){void 0===e&&(e={});var t=Je(e);return function(e){e.on("start",(function(){var t=e.config(),i=t.userId,o=t.sample,s=Ue(i,o,ve,we,[function(){e.destroy()},function(t){e.destroyAgent.removeByEvType(t)}]);e.on("build",s)}))}(t),Ae(t),t}();const Qe=X("slardar:transport"),Ye=()=>{};function Ze(e){const{url:t,method:i,data:o,success:s=Ye,fail:a=Ye,getResponseText:c=Ye}=e;if(Qe("Making %s request to %s",i,t),o&&Qe("Request data: %s",o.slice(0,200)),!t||"string"!=typeof t){const e=new Error(`Invalid URL: ${t}`);return Qe("Invalid URL provided: %o",t),void a(e)}try{const e=new URL(t);Qe("Parsed URL - protocol: %s, hostname: %s, port: %s, path: %s",e.protocol,e.hostname,e.port,e.pathname);const d="https:"===e.protocol,l=(d?r.request:n.request)({hostname:e.hostname,port:e.port,path:e.pathname+e.search,method:i,headers:{"Content-Type":"application/json",...o&&{"Content-Length":Buffer.byteLength(o)}}},(e=>{Qe("Response callback triggered: status=%s",e.statusCode);let t="";e.on("data",(e=>{Qe("Response data chunk received: %s bytes",e.length),t+=e.toString()})),e.on("end",(()=>{Qe("Response end event fired"),Qe("Response received: status=%s, body=%s",e.statusCode,t.slice(0,200)),c(t);try{if(e.statusCode&&e.statusCode>=400)Qe("Request failed with status %s: %s",e.statusCode,t),a(new Error(t||e.statusMessage||"Request failed"));else if(t){const e=JSON.parse(t);Qe("Request succeeded"),s(e)}else Qe("Request succeeded with empty response"),s({})}catch(e){Qe("Failed to parse response: %s",e.message),a(e)}}))}));l.on("error",(e=>{Qe("Request error: %s",e.message),a(e)})),l.on("timeout",(()=>{Qe("Request timeout"),l.destroy(),a(new Error("Request timeout"))})),o&&l.write(o),l.end()}catch(e){Qe("Exception during request: %s",e.message),a(e)}}function Xe(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 et=X("slardar:reporter");class it{constructor(){it.prototype.__init.call(this),it.prototype.__init2.call(this)}__init(){this.initialized=!1}__init2(){this.client=Ke}setup(e){var t,i;if(this.initialized)et("Already initialized, skipping setup");else try{et("Initializing Slardar with config:",{bid:e.bid,release:e.release,env:e.env,userId:e.userId,projectId:e.projectId});const o={get(e){Qe("Transport GET called: %s",e.url),Ze({method:"GET",...e})},post({url:e,data:t}){Qe("Transport POST called: %s",e),Ze({method:"POST",url:e,data:t?"string"==typeof t?t:JSON.stringify(t):void 0})}};this.client.init({bid:e.bid,transport:o,userId:e.userId,pid:e.projectId,deviceId:e.deviceId,sessionId:e.sessionId,release:e.release,env:e.env,name:e.name,useLocalConfig:(t=e.useLocalConfig,i=()=>!1,null!=t?t:i()),domain:e.domain,sample:{sample_rate:1,include_users:[],sample_granularity:"session",rules:{}}}),this.client.on("send",(e=>{et("send hook called for event: %s",Xe([e,"optionalAccess",e=>e.ev_type])||"unknown")})),this.client.start(),this.initialized=!0,et("Slardar initialized successfully")}catch(e){et("Failed to initialize:",e)}}ensureInitialized(){return!!this.initialized||(et("Not initialized, call setup() first"),!1)}sendEvent(e,t,i){if(this.ensureInitialized())try{et("Sending event:",{name:e,metrics:t,categories:i});const o=t?Object.fromEntries(Object.entries(t).filter((([,e])=>void 0!==e))):void 0,s=i?Object.fromEntries(Object.entries(i).filter((([,e])=>void 0!==e))):void 0;Xe([this,"access",e=>e.client,"access",e=>e.sendEvent,"optionalCall",t=>t({name:e,metrics:o,categories:s})])}catch(e){et("Failed to send event:",e)}}sendLog(e,t,i){if(this.ensureInitialized())try{et("Sending log:",{level:e,message:t,extra:i}),this.sendEvent("cli_log",void 0,{level:e,message:t,...i})}catch(e){et("Failed to send log:",e)}}reportError(e,t,i){if(this.ensureInitialized())try{const o={ev_type:"js_error",payload:{error:{name:e.name,message:e.message,stack:e.stack},breadcrumbs:[],extra:t,source:i||{type:"manual"}}};et("Reporting JS error:",{name:e.name,message:e.message.slice(0,100),stack:Xe([e,"access",e=>e.stack,"optionalAccess",e=>e.slice,"call",e=>e(0,200)]),extra:t,source:i}),this.client.report(o),et("JS error reported successfully")}catch(e){et("Failed to report error:",e)}}setContext(e,t){this.ensureInitialized()&&Xe([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.set,"call",i=>i(e,t)])}mergeContext(e){this.ensureInitialized()&&(et("Merging context:",e),Xe([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.merge,"call",t=>t(e)]))}deleteContext(e){this.ensureInitialized()&&Xe([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.delete,"call",t=>t(e)])}clearContext(){this.ensureInitialized()&&Xe([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.clear,"call",e=>e()])}updateConfig(e){if(this.ensureInitialized())try{et("Updating config:",e),this.client.config({userId:e.userId,release:e.release,sessionId:e.sessionId,env:e.env})}catch(e){et("Failed to update config:",e)}}async flush(e=1500){this.ensureInitialized()&&(et("Flushing Slardar data..."),Xe([this,"access",e=>e.client,"access",e=>e.getSender,"optionalCall",e=>e(),"optionalAccess",e=>e.flush,"call",e=>e()]),et("Waiting %dms for events to be sent...",e),await new Promise((t=>setTimeout(t,e))),et("Slardar data flushed"))}getRawClient(){return this.client}}const ot=new it;function st(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 nt="cli_start",rt="cli_command",at="cli_command_complete",ct="cli_error",dt="network_request",lt="file_operation",pt={cliStart:e=>({name:nt,metrics:{duration:0,...e}}),cliCommand:(e,t)=>({name:rt,categories:{command:e,args:st([t,"optionalAccess",e=>e.args]),status:"running",...st([t,"optionalAccess",e=>e.categories])},metrics:st([t,"optionalAccess",e=>e.metrics])}),cliCommandComplete:(e,t,i,o)=>({name:at,categories:{command:e,args:st([o,"optionalAccess",e=>e.args]),status:t?"success":"fail",...st([o,"optionalAccess",e=>e.categories])},metrics:{duration:i,...st([o,"optionalAccess",e=>e.errorCode])&&{errorCode:o.errorCode}}}),networkRequest:(e,t)=>({name:dt,categories:{url:e,method:st([t,"optionalAccess",e=>e.method])||"GET",statusCode:st([t,"optionalAccess",e=>e.statusCode,"optionalAccess",e=>e.toString,"call",e=>e()]),status:st([t,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:st([t,"optionalAccess",e=>e.duration])}}),fileOperation:(e,t,i)=>({name:lt,categories:{operation:e,filePath:t,status:st([i,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:st([i,"optionalAccess",e=>e.duration]),fileSize:st([i,"optionalAccess",e=>e.fileSize])}}),cliError:(e,t)=>({name:ct,categories:{errorName:e.name,errorMessage:e.message,stack:e.stack||"",...t},metrics:{errorCode:1}})};function ut(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 _t(e){return(...t)=>{try{const i=e(...t);return i instanceof Promise?i.catch((()=>{})):i}catch(e){}}}const ht=_t((()=>{var e,t;ot.setup({bid:"coze_cli",release:W,env:"production",userId:process.env.USER||"",useLocalConfig:!1,domain:"mon.zijieapi.com"}),ot.mergeContext({platform:process.platform,callerPlatform:(e=process.env.COZE_CLI_PLATFORM,t=()=>"unknown",null!=e?e:t()),nodeVersion:process.version,cliVersion:W})})),mt=_t((e=>{const t=pt.cliCommand(e);ot.sendEvent(t.name,t.metrics,t.categories)})),gt=_t(((e,t,i,o)=>{const s=pt.cliCommandComplete(e,t,i,{errorCode:ut([o,"optionalAccess",e=>e.errorCode])});ot.sendEvent(s.name,s.metrics,s.categories)})),ft=_t(((e,t)=>{ot.reportError(e,t,{type:"cli",data:t})})),yt=_t((async()=>{await ot.flush()}));async function vt(e,t){if(e.config.disableTelemetry)return void await t();ht();const i=function(e){if(e.commandName)return e.commandName;const t=[];for(const i of e.argv){if(i.startsWith("-"))break;t.push(i)}return t.join(" ")||"unknown"}(e);mt(i);const o=Date.now();let s,n=!0;try{await t()}catch(e){throw n=!1,s=e instanceof Error?e:new Error(String(e)),e}finally{const e=Date.now()-o;try{n?gt(i,!0,e):(s&&ft(s,{command:i}),gt(i,!1,e)),await yt()}catch(e){}}}function wt(e,t){return null!=e?e:t()}const bt=c.join(d.homedir(),".coze","logs");class St{__init(){this.fileStream=null}__init2(){this.writeError=!1}constructor(e={}){St.prototype.__init.call(this),St.prototype.__init2.call(this),this.format=wt(e.format,(()=>"text")),this.printToStderr=wt(e.printToStderr,(()=>!1)),this.tags=wt(e.tags,(()=>({}))),this.startTime=Date.now();const t=wt(e.logFile,(()=>this.getDefaultLogPath()));this.logFile=t;try{this.ensureLogDir(),this.rotateLogFiles(),this.fileStream=l.createWriteStream(t,{flags:"a"}),this.fileStream.on("error",(()=>{this.fileStream=null}))}catch(e){this.logFile=null,this.fileStream=null}}getDefaultLogPath(){const e=(new Date).toISOString().replace(/[:.]/g,"-"),{pid:t}=process;return c.join(bt,`${e}-${t}.log`)}ensureLogDir(){l.existsSync(bt)||l.mkdirSync(bt,{recursive:!0})}rotateLogFiles(){try{const e=l.readdirSync(bt).filter((e=>e.endsWith(".log"))).map((e=>({name:e,path:c.join(bt,e),mtime:l.statSync(c.join(bt,e)).mtime.getTime()}))).sort(((e,t)=>t.mtime-e.mtime));e.length>=10&&e.slice(9).forEach((e=>{try{l.unlinkSync(e.path)}catch(e){}}))}catch(e){}}verbose(e,...t){this.log("verbose",e,t)}info(e,...t){this.log("info",e,t)}warn(e,...t){this.log("warn",e,t)}error(e,...t){this.log("error",e,t)}success(e,...t){this.log("success",e,t)}debug(e,...t){this.log("debug",e,t)}debugFileOnly(e,...t){this.log("debug",e,t,!1)}log(e,t,i,o=this.printToStderr){const s=this.formatEntry(e,t,i);if(this.fileStream)try{this.fileStream.write(`${s}\n`)}catch(e){!this.writeError&&o&&(process.stderr.write("Warning: Log write failed\n"),this.writeError=!0)}o&&process.stderr.write(`${s}\n`)}formatEntry(e,t,i){const o=(new Date).toISOString(),s=Date.now()-this.startTime;if("json"===this.format){const n={level:e,timestamp:o,delta:s,...this.tags,message:t};return i.length>0&&(n.args=i),JSON.stringify(n)}const n=Object.entries(this.tags).map((([e,t])=>`${e}=${t}`)).join(" "),r=i.length>0?` ${i.map(String).join(" ")}`:"";return`${e.toUpperCase().padEnd(7)} [${o}] +${s}ms ${n} ${t}${r}`}close(){if(this.fileStream)try{this.fileStream.end()}catch(e){}}}function Pt(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 Ct=new Set(["authorization","cookie","set-cookie"]),Tt=/(^|_|-)(token|secret|password|authorization|cookie)(_|-|$)/i,Et=Symbol("request-debug-json-parse-fallback");let It=null,kt=!1,At=!1;const jt=e.customFetch.fetch.bind(e.customFetch),Rt=e=>"[object Object]"===Object.prototype.toString.call(e),zt=e=>{try{return JSON.stringify(e)}catch(t){return JSON.stringify(String(e))}},Lt=e=>{if("string"!=typeof e)return"***";const t=e.trim(),i=Pt([/^bearer\s+/i,"access",e=>e.exec,"call",e=>e(t),"optionalAccess",e=>e[0]]);return i?`${i}***`:"***"},Ut=(e,t)=>t&&Tt.test(t)?Lt(e):Array.isArray(e)?e.map((e=>Ut(e))):Rt(e)?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,Ut(t,e)]))):e,Ot=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(Array.from(e.entries()).map((([e,t])=>[e.toLowerCase(),t])));if(Array.isArray(e))return Object.fromEntries(e.map((([e,t])=>[e.toLowerCase(),String(t)])));const t=e;return"function"==typeof t.toJSON?Ot(t.toJSON()):"function"==typeof t.entries?Object.fromEntries(Array.from(t.entries()).map((([e,t])=>[e.toLowerCase(),t]))):Object.fromEntries(Object.entries(e).map((([e,t])=>[e.toLowerCase(),Array.isArray(t)?t.map((e=>String(e))).join(", "):String(t)])))},xt=(e,t)=>e[t.toLowerCase()],Bt=(e,t,i="binary")=>{const o=(e=>"string"==typeof e?a.Buffer.byteLength(e):a.Buffer.isBuffer(e)?e.length:e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:"undefined"!=typeof Blob&&e instanceof Blob?e.size:void 0)(e),s=[i];return t&&s.push(t),"number"==typeof o&&s.push(`${o} bytes`),`[${s.join("; ")}]`},qt=(t,i)=>{if(null==t||""===t)return"<empty>";const o=Pt([xt,"call",e=>e(i,"content-type"),"optionalAccess",e=>e.toLowerCase,"call",e=>e()]);if(Pt([o,"optionalAccess",e=>e.includes,"call",e=>e("multipart/form-data")]))return Bt(t,o,"multipart");if(t instanceof URLSearchParams)return zt(Ut(Object.fromEntries(Array.from(t.entries()))));if(a.Buffer.isBuffer(t)||t instanceof Uint8Array||t instanceof ArrayBuffer||"undefined"!=typeof Blob&&t instanceof Blob)return Bt(t,o);if("string"==typeof t){const i=(t=>{const i=e.safeJsonParse(t,Et);if(i!==Et)return i})(t);return void 0!==i?zt(Ut(i)):JSON.stringify(t)}return Array.isArray(t)||Rt(t)?zt(Ut(t)):Bt(t,o,typeof t)},Dt=(e,t)=>{try{return new URL(e,t).toString()}catch(i){return t?`${t}${e}`:e}},Mt=e=>{const t=Ot(e);return t["x-tt-logid"]||t["x-tt-log-id"]||t.logid||""},Nt=e=>(e||"GET").toUpperCase(),Gt=e=>{kt&&It&&(It instanceof St?It.debugFileOnly(e):It.debug(e))},$t=({method:e,url:t,headers:i,body:o})=>{const s=Ot(i);Gt(`[DBG][HTTP][REQ] ${e} ${t}\nheaders: ${zt((e=>Object.fromEntries(Object.entries(e).map((([e,t])=>[e,Ct.has(e)?Lt(t):t]))))(s))}\nbody: ${qt(o,s)}`)},Ft=({method:e,url:t,status:i,logId:o})=>{Gt(`[DBG][HTTP][RES] ${e} ${t} status=${i} logid=${o||"-"}`)},Vt=({method:e,url:t,status:i,logId:o,message:s})=>{const n=(a=()=>"ERR",null!=(r=i)?r:a());var r,a;const c=s?` error=${JSON.stringify(s)}`:"";Gt(`[DBG][HTTP][ERR] ${e} ${t} status=${n} logid=${o||"-"}${c}`)},Wt=(e,t)=>t&&"body"in t?t.body:"object"==typeof e&&e&&"body"in e&&null!==e.body?"[request body stream]":void 0,Ht=()=>{e.axiosInstance.interceptors.request.use((e=>((e=>{const t=Nt(e.method),i=Dt(e.url||"",e.baseURL),o=Ot(e.headers);$t({method:t,url:i,headers:o,body:e.data})})(e),e))),e.axiosInstance.interceptors.response.use((e=>((e=>{const t=Nt(Pt([e,"access",e=>e.config,"optionalAccess",e=>e.method])),i=Dt(Pt([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",Pt([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Ft({method:t,url:i,status:e.status,logId:Mt(e.headers)})})(e),e)),(e=>((e=>{const t=Nt(Pt([e,"access",e=>e.config,"optionalAccess",e=>e.method])),i=Dt(Pt([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",Pt([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Vt({method:t,url:i,status:Pt([e,"access",e=>e.response,"optionalAccess",e=>e.status]),logId:Mt(Pt([e,"access",e=>e.response,"optionalAccess",e=>e.headers])),message:e.message})})(e),Promise.reject(e))))},Jt=()=>{e.customFetch.fetch=async(t,i)=>{const o=((e,t)=>Pt([t,"optionalAccess",e=>e.method])?Nt(t.method):"object"==typeof e&&e&&"method"in e&&"string"==typeof e.method?Nt(e.method):"GET")(t,i),s=(e=>"string"==typeof e?e:e instanceof URL?e.toString():"object"==typeof e&&e&&"url"in e&&"string"==typeof e.url?e.url:String(e))(t),n=e.customFetch.getRequestHeaders(t,i);$t({method:o,url:s,headers:n,body:Wt(t,i)});try{const e=await jt(t,i);return Ft({method:o,url:s,status:e.status,logId:Mt(e.headers)}),e}catch(e){throw Vt({method:o,url:s,message:e instanceof Error?e.message:String(e)}),e}}};function Kt(e,t){return null!=e?e:t()}function Qt(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 Yt;!function(e){e.AUTHORIZATION_PENDING="authorization_pending";e.SLOW_DOWN="slow_down";e.ACCESS_DENIED="access_denied";e.EXPIRED_TOKEN="expired_token"}(Yt||(Yt={}));const Zt=e=>new Promise((t=>setTimeout(t,e))),Xt=e.createRequestClient({baseURL:"https://api.coze.com",useDefaultPlugins:!0,plugins:[{name:"oauth-error-handler",onError:t=>{if(e.isHttpError(t))throw t;const i=t,o=Kt(Qt([i,"access",e=>e.response,"optionalAccess",e=>e.data]),(()=>({}))),s=o.error_description||o.error||i.message,n={status:Qt([i,"access",e=>e.response,"optionalAccess",e=>e.status]),code:o.error,config:i.config,response:i.response,data:o};throw new e.HttpError(Kt(s,(()=>"OAuth request failed")),n)}}]});async function ei(e){return(await Xt.post("/api/permission/oauth2/token",{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode},{baseURL:e.baseURL})).data}const ti=async(t,i)=>{const o=process.env.HTTP_PROXY||process.env.http_proxy,s=process.env.HTTPS_PROXY||process.env.https_proxy;if(s||o){const i=new p.EnvHttpProxyAgent;e.customFetch.setDispatcher(i);const[{HttpProxyAgent:n},{HttpsProxyAgent:r}]=await Promise.all([import("http-proxy-agent"),import("https-proxy-agent")]);e.axiosInstance$1.defaults.proxy=!1,Xt.defaults.proxy=!1,s&&(e.axiosInstance$1.defaults.httpsAgent=new r(s),Xt.defaults.httpsAgent=new r(s),t.ui.debug(`HTTPS proxy enabled: ${s}`)),o&&(e.axiosInstance$1.defaults.httpAgent=new n(o),Xt.defaults.httpAgent=new n(o),t.ui.debug(`HTTP proxy enabled: ${o}`))}await i()};let ii=()=>{},oi=null;const si=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ni=(e,t)=>{return si(i=e)&&"function"==typeof i.set?(Object.entries(t).forEach((([t,i])=>{e.set(t,i)})),e):{...si(e)?e:{},...t};var i},ri=t=>{ii=t,null===oi&&(oi=e.axiosInstance$1.interceptors.request.use((t=>{const i=s.getCozeAccountHeaders(ii());return 0!==Object.keys(i).length&&s.shouldInjectCozeAccountHeader((t=>{const i=t.url;if(!i)return"";try{return new URL(i,t.baseURL||e.axiosInstance$1.defaults.baseURL).toString()}catch(e){return""}})(t))?(t.headers=ni(t.headers,i),t):t})))};async function ai(t,i){ri((()=>t.config.organizationId)),s.installScopedCozeAccountFetchHeader({getOrganizationId:()=>t.config.organizationId});const o=await t.auth.getValidAccessToken();e.axiosInstance$1.defaults.baseURL=t.config.apiBaseUrl;const n=`Bearer ${o}`;e.axiosInstance$1.defaults.headers.Authorization=n,e.axiosInstance$1.defaults.headers["x-request-from-coze-cli"]="1",e.customFetch.setHeaders({Authorization:n,"x-request-from-coze-cli":"1"}),t.config.xTTEnv&&(e.axiosInstance$1.defaults.headers["x-use-ppe"]="1",e.axiosInstance$1.defaults.headers["x-tt-env"]=t.config.xTTEnv,e.customFetch.setHeaders({"x-use-ppe":"1","x-tt-env":t.config.xTTEnv})),await i()}function ci(e){if(!Array.isArray(e))throw new TypeError("Middleware stack must be an array!");for(const t of e)if("function"!=typeof t)throw new TypeError("Middleware must be composed of functions!");return function(t,i){let o=-1;return function s(n){if(n<=o)return Promise.reject(new Error("next() called multiple times"));o=n;let r=e[n];n===e.length&&(r=i);if(!r)return Promise.resolve();try{return Promise.resolve(r(t,s.bind(null,n+1)))}catch(e){return Promise.reject(e)}}(0)}}var di,li,pi,ui,_i,hi,mi,gi,fi,yi,vi,wi,bi,Si,Pi,Ci,Ti,Ei,Ii,ki,Ai,ji,Ri,zi,Li,Ui,Oi,xi,Bi,qi,Di,Mi,Ni,Gi,$i,Fi,Vi,Wi,Hi,Ji,Ki,Qi,Yi,Zi,Xi,eo,to,io,oo,so,no,ro,ao,co,lo;function po(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.app="app";e.pat="pat"}(di||(di={})),function(e){e.can_apply2="CanApply";e.already_applied2="AlreadyApplied";e.joined4="Joined";e.deny3="Deny"}(li||(li={})),function(e){e.processing="Processing";e.approved="Approved";e.rejected="Rejected";e.auto_approved="AutoApproved"}(pi||(pi={})),function(e){e.normal="Normal";e.connector="Connector";e.privilege="Privilege"}(ui||(ui={})),function(e){e.auth_app="AuthApp";e.on_behalf_of_user="OnBehalfOfUser"}(_i||(_i={})),function(e){e.password="Password";e.sms="Sms";e.email="Email";e.unknown3="Unknown"}(hi||(hi={})),function(e){e.email2="Email";e.phone="Phone";e.unknown4="Unknown"}(mi||(mi={})),function(e){e.authorized="authorized";e.unauthorized="unauthorized";e.expired4="expired"}(gi||(gi={})),function(e){e.api_key="api_key";e.wechat_official="wechat_official";e.oauth_2="oauth2"}(fi||(fi={})),function(e){e.noncertificated="Noncertificated";e.certificated="Certificated"}(yi||(yi={})),function(e){e.uncertified="Uncertified";e.personal_certification="PersonalCertification";e.enterprise_certification="EnterpriseCertification"}(vi||(vi={})),function(e){e.obo="Obo";e.app_auth="AppAuth";e.personal_access_token="PersonalAccessToken"}(wi||(wi={})),function(e){e.legacy="Legacy";e.web_backend="WebBackend";e.single_page_or_native="SinglePageOrNative";e.terminal="Terminal";e.service="Service"}(bi||(bi={})),function(e){e.bot_editor="BotEditor";e.bot_developer="BotDeveloper";e.bot_operator="BotOperator"}(Si||(Si={})),function(e){e.workspace="Workspace";e.o_auth_app="OAuthApp";e.authorized_o_auth_app="AuthorizedOAuthApp";e.service_access_token="ServiceAccessToken";e.personal_access_token2="PersonalAccessToken";e.connector2="Connector";e.normal_api_app="NormalApiApp";e.connector_api_app="ConnectorApiApp"}(Pi||(Pi={})),function(e){e.visitors_prohibited="VisitorsProhibited";e.guest_prohibited_by_invited_user_enterprise2="GuestProhibitedByInvitedUserEnterprise";e.prohibited_by_custom_people_management="ProhibitedByCustomPeopleManagement"}(Ci||(Ci={})),function(e){e.dev2="DEV";e.prod2="PROD"}(Ti||(Ti={})),function(e){e._1="1";e._30="30";e._90="90";e._180="180";e._365="365";e.customize="customize";e.permanent="permanent"}(Ei||(Ei={})),function(e){e._12="1";e._302="30";e._902="90";e._1802="180";e._3652="365";e.customize2="customize";e.permanent2="permanent"}(Ii||(Ii={})),function(e){e.aes_256_gcm="AES-256-GCM"}(ki||(ki={})),function(e){e.conversation="Conversation";e.unknown="Unknown"}(Ai||(Ai={})),function(e){e.active3="Active";e.inactive="Inactive"}(ji||(ji={})),function(e){e.cloud_kms="CloudKMS",e.default="Default";e.unknown2="Unknown"}(Ri||(Ri={})),function(e){e.user_custom2="user_custom";e.consumer3="consumer"}(zi||(zi={})),function(e){e.super_admin="SuperAdmin";e.admin="Admin";e.member="Member";e.guest="Guest"}(Li||(Li={})),function(e){e.join_enterprise_share_link_expiration_time="JoinEnterpriseShareLinkExpirationTime";e.sso="SSO";e.forbid_guest_join_enterprise="ForbidGuestJoinEnterprise";e.forbid_member_join_other_enterprise="ForbidMemberJoinOtherEnterprise";e.replace_enterprise_logo="ReplaceEnterpriseLogo";e.forbid_custom_people_management="ForbidCustomPeopleManagement";e.forbid_coze_store_plugin_access="ForbidCozeStorePluginAccess";e.enterprise_member_listing_skill_coze_store="EnterpriseMemberListingSkillCozeStore";e.listing_skill_enterprise_store_audit="ListingSkillEnterpriseStoreAudit"}(Ui||(Ui={})),function(e){e.string="String";e.boolean="Boolean";e.integer="Integer";e.string_list="StringList"}(Oi||(Oi={})),function(e){e.must_handle="MustHandle";e.no_need_handle="NoNeedHandle"}(xi||(xi={})),function(e){e.pending_review_app_auth="pending_review_app_auth";e.pending_review_app_obo="pending_review_app_obo";e.approved_app_auth="approved_app_auth";e.approved_app_obo="approved_app_obo"}(Bi||(Bi={})),function(e){e.no_permission="NoPermission";e.guest_prohibited_by_enterprise2="GuestProhibitedByEnterprise";e.guest_prohibited_by_invited_user_enterprise3="GuestProhibitedByInvitedUserEnterprise";e.guest_prohibited_by_custom_people_management="GuestProhibitedByCustomPeopleManagement"}(qi||(qi={})),function(e){e.confirming2="Confirming";e.joined3="Joined";e.rejected3="Rejected";e.revoked2="Revoked";e.expired3="Expired";e.deny2="Deny"}(Di||(Di={})),function(e){e.confirming="Confirming";e.joined2="Joined";e.rejected2="Rejected";e.revoked="Revoked";e.expired2="Expired"}(Mi||(Mi={})),function(e){e.can_join="CanJoin";e.guest_prohibited_by_enterprise="GuestProhibitedByEnterprise";e.guest_prohibited_by_invited_user_enterprise="GuestProhibitedByInvitedUserEnterprise"}(Ni||(Ni={})),function(e){e.can_apply="CanApply";e.already_applied="AlreadyApplied";e.joined="Joined";e.expired="Expired";e.deny="Deny"}(Gi||(Gi={})),function(e){e.free="Free";e.premium_lite="PremiumLite";e.premium="Premium";e.premium_plus="PremiumPlus";e.v_1_pro_instance="V1ProInstance";e.pro_personal="ProPersonal";e.coze_personal_plus="CozePersonalPlus";e.coze_personal_advanced="CozePersonalAdvanced";e.coze_personal_pro="CozePersonalPro";e.team="Team";e.enterprise_basic="EnterpriseBasic";e.enterprise="Enterprise";e.enterprise_pro="EnterprisePro"}($i||($i={})),function(e){e.user_custom_only="user_custom_only";e.all2="all"}(Fi||(Fi={})),function(e){e.system="system";e.custom="custom"}(Vi||(Vi={})),function(e){e.not_in_enterprise="NotInEnterprise";e.prohibited_by_custom_people_management2="ProhibitedByCustomPeopleManagement"}(Wi||(Wi={})),function(e){e.can_apply3="CanApply";e.already_applied3="AlreadyApplied";e.joined5="Joined";e.deny4="Deny"}(Hi||(Hi={})),function(e){e.super_admin2="SuperAdmin";e.admin2="Admin";e.member2="Member";e.guest2="Guest"}(Ji||(Ji={})),function(e){e.member_joining_auto_approved="MemberJoiningAutoApproved"}(Ki||(Ki={})),function(e){e.string2="String";e.boolean2="Boolean";e.integer2="Integer";e.string_list2="StringList"}(Qi||(Qi={})),function(e){e.developer="developer";e.consumer2="consumer"}(Yi||(Yi={})),function(e){e.all="all";e.owned="owned";e.others="others"}(Zi||(Zi={})),function(e){e.enterprise_member="EnterpriseMember";e.enterprise_guest="EnterpriseGuest"}(Xi||(Xi={})),function(e){e.not_created="NotCreated";e.enabled="Enabled";e.disabled="Disabled"}(eo||(eo={})),function(e){e.not_created2="NotCreated";e.not_support_not_supabase="NotSupportNotSupabase";e.enabled2="Enabled";e.disabled2="Disabled";e.not_support_project_type="NotSupportProjectType"}(to||(to={})),function(e){e.production="Production";e.development="Development"}(io||(io={})),(oo||(oo={})).skill="skill",function(e){e.dev="dev";e.prod="prod"}(so||(so={})),function(e){e.user_custom="user_custom";e.coze_default="coze_default";e.consumer="consumer"}(no||(no={})),function(e){e.active2="Active";e.deactive="Deactive"}(ro||(ro={})),function(e){e.active="active";e.deactivated="deactivated";e.offboarded="offboarded"}(ao||(ao={})),function(e){e.studio_space_selector="studio_space_selector";e.studio_create_project_btn="studio_create_project_btn";e.studio_home_page="studio_home_page";e.studio_develop="studio_develop";e.studio_library="studio_library";e.studio_tasks="studio_tasks";e.studio_evaluate="studio_evaluate";e.studio_space_manage="studio_space_manage";e.studio_templates_store="studio_templates_store";e.studio_plugins_store="studio_plugins_store";e.studio_agents_store="studio_agents_store";e.studio_playground="studio_playground";e.studio_docs="studio_docs";e.studio_enterprise_agents_store="studio_enterprise_agents_store";e.studio_enterprise_plugins_store="studio_enterprise_plugins_store";e.studio_organization_manage="studio_organization_manage";e.studio_enterprise_card="studio_enterprise_card";e.studio_subscription_card="studio_subscription_card";e.studio_personal_menu="studio_personal_menu";e.studio_more_products="studio_more_products";e.studio_notice="studio_notice";e.studio_migration_banner="studio_migration_banner";e.coding_space_selector="coding_space_selector";e.coding_create_project="coding_create_project";e.coding_project_manage="coding_project_manage";e.coding_integrations="coding_integrations";e.coding_library="coding_library";e.coding_tasks="coding_tasks";e.coding_playground="coding_playground";e.coding_evaluate="coding_evaluate";e.coding_coze_redirect="coding_coze_redirect";e.coding_docs="coding_docs";e.coding_community="coding_community";e.coding_enterprise_card="coding_enterprise_card";e.coding_subscription_card="coding_subscription_card";e.coding_personal_menu="coding_personal_menu";e.coding_notice="coding_notice";e.admin_organization_manage="admin_organization_manage";e.admin_member_manage="admin_member_manage";e.admin_enterprise_config="admin_enterprise_config"}(co||(co={})),function(e){e.root_user="RootUser";e.basic_user="BasicUser"}(lo||(lo={}));class uo{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){uo.prototype.__init.call(this),uo.prototype.__init2.call(this),this.request=po([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=po([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}CreatePersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/create_personal_access_token_and_permission"),s={name:i.name,expire_at:i.expire_at,duration_day:i.duration_day,organization_id:i.organization_id,workspace_permission:i.workspace_permission,account_permission:i.account_permission,workspace_permission_v2:i.workspace_permission_v2,enterprise_permission:i.enterprise_permission},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}UpdatePersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/update_personal_access_token_and_permission"),s={workspace_permission:i.workspace_permission,account_permission:i.account_permission,workspace_permission_v2:i.workspace_permission_v2,enterprise_permission:i.enterprise_permission,id:i.id,name:i.name},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}DeletePersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/delete_personal_access_token_and_permission"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}ListPersonalAccessTokens(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/pat/list_personal_access_tokens"),s={organization_id:i.organization_id,page:i.page,size:i.size,search_option:i.search_option};return this.request({url:o,method:"GET",params:s},t)}GetPersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/get_personal_access_token_and_permission"),s={id:i.id};return this.request({url:o,method:"GET",params:s},t)}ListPersonalAccessTokenSupportPermissions(e,t){const i=this.genBaseURL("/api/permission_api/pat/list_personal_access_token_support_permissions");return this.request({url:i,method:"GET"},t)}CheckPersonalAccessTokenInWorkspace(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/check_personal_access_token_in_workspace"),s={workspace_id:i.workspace_id};return this.request({url:o,method:"GET",params:s},t)}AddCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/add_collaborator"),s={collaborator_types:i.collaborator_types,principal:i.principal,resource:i.resource};return this.request({url:o,method:"POST",data:s},t)}RemoveCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/remove_collaborator"),s={principal:i.principal,resource:i.resource};return this.request({url:o,method:"POST",data:s},t)}CreateAppMeta(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/create_app_meta"),s={app_type:i.app_type,client_type:i.client_type,name:i.name,description:i.description,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListAppMeta(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/list_app_meta"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}GetAppMeta(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_app_meta"),s={appid:i.appid},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}UpdateAppMeta(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/update_app_meta"),s={status:i.status,oauth2_configuration:i.oauth2_configuration,appid:i.appid,name:i.name,description:i.description,declared_permission:i.declared_permission,declared_permission_v2:i.declared_permission_v2},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}UploadPublicKey(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/upload_public_key"),s={appid:i.appid,public_key_pem:i.public_key_pem};return this.request({url:o,method:"POST",data:s},t)}DeletePublicKey(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/delete_public_key"),s={fingerprint:i.fingerprint};return this.request({url:o,method:"POST",data:s},t)}CreateClientSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/create_client_secret"),s={appid:i.appid};return this.request({url:o,method:"POST",data:s},t)}DeleteClientSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/delete_client_secret"),s={appid:i.appid,client_secret_id:i.client_secret_id};return this.request({url:o,method:"POST",data:s},t)}PutOAuth2Configuration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/put_oauth2_configuration"),s={oauth2_configuration:i.oauth2_configuration,appid:i.appid};return this.request({url:o,method:"POST",data:s},t)}AuthorizeAppWithDeclaredPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/authorize_app_with_declared_permission"),s={appid:i.appid,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListAuthorizedApps(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/list_authorized_apps"),s={page:i.page,size:i.size},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}GetAppAuthorizationRequestInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_app_authorization_request_info"),s={authorize_key:i.authorize_key},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}RevokeAppAuthorizedPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/revoke_app_authorized_permission"),s={authorization_type:i.authorization_type,appid:i.appid,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}DeleteApp(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/delete_app"),s={appid:i.appid};return this.request({url:o,method:"POST",data:s},t)}ModifyCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/modify_collaborator"),s={principal:i.principal,resource:i.resource,collaborator_types:i.collaborator_types};return this.request({url:o,method:"POST",data:s},t)}BatchAddCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/batch_add_collaborator"),s={principal_type:i.principal_type,resource:i.resource,principal_ids:i.principal_ids,collaborator_types:i.collaborator_types};return this.request({url:o,method:"POST",data:s},t)}GetAppInstallationRequestInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_app_installation_request_info"),s={appid:i.appid},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}AppInstallationConsent(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/app_installation_consent"),s={appid:i.appid,installation_account_hint:i.installation_account_hint};return this.request({url:o,method:"POST",data:s},t)}ImpersonateCozeUser(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/coze_web_app/impersonate_coze_user"),s={duration_seconds:i.duration_seconds,scope:i.scope,connector_info:i.connector_info};return this.request({url:o,method:"POST",data:s},t)}GetVolcanoConnectInfoWithInsName(e,t){const i=this.genBaseURL("/api/permission_api/volcano/get_volcano_connect_info_with_ins_name");return this.request({url:i,method:"GET"},t)}GetVolcanoMaskedMobile(e,t){const i=this.genBaseURL("/api/permission_api/volcano/get_volcano_masked_mobile");return this.request({url:i,method:"GET"},t)}BindVolcano(e,t){const i=this.genBaseURL("/api/permission_api/volcano/bind_volcano");return this.request({url:i,method:"POST"},t)}AuthorizeAppWithSpecifiedWorkspace(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/authorize_app_with_specified_permission"),s={appid:i.appid,workspace_list:i.workspace_list,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}GetUserProfile(e,t){const i=this.genBaseURL("/v1/users/me");return this.request({url:i,method:"GET"},t)}ListAppAuthorizations(e,t){const i=e,o=this.genBaseURL(`/v1/oauth-apps/${i.appid}/authorizations`),s={page_num:i.page_num,page_size:i.page_size},n={authorization:i.authorization};return this.request({url:o,method:"GET",params:s,headers:n},t)}GetCertificationInfo(e,t){const i=this.genBaseURL("/api/permission_api/enterprise/get_certification_info");return this.request({url:i,method:"GET"},t)}NeedCreateEnterprise(e,t){const i=this.genBaseURL("/api/permission_api/enterprise/need_create_enterprise");return this.request({url:i,method:"GET"},t)}CreateEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_enterprise"),s={name:i.name,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}ListEnterprise(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/enterprise/list_enterprises"),s={contain_enterprise_of_user:i.contain_enterprise_of_user,contain_organization_of_user:i.contain_organization_of_user,contain_guest_enterprise_of_user:i.contain_guest_enterprise_of_user,is_space:i.is_space};return this.request({url:o,method:"GET",params:s},t)}GetEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_enterprise"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"GET",params:s},t)}UpdateEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_enterprise"),s={enterprise_id:i.enterprise_id,name:i.name,icon_uri:i.icon_uri,replace_logo:i.replace_logo};return this.request({url:o,method:"POST",data:s},t)}UpdateEnterpriseSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_settings"),s={enterprise_id:i.enterprise_id,enterprise_settings:i.enterprise_settings};return this.request({url:o,method:"POST",data:s},t)}BatchAddEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_add_enterprise_people"),s={enterprise_id:i.enterprise_id,enterprise_people:i.enterprise_people,need_check_people_valid:i.need_check_people_valid};return this.request({url:o,method:"POST",data:s},t)}RemoveEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/remove_enterprise_people"),s={enterprise_id:i.enterprise_id,user_id:i.user_id,receiver:i.receiver,sync_default_organization:i.sync_default_organization};return this.request({url:o,method:"POST",data:s},t)}UpdateEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_people"),s={enterprise_id:i.enterprise_id,user_id:i.user_id,enterprise_role_type_list:i.enterprise_role_type_list,sync_default_organization:i.sync_default_organization};return this.request({url:o,method:"POST",data:s},t)}CreateEnterpriseInviteLink(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_enterprise_invite_link"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}CreateJoinApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_join_application"),s={key:i.key,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}GetInviteInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_invite_info"),s={invite_key:i.invite_key};return this.request({url:o,method:"GET",params:s},t)}UpdateJoinApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_join_application"),s={application_status:i.application_status,enterprise_id:i.enterprise_id,join_application_id_list:i.join_application_id_list};return this.request({url:o,method:"POST",data:s},t)}ListPersonalAccessTokensByCreator(e,t){const i=e,o=this.genBaseURL("/api/permission_api/permission/list_personal_access_tokens_by_creator"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}ListAppInstallations(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/list_app_installations"),s={enterprise_id:i.enterprise_id,organization_id:i.organization_id},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}GetEnterpriseSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_enterprise_settings"),s={enterprise_id:i.enterprise_id,enterprise_setting_key_list:i.enterprise_setting_key_list};return this.request({url:o,method:"POST",data:s},t)}SearchCanAddEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_can_add_enterprise_people"),s={people_type:i.people_type,enterprise_id:i.enterprise_id,search_key:i.search_key};return this.request({url:o,method:"POST",data:s},t)}SearchEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_enterprise_people"),s={people_type:i.people_type,enterprise_id:i.enterprise_id,search_key:i.search_key,enterprise_role_type_list:i.enterprise_role_type_list,need_volcano_user_info:i.need_volcano_user_info,need_people_number:i.need_people_number,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}ListJoinApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/list_join_application"),s={application_status:i.application_status,enterprise_id:i.enterprise_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}PostAdapterMpV1Code2Session(e,t){const i=e||{},o=this.genBaseURL("/adapter/mp/v1/code2session"),s={bot_id:i.bot_id,app_id:i.app_id,connector_id:i.connector_id,code:i.code,with_userinfo:i.with_userinfo,execute_mode:i.execute_mode,agent_type:i.agent_type,agent_version:i.agent_version};return this.request({url:o,method:"POST",data:s},t)}SubmitAppOboInstallationReview(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/submit_app_obo_installation_review"),s={appid:i.appid,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}InstallAppObo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/install_app_obo"),s={appid:i.appid,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}UninstallAppObo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/uninstall_app_obo"),s={appid:i.appid,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}GetChecklistForWorkspaceMigration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_checklist_for_workspace_migration"),s={workspace_id_list:i.workspace_id_list};return this.request({url:o,method:"POST",data:s},t)}CheckEnterpriseExist(e,t){const i=this.genBaseURL("/api/permission_api/enterprise/check_enterprise_exist");return this.request({url:i,method:"GET"},t)}GetSSOSetting(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_sso_setting"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}BatchMigrateAuthorization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/batch_migrate_authorization"),s={authorization_list:i.authorization_list,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/list_join_invitation"),s={invitation_status:i.invitation_status,enterprise_id:i.enterprise_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}RevokeJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/revoke_join_invitation"),s={enterprise_id:i.enterprise_id,join_invitation_id:i.join_invitation_id};return this.request({url:o,method:"POST",data:s},t)}UpdateJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_join_invitation"),s={enterprise_id:i.enterprise_id,join_invitation_id:i.join_invitation_id,joined:i.joined};return this.request({url:o,method:"POST",data:s},t)}GetJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_join_invitation"),s={join_invitation_id:i.join_invitation_id};return this.request({url:o,method:"POST",data:s},t)}SearchPeopleInOtherEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_people_in_other_enterprise"),s={enterprise_id:i.enterprise_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}CreateApplicationForEnterpriseMember(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_application_for_enterprise_member"),s={enterprise_id:i.enterprise_id,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}GetApplicationForEnterpriseMember(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_application_for_enterprise_member"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}AuthorizeAppsAndPersonalaccesstokenListWithPersonalAccountPermission(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/authorize_apps_and_patlist_with_personalaccountpermission"),s={crossaccount_authinfo_list:i.crossaccount_authinfo_list};return this.request({url:o,method:"POST",data:s},t)}RevokeAppAndPersonalaccesstokenPersonalAccountPermission(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/revoke_app_and_pat_personalaccountpermission"),s={crossaccount_authinfo:i.crossaccount_authinfo};return this.request({url:o,method:"POST",data:s},t)}GetAppsAndPersonalAccessTokenListForPersonalAccountPermissionAuthorization(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/get_apps_and_patlist_for_personalaccountpermission_authorization"),s={page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}create_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/create_service_identity"),s={name:i.name,organization_id:i.organization_id,expire_at:i.expire_at,duration_day:i.duration_day,permission:i.permission},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}get_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/get_service_identity"),s={id:i.id};return this.request({url:o,method:"GET",params:s},t)}update_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/update_service_identity"),s={permission:i.permission,id:i.id,name:i.name,expire_at:i.expire_at,duration_day:i.duration_day},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}delete_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/delete_service_identity"),s={id:i.id};return this.request({url:o,method:"POST",params:s},t)}list_service_identities(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/service/list_service_identities"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}ListEncryptionConfiguration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterpise/list_encryption_configuration"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}UpdateEncryptionConfiguration(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/enterpise/update_encryption_configuration"),s={encryption_configuration:i.encryption_configuration};return this.request({url:o,method:"POST",data:s},t)}SearchOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_organization"),s={enterprise_id:i.enterprise_id,search_key:i.search_key,joined:i.joined,need_people_number:i.need_people_number,need_workspace_number:i.need_workspace_number,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}CreateOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_organization"),s={enterprise_id:i.enterprise_id,name:i.name,icon_uri:i.icon_uri,description:i.description};return this.request({url:o,method:"POST",data:s},t)}GetOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_organization"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}UpdateOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_organization"),s={organization_id:i.organization_id,name:i.name,icon_uri:i.icon_uri,description:i.description};return this.request({url:o,method:"POST",data:s},t)}SearchCanAddOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_can_add_organization_people"),s={organization_id:i.organization_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}SearchOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_organization_people"),s={organization_role_type:i.organization_role_type,people_type:i.people_type,organization_id:i.organization_id,search_key:i.search_key,page:i.page,page_size:i.page_size,organization_role_type_list:i.organization_role_type_list};return this.request({url:o,method:"POST",data:s},t)}CreateJoinOrganizationApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_join_organization_application"),s={organization_id:i.organization_id,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}ListJoinOrganizationApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/list_join_organization_application"),s={application_status:i.application_status,organization_id:i.organization_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}UpdateJoinOrganizationApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_join_organization_application"),s={application_status:i.application_status,organization_id:i.organization_id,join_application_id_list:i.join_application_id_list};return this.request({url:o,method:"POST",data:s},t)}GetOrganizationApplicationForEnterpriseMember(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_organization_application_for_enterprise_member"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}CanCustomEncryptionConfiguration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterpise/can_custom_encryption_configuration"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"GET",params:s},t)}BatchAddOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_add_organization_people"),s={organization_id:i.organization_id,organization_people:i.organization_people};return this.request({url:o,method:"POST",data:s},t)}RemoveOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/remove_organization_people"),s={organization_id:i.organization_id,user_id:i.user_id,receiver:i.receiver};return this.request({url:o,method:"POST",data:s},t)}UpdateOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_organization_people"),s={organization_role_type:i.organization_role_type,organization_id:i.organization_id,user_id:i.user_id};return this.request({url:o,method:"POST",data:s},t)}DownloadRemoteAttestationEvidence(e,t){const i=e,o=this.genBaseURL("/api/permission_api/aicc/download_remote_attestation_evidence"),s={component_name:i.component_name};return this.request({url:o,method:"GET",params:s},t)}GetAgentAiccInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/aicc/get_agent_aicc_info"),s={agent_id:i.agent_id};return this.request({url:o,method:"GET",params:s},t)}CheckDeleteOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/check_delete_organization"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}DeleteOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/delete_organization"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListProjectUsers(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/list_project_users"),s={project_id:i.project_id,page_size:i.page_size,page_number:i.page_number,environment:i.environment,filter:i.filter};return this.request({url:o,method:"POST",data:s},t)}DeleteProjectUser(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user"),s={environment:i.environment,project_id:i.project_id,user_id:i.user_id};return this.request({url:o,method:"POST",data:s},t)}GetProjectAuthConfig(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}UpdateProjectAuthConfig(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config"),s={project_id:i.project_id,configuration:i.configuration};return this.request({url:o,method:"POST",data:s},t)}ListProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/list_project_secret"),s={env:i.env,project_id:i.project_id,with_providers:i.with_providers,deploy_id:i.deploy_id,option:i.option};return this.request({url:o,method:"POST",data:s},t)}UpdateProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/update_project_secret"),s={project_id:i.project_id,update_secrets:i.update_secrets,update_cred_provider:i.update_cred_provider};return this.request({url:o,method:"POST",data:s},t)}DeleteProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/delete_project_secret"),s={project_id:i.project_id,keys:i.keys,cred_provider_ids:i.cred_provider_ids};return this.request({url:o,method:"POST",data:s},t)}EncryptProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/encrypt_project_secret"),s={project_id:i.project_id,project_type:i.project_type,encrypt_secrets:i.encrypt_secrets};return this.request({url:o,method:"POST",data:s},t)}InsertProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/insert_project_secret"),s={project_id:i.project_id,insert_secrets:i.insert_secrets};return this.request({url:o,method:"POST",data:s},t)}OutboundAuthCallback(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/outbound_auth/callback"),s={session_id:i.session_id,error:i.error};return this.request({url:o,method:"GET",params:s},t)}CreateAgentAccessToken(e,t){const i=e,o=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:i.project_id,deployment_env:i.deployment_env};return this.request({url:o,method:"POST",data:s},t)}ListAgentAccessTokens(e,t){const i=e,o=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}DeleteAgentAccessToken(e,t){const i=e,o=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={token_id:i.token_id,project_id:i.project_id};return this.request({url:o,method:"DELETE",data:s},t)}GenerateInviteCode(e,t){const i=this.genBaseURL("/api/permission_api/coze_user/generate_invite_code");return this.request({url:i,method:"POST"},t)}GetInviteCodeInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/coze_user/get_invite_code_info"),s={invite_code:i.invite_code};return this.request({url:o,method:"GET",params:s},t)}AuthorizeCredProvider(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/authorize"),s={provider_id:i.provider_id};return this.request({url:o,method:"GET",params:s},t)}ProjectSecretAuthCallback(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/project_secret/callback"),s={code:i.code,state:i.state,error:i.error};return this.request({url:o,method:"GET",params:s},t)}ListAuthInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/list_auth_info"),s={credential_ids:i.credential_ids};return this.request({url:o,method:"POST",data:s},t)}RevokeAuthorization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/revoke"),s={credential_id:i.credential_id};return this.request({url:o,method:"POST",data:s},t)}UpdateProjectAuthConfigV2(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config_v2"),s={environment:i.environment,project_id:i.project_id,configuration:i.configuration};return this.request({url:o,method:"POST",data:s},t)}DeleteProjectUserV2(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user_v2"),s={environment:i.environment,project_id:i.project_id,user_id:i.user_id};return this.request({url:o,method:"POST",data:s},t)}VisibilityConfig(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/visibility_config"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}GetVolcanoLoginMaskedMobile(e,t){const i=this.genBaseURL("/api/permission_api/volcano/get_volcano_login_masked_mobile");return this.request({url:i,method:"GET"},t)}ListProjectUsersV2(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/list_project_users_v2"),s={environment:i.environment,project_id:i.project_id,page_size:i.page_size,page_number:i.page_number,filter:i.filter};return this.request({url:o,method:"POST",data:s},t)}GetProjectAuthConfigV2(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config_v2"),s={environment:i.environment,project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}BatchGetPeopleJoinedOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_get_people_joined_organization"),s={enterprise_id:i.enterprise_id,user_ids:i.user_ids};return this.request({url:o,method:"POST",data:s},t)}BatchRemoveOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_remove_organization_people"),s={enterprise_id:i.enterprise_id,remove_user_list:i.remove_user_list};return this.request({url:o,method:"POST",data:s},t)}BatchRemoveEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_remove_enterprise_people"),s={enterprise_id:i.enterprise_id,remove_user_list:i.remove_user_list};return this.request({url:o,method:"POST",data:s},t)}GetOrganizationSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_organization_settings"),s={organization_id:i.organization_id,organization_setting_key_list:i.organization_setting_key_list};return this.request({url:o,method:"POST",data:s},t)}UpdateOrganizationSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_organization_settings"),s={organization_id:i.organization_id,organization_settings:i.organization_settings};return this.request({url:o,method:"POST",data:s},t)}GithubAuthCallback(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/github_auth/callback"),s={code:i.code,state:i.state,error:i.error};return this.request({url:o,method:"GET",params:s},t)}BatchListOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_list_organization_people"),s={organization_ids:i.organization_ids,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}}const _o=new uo({});function ho(e,t){return null!=e?e:t()}const mo=1e3,go=Math.floor(new Date("2000-01-01T00:00:00.000Z").getTime()/mo),fo=e=>e instanceof Error?e.message:String(e);class yo{constructor(e){this.ctx=e,this.config=e.config}getOAuthConfig(){return{baseURL:ho(this.config.openApiBaseUrl,(()=>s.DEFAULT_CONFIG.openApiBaseUrl)),clientId:ho(this.config.clientId,(()=>s.DEFAULT_CONFIG.clientId))}}async clearUserContext(){this.config.organizationId=void 0,this.config.enterpriseId=void 0,this.config.spaceId=void 0,await s.saveConfig({organizationId:void 0,enterpriseId:void 0,spaceId:void 0})}openInBrowser(e){const t="darwin"===process.platform?"open":"win32"===process.platform?"cmd":"xdg-open",i="win32"===process.platform?["/c","start",'""',e]:[e],s="Failed to open browser automatically. Please open the URL manually.";try{const e=o.spawn(t,i,{detached:!0,stdio:"ignore"});e.on("error",(()=>{this.ctx.ui.verbose(s)})),e.unref()}catch(e){this.ctx.ui.verbose(`${s} ${e instanceof Error?e.message:String(e)}`)}}async clearAuthData(){this.config.accessToken=void 0,this.config.refreshToken=void 0,this.config.tokenExpiresAt=void 0,await s.saveConfig({accessToken:void 0,refreshToken:void 0,tokenExpiresAt:void 0})}async login(t){if(this.ctx.ui.verbose("Initiating login process..."),t.token)return this.ctx.ui.info("Using Personal Access Token (PAT)..."),this.config.accessToken=t.token,await s.saveConfig({accessToken:t.token,refreshToken:void 0,tokenExpiresAt:void 0}),await this.clearUserContext(),this.ctx.ui.info("Authentication successful. Credentials saved."),void("json"===this.ctx.format&&this.ctx.response.print({success:!0,method:"PAT"}));try{this.ctx.ui.info("Starting OAuth flow...");const{baseURL:t,clientId:o}=this.getOAuthConfig();this.ctx.ui.verbose("Starting OAuth device flow...");const s=await async function(e){const t=e.workspaceId?`/api/permission/oauth2/workspace_id/${e.workspaceId}/device/code`:"/api/permission/oauth2/device/code";return(await Xt.post(t,{client_id:e.clientId},{baseURL:e.baseURL})).data}({baseURL:t,clientId:o}),n=`${s.verification_uri}?user_code=${s.user_code}`;this.ctx.ui.info(`Please visit ${i.underline(n)} and authorize the application.\n\nPrivacy Policy: ${i.underline("https://docs.coze.cn/guides/privacy")}\nTerms of Service: ${i.underline("https://docs.coze.cn/guides/terms-of-service")}\n\nIf you are an agent using Coze CLI, please share the authorization link,\nPrivacy Policy, and Terms of Service with your users.\n `),this.openInBrowser(n);const r=await async function(t,i){if(!t.poll)return ei(t);let o=5e3;for(i.ui.debug("Start Polling for device token..."),i.ui.debug(`Polling interval: ${o}ms`),i.ui.debug("Polling timeout: 30000ms");;)try{i.ui.debug(`Polling for device token..., ${JSON.stringify(t)}`);const e=await ei(t);return i.ui.debug(`Polling for device token success: ${JSON.stringify(e)}`),e}catch(t){if(e.isHttpError(t)){const e=t;i.ui.debug(`Polling for device token error, the error is a HttpError.\n logid: ${Qt([e,"access",e=>e.response,"optionalAccess",e=>e.headers,"access",e=>e["x-tt-logid"]])}`),i.ui.debug(`Polling for device token error: ${JSON.stringify(Kt(Qt([e,"access",e=>e.toJSON,"optionalCall",e=>e()]),(()=>e)))}`);const s=e.data;if(Qt([s,"optionalAccess",e=>e.error])===Yt.AUTHORIZATION_PENDING){i.ui.debug("Polling for device token: user has not completed authorization yet."),await Zt(o);continue}if(Qt([s,"optionalAccess",e=>e.error])===Yt.SLOW_DOWN){o<3e4&&(o+=5e3),i.ui.debug(`Polling for device token: client is polling too frequently. Increasing interval to ${o}ms`),await Zt(o);continue}}const s=t;throw i.ui.debug(`Polling for device token error, the error is: ${s.message}\n ${s.stack}\n `),t}}({baseURL:t,clientId:o,deviceCode:s.device_code,poll:!0},this.ctx);this.ctx.ui.debug(`Polling for device token success: ${JSON.stringify(r)}`),await this.saveOAuthToken(r),this.ctx.ui.debug("Saving OAuth token successfully."),await this.clearUserContext(),this.ctx.ui.info("Authentication successful. Credentials saved."),"json"===this.ctx.format&&this.ctx.response.print({success:!0,method:"OAuth"})}catch(e){throw this.ctx.ui.error(`OAuth login failed: ${fo(e)}`),e}}async logout(){await this.clearAuthData(),await this.clearUserContext(),this.ctx.ui.info("You have been logged out. Credentials cleared."),"json"===this.ctx.format&&this.ctx.response.print({success:!0,logged_out:!0})}async whoami(){if(!await this.getValidAccessToken())return void this.ctx.response.print({logged_in:!1});this.ctx.ui.info("Fetching user information...");this.ctx.response.print({logged_in:!0,user:"mock-user@coze.io",org:"mock-org",profile:"default"})}async status(){const e=await this.getValidAccessToken();if(this.ctx.ui.info("Checking authentication status..."),!e)return void this.ctx.response.print({logged_in:!1});const t=this.config.tokenExpiresAt,i=!!this.config.refreshToken,{data:o}=await _o.GetUserProfile({},{baseURL:this.config.openApiBaseUrl}),s={logged_in:!0,user:o,token_expires_at:t?new Date(t).toISOString():i?void 0:"Never (PAT)"};this.ctx.response.print(s)}async getValidAccessToken(){const{accessToken:e,refreshToken:t,tokenExpiresAt:i}=this.config;if(e){if(!t)return e;if((e=>{if(!e)return!1;const t=Date.now();return!(e-t>316224e5)&&t<e-3e5})(i))return e;this.ctx.ui.verbose("Access token is expired or expiring soon, refreshing...");try{const{baseURL:e,clientId:i}=this.getOAuthConfig(),o=await async function(e){const t={};return e.clientSecret&&(t.Authorization=`Bearer ${e.clientSecret}`),(await Xt.post("/api/permission/oauth2/token",{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken},{baseURL:e.baseURL,headers:t})).data}({baseURL:e,clientId:i,refreshToken:t});return await this.saveOAuthToken(o),this.ctx.ui.verbose("Token refreshed successfully."),o.access_token}catch(e){return this.ctx.ui.error(`Failed to refresh token: ${fo(e)}`),void await this.clearAuthData()}}}async saveOAuthToken(e){const t=(i=e.expires_in)>=go?i*mo:Date.now()+i*mo;var i;this.config.accessToken=e.access_token,this.config.refreshToken=e.refresh_token,this.config.tokenExpiresAt=t,await s.saveConfig({accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:t})}}const vo="",wo="",bo="",So="",Po="",Co="",To="",Eo="",Io="[PROC]",ko="[INFO]",Ao="[WARN]",jo="[ERR]",Ro="[DONE]",zo="[DBG]",Lo={debug:0,verbose:1,info:2,success:3,warn:4,error:5};function Uo(e){return`${bo}${wo}${e}${vo}`}class Oo{constructor(e,t,i="info"){var o,s;this.log=e,this.silent="json"===t,this.useColor=this.detectColorSupport(),this.level=i,this.levelPriority=(s=()=>2,null!=(o=Lo[i])?o:s())}detectColorSupport(){return!0===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}([process,"access",e=>e.stderr,"optionalAccess",e=>e.isTTY])&&void 0===process.env.NO_COLOR}paint(e,t){return this.useColor?`${e}${t}${vo}`:t}shouldOutput(e){return!this.silent&&Lo[e]>=this.levelPriority}verbose(e,...t){this.log.verbose(e,...t),this.shouldOutput("verbose")&&process.stderr.write(`${Uo(Io)} ${this.paint(To,e)}\n`)}info(e,...t){this.log.info(e,...t),this.shouldOutput("info")&&process.stderr.write(`${Uo(ko)} ${this.paint(vo,e)}\n`)}warn(e,...t){this.log.warn(e,...t),this.shouldOutput("warn")&&process.stderr.write(`${Uo(Ao)} ${this.paint(Co,e)}\n`)}error(e,...t){this.log.error(e,...t),this.shouldOutput("error")&&process.stderr.write(`${Uo(jo)} ${this.paint(So,e)}\n`)}success(e,...t){this.log.success(e,...t),this.shouldOutput("success")&&process.stderr.write(`${Uo(Ro)} ${this.paint(Po,e)}\n`)}debug(e,...t){this.log.debug(e,...t),this.shouldOutput("debug")&&process.stderr.write(`${Uo(zo)} ${this.paint(Eo,e)}\n`)}}class xo{constructor(e){const{format:t}=e;this.formatter=function(e){return"text"===e?new x:new P}(t)}print(e){const t=this.formatter.format(e);process.stdout.write(t)}eprint(e){const t=this.formatter.formatError(e);process.stderr.write(t)}}function Bo(e,t){return null!=e?e:t()}async function qo(e,t){const i=Date.now();e.ui.verbose(`[Logger] CLI start: ${e.argv.join(" ")}`);try{await t()}finally{const t=Date.now()-i;e.ui.verbose(`[Logger] CLI end (took ${t}ms)`)}}var Do,Mo,No,Go,$o,Fo,Vo,Wo,Ho,Jo,Ko,Qo,Yo,Zo,Xo,es,ts,is,os,ss,ns,rs,as,cs,ds,ls,ps,us,_s,hs,ms,gs,fs,ys,vs,ws,bs,Ss,Ps,Cs,Ts,Es,Is,ks,As,js,Rs,zs,Ls,Us,Os,xs,Bs,qs,Ds,Ms,Ns,Gs,$s,Fs,Vs,Ws,Hs,Js,Ks,Qs,Ys,Zs,Xs,en,tn,on,sn,nn,rn,an,cn,dn,ln,pn,un,_n,hn,mn,gn,fn,yn,vn,wn,bn,Sn,Pn,Cn,Tn,En,In,kn,An,jn,Rn,zn,Ln,Un,On,xn,Bn,qn,Dn,Mn,Nn,Gn,$n,Fn,Vn,Wn,Hn,Jn,Kn,Qn,Yn,Zn,Xn,er,tr,ir,or,sr,nr,rr,ar,cr;function dr(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[e.Start_Agent=0]="Start_Agent";e[e.LLM_Agent=1]="LLM_Agent";e[e.Task_Agent=2]="Task_Agent";e[e.Global_Agent=3]="Global_Agent";e[e.Bot_Agent=4]="Bot_Agent"}(Do||(Do={})),function(e){e[e.OldVersion=0]="OldVersion";e[e.MiddleVersion=1]="MiddleVersion";e[e.NewVersion=2]="NewVersion";e[e.MiddleVersionNotPrompt=3]="MiddleVersionNotPrompt"}(Mo||(Mo={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(No||(No={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(Go||(Go={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}($o||($o={})),function(e){e[e.Current=1]="Current";e[e.Previous=2]="Previous";e[e.Start=3]="Start";e[e.MostSuitable=4]="MostSuitable"}(Fo||(Fo={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Vo||(Vo={})),function(e){e[e.Default=0]="Default";e[e.Function=1]="Function"}(Wo||(Wo={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned"}(Ho||(Ho={})),function(e){e[e.LimitedReadWrite=1]="LimitedReadWrite";e[e.ReadOnly=2]="ReadOnly";e[e.UnlimitedReadWrite=3]="UnlimitedReadWrite";e[e.RWModeMax=4]="RWModeMax"}(Jo||(Jo={})),function(e){e[e.Default=0]="Default";e[e.DouyinAvatar=1]="DouyinAvatar"}(Ko||(Ko={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(Qo||(Qo={})),function(e){e[e.Chat=0]="Chat";e[e.FunctionCall_1=1]="FunctionCall_1";e[e.FunctionCall_2=2]="FunctionCall_2";e[e.FunctionCall_3=3]="FunctionCall_3"}(Yo||(Yo={})),function(e){e[e.NotSet=0]="NotSet";e[e.Text=1]="Text";e[e.Voice=2]="Voice";e[e.Call=3]="Call";e[e.VideoCall=4]="VideoCall"}(Zo||(Zo={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Xo||(Xo={})),function(e){e[e.Text=1]="Text";e[e.Number=2]="Number";e[e.Date=3]="Date";e[e.Float=4]="Float";e[e.Boolean=5]="Boolean"}(es||(es={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(ts||(ts={})),function(e){e[e.SLM=0]="SLM";e[e.LLM=1]="LLM"}(is||(is={})),function(e){e[e.Pre=1]="Pre";e[e.Post=2]="Post";e[e.PreAndPost=3]="PreAndPost"}(os||(os={})),function(e){e[e.Default=0]="Default";e[e.CustomizePrompt=1]="CustomizePrompt"}(ss||(ss={})),function(e){e[e.ReplyBottom=0]="ReplyBottom";e[e.CardList=1]="CardList"}(ns||(ns={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(rs||(rs={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(as||(as={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(cs||(cs={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Trigger=4]="Trigger";e[e.KnowledgeText=5]="KnowledgeText";e[e.KnowledgeTable=6]="KnowledgeTable";e[e.KnowledgeAutoCall=7]="KnowledgeAutoCall";e[e.KnowledgeOnDemandCall=8]="KnowledgeOnDemandCall";e[e.Variable=9]="Variable";e[e.Database=10]="Database";e[e.LongTermMemory=11]="LongTermMemory";e[e.FileBox=12]="FileBox";e[e.Onboarding=13]="Onboarding";e[e.Suggestion=14]="Suggestion";e[e.ShortcutCommand=15]="ShortcutCommand";e[e.BackGroundImage=16]="BackGroundImage";e[e.TTS=17]="TTS";e[e.MultiAgentRecognize=18]="MultiAgentRecognize";e[e.KnowledgePhoto=19]="KnowledgePhoto";e[e.HookInfo=20]="HookInfo";e[e.KnowledgeValcanoUnstructured=21]="KnowledgeValcanoUnstructured";e[e.KnowledgeValcanoStructured=22]="KnowledgeValcanoStructured";e[e.Model=23]="Model";e[e.KnowledgeThirdPartyUnstructured=24]="KnowledgeThirdPartyUnstructured";e[e.KnowledgeThirdPartyStructured=25]="KnowledgeThirdPartyStructured"}(ds||(ds={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(ls||(ls={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(ps||(ps={})),function(e){e[e.Curve=0]="Curve";e[e.Straight=1]="Straight"}(us||(us={})),function(e){e[e.Flow=1]="Flow";e[e.Host=2]="Host"}(_s||(_s={})),function(e){e[e.NO_NEED=1]="NO_NEED";e[e.USE_MANUAL=2]="USE_MANUAL";e[e.USE_LLM=3]="USE_LLM"}(hs||(hs={})),function(e){e[e.EQUAL=1]="EQUAL";e[e.NOT_EQUAL=2]="NOT_EQUAL";e[e.GREATER_THAN=3]="GREATER_THAN";e[e.LESS_THAN=4]="LESS_THAN";e[e.GREATER_EQUAL=5]="GREATER_EQUAL";e[e.LESS_EQUAL=6]="LESS_EQUAL";e[e.IN=7]="IN";e[e.NOT_IN=8]="NOT_IN";e[e.IS_NULL=9]="IS_NULL";e[e.IS_NOT_NULL=10]="IS_NOT_NULL";e[e.LIKE=11]="LIKE";e[e.NOT_LIKE=12]="NOT_LIKE"}(ms||(ms={})),function(e){e[e.Input=0]="Input";e[e.Variable=1]="Variable"}(gs||(gs={})),function(e){e[e.Default=0]="Default";e[e.FromSaas=1]="FromSaas"}(fs||(fs={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(ys||(ys={})),function(e){e[e.FunctionCall=1]="FunctionCall";e[e.Independent=2]="Independent"}(vs||(vs={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(ws||(ws={})),function(e){e[e.ManualUpdate=1]="ManualUpdate";e[e.AutoUpdate=2]="AutoUpdate"}(bs||(bs={})),function(e){e[e.SemanticSearch=0]="SemanticSearch";e[e.HybirdSearch=1]="HybirdSearch";e[e.FullTextSearch=20]="FullTextSearch"}(Ss||(Ss={})),function(e){e[e.Public=1]="Public";e[e.Anonymous=2]="Anonymous";e[e.Custom=3]="Custom"}(Ps||(Ps={})),function(e){e[e.Random=0]="Random";e[e.All=1]="All"}(Cs||(Cs={})),function(e){e[e.System=0]="System";e[e.Custom=1]="Custom";e[e.Disable=2]="Disable";e[e.OriBot=3]="OriBot"}(Ts||(Ts={})),function(e){e[e.ListString=1]="ListString";e[e.String=2]="String";e[e.Integer=3]="Integer";e[e.Float=4]="Float";e[e.Boolean=5]="Boolean"}(Es||(Es={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Is||(Is={})),function(e){e[e.CozeOldTimeCapsule=0]="CozeOldTimeCapsule";e[e.VolcanoTimeCapsule=1]="VolcanoTimeCapsule"}(ks||(ks={})),function(e){e[e.Workflow=0]="Workflow";e[e.Imageflow=1]="Imageflow";e[e.SceneFlow=2]="SceneFlow";e[e.ChatFlow=3]="ChatFlow";e[e.All=100]="All"}(As||(As={})),function(e){e[e.BotQuery=1]="BotQuery";e[e.Plugin=2]="Plugin";e[e.Workflow=3]="Workflow"}(js||(js={})),function(e){e[e.Unknown=0]="Unknown";e[e.Webhook=1]="Webhook"}(Rs||(Rs={})),function(e){e[e.Unknown=0]="Unknown";e[e.Time=1]="Time";e[e.Event=2]="Event"}(zs||(zs={})),function(e){e[e.NoHistory=0]="NoHistory";e[e.NeedHistory=1]="NeedHistory"}(Ls||(Ls={})),function(e){e[e.NoTriggered=0]="NoTriggered";e[e.Triggered=1]="Triggered";e[e.DoAction=2]="DoAction";e[e.WaitToPush=3]="WaitToPush";e[e.PushSuccess=4]="PushSuccess";e[e.PushFail=5]="PushFail"}(Us||(Us={})),function(e){e[e.Init=0]="Init";e[e.Activated=1]="Activated";e[e.Deactivated=2]="Deactivated";e[e.Suspended=3]="Suspended"}(Os||(Os={})),function(e){e[e.Preset=1]="Preset";e[e.UserTask=2]="UserTask";e[e.PluginRunTask=3]="PluginRunTask"}(xs||(xs={})),function(e){e[e.Deploying=0]="Deploying";e[e.Successful=1]="Successful";e[e.Failed=2]="Failed"}(Bs||(Bs={})),function(e){e[e.All=0]="All";e[e.Bind=1]="Bind";e[e.UnBind=2]="UnBind"}(qs||(qs={})),function(e){e[e.CreateTime=0]="CreateTime";e[e.UpdateTime=1]="UpdateTime"}(Ds||(Ds={})),function(e){e[e.EventMeta=1]="EventMeta";e[e.ProfileMeta=2]="ProfileMeta"}(Ms||(Ms={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Ns||(Ns={})),function(e){e[e.GPT=1]="GPT";e[e.SEED=2]="SEED";e[e.Claude=3]="Claude";e[e.MiniMax=4]="MiniMax";e[e.Plugin=5]="Plugin";e[e.StableDiffusion=6]="StableDiffusion";e[e.ByteArtist=7]="ByteArtist";e[e.Maas=9]="Maas";e[e.QianFan=10]="QianFan";e[e.Gemini=11]="Gemini";e[e.Moonshot=12]="Moonshot";e[e.GLM=13]="GLM";e[e.MaaSAutoSync=14]="MaaSAutoSync";e[e.QWen=15]="QWen";e[e.Cohere=16]="Cohere";e[e.Baichuan=17]="Baichuan";e[e.Ernie=18]="Ernie";e[e.DeekSeek=19]="DeekSeek";e[e.Llama=20]="Llama";e[e.StepFun=23]="StepFun";e[e.Custom=24]="Custom";e[e.Other=999]="Other"}(Gs||(Gs={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}($s||($s={})),function(e){e[e.ModelType=1]="ModelType";e[e.ModelUserRight=2]="ModelUserRight";e[e.ModelFeature=3]="ModelFeature";e[e.ModelFunction=4]="ModelFunction";e[e.ModelPaid=15]="ModelPaid";e[e.ModelAbility=16]="ModelAbility";e[e.ModelStatus=17]="ModelStatus";e[e.Custom=20]="Custom";e[e.Others=100]="Others"}(Fs||(Fs={})),function(e){e[e.Flagship=1]="Flagship";e[e.HighSpeed=2]="HighSpeed";e[e.ToolInvocation=3]="ToolInvocation";e[e.RolePlaying=4]="RolePlaying";e[e.LongText=5]="LongText";e[e.ImageUnderstanding=6]="ImageUnderstanding";e[e.Reasoning=7]="Reasoning";e[e.VideoUnderstanding=8]="VideoUnderstanding";e[e.CostPerformance=9]="CostPerformance";e[e.CodeSpecialization=10]="CodeSpecialization";e[e.AudioUnderstanding=11]="AudioUnderstanding"}(Vs||(Vs={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(Ws||(Ws={})),function(e){e[e.Start_Agent=0]="Start_Agent";e[e.LLM_Agent=1]="LLM_Agent";e[e.Task_Agent=2]="Task_Agent";e[e.Global_Agent=3]="Global_Agent";e[e.Bot_Agent=4]="Bot_Agent"}(Hs||(Hs={})),function(e){e[e.Upgrade=1]="Upgrade";e[e.BrowseOldNoPrompt=2]="BrowseOldNoPrompt"}(Js||(Js={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(Ks||(Ks={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(Qs||(Qs={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(Ys||(Ys={})),function(e){e[e.Visit=1]="Visit";e[e.Edit=2]="Edit"}(Zs||(Zs={})),function(e){e[e.Online=1]="Online";e[e.Offline=2]="Offline"}(Xs||(Xs={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online"}(en||(en={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(tn||(tn={})),function(e){e[e.AutoGenBeforePublish=1]="AutoGenBeforePublish"}(on||(on={})),function(e){e[e.CozeHome=1]="CozeHome";e[e.Space=2]="Space"}(sn||(sn={})),function(e){e[e.Undefined=0]="Undefined";e[e.PersonalDraft=1]="PersonalDraft";e[e.Base=2]="Base";e[e.Publish=3]="Publish"}(nn||(nn={})),function(e){e[e.Undefined=0]="Undefined";e[e.Committed=1]="Committed";e[e.Behind=2]="Behind";e[e.NoDraftReplica=3]="NoDraftReplica"}(rn||(rn={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(an||(an={})),function(e){e[e.USER_RES=0]="USER_RES";e[e.USER_LLM_RES=1]="USER_LLM_RES";e[e.USER_LLM_APILEN_RES=2]="USER_LLM_APILEN_RES";e[e.USER_LLM_API_RES=3]="USER_LLM_API_RES"}(cn||(cn={})),function(e){e[e.Personal=1]="Personal";e[e.Organization=2]="Organization"}(dn||(dn={})),function(e){e[e.Agent=1]="Agent";e[e.Project=2]="Project";e[e.Knowledge=3]="Knowledge";e[e.Dataset=4]="Dataset";e[e.Plugin=5]="Plugin";e[e.Memorybase=6]="Memorybase"}(ln||(ln={})),function(e){e[e.Text=0]="Text";e[e.Table=1]="Table";e[e.Image=2]="Image";e[e.VolcanoStructured=4]="VolcanoStructured";e[e.VolcanoUnstructured=5]="VolcanoUnstructured";e[e.ThirdPartyStructured=7]="ThirdPartyStructured";e[e.ThirdPartyUnstructured=8]="ThirdPartyUnstructured"}(pn||(pn={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned";e[e.MoveFail=3]="MoveFail"}(un||(un={})),function(e){e[e.ByteTree=1]="ByteTree";e[e.GPTAK=2]="GPTAK";e[e.MaasAK=3]="MaasAK"}(_n||(_n={})),function(e){e[e.Init=0]="Init";e[e.Generating=1]="Generating";e[e.Success=2]="Success";e[e.Fail=3]="Fail";e[e.Cancel=4]="Cancel"}(hn||(hn={})),function(e){e[e.BotStore=1]="BotStore"}(mn||(mn={})),function(e){e[e.shorcutIcon=1]="shorcutIcon"}(gn||(gn={})),function(e){e[e.Onboarding=0]="Onboarding";e[e.BackgroundImage=1]="BackgroundImage"}(fn||(fn={})),function(e){e[e.BasicUser=1]="BasicUser";e[e.ExternalUser=2]="ExternalUser";e[e.RootUser=3]="RootUser"}(yn||(yn={})),function(e){e[e.GetInfo=1]="GetInfo"}(vn||(vn={})),function(e){e[e.Normal=1]="Normal";e[e.Invalid=2]="Invalid";e[e.Expired=3]="Expired";e[e.Rejected=4]="Rejected";e[e.Applying=5]="Applying"}(wn||(wn={})),function(e){e[e.Apply=1]="Apply";e[e.Invite=2]="Invite";e[e.EnterpriseApply=3]="EnterpriseApply"}(bn||(bn={})),function(e){e[e.GPT=1]="GPT";e[e.Claude=3]="Claude";e[e.Gemini=11]="Gemini";e[e.Moonshot=12]="Moonshot";e[e.GLM=13]="GLM";e[e.QWen=15]="QWen";e[e.DeekSeek=19]="DeekSeek";e[e.StepFun=23]="StepFun"}(Sn||(Sn={})),function(e){e[e.Douyin=1]="Douyin"}(Pn||(Pn={})),function(e){e[e.GPTOpenAPI=1]="GPTOpenAPI";e[e.Maas=2]="Maas";e[e.LLMFlow=3]="LLMFlow";e[e.Merlin=4]="Merlin"}(Cn||(Cn={})),function(e){e[e.Move=0]="Move";e[e.ForcedMove=1]="ForcedMove";e[e.RetryMove=2]="RetryMove";e[e.Preview=3]="Preview";e[e.ViewTask=4]="ViewTask";e[e.CancelTask=5]="CancelTask"}(Tn||(Tn={})),function(e){e[e.All=0]="All";e[e.Unread=1]="Unread"}(En||(En={})),function(e){e[e.Bot=1]="Bot"}(In||(In={})),function(e){e[e.CharactersAnime=1]="CharactersAnime";e[e.CharactersRealistic=2]="CharactersRealistic";e[e.CharactersCGThickPainting=3]="CharactersCGThickPainting";e[e.CharactersJapaneseShowa=4]="CharactersJapaneseShowa";e[e.CharactersAmericanComics=5]="CharactersAmericanComics";e[e.CharactersChineseWatercolor=6]="CharactersChineseWatercolor";e[e.ScenesScienceFiction=7]="ScenesScienceFiction";e[e.ScenesRealistic=8]="ScenesRealistic";e[e.ScenesChinesePainting=9]="ScenesChinesePainting";e[e.ScenesCartoonIllustrations=10]="ScenesCartoonIllustrations";e[e.ScenesCartoon3D=11]="ScenesCartoon3D"}(kn||(kn={})),function(e){e[e.IconStatic=1]="IconStatic";e[e.IconGif=2]="IconGif";e[e.BackgroundStatic=3]="BackgroundStatic";e[e.BackgroundGif=4]="BackgroundGif";e[e.PicPrompt=5]="PicPrompt"}(An||(An={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ShortcutCommand=3]="ShortcutCommand";e[e.Task=4]="Task"}(jn||(jn={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Knowledge=4]="Knowledge"}(Rn||(Rn={})),function(e){e[e.NoPublish=0]="NoPublish";e[e.HadPublished=1]="HadPublished"}(zn||(zn={})),function(e){e[e.Success=1]="Success";e[e.Failed=2]="Failed";e[e.InReview=3]="InReview"}(Ln||(Ln={})),function(e){e[e.Unread=1]="Unread";e[e.Read=2]="Read"}(Un||(Un={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(On||(On={})),function(e){e[e.UnLimit=1]="UnLimit";e[e.Forbidden=2]="Forbidden"}(xn||(xn={})),function(e){e[e.Plugin=1]="Plugin";e[e.NewBotIDEGuide=2]="NewBotIDEGuide";e[e.NewBeginnerGuide=3]="NewBeginnerGuide"}(Bn||(Bn={})),function(e){e[e.Default=0]="Default";e[e.Explore=1]="Explore";e[e.BotStore=2]="BotStore";e[e.CozeHome=3]="CozeHome";e[e.Playground=4]="Playground";e[e.Evaluation=5]="Evaluation";e[e.AgentApp=6]="AgentApp";e[e.GenerateAgentInfo=8]="GenerateAgentInfo";e[e.Template=9]="Template";e[e.EnterpriseStore=10]="EnterpriseStore"}(qn||(qn={})),function(e){e[e.All=0]="All";e[e.Self=1]="Self"}(Dn||(Dn={})),function(e){e[e.All=0]="All";e[e.Joined=1]="Joined";e[e.Confirming=2]="Confirming";e[e.Rejected=3]="Rejected";e[e.AutoApproved=4]="AutoApproved"}(Mn||(Mn={})),function(e){e[e.All=0]="All";e[e.Joined=1]="Joined";e[e.Confirming=2]="Confirming";e[e.Rejected=3]="Rejected";e[e.Revoked=4]="Revoked";e[e.Expired=5]="Expired"}(Nn||(Nn={})),function(e){e[e.EnterpriseUser=1]="EnterpriseUser";e[e.ExternalUser=2]="ExternalUser"}(Gn||(Gn={})),function(e){e[e.Normal=0]="Normal";e[e.DevMode=1]="DevMode"}($n||($n={})),function(e){e[e.DraftBot=1]="DraftBot";e[e.Project=2]="Project";e[e.Space=3]="Space";e[e.DouyinAvatarBot=4]="DouyinAvatarBot"}(Fn||(Fn={})),function(e){e[e.Default=0]="Default";e[e.Owner=1]="Owner";e[e.Admin=2]="Admin";e[e.Member=3]="Member";e[e.Guest=4]="Guest"}(Vn||(Vn={})),function(e){e[e.Professional=1]="Professional"}(Wn||(Wn={})),function(e){e[e.Personal=1]="Personal";e[e.Team=2]="Team"}(Hn||(Hn={})),function(e){e[e.Dark=1]="Dark";e[e.Light=2]="Light"}(Jn||(Jn={})),function(e){e[e.AlwaysOn=0]="AlwaysOn";e[e.AlwaysOff=1]="AlwaysOff"}(Kn||(Kn={})),function(e){e[e.CozeAssistantGuide=1]="CozeAssistantGuide"}(Qn||(Qn={})),function(e){e[e.Normal=1]="Normal";e[e.Banned=2]="Banned";e[e.Canceled=3]="Canceled"}(Yn||(Yn={})),function(e){e[e.External=0]="External";e[e.Internal=1]="Internal"}(Zn||(Zn={})),function(e){e[e.Invisible=0]="Invisible";e[e.Visible=1]="Visible";e[e.SocietyInvisible=2]="SocietyInvisible"}(Xn||(Xn={})),function(e){e[e.SingleAgent=1]="SingleAgent";e[e.MultiAgent=2]="MultiAgent";e[e.WorkflowAsAgent=3]="WorkflowAsAgent"}(er||(er={})),function(e){e[e.Preset=1]="Preset";e[e.Library=2]="Library"}(tr||(tr={})),function(e){e[e.DatasetServiceValid=0]="DatasetServiceValid";e[e.DatasetServiceInvalid=1]="DatasetServiceInvalid"}(ir||(ir={})),function(e){e[e.DatasetValid=0]="DatasetValid";e[e.DatasetInvalid=1]="DatasetInvalid"}(or||(or={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(sr||(sr={})),function(e){e[e.Workflow=0]="Workflow";e[e.Imageflow=1]="Imageflow";e[e.SceneFlow=2]="SceneFlow";e[e.ChatFlow=3]="ChatFlow";e[e.All=100]="All"}(nr||(nr={})),function(e){e[e.TextInput=0]="TextInput";e[e.Select=1]="Select";e[e.UploadImage=2]="UploadImage";e[e.UploadDoc=3]="UploadDoc";e[e.UploadTable=4]="UploadTable";e[e.UploadAudio=5]="UploadAudio";e[e.MixUpload=6]="MixUpload";e[e.VIDEO=7]="VIDEO";e[e.ARCHIVE=8]="ARCHIVE";e[e.CODE=9]="CODE";e[e.TXT=10]="TXT";e[e.PPT=11]="PPT"}(rr||(rr={})),function(e){e[e.SendTypeQuery=0]="SendTypeQuery";e[e.SendTypePanel=1]="SendTypePanel"}(ar||(ar={})),function(e){e[e.ToolTypeWorkFlow=1]="ToolTypeWorkFlow";e[e.ToolTypePlugin=2]="ToolTypePlugin"}(cr||(cr={}));class lr{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){lr.prototype.__init.call(this),lr.prototype.__init2.call(this),this.request=dr([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=dr([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}GetSpaceInfoV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/info"),s={space_id:i.space_id,join_space_type:i.join_space_type};return this.request({url:o,method:"POST",data:s},t)}DeleteSpaceV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/delete"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}SaveSpaceV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/save"),s={space_id:i.space_id,name:i.name,description:i.description,icon_uri:i.icon_uri,space_type:i.space_type,space_mode:i.space_mode,space_config:i.space_config,enterprise_id:i.enterprise_id,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}GetSpaceListV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/list"),s={search_word:i.search_word,enterprise_id:i.enterprise_id,organization_id:i.organization_id,scope_type:i.scope_type,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}UpdateAgent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/update_agent"),s={id:i.id,reference_id:i.reference_id,current_version:i.current_version,space_id:i.space_id,bot_id:i.bot_id,base_commit_version:i.base_commit_version,name:i.name,description:i.description,position:i.position,icon_uri:i.icon_uri,intents:i.intents,work_info:i.work_info,is_delete:i.is_delete};return this.request({url:o,method:"POST",data:s},t)}BatchCreateAgent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/batch_create_agent"),s={space_id:i.space_id,bot_id:i.bot_id,agent_type:i.agent_type,position:i.position,references:i.references,agent_cnt:i.agent_cnt,base_commit_version:i.base_commit_version,version_compat:i.version_compat};return this.request({url:o,method:"POST",data:s},t)}GetPublishBotList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_publish_bot_list"),s={space_id:i.space_id,bot_mode:i.bot_mode,page_num:i.page_num,page_size:i.page_size,name:i.name,login_user_create:i.login_user_create,bot_id:i.bot_id};return this.request({url:o,method:"GET",params:s},t)}MGetBotByVersion(e,t){const i=e,o=this.genBaseURL("/api/playground_api/mget_bot_by_version"),s={bot_versions:i.bot_versions,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}BotLastPublishInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bot_last_publish_info"),s={space_id:i.space_id,bot_id:i.bot_id,bot_mode:i.bot_mode};return this.request({url:o,method:"GET",params:s},t)}ProduceBot(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/produce/create_bot"),s={space_id:i.space_id,name:i.name,description:i.description,icon_url:i.icon_url,icon_uri:i.icon_uri,prompt:i.prompt,plugin_apis:i.plugin_apis,prologue:i.prologue,suggested_questions:i.suggested_questions,bot_source:i.bot_source};return this.request({url:o,method:"POST",data:s},t)}UpdateProducedBot(e,t){const i=e,o=this.genBaseURL("/api/playground_api/produce/update_bot"),s={bot_id:i.bot_id,name:i.name,description:i.description,icon_url:i.icon_url,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}GetPublishedBotList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bot_version/get_published_bot_list"),s={space_id_list:i.space_id_list,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}GetBotVersionInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bot_version/get_bot_version_info"),s={bot_id:i.bot_id,version:i.version,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}DuplicateBotVersionToSpace(e,t){const i=e,o=this.genBaseURL("/api/playground_api/dup_bot_version"),s={target_space_id:i.target_space_id,bot_id:i.bot_id,version:i.version,name:i.name,dup_society_host:i.dup_society_host};return this.request({url:o,method:"POST",data:s},t)}UpdateUserRiskAlertInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/update_user_risk_alert_info"),s={risk_alert_type:i.risk_alert_type,switch_info:i.switch_info};return this.request({url:o,method:"POST",data:s},t)}GetUserRiskAlertInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_user_risk_alert_info"),s={risk_alert_type_list:i.risk_alert_type_list,switch_type_list:i.switch_type_list},n={Cookie:i.Cookie};return this.request({url:o,method:"POST",data:s,headers:n},t)}DraftBotCollaboration(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/collaboration"),s={space_id:i.space_id,bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}BotInfoAudit(e,t){const i=e,o=this.genBaseURL("/api/playground_api/audit/bot_info"),s={bot_id:i.bot_id,bot_audit_info:i.bot_audit_info,space_id:i.space_id,bot_mode:i.bot_mode};return this.request({url:o,method:"POST",data:s},t)}TimeCapsuleInvokeEvent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/timecapsule_invoke_event"),s={bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}InviteMemberLinkV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/invite"),s={space_id:i.space_id,team_invite_link_status:i.team_invite_link_status,func:i.func};return this.request({url:o,method:"POST",data:s},t)}SpaceMemberDetailV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/detail"),s={space_id:i.space_id,search_word:i.search_word,space_role_type:i.space_role_type,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}JoinSpaceV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/join"),s={space_id:i.space_id,join_space_type:i.join_space_type,is_reject:i.is_reject};return this.request({url:o,method:"POST",data:s},t)}UpdateSpaceMemberV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/update"),s={space_id:i.space_id,user_id:i.user_id,space_role_type:i.space_role_type};return this.request({url:o,method:"POST",data:s},t)}TransferSpaceV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/transfer"),s={space_id:i.space_id,transfer_user_id:i.transfer_user_id};return this.request({url:o,method:"POST",data:s},t)}RemoveSpaceMemberV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/remove"),s={space_id:i.space_id,remove_user_id:i.remove_user_id,transfer_user_id:i.transfer_user_id};return this.request({url:o,method:"POST",data:s},t)}SearchMemberV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/member/search"),s={search_list:i.search_list,space_id:i.space_id,search_volcano_account_list:i.search_volcano_account_list,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}AddBotSpaceMemberV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/member/add"),s={member_info_list:i.member_info_list,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}ExitSpaceV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/exit"),s={space_id:i.space_id,transfer_user_id:i.transfer_user_id};return this.request({url:o,method:"POST",data:s},t)}GetBotPopupInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/operate/get_bot_popup_info"),s={bot_popup_types:i.bot_popup_types,bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}UpdateBotPopupInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/operate/update_bot_popup_info"),s={bot_popup_type:i.bot_popup_type,bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}GenerateDescription(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/generate_description"),s={bot_name:i.bot_name,prompt:i.prompt};return this.request({url:o,method:"POST",data:s},t)}DraftBotPublishHistoryDetail(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/publish_history_detail"),s={bot_id:i.bot_id,space_id:i.space_id,publish_id:i.publish_id,version:i.version};return this.request({url:o,method:"POST",data:s},t)}GenerateStoreCategory(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/generate_store_category"),s={bot_name:i.bot_name,bot_description:i.bot_description,prompt:i.prompt};return this.request({url:o,method:"POST",data:s},t)}UpdateMultiAgent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/update_multi_agent"),s={space_id:i.space_id,bot_id:i.bot_id,session_type:i.session_type,base_commit_version:i.base_commit_version,connector_type:i.connector_type};return this.request({url:o,method:"POST",data:s},t)}SwitchAgentVersion(e,t){const i=e,o=this.genBaseURL("/api/playground_api/switch_agent_version"),s={bot_id:i.bot_id,space_id:i.space_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}LangDetect(e,t){const i=e,o=this.genBaseURL("/api/playground_api/audio/lang/detect"),s={detect_text_list:i.detect_text_list};return this.request({url:o,method:"POST",data:s},t)}GetImagexShortUrl(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_imagex_url"),s={uris:i.uris,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetPlatformCommonConfig(e,t){const i=this.genBaseURL("/api/playground_api/get_platform_common_config");return this.request({url:i,method:"GET"},t)}CreateShortcutCommand(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/create_shortcut_command"),s={object_id:i.object_id,shortcuts:i.shortcuts};return this.request({url:o,method:"POST",data:s},t)}MGetUserBasicInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/mget_user_info"),s={user_ids:i.user_ids,need_user_status:i.need_user_status,need_enterprise_identity:i.need_enterprise_identity,need_volcano_user_name:i.need_volcano_user_name};return this.request({url:o,method:"POST",data:s},t)}BindVolcanoTrn(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/bind_volcano_trn"),s={space_id:i.space_id,trn:i.trn,account_name:i.account_name};return this.request({url:o,method:"POST",data:s},t)}UnbindVolcanoTrn(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/unbind_volcano_trn"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}RetrieveFileOpen(e,t){const i=e,o=this.genBaseURL("/v1/files/retrieve"),s={file_id:i.file_id};return this.request({url:o,method:"GET",params:s},t)}RetrieveFileContentOpen(e,t){const i=e,o=this.genBaseURL("/v1/files/content/retrieve"),s={file_id:i.file_id};return this.request({url:o,method:"GET",params:s},t)}UploadFileOpen(e,t){const i=e,o=this.genBaseURL("/v1/files/upload"),s={Data:i.Data},n={"Content-Type":i["Content-Type"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}BotInfoCheck(e,t){const i=e,o=this.genBaseURL("/api/playground_api/check/bot_info_check"),s={bot_id:i.bot_id,space_id:i.space_id,bot_audit_info:i.bot_audit_info};return this.request({url:o,method:"POST",data:s},t)}SupportVoiceCall(e,t){const i=e,o=this.genBaseURL("/api/playground_api/support_voice_call"),s={voice_id_list:i.voice_id_list};return this.request({url:o,method:"POST",data:s},t)}CreateUpdateShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/playground_api/create_update_shortcut_command"),s={object_id:i.object_id,space_id:i.space_id,shortcuts:i.shortcuts};return this.request({url:o,method:"POST",data:s},t)}MoveDraftBot(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/move_draft_bot"),s={bot_id:i.bot_id,target_spaceId:i.target_spaceId,from_spaceId:i.from_spaceId,move_action:i.move_action};return this.request({url:o,method:"POST",data:s},t)}GetShortcutAvailNodes(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_shortcut_avail_nodes"),s={bot_id:i.bot_id,space_id:i.space_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}MarkReadNotice(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gen_img/mark_read_notice"),s={bot_id:i.bot_id,pic_type:i.pic_type};return this.request({url:o,method:"POST",data:s},t)}CancelGenerateGif(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gen_img/cancel_generate_gif"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}GetPicTask(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gen_img/get_pic_task"),s={bot_id:i.bot_id,pic_type:i.pic_type};return this.request({url:o,method:"POST",data:s},t)}GeneratePic(e,t){const i=e,o=this.genBaseURL("/api/playground_api/gen_img/generate_pic"),s={gen_prompt:i.gen_prompt,image_url:i.image_url,image_uri:i.image_uri,bot_id:i.bot_id,pic_type:i.pic_type,device_id:i.device_id,bot_name:i.bot_name,bot_desc:i.bot_desc};return this.request({url:o,method:"POST",data:s},t)}GetGenPicTimes(e,t){const i=this.genBaseURL("/api/playground_api/gen_img/get_gen_pic_times");return this.request({url:i,method:"POST"},t)}ListStyle(e,t){const i=this.genBaseURL("/api/playground_api/gen_img/list_style");return this.request({url:i,method:"POST"},t)}GetFileUrls(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_file_list"),s={scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetDraftBotInfoAgw(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/get_draft_bot_info"),s={bot_id:i.bot_id,version:i.version,commit_version:i.commit_version};return this.request({url:o,method:"POST",data:s},t)}CommitDraftBotInfoAgw(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/commit_draft_bot_info"),s={bot_id:i.bot_id,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}UpdateDraftBotInfoAgw(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/draftbot/update_draft_bot_info"),s={bot_info:i.bot_info,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}GetUserQueryCollectOption(e,t){const i=this.genBaseURL("/api/playground_api/draftbot/get_user_query_collect_option");return this.request({url:i,method:"GET"},t)}GenerateUserQueryCollectPolicy(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/draftbot/generate_user_query_collect_policy"),s={bot_id:i.bot_id,developer_name:i.developer_name,contact_information:i.contact_information};return this.request({url:o,method:"POST",data:s},t)}GetCozeProRights(e,t){const i=this.genBaseURL("/api/playground_api/get_coze_pro_rights");return this.request({url:i,method:"POST"},t)}GetPolicyContent(e,t){const i=e,o=this.genBaseURL(`/api/playground_api/private_policy/${i.secret}`);return this.request({url:o,method:"GET"},t)}UpdateAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/update_agent_v2"),s={id:i.id,reference_id:i.reference_id,current_version:i.current_version,space_id:i.space_id,bot_id:i.bot_id,base_commit_version:i.base_commit_version,name:i.name,description:i.description,position:i.position,icon_uri:i.icon_uri,intents:i.intents,is_delete:i.is_delete,prompt_info:i.prompt_info,model_info:i.model_info,plugin_info_list:i.plugin_info_list,knowledge:i.knowledge,workflow_info_list:i.workflow_info_list,jump_config:i.jump_config,suggest_reply_info:i.suggest_reply_info,hook_info:i.hook_info};return this.request({url:o,method:"POST",data:s},t)}CopyAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/copy_agent_v2"),s={bot_id:i.bot_id,agent_id:i.agent_id,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}CreateAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/create_agent_v2"),s={bot_id:i.bot_id,agent_type:i.agent_type,position:i.position,references:i.references,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}BatchCreateAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/batch_create_agent_v2"),s={bot_id:i.bot_id,agent_type:i.agent_type,position:i.position,references:i.references,agent_cnt:i.agent_cnt,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}CozeProCopyGetLinkMetaInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/get_link_meta_info"),s={auth_code:i.auth_code};return this.request({url:o,method:"POST",data:s},t)}CozeProCopyTaskConfirm(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/copy_task_confirm"),s={auth_code:i.auth_code};return this.request({url:o,method:"POST",data:s},t)}CozeProCopyGenerateAuthLink(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/generate_auth_link"),s={copy_user_id:i.copy_user_id,target_space_id:i.target_space_id};return this.request({url:o,method:"POST",data:s},t)}GetOpVoiceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_op_voice_list"),s={voice_ids:i.voice_ids,name:i.name,style_id:i.style_id,language_code:i.language_code,status:i.status,page_index:i.page_index,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetSupportLanguage(e,t){const i=this.genBaseURL("/api/playground_api/get_support_language");return this.request({url:i,method:"GET"},t)}SynchronizeVoiceList(e,t){const i=this.genBaseURL("/api/playground_api/synchronize_voice_list");return this.request({url:i,method:"GET"},t)}CheckBotAllModelPluginIds(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/check_bot_all_model_plugin_ids"),s={bot_id:i.bot_id,commit_version:i.commit_version};return this.request({url:o,method:"POST",data:s},t)}GetBotCollaborationQuota(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/collaboration_quota"),s={bot_id:i.bot_id,only_config_item:i.only_config_item,account_type:i.account_type};return this.request({url:o,method:"POST",data:s},t)}OpenCreateSpace(e,t){const i=e||{},o=this.genBaseURL("/v1/workspaces"),s={name:i.name,description:i.description,icon_file_id:i.icon_file_id,coze_account_id:i.coze_account_id,owner_uid:i.owner_uid};return this.request({url:o,method:"POST",data:s},t)}NoticeMarkRead(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/notice/mark_read"),s={notice_ids:i.notice_ids,mark_all:i.mark_all};return this.request({url:o,method:"POST",data:s},t)}GetNoticeList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/notice/get_list"),s={cursor:i.cursor,count:i.count,notice_rank_type:i.notice_rank_type};return this.request({url:o,method:"POST",data:s},t)}GetNoticeUnreadCount(e,t){const i=this.genBaseURL("/api/playground_api/notice/get_unread_count");return this.request({url:i,method:"POST"},t)}OpenSpaceList(e,t){const i=e||{},o=this.genBaseURL("/v1/workspaces"),s={page_num:i.page_num,page_size:i.page_size,enterprise_id:i.enterprise_id,user_id:i.user_id,coze_account_id:i.coze_account_id,scope:i.scope};return this.request({url:o,method:"GET",params:s},t)}ReportUserBehavior(e,t){const i=e,o=this.genBaseURL("/api/playground_api/report_user_behavior"),s={resource_id:i.resource_id,resource_type:i.resource_type,behavior_type:i.behavior_type,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetUserConfig(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_user_config"),s={risk_alert_type_list:i.risk_alert_type_list,switch_type_list:i.switch_type_list},n={Cookie:i.Cookie};return this.request({url:o,method:"POST",data:s,headers:n},t)}UpdateUserConfig(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/update_user_config"),s={risk_alert_type:i.risk_alert_type,switch_info:i.switch_info};return this.request({url:o,method:"POST",data:s},t)}GetRecentDraftBotList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/get_recent_draft_bot"),s={behavior_type:i.behavior_type,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}GetPromptResourceInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_prompt_resource_info"),s={prompt_resource_id:i.prompt_resource_id};return this.request({url:o,method:"GET",params:s},t)}UpsertPromptResource(e,t){const i=e,o=this.genBaseURL("/api/playground_api/upsert_prompt_resource"),s={prompt:i.prompt};return this.request({url:o,method:"POST",data:s},t)}DeletePromptResource(e,t){const i=e,o=this.genBaseURL("/api/playground_api/delete_prompt_resource"),s={prompt_resource_id:i.prompt_resource_id};return this.request({url:o,method:"POST",data:s},t)}GetPromptReferenceInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_prompt_reference_info"),s={space_id:i.space_id,reference_id:i.reference_id,reference_type:i.reference_type,api_id:i.api_id,project_id:i.project_id,avatar_bot_id:i.avatar_bot_id};return this.request({url:o,method:"POST",data:s},t)}GetOfficialPromptResourceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_official_prompt_list"),s={keyword:i.keyword};return this.request({url:o,method:"POST",data:s},t)}GetByteTreeByName(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/search_byte_tree"),s={name:i.name},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}CreatePrivateModel(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/create_private_model"),s={space_id:i.space_id,model_vendor:i.model_vendor,model_show_name:i.model_show_name,model_arch:i.model_arch,ak:i.ak,token_limit:i.token_limit,upper_limit_of_max_token:i.upper_limit_of_max_token,function_call:i.function_call,multimodal:i.multimodal,multimodal_types:i.multimodal_types,form_detail:i.form_detail,record_id:i.record_id,maas_model_name:i.maas_model_name,maas_model_version:i.maas_model_version,maas_model_customer_id:i.maas_model_customer_id,model_family:i.model_family,space_id_i18n:i.space_id_i18n,operator:i.operator,email:i.email,employee_id:i.employee_id,presence_penalty_config:i.presence_penalty_config,frequency_penalty_config:i.frequency_penalty_config,temperature_config:i.temperature_config,top_p_config:i.top_p_config},n={"x-inner-auth":i["x-inner-auth"],"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}CheckExemptFormInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/check_exempt_form_info"),s={exempt_form_type:i.exempt_form_type,space_id:i.space_id},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}SetByteTreeForSpace(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/set_byte_tree_for_space"),s={space_id:i.space_id,byte_tree_node_id:i.byte_tree_node_id,byte_tree_node_name:i.byte_tree_node_name,form_detail:i.form_detail,record_id:i.record_id},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}GetModelCapability(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bpm/get_model_capability"),s={vendor:i.vendor,model_arch:i.model_arch,maas_model_name:i.maas_model_name,maas_model_version:i.maas_model_version,maas_customer_id:i.maas_customer_id},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}GetSpaceDetail(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/detail"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}RevocateSpaceInvite(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/revocate_invite"),s={space_id:i.space_id,invite_user_id:i.invite_user_id};return this.request({url:o,method:"GET",params:s},t)}SaveVolcanoUserManageInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/save_volcano_user_manage_info"),s={volcano_basic_user_config:i.volcano_basic_user_config};return this.request({url:o,method:"POST",data:s},t)}GetVolcanoUserManageInfo(e,t){const i=this.genBaseURL("/api/playground_api/coze_pro/get_volcano_user_manage_info");return this.request({url:i,method:"POST"},t)}GetSpaceInviteManageList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/invite_manage_list"),s={space_id:i.space_id,space_invite_status:i.space_invite_status,search_word:i.search_word,page:i.page,size:i.size};return this.request({url:o,method:"GET",params:s},t)}DebugDouYin(e,t){const i=e,o=this.genBaseURL("/api/playground_api/douyin/debug"),s={bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}GetDouYinAuthCode(e,t){const i=this.genBaseURL("/api/playground_api/douyin/get_auth_qr_code");return this.request({url:i,method:"GET"},t)}GetDouyinAvatarInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/douyin/v1/get_avatar_info"),s={is_draft:i.is_draft,body:i.body},n={"Open-Platform-App-ID":i["Open-Platform-App-ID"],"Byte-Signature":i["Byte-Signature"],"Byte-Timestamp":i["Byte-Timestamp"],"Byte-Nonce-Str":i["Byte-Nonce-Str"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}DouYinAuthUserList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/douyin/auth_user_list"),s={page_index:i.page_index,page_size:i.page_size,bind_status:i.bind_status,order_by:i.order_by};return this.request({url:o,method:"POST",data:s},t)}GetDebugDouYinStatus(e,t){const i=e,o=this.genBaseURL("/api/playground_api/douyin/get_debug_status"),s={bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}CanUserApplyClose(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/coze_pro/can_user_apply_close"),s={AccountId:i.AccountId,EventName:i.EventName,Action:i.Action,Version:i.Version},n={"X-Tt-Logid":i["X-Tt-Logid"],"X-Top-Service":i["X-Top-Service"],"X-Top-Region":i["X-Top-Region"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}CreateRoom(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/create_room"),s={bot_id:i.bot_id,conversation_id:i.conversation_id,scene:i.scene,voice_id:i.voice_id,video_config:i.video_config};return this.request({url:o,method:"POST",data:s},t)}GetVoiceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_voice_list"),s={page_index:i.page_index,page_size:i.page_size,language_code:i.language_code};return this.request({url:o,method:"POST",data:s},t)}GetVoiceByIds(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_voice_by_ids"),s={voice_id_map:i.voice_id_map,voice_type:i.voice_type,space_id:i.space_id,emotion_config:i.emotion_config,voice_biz_scene:i.voice_biz_scene};return this.request({url:o,method:"POST",data:s},t)}GrayVoice(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gray_voice"),s={bot_id:i.bot_id,language_to_voice_id:i.language_to_voice_id};return this.request({url:o,method:"POST",data:s},t)}GetSpaceApplyManageList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/apply_manage_list"),s={space_id:i.space_id,space_apply_status:i.space_apply_status,search_word:i.search_word,page:i.page,size:i.size};return this.request({url:o,method:"GET",params:s},t)}DraftBotCrossSpaceCopy(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/draftbot/crossspace_copy"),s={bot_id:i.bot_id,to_space_id:i.to_space_id};return this.request({url:o,method:"POST",data:s},t)}RemovePublishMember(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/remove_publish_member"),s={space_id:i.space_id,member_list:i.member_list};return this.request({url:o,method:"POST",data:s},t)}AddPublishMember(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/add_publish_member"),s={space_id:i.space_id,member_list:i.member_list};return this.request({url:o,method:"POST",data:s},t)}SearchAddablePublishMember(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/search_addable_publish_member"),s={space_id:i.space_id,search_word:i.search_word,cursor_id:i.cursor_id,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}PublishMemberList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/publish_member_list"),s={space_id:i.space_id,search_word:i.search_word,cursor_id:i.cursor_id,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}OperateSpaceApply(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/operate_apply"),s={space_id:i.space_id,enterprise_id:i.enterprise_id,organization_id:i.organization_id,apply_id_list:i.apply_id_list,space_apply_status:i.space_apply_status};return this.request({url:o,method:"POST",data:s},t)}ImportSpaceConfirm(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/import/confirm"),s={space_id_list:i.space_id_list,enterprise_id:i.enterprise_id,organization_id:i.organization_id,personal_space_new_name:i.personal_space_new_name,user_id_list:i.user_id_list};return this.request({url:o,method:"POST",data:s},t)}ImportSpaceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/import/list"),s={enterprise_id:i.enterprise_id,organization_id:i.organization_id,search_word:i.search_word};return this.request({url:o,method:"GET",params:s},t)}ImportSpaceUserList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/import/user_list"),s={space_id_list:i.space_id_list,enterprise_id:i.enterprise_id,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}GetDouYinInfo(e,t){const i=this.genBaseURL("/api/playground_api/douyin/get_douyin_info");return this.request({url:i,method:"POST"},t)}LongTermMemoryList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/list"),s={bot_id:i.bot_id,connector_id:i.connector_id,offset:i.offset,limit:i.limit,time_capsule_item_type:i.time_capsule_item_type};return this.request({url:o,method:"GET",params:s},t)}LongTermMemoryUpdate(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/update"),s={bot_id:i.bot_id,connector_id:i.connector_id,biz_id:i.biz_id,new_content:i.new_content,event_ms:i.event_ms,ext:i.ext,tags:i.tags,time_capsule_item_type:i.time_capsule_item_type,iid:i.iid,meta_type:i.meta_type,memory_type:i.memory_type};return this.request({url:o,method:"POST",data:s},t)}LongTermMemoryClearAll(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/clear_all"),s={bot_id:i.bot_id,connector_id:i.connector_id,time_capsule_item_type:i.time_capsule_item_type};return this.request({url:o,method:"POST",data:s},t)}LongTermMemoryDelete(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/delete"),s={bot_id:i.bot_id,connector_id:i.connector_id,biz_ids:i.biz_ids,time_capsule_item_type:i.time_capsule_item_type,iids:i.iids,memory_meta_type_map:i.memory_meta_type_map};return this.request({url:o,method:"POST",data:s},t)}LongTermMemoryVersion(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/version"),s={bot_id:i.bot_id};return this.request({url:o,method:"GET",params:s},t)}GetVoiceListV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_voice_list_v2"),s={language_code:i.language_code,space_id:i.space_id,voice_type:i.voice_type,page_size:i.page_size,next_cursor:i.next_cursor};return this.request({url:o,method:"POST",data:s},t)}GetUserUpdateProfileTag(e,t){const i=this.genBaseURL("/api/playground_api/get_user_update_profile_tag");return this.request({url:i,method:"GET"},t)}OpenRemoveSpaceMember(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members`),s={user_ids:i.user_ids};return this.request({url:o,method:"DELETE",data:s},t)}OpenSpaceMemberList(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members`),s={page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}OpenAddSpaceMember(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members`),s={users:i.users};return this.request({url:o,method:"POST",data:s},t)}OpenGetBotInfo(e,t){const i=e||{},o=this.genBaseURL(`/v1/bots/${i.bot_id}`),s={is_published:i.is_published,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}OpenApplyJoinSpace(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members/apply`),s={user_ids:i.user_ids};return this.request({url:o,method:"POST",data:s},t)}OpenRemoveSpace(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}`);return this.request({url:o,method:"DELETE"},t)}GetTypeList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_type_list"),s={model:i.model,voice:i.voice,raw_model:i.raw_model,space_id:i.space_id,cur_model_id:i.cur_model_id,cur_model_ids:i.cur_model_ids,model_scene:i.model_scene,tag_filters:i.tag_filters};return this.request({url:o,method:"POST",data:s},t)}GetCozeLaneInfo(e,t){const i=this.genBaseURL("/api/playground_api/get_coze_lane_info");return this.request({url:i,method:"POST"},t)}OpenUpdateSpaceMember(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members/${i.user_id}`),s={role_type:i.role_type};return this.request({url:o,method:"PUT",data:s},t)}OpenListBotVersions(e,t){const i=e||{},o=this.genBaseURL(`/v1/bots/${i.bot_id}/versions`),s={page_num:i.page_num,page_size:i.page_size,publish_status:i.publish_status,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}OpenSwitchBotDevelopMode(e,t){const i=e||{},o=this.genBaseURL(`/v1/bots/${i.bot_id}/collaboration_mode`),s={collaboration_mode:i.collaboration_mode};return this.request({url:o,method:"POST",data:s},t)}OpenUpdateSpace(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}`),s={name:i.name,description:i.description};return this.request({url:o,method:"PUT",data:s},t)}}const pr=new lr({});function ur(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}async function _r(t,o){if(ur([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipAuth]))return void await o();if(!t.config.accessToken)throw new e.CozeError(e.ErrorCode.E2001,"No API token found. Please authenticate first.",void 0,{fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"});if(ur([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipOrgCheck]))return void await o();const s=await async function(t){let o=t.config.organizationId,{enterpriseId:s}=t.config,n=!1;const{data:r}=await _o.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0}),a=r.enterprise_info_list||[],c=r.personal_account_info;if(o){if(!a.some((e=>ur([e,"access",e=>e.organization_info_list,"optionalAccess",e=>e.some,"call",e=>e((e=>e.organization_id===o))]))))throw new e.CozeError(e.ErrorCode.E1000,`Organization ID ${o} is invalid or not found`,void 0,{fix:"Run `coze organization list` and select a valid organization",example:"coze organization use <organization_id>"})}else{if(c.available)return!1;let r;t.ui.info(i.gray("[Context] Organization ID not found. Attempting to auto-initialize..."));for(const e of a)if(e.organization_info_list&&e.organization_info_list.length>0){const t=e.organization_info_list[0];r={id:t.organization_id,name:t.organization_name,entId:e.enterprise_id};break}if(!r)throw new e.CozeError(e.ErrorCode.E3000,"No organizations found",void 0,{fix:"Create an organization or join an existing one",example:"coze organization list"});o=r.id,s=r.entId,t.config.organizationId=o,t.config.enterpriseId=s,n=!0,t.ui.info(`[Context] Auto-selected Organization: ${r.name} (${r.id})`)}return n}(t);if(ur([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipSpaceCheck]))return s&&await hr(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId}),void await o();const n=await async function(t){const i=t.config.organizationId,{enterpriseId:o}=t.config;let{spaceId:s}=t.config,n=!1;try{if(s){const{data:t}=await pr.GetSpaceListV2({organization_id:i,enterprise_id:o}),n=ur([t,"optionalAccess",e=>e.bot_space_list])||[];if(!n.some((e=>e.id===s))){const t=i?`[Context] Space ID ${s} is invalid or not found in organization ${i}.`:`[Context] Space ID ${s} is invalid or not found.`;throw new e.CozeError(e.ErrorCode.E1000,t,void 0,{fix:"Run `coze space list` and select a valid space",example:"coze space use <space_id>"})}}else{t.ui.info("[Context] Space ID not found. Attempting to auto-initialize...");const{data:r}=await pr.GetSpaceListV2({organization_id:i,enterprise_id:o,page:1,size:1}),a=ur([r,"optionalAccess",e=>e.bot_space_list,"optionalAccess",e=>e[0]]);if(!a){const t=i?`[Context] No spaces found in organization ${i}. Please create one.`:"[Context] No spaces found. Please create one.";throw new e.CozeError(e.ErrorCode.E3000,t,void 0,{fix:"Create a space in the current organization",example:"coze space list"})}s=a.id,t.config.spaceId=s,n=!0,t.ui.success(`[Context] Auto-selected Space: ${a.name} (${a.id})`)}}catch(t){const i=t instanceof e.CozeError?t:new e.CozeError(e.ErrorCode.E5000,t.message,t instanceof Error?t.stack:t);throw i.fix??="Switch organization or space using `coze organization use <organization_id>` or `coze space use <space_id>`",i.example??="coze organization list",i}return n}(t);await mr(t),(s||n)&&await hr(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId,spaceId:t.config.spaceId,billingProjectId:t.config.billingProjectId}),await o()}async function hr(e,t){try{await s.saveConfig(t)}catch(t){e.ui.warn(`Failed to save auto-initialized context: ${t}`)}}const mr=async i=>{const{spaceId:o}=i.config;try{const{data:s}=await t.IdeApi.GetOrCreateBillingProject({space_id:o});if(!ur([s,"optionalAccess",e=>e.project_id]))throw new e.CozeError(e.ErrorCode.E5002,"[Context] Failed to get billing project ID from response.",s);i.config.billingProjectId=s.project_id,i.ui.success(`[Context] Billing Project: ${s.project_id} (space: ${o})`)}catch(e){const t=[`Failed to get billing project, ${e.message}. please check your space context:`," coze space list"," coze space use <space_id>"];throw e.message=`${t.join("\n")}`,e}};function gr(e,t){return null!=e?e:t()}function fr(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 yr=t=>{const i=t.command("space").config({skipSpaceCheck:!0,help:{brief:"Workspace (Space) context management commands",description:"Provides workspace viewing and switching functionality, used to set the default Space ID for subsequent commands",examples:[{desc:"List all available workspaces",cmd:"coze space list"},{desc:"Set default space",cmd:"coze space use 123456789"}],seeAlso:["coze organization"]}}).description("Manage workspace (Space) context");i.command("list").description("List all spaces").config({help:{brief:"List all workspaces under the current organization",description:"Retrieve and display a list of all available Spaces under the currently configured Organization or Enterprise. Defaults to fetching up to the first 100.",examples:[{desc:"List space list",cmd:"coze space list",tags:["[RECOMMENDED]"]},{desc:"List in JSON format",cmd:"coze space list --format json"}],schema:{output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Space ID"},name:{type:"string",description:"Space name"},org_id:{type:"string",description:"Belonging Organization ID"}}}}}}}).action((async(e,t)=>{const i=t.getContext(),o=e.orgId||fr([i,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),s=fr([i,"optionalAccess",e=>e.config,"access",e=>e.enterpriseId]);fr([i,"optionalAccess",e=>e.ui,"access",e=>e.verbose,"call",e=>e(`Fetching spaces for organization '${o}'...`)]);const n=await async function(e){const{data:t}=await pr.GetSpaceListV2({organization_id:e.orgId,enterprise_id:e.enterpriseId,page:1,size:100});return gr(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}([t,"optionalAccess",e=>e.bot_space_list]),(()=>[])).map((t=>({id:gr(t.id,(()=>"")),name:gr(t.name,(()=>"")),org_id:gr(e.orgId,(()=>""))})))}({orgId:o,enterpriseId:s});fr([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Spaces:")]),fr([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)]);const r=["Please use the following command to switch space:"," coze space use <space_id>"];fr([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(r.join("\n"))])})),i.command("use").description("Set the default workspace context").argument("<space_id>","Space ID to set as default context").config({help:{brief:"Switch current default Space",description:"Save the specified space_id to the local configuration as the default workspace for subsequent commands.",examples:[{desc:"Switch space",cmd:"coze space use 7349123847123",tags:["[RECOMMENDED]"]}],schema:{input:{space_id:{type:"string",required:!0,description:"Space ID to switch to"}},output:{status:{type:"string"},message:{type:"string"}}}}}).action((async(t,i,o)=>{const n=o.getContext();fr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to space '${t}'...`)]),await async function(t){try{await s.saveConfig({spaceId:t})}catch(i){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set default space to '${t}': ${i.message}`,i.stack)}}(t),fr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default space set to '${t}' successfully.`)]),"json"===fr([n,"optionalAccess",e=>e.format])&&fr([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default space set to '${t}'.`})])}))};function vr(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 wr=async t=>{vr([t,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switching to personal account...")]);const{available:i}=await async function(){const[e,{data:t}]=await Promise.all([s.loadConfig(),_o.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);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}([t.personal_account_info,"optionalAccess",e=>e.available]))return{available:!1};const i=!!e.organizationId;return await s.saveConfig({organizationId:void 0,enterpriseId:void 0,...i?{spaceId:void 0}:{}}),{available:!0}}();if(!i)throw new e.CozeError(e.ErrorCode.E1000,"Personal account is not available for the current user.");vr([t,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switched to personal account successfully.")]),"json"===vr([t,"optionalAccess",e=>e.format])&&vr([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:"Switched to personal account."})])},br=t=>{const i=t.command("organization").config({skipOrgCheck:!0,help:{brief:"Manage organization context",description:"Provides viewing and switching functions for organizations, used to set the default Organization ID for subsequent commands. Supports switching to personal account by omitting the org_id.",examples:[{desc:"List all accessible organizations",cmd:"coze organization list"},{desc:"Set default organization",cmd:"coze organization use 123456"},{desc:"Switch to personal account",cmd:"coze organization use"},{desc:"List organizations (alias)",cmd:"coze org list"},{desc:"Set default organization (alias)",cmd:"coze org use 123456"}],seeAlso:["coze space"]}}).alias("org").description("Manage organization context");i.command("list").description("List all accessible organizations").config({help:{brief:"List all accessible organizations",description:"Retrieve and display all organizations (Teams) and their corresponding enterprises accessible to the current logged-in user.",examples:[{desc:"List organizations",cmd:"coze organization list",tags:["[RECOMMENDED]"]},{desc:"Output in JSON format",cmd:"coze organization list --format json"}],schema:{output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Organization ID"},name:{type:"string",description:"Organization name"},enterprise_id:{type:"string",description:"Belonging Enterprise ID"},enterprise_name:{type:"string",description:"Belonging Enterprise name"}}}}}}}).action((async(e,t)=>{const i=t.getContext();vr([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching organizations...")]);const o=await async function(){const{data:e}=await _o.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0});return e.enterprise_info_list.flatMap((e=>(e.organization_info_list||[]).map((t=>({id:t.organization_id,name:t.organization_name,enterprise_id:e.enterprise_id,enterprise_name:e.name})))))}();vr([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Organizations (Teams):")]),vr([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(o)]);const s=["Please use the following command to switch organization:"," coze organization use <organization_id>","Please use the following command to switch space:"," coze space list"," coze space use <space_id>"];vr([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])})),i.command("use").description("Set the default organization context").argument("[org_id]","Organization ID to set as default context (empty to switch to personal account)").config({help:{brief:"Set default organization or switch to personal account",description:"Save the specified org_id to the local configuration as the default organization for subsequent commands. The command will automatically retrieve and save the corresponding Enterprise ID. If the org_id is not found in the user's enterprise list, the command will fail without modifying the configuration. When switching to a different organization, the saved spaceId will be cleared. Omit org_id to switch to personal account mode (requires personal account to be available).",examples:[{desc:"Switch organization",cmd:"coze organization use 12345678",tags:["[RECOMMENDED]"]},{desc:"Switch to personal account",cmd:"coze organization use"},{desc:"Switch to personal account (explicit empty string)",cmd:'coze organization use ""'}],errors:[{code:e.ErrorCode.E3001,name:"RESOURCE_NOT_FOUND",desc:"Organization not found",fix:"Run `coze organization list` to see available organizations."},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Personal account not available",fix:"Your account does not have personal account access. Use `coze organization use <org_id>` to switch to an organization instead."}],schema:{input:{org_id:{type:"string",required:!1,description:"Organization ID to switch to. Empty or omitted to switch to personal account."}},output:{status:{type:"string",description:"Operation result status"},message:{type:"string",description:"Human-readable result message"},enterprise_id:{type:"string",description:"Enterprise ID of the selected organization (empty for personal account)"},organization_id:{type:"string",description:"Organization ID that was set (empty for personal account)"}}}}}).action((async(t,i,o)=>{const n=o.getContext();if(!t)return void await wr(n);vr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to organization '${t}'...`)]);const{enterpriseId:r}=await async function(t){const[i,{data:o}]=await Promise.all([s.loadConfig(),_o.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);let n="",r=!1;for(const e of o.enterprise_info_list)if((e.organization_info_list||[]).find((e=>e.organization_id===t))){n=e.enterprise_id,r=!0;break}if(!r)throw new e.CozeError(e.ErrorCode.E3000,`Organization '${t}' not found in current user's enterprises.`);const a=i.organizationId!==t;return await s.saveConfig({organizationId:t,enterpriseId:n,...a?{spaceId:void 0}:{}}),{enterpriseId:n}}(t);vr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Organization '${t}' found in enterprise '${r}'. Config saved.`)]),vr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default organization set to '${t}' successfully.`)]),"json"===vr([n,"optionalAccess",e=>e.format])&&vr([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default organization set to '${t}'.`,enterprise_id:r,organization_id:t})])}))};function Sr(e,t){return null!=e?e:t()}const Pr=async(e={})=>{const t=Sr(e.stdin,(()=>process.stdin));return!0===Sr(e.isTTY,(()=>t.isTTY))?null:await(async e=>{let t="";e.setEncoding("utf-8");for await(const i of e)t+=i;return t})(t)},Cr=e=>{process.stdout.write(e.endsWith("\n")?e:`${e}\n`)},Tr=e=>{Cr(JSON.stringify(e))},Er=async(e,t)=>{const i=c.resolve(e),o=c.dirname(i);if(await u.mkdir(o,{recursive:!0}),t instanceof Blob){const e=Buffer.from(await t.arrayBuffer());await u.writeFile(i,e)}else Buffer.isBuffer(t)?await u.writeFile(i,t):t instanceof ArrayBuffer?await u.writeFile(i,Buffer.from(t)):await u.writeFile(i,String(t));return i};const Ir=e=>"object"==typeof e&&null!==e,kr=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},Ar=e=>Ir(e)&&"data"in e&&void 0!==e.data?e.data:e,jr=(e,t)=>{try{const{pathname:i}=new URL(e);return c.extname(i)||t}catch(e){return t}},Rr=()=>{const e=new Date;return`${e.getFullYear()}${String(e.getMonth()+1).padStart(2,"0")}${String(e.getDate()).padStart(2,"0")}_${String(e.getHours()).padStart(2,"0")}${String(e.getMinutes()).padStart(2,"0")}${String(e.getSeconds()).padStart(2,"0")}`},zr=e=>{const{outputPath:t,type:i,index:o,ext:s,timestamp:n}=e,r=`${i}_${n}_${o}${s}`;return c.join(t,r)},Lr=async(t,i={})=>{let o=null;i.stdin&&(o=await Pr());const s=kr(t),n=kr(o),r=(c=()=>n,null!=(a=s)?a:c());var a,c;if(!r)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin with piped content");return r},Ur="720p",Or="16:9",xr=!1,Br=!1;function qr(e,t){return null!=e?e:t()}function Dr(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 Mr=(e,t)=>{if(null==e)return 5;const i=Number(e);if(!Number.isFinite(i))return Dr([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --duration '${String(e)}', falling back to 5`)]),5;const o=Math.floor(i);return o<4||o>12?(Dr([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`--duration '${String(e)}' out of bounds (4..12), falling back to -1 as per documentation (letting the model decide)`)]),-1):o},Nr=(e,t)=>{if(null==e)return;const i=Number(e);if(Number.isSafeInteger(i)&&i>=0)return i;Dr([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --seed '${String(e)}', this parameter will be ignored`)])},Gr=e=>{const{content:t,options:i,ctx:o}=e,s=(e=>{if("string"!=typeof e)return null;const t=e.trim(),i=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(t);if(!i)return null;const o=Number(i[1]),s=Number(i[2]);if(!Number.isFinite(o)||!Number.isFinite(s)||o<=0)return null;const n=((e,t)=>{let i=Math.abs(e),o=Math.abs(t);for(;0!==o;){const e=i%o;i=o,o=e}return i})(o,s)||1,r=`${Math.round(o/n)}:${Math.round(s/n)}`,a=Math.max(o,s);return{ratio:r,resolution:a<=854?"480p":a<=1280?"720p":"1080p"}})(i.size),n=((e,t)=>"480p"===e||"720p"===e||"1080p"===e?e:(void 0!==e&&Dr([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --resolution '${String(e)}', falling back to '${Ur}'`)]),Ur))(qr(i.resolution,(()=>Dr([s,"optionalAccess",e=>e.resolution]))),o),r=((e,t)=>{if("string"==typeof e){const t=e.trim();if(t.length>0)return t}return void 0!==e&&Dr([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --ratio '${String(e)}', falling back to '${Or}'`)]),Or})(qr(i.ratio,(()=>Dr([s,"optionalAccess",e=>e.ratio]))),o);return{model:"doubao-seedance-1-5-pro-251215",content:t,callback_url:qr(kr(i.callbackUrl),(()=>{})),return_last_frame:"boolean"==typeof i.returnLastFrame?i.returnLastFrame:Br,resolution:n,ratio:r,duration:Mr(i.duration,o),watermark:"boolean"!=typeof i.watermark||i.watermark,seed:Nr(i.seed,o),camerafixed:"boolean"==typeof i.camerafixed?i.camerafixed:xr,generate_audio:"boolean"!=typeof i.generateAudio||i.generateAudio}},$r=async t=>{const i=await e.customFetch.fetch(t);if(!i.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download generated resource: ${i.status} ${i.statusText}`,{url:t});return Buffer.from(await i.arrayBuffer())},Fr=async e=>{const{outputPath:t,videoUrl:i,lastFrameUrl:o,shouldSaveLastFrame:s}=e,n=jr(i,".mp4"),r=Rr(),a=zr({outputPath:t,type:"video",index:0,ext:n,timestamp:r}),d=await $r(i),l=[await Er(a,d)];if(s&&"string"==typeof o&&o.length>0){const e=(e=>{const{outputPath:t,ext:i,timestamp:o}=e,s=`last_frame_${o}_0${i}`;return c.join(t,s)})({outputPath:t,ext:jr(o,".png"),timestamp:r}),i=await $r(o),s=await Er(e,i);l.push(s)}return l};var Vr,Wr,Hr,Jr,Kr,Qr,Yr,Zr,Xr,ea,ta,ia,oa,sa,na,ra,aa,ca,da;function la(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[e.TotalTokens=1]="TotalTokens";e[e.TotalInputTokens=2]="TotalInputTokens";e[e.TotalOutputTokens=3]="TotalOutputTokens"}(Vr||(Vr={})),function(e){e[e.ASC=1]="ASC";e[e.DESC=2]="DESC"}(Wr||(Wr={})),function(e){e[e.None=0]="None";e[e.APIKey=1]="APIKey";e[e.Oauth3LO=2]="Oauth3LO";e[e.Oauth2LO=3]="Oauth2LO";e[e.SAT=4]="SAT"}(Hr||(Hr={})),function(e){e[e.Free=1]="Free";e[e.Trial=2]="Trial";e[e.Paid=3]="Paid"}(Jr||(Jr={})),function(e){e[e.Inactive=1]="Inactive";e[e.Active=2]="Active"}(Kr||(Kr={})),function(e){e[e.CNY=1]="CNY";e[e.ResourcePoint=2]="ResourcePoint"}(Qr||(Qr={})),function(e){e[e.Cancellable=0]="Cancellable";e[e.NoCancellable=1]="NoCancellable";e[e.AlwaysDefault=2]="AlwaysDefault"}(Yr||(Yr={})),function(e){e[e.LLMModel=1]="LLMModel";e[e.ImageModel=2]="ImageModel";e[e.VideoModel=3]="VideoModel";e[e.AudioModel=4]="AudioModel";e[e.Database=5]="Database";e[e.Storage=6]="Storage";e[e.WebSearch=7]="WebSearch";e[e.EmbeddingModel=8]="EmbeddingModel";e[e.ContentProcessing=9]="ContentProcessing"}(Zr||(Zr={})),function(e){e[e.Internal=1]="Internal";e[e.External=2]="External";e[e.Infra=3]="Infra"}(Xr||(Xr={})),function(e){e[e.Text=1]="Text";e[e.Image=2]="Image";e[e.Video=3]="Video";e[e.Audio=4]="Audio"}(ea||(ea={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String";e[e.JsonInput=5]="JsonInput"}(ta||(ta={})),function(e){e[e.Seed=1]="Seed";e[e.DeepSeek=2]="DeepSeek";e[e.Kimi=3]="Kimi";e[e.GLM=4]="GLM";e[e.MiniMax=5]="MiniMax";e[e.Qwen=6]="Qwen";e[e.StepFun=7]="StepFun";e[e.GPT=8]="GPT";e[e.Others=100]="Others"}(ia||(ia={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online";e[e.GradualRollout=2]="GradualRollout";e[e.ReadyToOffline=3]="ReadyToOffline"}(oa||(oa={})),function(e){e[e.None=0]="None";e[e.InProgress=1]="InProgress";e[e.Success=2]="Success";e[e.Fail=3]="Fail";e[e.RollingBack=4]="RollingBack"}(sa||(sa={})),function(e){e[e.Install=1]="Install";e[e.Uninstall=2]="Uninstall"}(na||(na={})),function(e){e[e.Default=0]="Default";e[e.Agent=1]="Agent";e[e.Workflow=2]="Workflow";e[e.App=4]="App";e[e.Skill=5]="Skill";e[e.Web=6]="Web";e[e.WechatMiniProgram=7]="WechatMiniProgram";e[e.AssistantAgent=8]="AssistantAgent";e[e.General=9]="General";e[e.Design=100]="Design";e[e.Integration=101]="Integration";e[e.Dev=102]="Dev"}(ra||(ra={})),function(e){e[e.Scene=1]="Scene";e[e.Type=2]="Type"}(aa||(aa={})),function(e){e[e.Official=1]="Official";e[e.Community=2]="Community"}(ca||(ca={})),function(e){e[e.Agent=1]="Agent";e[e.Automation=2]="Automation";e[e.WebApp=3]="WebApp";e[e.App=4]="App";e[e.Skill=5]="Skill";e[e.GeneralWeb=6]="GeneralWeb";e[e.WechatMiniProgram=7]="WechatMiniProgram";e[e.AssistantAgent=8]="AssistantAgent";e[e.General=9]="General";e[e.CLIBilling=101]="CLIBilling"}(da||(da={}));class pa{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){pa.prototype.__init.call(this),pa.prototype.__init2.call(this),this.request=la([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=la([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}ListIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/list"),s={space_id:i.space_id,project_id:i.project_id,integration_type:i.integration_type,integration_id:i.integration_id,filter_installed:i.filter_installed,org_id:i.org_id,search_words:i.search_words,page_num:i.page_num,page_size:i.page_size,project_type:i.project_type};return this.request({url:o,method:"POST",data:s},t)}SetIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/update"),s={integration_id:i.integration_id,space_id:i.space_id,auth_schema_value:i.auth_schema_value};return this.request({url:o,method:"POST",data:s},t)}DeleteIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/delete"),s={integration_id:i.integration_id,space_id:i.space_id,project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}AuthIntegrationStatus(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/auth/status"),s={integration_id:i.integration_id,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}ManageSpaceIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/space/manage"),s={space_ids:i.space_ids,integration_ids:i.integration_ids,op_type:i.op_type};return this.request({url:o,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/api/v3/contents/generations/tasks"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}FlashASR(e,t){const i=e||{},o=this.genBaseURL("/api/v3/auc/bigmodel/recognize/flash"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}ListModel(e,t){const i=e||{},o=this.genBaseURL("/v1/model/list"),s={model_type:i.model_type,current_model_ids:i.current_model_ids,integration_ids:i.integration_ids,need_model_config_param:i.need_model_config_param,page_size:i.page_size,offset:i.offset};return this.request({url:o,method:"POST",data:s},t)}ChatCompletions(e,t){const i=e||{},o=this.genBaseURL("/api/v3/chat/completions"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CreateResponses(e,t){const i=e||{},o=this.genBaseURL("/api/v3/responses"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}GenerateImages(e,t){const i=e||{},o=this.genBaseURL("/api/v3/images/generations"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const i=e||{},o=this.genBaseURL("/api/v3/tts/unidirectional"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}GetIntegrationOauthConfig(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/auth/oauth_config"),s={integration_id:i.integration_id,space_id:i.space_id,project_id:i.project_id,session_id:i.session_id};return this.request({url:o,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/api/v3/contents/generations/tasks/:id"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"GET",data:s,params:n},t)}WebSearch(e,t){const i=e||{},o=this.genBaseURL("/api/search_api/web_search"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}WebSearch(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/search_api/web_search"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CreateResponses(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/responses"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks/:id"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"GET",data:s,params:n},t)}FlashASR(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/auc/bigmodel/recognize/flash"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}GenerateImages(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/images/generations"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/tts/unidirectional"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}ChatCompletions(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/chat/completions"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CancelIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/cancel"),s={integration_id:i.integration_id,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}Embeddings(e,t){const i=e||{},o=this.genBaseURL("/api/v3/embeddings/multimodal"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}Embeddings(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/embeddings/multimodal"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}VideoEditingUtils(e,t){const i=e||{},o=this.genBaseURL("/api/v1/integration/video_editing_utils"),s={Body:i.Body},n={tool_name:i.tool_name};return this.request({url:o,method:"POST",data:s,params:n},t)}GetProjectDefaultSkill(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/default"),s={project_type:i.project_type,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetSkillByIDs(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/by_ids"),s={project_type:i.project_type,skill_ids:i.skill_ids,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetSkillCategoryList(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/category/list"),s={project_type:i.project_type};return this.request({url:o,method:"POST",data:s},t)}UploadSkill(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/upload"),s={data:i.data},n={"Content-Type":i["Content-Type"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}GetUserSkillList(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/user/list"),s={page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}DeleteSkill(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/delete"),s={skill_id:i.skill_id};return this.request({url:o,method:"POST",data:s},t)}GetSkillList(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/list"),s={project_type:i.project_type,category_type_list:i.category_type_list,space_id:i.space_id,source_list:i.source_list};return this.request({url:o,method:"POST",data:s},t)}UploadSkillConfirm(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/upload/confirm"),s={preview_skill_key:i.preview_skill_key};return this.request({url:o,method:"POST",data:s},t)}FetchTool(e,t){const i=e||{},o=this.genBaseURL("/api/v1/integration/fetch_tool"),s={url:i.url};return this.request({url:o,method:"POST",data:s},t)}GetModelSwitchStatus(e,t){const i=e||{},o=this.genBaseURL("/v1/model/switch/status"),s={model_id:i.model_id,project_ids:i.project_ids,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}StartSwitchModel(e,t){const i=e||{},o=this.genBaseURL("/v1/model/switch/start"),s={space_id:i.space_id,project_ids:i.project_ids,current_model:i.current_model,target_model:i.target_model};return this.request({url:o,method:"POST",data:s},t)}GetModelUsageList(e,t){const i=e||{},o=this.genBaseURL("/v1/model/usage/list"),s={space_id:i.space_id,model_id:i.model_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp,order_by_field:i.order_by_field,order_by_type:i.order_by_type,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetModelDetails(e,t){const i=e||{},o=this.genBaseURL("/v1/model/details"),s={model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}GetModelUsageDetail(e,t){const i=e||{},o=this.genBaseURL("/v1/model/usage/details"),s={space_id:i.space_id,model_id:i.model_id,project_id:i.project_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp};return this.request({url:o,method:"POST",data:s},t)}RollbackSwitchModel(e,t){const i=e||{},o=this.genBaseURL("/v1/model/switch/rollback"),s={space_id:i.space_id,project_ids:i.project_ids,current_model:i.current_model};return this.request({url:o,method:"POST",data:s},t)}TextEmbeddings(e,t){const i=e||{},o=this.genBaseURL("/api/v3/embeddings"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}TextEmbeddings(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/embeddings"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CheckModelReadyToOffline(e,t){const i=e||{},o=this.genBaseURL("/v1/model/ready_to_offline/check"),s={model_type:i.model_type};return this.request({url:o,method:"POST",data:s},t)}Audit(e,t){const i=e||{},o=this.genBaseURL("/api/v1/integration/audit"),s={content:i.content};return this.request({url:o,method:"POST",data:s},t)}}pa.prototype.UploadSkill=function(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/upload"),s=i.body;return this.request({url:o,method:"POST",data:s},t)},pa.prototype.GenerateImages=function(e,t){const i=e||{},o=this.genBaseURL("/api/v3/images/generations"),s=i.Body;return this.request({url:o,method:"POST",data:s},t)},pa.prototype.SubmitVideoGenerationsTasks=function(e,t){const i=e||{},o=this.genBaseURL("/api/v3/contents/generations/tasks"),s=i;return this.request({url:o,method:"POST",data:s},t)},pa.prototype.GetVideoGenerationsTasks=function(e,t){const i=e||{},o=this.genBaseURL(`/api/v3/contents/generations/tasks/${i.id}`);return this.request({url:o,method:"GET"},t)};const ua=new pa({});const _a=async e=>await new Promise((t=>setTimeout(t,e))),ha=async e=>{const{taskId:t,baseURL:i,accessToken:o,projectId:s}=e,n=await ua.GetVideoGenerationsTasks({id:t},{baseURL:i,headers:{Authorization:`Bearer ${o}`},params:{project_id:s}});return Ar(n)};function ma(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 ga=e=>`coze generate video status ${e}`,fa=e=>{const{ctx:t,response:i}=e;"json"!==ma([t,"optionalAccess",e=>e.format])?Cr((e=>{const t=[e.status],i=ma([e,"access",e=>e.content,"optionalAccess",e=>e.video_url]),o=ma([e,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);return"succeeded"===e.status?("string"==typeof i&&i.length>0&&t.push(i),"string"==typeof o&&o.length>0&&t.push(o),t.join("\n")):("string"==typeof e.error_message&&e.error_message&&t.push(e.error_message),t.join("\n"))})(i)):Tr(i)},ya=t=>{const i=t.getContext(),{outputPath:o}=t.optsWithGlobals(),n=(r=ma([i,"optionalAccess",e=>e.config,"optionalAccess",e=>e.integrationApiBaseUrl]),a=()=>s.DEFAULT_CONFIG.integrationApiBaseUrl,null!=r?r:a());var r,a;const c=ma([i,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]);if(!c)throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login --oauth` or `coze auth login --token <token>` first");return{accessToken:c,ctx:i,integrationApiBaseUrl:n,outputPath:o}},va=async(t,i,o)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:r,outputPath:a}=ya(o);let c=null;i.stdin&&(c=await Pr());const{content:d}=(t=>{const{prompt:i,stdinPrompt:o,options:s}=t,n=qr(kr(i),(()=>kr(o))),r=kr(s.firstFrame),a=kr(s.lastFrame),c=Boolean(r)||Boolean(a);if(!n&&!c)throw new e.CozeError(e.ErrorCode.E1000,"Missing input: Please provide PROMPT/stdin text, or provide images (--first-frame/--last-frame/--reference-image)");const d=[];return n&&d.push({type:"text",text:n}),r&&d.push({type:"image_url",image_url:{url:r},role:"first_frame"}),a&&d.push({type:"image_url",image_url:{url:a},role:"last_frame"}),{content:d}})({prompt:t,stdinPrompt:c,options:i}),l=Gr({content:d,options:i,ctx:n}),p=n.format,u=ma([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!u)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const{createResp:_,taskId:h}=await(async t=>{const{requestBody:i,baseURL:o,accessToken:s,projectId:n}=t,r=await ua.SubmitVideoGenerationsTasks(i,{baseURL:o,headers:{Authorization:`Bearer ${s}`},params:{project_id:n}}),a=Ar(r),c=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,"optionalAccess",e=>e.id]);if(!c||"string"!=typeof c)throw new e.CozeError(e.ErrorCode.E5002,"Video generation task created successfully but no valid task_id was returned",a);return{taskId:c,createResp:a}})({requestBody:l,baseURL:r,accessToken:s,projectId:u});if(!i.wait)return"json"===p?void Tr({query_command:ga(h),response:_,task_id:h}):void Cr((e=>["Video generation task created successfully.",`taskId: ${e}`,`Use \`${ga(e)}\` to query status.`].join("\n"))(h));const m=await(async t=>{const{taskId:i,baseURL:o,accessToken:s,pollIntervalMs:n,pollTimeoutMs:r,projectId:a}=t,c=Date.now();for(;;){const t=await ha({taskId:i,baseURL:o,accessToken:s,projectId:a});if("succeeded"===t.status)return t;if("failed"===t.status||"cancelled"===t.status)throw new e.CozeError(e.ErrorCode.E5002,`Video generation failed (status=${t.status}): ${d=t.error_message,l=()=>"unknown",null!=d?d:l()}`,t);if(Date.now()-c>r)throw new e.CozeError(e.ErrorCode.E5003,[`Video generation timed out after ${r}ms.`,`taskId: ${i}`,`Use \`coze generate video status ${i}\` to query status.`].join("\n"),{task_id:i,last_status:t.status});await _a(n)}var d,l})({taskId:h,baseURL:r,accessToken:s,pollIntervalMs:2e3,pollTimeoutMs:3e5,projectId:u}),g=ma([m,"access",e=>e.content,"optionalAccess",e=>e.video_url]),f=ma([m,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);if(!g||"string"!=typeof g)throw new e.CozeError(e.ErrorCode.E5002,"Video generated successfully but video_url was not returned");if(a){const e=await Fr({outputPath:a,videoUrl:g,lastFrameUrl:f,shouldSaveLastFrame:!0===i.returnLastFrame});return"json"===p?void Tr({task_id:h,request:l,response:m,saved_paths:e}):void Cr(e.join("\n"))}if("json"===p)return void Tr({task_id:h,request:l,response:m});const y=[g];!0===i.returnLastFrame&&"string"==typeof f&&f.length>0&&y.push(f),Cr(y.join("\n"))},wa=(e,t)=>{const i=t.getContext();V(e,i)},ba=t=>{var i;i=t.command("create [prompt]").description("Create a video generation task").config({help:{brief:"Create video generation task",description:"Create a video generation task from text prompts or images. By default the command returns taskId immediately; use `--wait` to poll until completion.",examples:[{desc:"Create video from text",cmd:'coze generate video create "A dancing kitten"'},{desc:"Create task and wait for completion",cmd:'coze generate video create "A dancing kitten" --wait'},{desc:"Save result to file",cmd:'coze generate video create "A dancing kitten" --wait --output-path ./video.mp4'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --first-frame/--last-frame) with -h."},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid access token",fix:"Run `coze auth login --oauth` or set COZE_API_TOKEN/related credentials first"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server returned an error or response parsing failed",fix:"Please retry later. Use --debug for more details"},{code:e.ErrorCode.E5003,name:"TIMEOUT",desc:"Video generation request timed out",fix:"Please retry later or use `coze generate video status <taskId>` to query task status"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text prompt (can also be passed via stdin)"}},output:{type:"object",properties:{query_command:{type:"string"},task_id:{type:"string"},request:{type:"object"},response:{type:"object"},saved_paths:{type:"array",items:{type:"string"}}}}}}}).action((async(e,t,i)=>{try{await va(e,t,i)}catch(e){wa(e,i)}})),i.option("--callback-url <url>","Callback URL for task status changes").option("--return-last-frame","Return last frame URL (default: disabled)",Br).option("--resolution <res>","Resolution: 480p|720p|1080p",Ur).option("--ratio <ratio>",`Aspect ratio (default: ${Or})`,Or).option("--size <size>","Derive ratio/resolution from WIDTHxHEIGHT (lower priority than explicit parameters)").option("--duration <seconds>","Duration (seconds, 4..12; out-of-bounds fallback -1), default: 5",String(5)).option("--no-watermark","Disable watermark (default: enabled)").option("--seed <seed>","Random seed (safe integer)").option("--camerafixed","Fixed camera position (default: disabled)",xr).option("--no-generate-audio","Do not generate accompanying audio (default: generate)").option("--first-frame <url>","First frame image URL").option("--last-frame <url>","Last frame image URL").option("--stdin","Read prompt from stdin (pipe input)").option("--wait","Wait for task completion by polling; by default the command returns taskId immediately")},Sa=t=>{t.command("status <taskId>").description("Query video generation task status by task ID").option("--output <format>","Output format: text|json").config({help:{brief:"Query video task status",description:"Query the latest status of a video generation task by task ID. This command does not create a new task.",examples:[{desc:"Query task status",cmd:"coze generate video status task_123"},{desc:"Output full response as JSON",cmd:"coze generate video status task_123 --output json"}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid task ID or request parameters",fix:"Please confirm <taskId> is correct and try again",example:"coze generate video status task_123"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server returned an error or response parsing failed",fix:"Please retry later. Use --debug for more details"},{code:e.ErrorCode.E5003,name:"TIMEOUT",desc:"Request timed out",fix:"Please retry later"}],schema:{input:{taskId:{type:"string",required:!0,description:"Video generation task ID"}},output:{type:"object",properties:{id:{type:"string"},status:{type:"string"},model:{type:"string"},content:{type:"object"},error_message:{type:"string"}}}}}}).action((async(t,i,o)=>{try{await(async(t,i,o)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:r}=ya(o),a=ma([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!a)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const c=await ha({taskId:t,baseURL:r,accessToken:s,projectId:a});fa({ctx:n,response:c})})(t,0,o)}catch(e){wa(e,o)}}))};function Pa(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 Ca="2K",Ta="url",Ea="standard",Ia="disabled",ka=3686400,Aa=16777216,ja=e=>"object"==typeof e&&null!==e,Ra=e=>{if("string"==typeof e){const t=e.trim();return t.length?t:Ea}return Ea},za=e=>{if(null==e)return;const t=(Array.isArray(e)?e:[e]).filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return 0!==t.length?1===t.length?t[0]:t:void 0},La=t=>{t.command("image [prompt]").description("Generate images from text prompts").config({help:{brief:"Generate images from text",description:"Generate images based on text prompts. Supports setting size, watermark, and multiple images.",examples:[{desc:"Generate image",cmd:'coze generate image "A futuristic city"'},{desc:"Save to file",cmd:'coze generate image "A cat" --output-path ./cat.png'},{desc:"Specify size",cmd:'coze generate image "A dog" --size 1024x1024'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --size/--max-images) with -h."},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Please configure billing project ID and retry"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"API response parsing failed or server returned an error",fix:"Please retry later. Use --debug for more details"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text prompt (can also be passed via stdin)"}},output:{type:"object",properties:{model:{type:"string"},created:{type:"number"},image_0:{type:"object"},saved_paths:{type:"array",items:{type:"string"}}}}}}}).option("--size <size>","Image size: 2K|4K or WIDTHxHEIGHT (local validation)",Ca).option("--no-watermark","Disable watermark (default: enabled)").option("--image <url>","Reference image URL (can be used multiple times)",((e,t)=>[...t,e]),[]).option("--response-format <format>","Response format: url|b64_json",Ta).option("--optimize-prompt-mode <mode>",`Prompt optimization mode (default: ${Ea})`,Ea).option("--sequential <mode>","Group image generation mode: auto|disabled",Ia).option("--max-images <n>","Maximum number of group images (1-15)",String(15)).option("--stdin","Read prompt from stdin (pipe input)").action((async(t,i,o)=>{const n=o.getContext(),{outputPath:r}=o.optsWithGlobals(),a=await Lr(t,{stdin:i.stdin}),c=Pa([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const d=((e,t)=>{if(null==e)return{value:Ca};if("string"!=typeof e)return Pa([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --size '${String(e)}', falling back to '${Ca}'`)]),{value:Ca};const i=e.trim();if("2K"===i||"4K"===i)return{value:i};const o=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(i);if(!o)return{value:Ca,warning:`Invalid --size '${i}', falling back to '${Ca}'. Expected 2K/4K or WIDTHxHEIGHT`};const s=Number(o[1]),n=Number(o[2]),r=s*n,a=s/n;return Number.isFinite(s)&&Number.isFinite(n)&&s>0&&n>0&&r>=ka&&r<=Aa&&a>=.0625&&a<=16?{value:`${s}x${n}`}:{value:Ca,warning:`Invalid --size '${i}', falling back to '${Ca}'. Total pixels must be in [3686400, 16777216], aspect ratio must be in [1:16, 16:1].`}})(i.size,n),l="url"===(p=i.responseFormat)||"b64_json"===p?{value:p}:void 0!==p?{value:Ta,warning:`Invalid --response-format '${String(p)}', falling back to '${Ta}'`}:{value:Ta};var p;const u=(e=>"auto"===e||"disabled"===e?{value:e}:void 0!==e?{value:Ia,warning:`Invalid --sequential '${String(e)}', falling back to '${Ia}'`}:{value:Ia})(i.sequential),_=(e=>{if(null==e)return{value:15};const t=Number(e);if(Number.isFinite(t)){const e=Math.floor(t);if(e>=1&&e<=15)return{value:e}}return{value:15,warning:`Invalid --max-images '${String(e)}', falling back to '15'`}})(i.maxImages);d.warning&&Pa([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(d.warning)]),l.warning&&Pa([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(l.warning)]),u.warning&&Pa([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(u.warning)]),_.warning&&Pa([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(_.warning)]);const h={model:"doubao-seedream-4-5-251128",prompt:a,size:d.value,watermark:"boolean"!=typeof i.watermark||i.watermark,image:za(i.image),response_format:l.value,optimize_prompt_options:{mode:Ra(i.optimizePromptMode)},sequential_image_generation:u.value,sequential_image_generation_options:{max_images:_.value}},m=(t=>{const i=ja(t)&&"data"in t?t.data:t;if(ja(o=i)&&"string"==typeof o.model&&"number"==typeof o.created&&Array.isArray(o.data))return i;var o;throw new e.CozeError(e.ErrorCode.E5002,"Image generation API returned an unexpected response format",t)})(await ua.GenerateImages({Body:h},{baseURL:s.DEFAULT_CONFIG.integrationApiBaseUrl,params:{project_id:c}}));if(m.error)throw new e.CozeError(e.ErrorCode.E5002,"Image generation failed (top-level error)",m.error);const g=(y=()=>Ta,null!=(f=h.response_format)?f:y());var f,y;const v=m.data.filter((e=>!e.error&&("url"===g?"string"==typeof e.url&&e.url.length>0:"string"==typeof e.b64_json&&e.b64_json.length>0)));if(0===v.length)throw new e.CozeError(e.ErrorCode.E5002,"Image generation succeeded but no valid image data was returned",m);if(r){const t=[],i=Rr();for(const[o,s]of v.entries()){const n="url"===g&&s.url?jr(s.url,".png"):".png",a=zr({outputPath:r,type:"image",index:o,ext:n,timestamp:i});let c;if("url"===g){const t=await e.customFetch.fetch(s.url);if(!t.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download generated image: ${t.status} ${t.statusText}`);c=Buffer.from(await t.arrayBuffer())}else c=Buffer.from(s.b64_json,"base64");const d=await Er(a,c);t.push(d)}const{model:o,usage:s,HttpHeader:a,...c}=(e=>{const{data:t,...i}=e,o=Object.fromEntries(t.map(((e,t)=>[`image_${t}`,e])));return{...i,...o}})(m);Pa([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...c,saved_paths:t})])}else Pa([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(m.data)])}))};function Ua(e,t){return null!=e?e:t()}function Oa(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 xa="cli_user",Ba="zh_female_xiaohe_uranus_bigtts",qa="mp3",Da=24e3,Ma=(e,t)=>"pcm"===e||"mp3"===e||"ogg_opus"===e?e:(void 0!==e&&Oa([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --audio-format '${String(e)}', falling back to '${qa}'`)]),qa),Na=(e,t,i,o)=>{if(null==e)return t;const s=Number(e);return Number.isFinite(s)?Math.floor(s):(Oa([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",o=>o(`Invalid --${i} '${String(e)}', falling back to ${t}`)]),t)},Ga=t=>{const i=t.trim();if(0===i.length)return null;const o=i.startsWith("data:")?i.slice(5).trim():i;if(0===o.length)return null;const s=o[0];if("{"!==s&&"["!==s)return null;const n=e.safeJsonParse(o,void 0,{onError:t=>{const o=t instanceof Error?t.message:String(t);throw new e.CozeError(e.ErrorCode.E5002,`Failed to parse response: ${o}`,{line:i})}});return void 0===n?null:Ir(n)&&"number"==typeof n.code?n:null},$a=t=>{const i=t.command("generate").description("Media generation commands (API TBD)").config({help:{brief:"Media generation commands",description:"Generate media such as audio, image, and video using Coze APIs.",examples:[{desc:"Generate image",cmd:'coze generate image "A cat"'},{desc:"Generate audio",cmd:'coze generate audio "Hello world"'},{desc:"Generate video",cmd:'coze generate video create "A dancing dog"'}],seeAlso:["coze auth"]}}).option("--output-path <path>","Directory path to save the generated media files");La(i),(t=>{t.command("audio [prompt]").description("Synthesize speech from text or SSML (streaming)").config({help:{brief:"Generate audio from text",description:"Synthesize speech from text or SSML. Supports streaming output and configurable audio encodings.",examples:[{desc:"Basic text to speech",cmd:'coze generate audio "Hello world"'},{desc:"Save to file",cmd:'coze generate audio "Hello" --output-path ./audio.mp3'},{desc:"Use SSML",cmd:'echo "<speak>Hello</speak>" | coze generate audio --ssml'},{desc:"Specify audio encoding",cmd:'coze generate audio "Hello" --audio-format ogg_opus'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --speaker/--audio-format) with -h."},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Configure billing project ID and retry",example:'coze generate audio "Hello"'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid access token",fix:"Run `coze auth login --oauth` or `coze auth login --token <token>` first"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"API response parsing failed or server returned an error",fix:"Please retry later. Use --debug for more details"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text or SSML prompt (can also be passed via stdin)"}},output:{type:"object",properties:{request:{type:"object"},url:{type:"string",description:"Audio download URL"},saved_path:{type:"string",description:"Local path if saved"}}}}}}).option("--output <format>","Output format: text|json").option("--uid <uid>",`User UID (default: ${xa})`,xa).option("--speaker <speaker>",`Speaker (default: ${Ba})`,Ba).option("--audio-format <format>","Audio encoding: pcm|mp3|ogg_opus",qa).option("--sample-rate <n>","Sample rate (default: 24000)",String(Da)).option("--speech-rate <n>","Speech rate (-50..100, default: 0)",String(0)).option("--loudness-rate <n>","Loudness (-50..100, default: 0)",String(0)).option("--ssml","Treat input as SSML (defaults to plain text)",!1).option("--stdin","Read prompt from stdin (pipe input)").action((async(t,i,o)=>{const s=o.getContext();try{const{outputPath:n}=o.optsWithGlobals(),r=Oa([s,"optionalAccess",e=>e.config,"access",e=>e.integrationApiBaseUrl]);if(!Oa([s,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]))throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login --oauth` or `coze auth login --token <token>` first");const a=await Lr(t,{stdin:i.stdin}),c=Oa([s,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const d={user:{uid:Ua(kr(i.uid),(()=>xa))},req_params:{speaker:Ua(kr(i.speaker),(()=>Ba)),audio_params:{format:Ma(i.audioFormat,s),sample_rate:Na(i.sampleRate,Da,"sample-rate",s),speech_rate:Na(i.speechRate,0,"speech-rate",s),loudness_rate:Na(i.loudnessRate,0,"loudness-rate",s)}}};i.ssml?d.req_params={...d.req_params,ssml:a}:d.req_params={...d.req_params,text:a};const l=new URL("/api/v3/tts/unidirectional",r);l.searchParams.append("project_id",c);const p=await e.customFetch.fetch(l.toString(),{method:"POST",body:JSON.stringify(d)});if(!p.ok)throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis request failed: ${p.status} ${p.statusText}`,{status:p.status,statusText:p.statusText});if(!p.body)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis response is empty (no streaming body returned)");const u=new TextDecoder("utf-8"),_=p.body.getReader(),h=[];let m;const g=t=>{if(0===t.code)return n&&"string"==typeof t.data&&h.push(Buffer.from(t.data,"base64")),!1;if(2e7===t.code)return"string"==typeof t.url&&t.url.length>0&&(m=t.url),!0;throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis failed (code=${t.code}): ${Ua(t.message,(()=>"unknown"))}`,t)};let f="";for(;;){const{done:e,value:t}=await _.read();if(e)break;f+=u.decode(t,{stream:!0});const i=f.split(/\r?\n/);f=Ua(i.pop(),(()=>""));for(const e of i){const t=Ga(e);if(t&&g(t)){await _.cancel();break}}if(m)break}if(!m){f+=u.decode();const e=f.split(/\r?\n/);f="";for(const t of e){const e=Ga(t);if(e&&g(e))break}}if(n){const t=Ua(Oa([d,"access",e=>e.req_params,"optionalAccess",e=>e.audio_params,"optionalAccess",e=>e.format]),(()=>qa)),i="pcm"===t?".pcm":"ogg_opus"===t?".ogg":".mp3",o=Rr(),r=zr({outputPath:n,type:"audio",index:0,ext:i,timestamp:o});let a=null;if(h.length>0)a=await Er(r,Buffer.concat(h));else if(m){const t=await e.customFetch.fetch(m);if(!t.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download synthesized speech: ${t.status} ${t.statusText}`,{status:t.status,statusText:t.statusText});const s=Buffer.from(await t.arrayBuffer()),r=jr(m,i),c=zr({outputPath:n,type:"audio",index:0,ext:r,timestamp:o});a=await Er(c,s)}if(!a)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis completed but no savable audio data was obtained (neither chunks nor download URL)",{url:m});return"json"===Oa([s,"optionalAccess",e=>e.format])?void Tr({request:d,url:m,saved_path:a}):void Cr(a)}if("json"===Oa([s,"optionalAccess",e=>e.format]))return void Tr({request:d,url:m});if(m)return void Cr(m);Cr("Speech synthesis completed, but no audio download URL was returned; you can use --output json to view details.")}catch(e){V(e,s)}}))})(i),(e=>{const t=(e=>e.command("video").description("Create videos or query video generation task status").config({help:{brief:"Generate videos",description:"Use explicit subcommands to create video generation tasks or query task status by task ID.",examples:[{desc:"Create video from text",cmd:'coze generate video create "A dancing kitten"'},{desc:"Query task status",cmd:"coze generate video status task_123"}],seeAlso:["coze generate image","coze generate audio"]}}))(e);ba(t),Sa(t)})(i)};function Fa(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 Va=i=>{(i=>{i.command("upload <path>").description("Upload a local file").config({help:{brief:"Upload a local file",description:"Upload a local file to Coze. The file can be used as an attachment or context in projects.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf",tags:["[RECOMMENDED]"]}],errors:[{code:e.ErrorCode.E3000,name:"RESOURCE_NOT_FOUND",desc:"Local file not found or not readable",fix:"Please confirm the file path exists and you have read permission"}],schema:{input:{path:{type:"string",required:!0,description:"Local file path to upload"}},output:{type:"string",description:"Uploaded file URL"}}}}).action((async(i,o,s)=>{let n;try{n=s.getContext();try{await h.access(i)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${i}`,{filePath:i})}const o=_.basename(i),r=_.extname(i),a=r?o.slice(0,-r.length):o,c=r.slice(1),d=new g;d.append("file_name",a),d.append("file_extension",c),d.append("file_content",m.createReadStream(i)),d.append("biz_type","cli_attachment");const l=await t.IdeApi.UploadFile({data:d},{headers:{...d.getHeaders()}});"json"===Fa([n,"optionalAccess",e=>e.format])?Fa([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(l.data)]):Fa([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(Fa([l,"access",e=>e.data,"optionalAccess",e=>e.file_url]))])}catch(e){V(e,n)}}))})(i.command("file").description("General file operations").config({help:{brief:"File upload and management",description:"Manage file operations for Coze projects. Currently supports uploading local files to Coze for use as attachments or context.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf"}],seeAlso:["coze code message send"]}}))};function Wa(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 Ha(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 Ja(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 Ka(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 Qa=t=>{const i=t.command("config").description("Manage Coze CLI configuration").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Manage local configuration",description:"Provides read, set, list, and delete operations for the CLI local configuration file (`~/.cozerc.json`).",examples:[{desc:"List all configurations",cmd:"coze config list"},{desc:"Set configuration value",cmd:"coze config set base_url https://api.coze.cn"}]}});(e=>{e.command("get <keys...>").description("Get configuration values and their sources").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Get configuration values",description:"Read and output the value of the specified configuration keys from `~/.cozerc.json`. If a key does not exist, prompts that it was not found.",examples:[{desc:"Get BaseURL configuration",cmd:"coze config get baseUrl"},{desc:"Get default Space ID",cmd:"coze config get spaceId"},{desc:"Get multiple configurations",cmd:"coze config get baseUrl spaceId"}],schema:{input:{keys:{type:"array",required:!0,description:"Configuration key names"}},output:{value:{type:"any",description:"Configuration value"}}}}}).action((async(e,t,i)=>{const o=i.getContext(),n=await s.listConfigs();for(const t of e){const e=n.find((e=>e.key===t));Wa(e?[o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)]:[o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Configuration '${t}' not found.`)])}}))})(i),(t=>{t.command("set <key> <value>").description("Set a configuration value").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Set a single configuration value",description:"Update or add the specified local configuration key-value pair. The configuration will be persistently saved in `~/.cozerc.json`.",examples:[{desc:"Modify default workspace",cmd:"coze config set spaceId 123456789"},{desc:"Modify BaseURL",cmd:"coze config set baseUrl https://api.coze.cn"}],errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to set configuration value",fix:"Please check the key/value and retry. Use --debug for more details."}],schema:{input:{key:{type:"string",required:!0,description:"Configuration key name"},value:{type:"string",required:!0,description:"New configuration value"}}}}}).action((async(t,i,o,n)=>{const r=n.getContext();try{const e={};e[t]=i;const o="global";await s.saveConfig(e,o);const n={key:t,value:i,scope:o,status:"updated",message:`Configuration '${t}' updated successfully in ${o} scope.`};if(Ha([r,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(n.message)]),"json"===Ha([r,"optionalAccess",e=>e.format]))return void Ha([r,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)])}catch(o){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set '${t}' to '${i}': ${o.message}`,o.stack)}}))})(i),(t=>{t.command("delete <keys...>").description("Delete a configuration value").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Delete configuration values",description:"Remove the specified configuration values from the local configuration file `~/.cozerc.json`.",examples:[{desc:"Delete a specific configuration key",cmd:"coze config delete spaceId"},{desc:"Delete multiple configuration keys",cmd:"coze config delete spaceId baseUrl"}],errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to delete configuration value",fix:"Please check the configuration key and retry. Use --debug for more details."}],schema:{input:{keys:{type:"array",required:!0,description:"Configuration key names"}}}}}).action((async(t,i,o)=>{const n=o.getContext();for(const i of t)try{await s.deleteConfig(i);const e={key:i,status:"deleted",message:`Configuration '${i}' has been removed.`};Ja([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleted ${i} from configuration file successfully.`)]),"json"===Ja([n,"optionalAccess",e=>e.format])&&Ja([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)])}catch(t){const o=t;throw new e.CozeError(e.ErrorCode.E5000,`Failed to delete config '${i}': ${o.message}`,o.stack)}}))})(i),(e=>{e.command("list").description("List all configuration values and their sources").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"List all local configuration values",description:"Print all configuration content stored in `~/.cozerc.json` in JSON format.",examples:[{desc:"List configurations",cmd:"coze config list"}],schema:{output:{type:"object",additionalProperties:!0,description:"Configuration key-value pairs"}}}}).action((async(e,t)=>{const i=t.getContext(),o=(await s.listConfigs()).map((({key:e,value:t,source:i})=>({key:e,value:t,source:i})));Ka([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Configurations found:")]),Ka([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(o)])}))})(i)},Ya="__COZE_FILE_COMP__";function Za(){const e=process.env.SHELL;if(e){if(e.includes("bash"))return"bash";if(e.includes("zsh"))return"zsh";if(e.includes("fish"))return"fish"}if(process.env.PSModulePath)return"powershell"}function Xa(e){const t=d.homedir();switch(e){case"bash":return c.join(t,"darwin"===process.platform?".bash_profile":".bashrc");case"zsh":return c.join(t,".zshrc");case"fish":return c.join(t,".config/fish/config.fish");case"powershell":return function(){const e=["pwsh","powershell"];for(const t of e)try{const e=o.execSync(`${t} -NoProfile -NoLogo -Command "echo $PROFILE"`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim();if(e)return e}catch(e){continue}return}();default:return}}function ec(){return["### coze completion - begin. generated by coze cli ###","if type compdef &>/dev/null; then"," _coze_completion() {"," local completions",' completions=("${(@f)$(coze --compzsh --compgen "${CURRENT}" "${words[CURRENT-1]}" "${BUFFER}")}")',` if [[ "\${completions[1]}" == "${Ya}" ]]; then`," _files"," else"," compadd -- $completions"," fi"," }"," compdef _coze_completion coze","elif type complete &>/dev/null; then"," _coze_completion() {"," local cur prev nb_colon"," _get_comp_words_by_ref -n : cur prev",' nb_colon=$(grep -o ":" <<< "$COMP_LINE" | wc -l)'," local completions",' completions=$(coze --compbash --compgen "$((COMP_CWORD - (nb_colon * 2)))" "$prev" "${COMP_LINE}")',` if [[ "$completions" == "${Ya}" ]]; then`," COMPREPLY=()"," return"," fi",' COMPREPLY=( $(compgen -W "$completions" -- "$cur") )',' __ltrim_colon_completions "$cur"'," }"," complete -o default -o bashdefault -F _coze_completion coze","elif type compctl &>/dev/null; then"," _coze_completion() {"," local cword line point si"," read -Ac words"," read -cn cword"," read -l line",' si="$IFS"',' if ! IFS=$\'\\n\' reply=($(coze --compzsh --compgen "${cword}" "${words[cword-1]}" "${line}")); then'," local ret=$?",' IFS="$si"'," return $ret"," fi",' IFS="$si"'," }"," compctl -K _coze_completion coze","fi","### coze completion - end ###"].join(d.EOL)}function tc(e){switch(e){case"bash":return`\n# begin coze completion\nsource ${c.join(d.homedir(),".coze","completion.sh")}\n# end coze completion\n`;case"zsh":return"\n# begin coze completion\n. <(coze --completion)\n# end coze completion\n";case"fish":return"\n# begin coze completion\ncoze --completion-fish | source\n# end coze completion\n";case"powershell":return`\n# begin coze completion\nRegister-ArgumentCompleter -Native -CommandName coze -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n $tokens = $commandAst.ToString().Split(" ", [StringSplitOptions]::RemoveEmptyEntries)\n $allArgs = @("--comppwsh")\n if ($tokens.Count -gt 1) {\n $allArgs += $tokens[1..($tokens.Count - 1)]\n }\n $result = & coze $allArgs 2>$null\n if ($result -and $result[0] -ne '${Ya}') {\n $result -split '\\n' | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n } else {\n Get-ChildItem -Path "$wordToComplete*" -ErrorAction SilentlyContinue | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_.Name, $_.Name, 'ProviderItem', $_.FullName)\n }\n }\n}\n# end coze completion\n`;default:return}}function ic(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}let oc,sc,nc=!1,rc=!1;function ac(e){const t=(i=e._args,o=()=>[],null!=i?i:o());var i,o;if(0===t.length)return!1;const s=/path|file|dir|folder/i;return t.some((e=>s.test(e._name)))}function cc(e){sc=e,function(){const e=process.argv.indexOf("--completion");e>-1&&(nc=!0,process.argv.splice(e,1));const t=process.argv.indexOf("--completion-fish");t>-1&&(rc=!0,process.argv.splice(t,1))}(),oc=f("coze"),oc.on("complete",((t,i)=>{const o=i.line.trimStart().split(/\s+/);o.length>0&&(o[0].endsWith("coze")||o[0].endsWith("bin/main"))&&o.shift();let s="";i.line.endsWith(" ")?(s="",""===o[o.length-1]&&o.pop()):s=o.pop()||"";const n=function(e,t,i){let o=e;for(const e of t){const t=o.commands.find((t=>t.name()===e||t.alias()===e));if(t)o=t;else if(!e.startsWith("-"))return ac(o)?[Ya]:[]}const s=[];o.commands.length>0&&o.commands.forEach((e=>{s.push(e.name())})),o.options.forEach((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))})),o!==e&&e.options.forEach((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}));const n=Array.from(new Set(s)).filter((e=>e.startsWith(i)));return 0===n.length&&ac(o)?[Ya]:n}(e,o,s);i.reply(n)})),e.command("completion").description("Setup shell auto-completion").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Configure terminal auto-completion",description:"Install or remove the auto-completion script for the current terminal environment (supports bash/zsh/fish/powershell).",examples:[{desc:"Install completion script",cmd:"coze completion --setup"},{desc:"Remove completion script",cmd:"coze completion --cleanup"}]}}).option("--setup","Install shell completion into your startup script (.zshrc / .bashrc / $PROFILE)").option("--cleanup","Remove shell completion from your startup script").action((async e=>{if(e.cleanup)!function(){const e=Za();if(!e)return;const t=Xa(e);if(!t||!l.existsSync(t))return;const i=tc(e);if(i){const e=l.readFileSync(t,"utf8").replace(new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"");l.writeFileSync(t,e)}if("bash"===e){const e=c.join(d.homedir(),".coze"),t=c.join(e,"completion.sh");l.existsSync(t)&&l.unlinkSync(t),l.existsSync(e)&&0===l.readdirSync(e).length&&l.rmdirSync(e)}}(),await s.saveConfig({completionInstalled:!1}),console.log("Shell completion removed! Please restart your terminal.");else{const e=Za();if(!e)return console.error("Could not detect your shell type. Supported shells: bash, zsh, fish, powershell."),void(process.exitCode=1);const t=function(){const e=Za();if(!e)return!1;const t=Xa(e);if(!t)return!1;if("bash"===e){const e=c.join(d.homedir(),".coze"),t=c.join(e,"completion.sh");l.existsSync(e)||l.mkdirSync(e,{recursive:!0}),l.writeFileSync(t,ec())}const i=c.dirname(t);l.existsSync(i)||l.mkdirSync(i,{recursive:!0});const o=tc(e);return!!o&&(l.appendFileSync(t,o),!0)}();t?(await s.saveConfig({completionInstalled:!0}),console.log(`Shell completion (${e}) setup successful! Please restart your terminal or source your config file.`)):(console.error(`Failed to setup shell completion for ${e}.`),process.exitCode=1)}}))}function dc(){return nc?(console.log(ec()),void process.exit()):rc?(console.log(["### coze completion - begin. generated by coze cli ###","function _coze_completion"," set -l completions (coze --compfish --compgen (count (commandline -poc)) (commandline -pt) (commandline -pb))",` if test (count $completions) -eq 1 -a "$completions[1]" = "${Ya}"`," return"," end"," for c in $completions"," echo $c"," end","end","complete -c coze -a '(_coze_completion)' -n '_coze_completion'","### coze completion - end ###"].join(d.EOL)),void process.exit()):void(process.argv.includes("--comppwsh")?function(){if(!sc)return void process.exit();const e=process.argv.indexOf("--comppwsh"),t=process.argv.slice(e+1);let i=sc;const o=[];for(const e of t){const t=ic([i,"access",e=>e.commands,"optionalAccess",e=>e.find,"call",t=>t((t=>t.name()===e||t.alias()===e))]);t?i=t:o.push(e)}const s=[];ic([i,"access",e=>e.commands,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{s.push(e.name())}))]),ic([i,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}))]),i!==sc&&ic([sc,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}))]);const n=o[o.length-1]||"",r=Array.from(new Set(s)).filter((e=>e.startsWith(n)));0===r.length&&ac(i)?console.log(Ya):r.length>0&&console.log(r.join("\n")),process.exit()}():oc&&oc.init())}function lc(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 pc(i){i.command("remove <skillId>").description("Remove skills from the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Remove skill from project",description:"Remove a configured skill from the specified project.",examples:[{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID to remove"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},removed_skill_ids:{type:"array",items:{type:"string"},description:"Removed skill IDs"},message:{type:"string",description:"Result message"}}}}},errors:[{code:e.ErrorCode.E3004,name:"SKILL_NOT_INSTALLED",desc:"The specified skill is not installed in the project",fix:"Please use `skill list` to confirm installed skills"}]}}).action((async function(e,i,o){const s=o.getContext(),{projectId:n}=i,r=new Set([e]),a=lc([(await t.IdeApi.GetVibeProject({project_id:n})).data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]);var c;const d=(c=lc([a,"optionalAccess",e=>e.skills]),Array.isArray(c)?c.map((e=>{return{skill_id:String((t=lc([e,"optionalAccess",e=>e.skill_id]),i=()=>"",null!=t?t:i())),is_preload:lc([e,"optionalAccess",e=>e.is_preload])};var t,i})).filter((e=>Boolean(e.skill_id))):[]).filter((e=>!r.has(e.skill_id))),l={filter_types:lc([a,"optionalAccess",e=>e.filter_types]),skills:d};await t.IdeApi.UpdateVibeProject({project_id:n,project_settings:{skill_setting:l}}),lc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill removed.")]),lc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,removed_skill_ids:Array.from(r),message:"removed Skills successfully."})])}))}function uc(e,t){return null!=e?e:t()}function _c(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 hc(i){i.command("list").description("List available skills for the project").requiredOption("-p, --project-id <projectId>","Project ID").option("--space-id <spaceId>","Space ID (optional, reads from config)").config({help:{brief:"List available skills for the project",description:"Retrieve a list of all available skills for the specified project type, with installation status indicating which skills are already added.",examples:[{desc:"List project skills",cmd:"coze code skill list --project-id <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{type:"array",items:{type:"object",properties:{description:{type:"string",description:"Skill description"},skill_id:{type:"string",description:"Skill ID"},name:{type:"string",description:"Skill name"},icon:{type:"string",description:"Skill icon URL"},is_installed:{type:"boolean",description:"Whether the skill is installed"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}]}}).action((async function(i,o){const s=o.getContext(),{projectId:n}=i,r=uc(uc(i.spaceId,(()=>_c([s,"optionalAccess",e=>e.config,"access",e=>e.spaceId]))),(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing spaceId: pass --space-id <spaceId> or set config.spaceId");const a=await t.IdeApi.GetVibeProject({project_id:n}),c=function(e){const t=[],i=_c([e,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_settings]);_c([i,"optionalAccess",e=>e.skill_setting,"optionalAccess",e=>e.skills])&&t.push(...i.skill_setting.skills);const o=t.map((e=>_c([e,"optionalAccess",e=>e.skill_id]))).filter(Boolean);return new Set(o)}(a.data||{}),d=_c([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),l=await ua.GetSkillList({project_type:d,space_id:r,category_type_list:[d]});_c([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${_c([l,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} skills.`)]),_c([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(_c([l,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({description:_c([e,"optionalAccess",e=>e.description]),skill_id:_c([e,"optionalAccess",e=>e.skill_id]),name:_c([e,"optionalAccess",e=>e.name]),icon:_c([e,"optionalAccess",e=>e.icon]),is_installed:c.has(e.skill_id||"")})))]))])}))}function mc(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 gc(i){i.command("add <skillId>").description("Add skills to the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add skill to project",description:"Add a specified skill to the project. Skills can extend project capabilities, such as adding search, code execution, etc.",examples:[{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},added_skill_ids:{type:"array",items:{type:"string"},description:"Added skill IDs"},message:{type:"string",description:"Result message"}}}}},errors:[{code:e.ErrorCode.E3002,name:"SKILL_NOT_FOUND",desc:"The specified skill does not exist",fix:"Please use `skill list` to confirm available skills"}]}}).action((async function(e,i,o){const s=o.getContext(),{projectId:n}=i,r=[e],a=(await t.IdeApi.GetVibeProject({project_id:n})).data||{},c=mc([a,"access",e=>e.project_info,"optionalAccess",e=>e.project_type]),d=mc([a,"access",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]),l=function(e){const t=new Map;for(const i of e){const e=mc([i,"optionalAccess",e=>e.skill_id])?String(i.skill_id):"";e&&(t.has(e)||t.set(e,{skill_id:e,is_preload:i.is_preload}))}return Array.from(t.values())}([...Array.isArray(mc([d,"optionalAccess",e=>e.skills]))?d.skills:[],...r.map((e=>({skill_id:String(e),is_preload:!0})))]),p={filter_types:mc([d,"optionalAccess",e=>e.filter_types])&&d.filter_types.length>0?d.filter_types:[c],skills:l};await t.IdeApi.UpdateVibeProject({project_id:n,project_settings:{skill_setting:p}}),mc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skills added successfully.")]),mc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,added_skill_ids:r,message:"added Skills successfully."})])}))}var fc,yc,vc,wc,bc,Sc,Pc,Cc,Tc,Ec,Ic,kc,Ac,jc,Rc,zc,Lc,Uc,Oc,xc,Bc,qc,Dc,Mc,Nc,Gc,$c,Fc,Vc,Wc,Hc,Jc,Kc,Qc,Yc,Zc,Xc,ed,td,id,od,sd,nd,rd,ad,cd,dd,ld,pd,ud,_d,hd,md,gd,fd,yd,vd,wd,bd,Sd,Pd,Cd,Td,Ed,Id,kd,Ad,jd,Rd,zd,Ld,Ud,Od,xd,Bd,qd,Dd;function Md(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[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(fc||(fc={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(yc||(yc={})),function(e){e[e.Chat=0]="Chat";e[e.FunctionCall_1=1]="FunctionCall_1";e[e.FunctionCall_2=2]="FunctionCall_2";e[e.FunctionCall_3=3]="FunctionCall_3"}(vc||(vc={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(wc||(wc={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Trigger=4]="Trigger";e[e.KnowledgeText=5]="KnowledgeText";e[e.KnowledgeTable=6]="KnowledgeTable";e[e.KnowledgeAutoCall=7]="KnowledgeAutoCall";e[e.KnowledgeOnDemandCall=8]="KnowledgeOnDemandCall";e[e.Variable=9]="Variable";e[e.Database=10]="Database";e[e.LongTermMemory=11]="LongTermMemory";e[e.FileBox=12]="FileBox";e[e.Onboarding=13]="Onboarding";e[e.Suggestion=14]="Suggestion";e[e.ShortcutCommand=15]="ShortcutCommand";e[e.BackGroundImage=16]="BackGroundImage";e[e.TTS=17]="TTS";e[e.MultiAgentRecognize=18]="MultiAgentRecognize";e[e.KnowledgePhoto=19]="KnowledgePhoto";e[e.HookInfo=20]="HookInfo";e[e.KnowledgeValcanoUnstructured=21]="KnowledgeValcanoUnstructured";e[e.KnowledgeValcanoStructured=22]="KnowledgeValcanoStructured";e[e.Model=23]="Model";e[e.KnowledgeThirdPartyUnstructured=24]="KnowledgeThirdPartyUnstructured";e[e.KnowledgeThirdPartyStructured=25]="KnowledgeThirdPartyStructured"}(bc||(bc={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(Sc||(Sc={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(Pc||(Pc={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(Cc||(Cc={})),function(e){e[e.Official=1]="Official";e[e.Public=2]="Public";e[e.Custom=3]="Custom";e[e.Others=101]="Others"}(Tc||(Tc={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(Ec||(Ec={})),function(e){e[e.App=1]="App";e[e.Resource=2]="Resource"}(Ic||(Ic={})),function(e){e[e.CozeModel=1]="CozeModel";e[e.VolcAccount=2]="VolcAccount";e[e.SelfAccount=3]="SelfAccount";e[e.SelfModel=4]="SelfModel"}(kc||(kc={})),function(e){e[e.Asc=1]="Asc";e[e.Desc=2]="Desc"}(Ac||(Ac={})),function(e){e[e.NoDetail=1]="NoDetail";e[e.Detail=2]="Detail";e[e.Operate=3]="Operate"}(jc||(jc={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(Rc||(Rc={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.Imageflow=3]="Imageflow";e[e.Knowledge=4]="Knowledge";e[e.UI=5]="UI";e[e.Prompt=6]="Prompt";e[e.Database=7]="Database";e[e.Variable=8]="Variable"}(zc||(zc={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi";e[e.MessagesApi=2]="MessagesApi"}(Lc||(Lc={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(Uc||(Uc={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(Oc||(Oc={})),function(e){e[e.Provider=1]="Provider";e[e.Custom=2]="Custom"}(xc||(xc={})),function(e){e[e.CozeAccountTypeUnknown=0]="CozeAccountTypeUnknown";e[e.CozeAccountTypePersonal=1]="CozeAccountTypePersonal";e[e.CozeAccountTypeOrganization=2]="CozeAccountTypeOrganization"}(Bc||(Bc={})),function(e){e[e.Intelligence=1]="Intelligence";e[e.App=2]="App";e[e.Plugin=3]="Plugin";e[e.Workflow=4]="Workflow";e[e.Knowledge=5]="Knowledge";e[e.Card=6]="Card";e[e.Prompt=7]="Prompt";e[e.Database=8]="Database";e[e.Voice=9]="Voice";e[e.VibeProjectAgent=11]="VibeProjectAgent";e[e.VibeProjectAutomation=12]="VibeProjectAutomation";e[e.VibeProjectWebApp=13]="VibeProjectWebApp";e[e.VibeProjectApp=14]="VibeProjectApp";e[e.VibeProjectSkill=15]="VibeProjectSkill";e[e.VibeProjectGeneralWeb=16]="VibeProjectGeneralWeb";e[e.VibeProjectWechatMiniProgram=17]="VibeProjectWechatMiniProgram";e[e.VibeProjectAssistantAgent=18]="VibeProjectAssistantAgent";e[e.VibeProjectGeneral=19]="VibeProjectGeneral"}(qc||(qc={})),function(e){e[e.Mobile=1]="Mobile";e[e.Web=2]="Web"}(Dc||(Dc={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(Mc||(Mc={})),function(e){e[e.Using=1]="Using";e[e.Deleted=2]="Deleted";e[e.Banned=3]="Banned";e[e.MoveFailed=4]="MoveFailed";e[e.Copying=5]="Copying";e[e.CopyFailed=6]="CopyFailed"}(Nc||(Nc={})),function(e){e[e.Bot=1]="Bot";e[e.Project=2]="Project";e[e.DouyinAvatarBot=3]="DouyinAvatarBot";e[e.VibeProjectAgent=11]="VibeProjectAgent";e[e.VibeProjectAutomation=12]="VibeProjectAutomation";e[e.VibeProjectWebApp=13]="VibeProjectWebApp";e[e.VibeProjectApp=14]="VibeProjectApp";e[e.VibeProjectSkill=15]="VibeProjectSkill";e[e.VibeProjectGeneralWeb=16]="VibeProjectGeneralWeb";e[e.VibeProjectWechatMiniProgram=17]="VibeProjectWechatMiniProgram";e[e.VibeProjectAssistantAgent=18]="VibeProjectAssistantAgent";e[e.VibeProjectGeneral=19]="VibeProjectGeneral"}(Gc||(Gc={})),function(e){e[e.DEFAULT=0]="DEFAULT";e[e.Chux=1]="Chux"}($c||($c={})),function(e){e[e.ProjectOwner=1]="ProjectOwner";e[e.ProjectEditor=2]="ProjectEditor";e[e.BotEditor=3]="BotEditor";e[e.BotDeveloper=4]="BotDeveloper";e[e.BotOperator=5]="BotOperator";e[e.BotOwner=6]="BotOwner"}(Fc||(Fc={})),function(e){e[e.PromptDiff=1]="PromptDiff";e[e.ModelDiff=2]="ModelDiff"}(Vc||(Vc={})),function(e){e[e.DraftBot=1]="DraftBot"}(Wc||(Wc={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(Hc||(Hc={})),function(e){e[e.Archive=1]="Archive";e[e.Rollback=2]="Rollback"}(Jc||(Jc={})),function(e){e[e.ProjectCopyCancel=1]="ProjectCopyCancel";e[e.ProjectCopyRetry=2]="ProjectCopyRetry"}(Kc||(Kc={})),function(e){e[e.ProjectCopy=1]="ProjectCopy";e[e.BotCopy=2]="BotCopy";e[e.VibeProjectCopy=3]="VibeProjectCopy"}(Qc||(Qc={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Yc||(Yc={})),function(e){e[e.Bot=1]="Bot";e[e.Workflow=2]="Workflow";e[e.Application=3]="Application"}(Zc||(Zc={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(Xc||(Xc={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(ed||(ed={})),function(e){e[e.BatchSize=1]="BatchSize";e[e.LearningRate=2]="LearningRate";e[e.Epochs=3]="Epochs"}(td||(td={})),function(e){e[e.GPT=1]="GPT";e[e.SEED=2]="SEED";e[e.Claude=3]="Claude";e[e.MiniMax=4]="MiniMax";e[e.Plugin=5]="Plugin";e[e.StableDiffusion=6]="StableDiffusion";e[e.ByteArtist=7]="ByteArtist";e[e.Maas=9]="Maas";e[e.QianFan=10]="QianFan";e[e.Gemini=11]="Gemini";e[e.Moonshot=12]="Moonshot";e[e.GLM=13]="GLM";e[e.MaaSAutoSync=14]="MaaSAutoSync";e[e.QWen=15]="QWen";e[e.Cohere=16]="Cohere";e[e.Baichuan=17]="Baichuan";e[e.Ernie=18]="Ernie";e[e.DeekSeek=19]="DeekSeek";e[e.Llama=20]="Llama";e[e.StepFun=23]="StepFun";e[e.Custom=24]="Custom";e[e.Other=999]="Other"}(id||(id={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(od||(od={})),function(e){e[e.Douyin=1]="Douyin"}(sd||(sd={})),function(e){e[e.Terminating=1]="Terminating";e[e.Terminated=2]="Terminated"}(nd||(nd={})),function(e){e[e.Online=1]="Online";e[e.Offline=2]="Offline";e[e.Deleted=3]="Deleted";e[e.FineTuneInQueue=4]="FineTuneInQueue";e[e.FineTuneRunning=5]="FineTuneRunning";e[e.FineTuneFailed=6]="FineTuneFailed";e[e.FineTuneTeminated=7]="FineTuneTeminated"}(rd||(rd={})),function(e){e[e.ModelType=1]="ModelType";e[e.ModelUserRight=2]="ModelUserRight";e[e.ModelFeature=3]="ModelFeature";e[e.ModelFunction=4]="ModelFunction";e[e.ModelScenario=5]="ModelScenario";e[e.ModelPayment=15]="ModelPayment";e[e.ModelAbility=16]="ModelAbility";e[e.ModelStatus=17]="ModelStatus";e[e.Custom=20]="Custom";e[e.Others=100]="Others"}(ad||(ad={})),function(e){e[e.Flagship=1]="Flagship";e[e.HighSpeed=2]="HighSpeed";e[e.ToolInvocation=3]="ToolInvocation";e[e.RolePlaying=4]="RolePlaying";e[e.LongText=5]="LongText";e[e.ImageUnderstanding=6]="ImageUnderstanding";e[e.Reasoning=7]="Reasoning";e[e.VideoUnderstanding=8]="VideoUnderstanding";e[e.CostPerformance=9]="CostPerformance";e[e.CodeSpecialization=10]="CodeSpecialization";e[e.AudioUnderstanding=11]="AudioUnderstanding"}(cd||(cd={})),function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInput=2]="TotalInput";e[e.TotalOutput=3]="TotalOutput"}(dd||(dd={})),function(e){e[e.stop=1]="stop";e[e.resume=2]="resume",e[e.delete=3]="delete"}(ld||(ld={})),function(e){e[e.Recommend=1]="Recommend"}(pd||(pd={})),function(e){e[e.Default=0]="Default";e[e.Terminate=1]="Terminate"}(ud||(ud={})),function(e){e[e.All=0]="All";e[e.WithBenefit=1]="WithBenefit"}(_d||(_d={})),function(e){e[e.upload=1]="upload";e[e.TrainingSetSplit=2]="TrainingSetSplit"}(hd||(hd={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(md||(md={})),function(e){e[e.Using=1]="Using";e[e.Deleted=2]="Deleted"}(gd||(gd={})),function(e){e[e.Publish=0]="Publish";e[e.Archive=1]="Archive"}(fd||(fd={})),function(e){e[e.User=0]="User";e[e.NL2App=1]="NL2App"}(yd||(yd={})),function(e){e[e.NoBindRequired=1]="NoBindRequired";e[e.AuthBind=2]="AuthBind";e[e.KvBind=3]="KvBind";e[e.KvAuthBind=4]="KvAuthBind";e[e.ApiBind=5]="ApiBind";e[e.WebSDKBind=6]="WebSDKBind";e[e.StoreBind=7]="StoreBind";e[e.AuthAndConfig=8]="AuthAndConfig";e[e.ConnectorCustom=9]="ConnectorCustom"}(vd||(vd={})),function(e){e[e.APIOrSDK=1]="APIOrSDK";e[e.SocialPlatform=2]="SocialPlatform";e[e.Coze=3]="Coze";e[e.MiniProgram=4]="MiniProgram";e[e.CozeSpaceExtensionLibrary=5]="CozeSpaceExtensionLibrary"}(wd||(wd={})),function(e){e[e.Configured=1]="Configured";e[e.NotConfigured=2]="NotConfigured";e[e.Disconnected=3]="Disconnected";e[e.Configuring=4]="Configuring";e[e.NeedReconfiguring=5]="NeedReconfiguring"}(bd||(bd={})),function(e){e[e.Default=0]="Default";e[e.Auditing=1]="Auditing";e[e.Success=2]="Success";e[e.Failed=3]="Failed";e[e.Disable=4]="Disable"}(Sd||(Sd={})),function(e){e[e.Normal=0]="Normal";e[e.InReview=1]="InReview";e[e.Offline=2]="Offline"}(Pd||(Pd={})),function(e){e[e.Packing=0]="Packing";e[e.PackFailed=1]="PackFailed";e[e.Auditing=2]="Auditing";e[e.AuditNotPass=3]="AuditNotPass";e[e.ConnectorPublishing=4]="ConnectorPublishing";e[e.PublishDone=5]="PublishDone"}(Cd||(Cd={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Authorizing=3]="Authorizing"}(Td||(Td={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.Imageflow=3]="Imageflow";e[e.Knowledge=4]="Knowledge";e[e.UI=5]="UI";e[e.Prompt=6]="Prompt";e[e.Database=7]="Database";e[e.Variable=8]="Variable";e[e.Voice=9]="Voice";e[e.Memorybase=10]="Memorybase";e[e.MCP=11]="MCP"}(Ed||(Ed={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Id||(Id={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.Name=2]="Name"}(kd||(kd={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime"}(Ad||(Ad={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.PublishTime=2]="PublishTime";e[e.OpenTime=3]="OpenTime"}(jd||(jd={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(Rd||(Rd={})),function(e){e[e.All=0]="All";e[e.CreateByMe=1]="CreateByMe";e[e.AllWithCollaborator=2]="AllWithCollaborator";e[e.CanImportToSpace=3]="CanImportToSpace"}(zd||(zd={})),function(e){e[e.Desc=0]="Desc";e[e.Asc=1]="Asc"}(Ld||(Ld={})),function(e){e[e.Copy=1]="Copy";e[e.Move=2]="Move";e[e.Publish=3]="Publish";e[e.ImportExport=4]="ImportExport"}(Ud||(Ud={})),function(e){e[e.Project=1]="Project";e[e.Space=2]="Space";e[e.Online=3]="Online";e[e.Template=4]="Template";e[e.Agent=5]="Agent"}(Od||(Od={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.Imageflow=3]="Imageflow";e[e.Knowledge=4]="Knowledge";e[e.UI=5]="UI";e[e.Project=6]="Project";e[e.Database=7]="Database";e[e.Variable=8]="Variable";e[e.Trigger=9]="Trigger";e[e.Agent=10]="Agent";e[e.Prompt=11]="Prompt";e[e.Shortcut=12]="Shortcut";e[e.Chux=13]="Chux";e[e.Memorybase=14]="Memorybase";e[e.VibeProjectAgent=15]="VibeProjectAgent";e[e.VibeProjectAutomation=16]="VibeProjectAutomation";e[e.VibeProjectWebApp=17]="VibeProjectWebApp";e[e.VibeProjectApp=18]="VibeProjectApp";e[e.VibeProjectSkill=19]="VibeProjectSkill";e[e.VibeProjectGeneralWeb=20]="VibeProjectGeneralWeb";e[e.VibeProjectWechatMiniProgram=21]="VibeProjectWechatMiniProgram";e[e.VibeProjectAssistantAgent=22]="VibeProjectAssistantAgent";e[e.VibeProjectGeneral=23]="VibeProjectGeneral"}(xd||(xd={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(Bd||(Bd={})),function(e){e[e.CopyResourceInProject=1]="CopyResourceInProject";e[e.CopyProjectResourceToLibrary=2]="CopyProjectResourceToLibrary";e[e.MoveProjectResourceToLibrary=3]="MoveProjectResourceToLibrary";e[e.CopyLibraryResourceToProject=4]="CopyLibraryResourceToProject";e[e.CopyProject=5]="CopyProject";e[e.PublishProject=6]="PublishProject";e[e.CopyTemplateToProject=7]="CopyTemplateToProject";e[e.PublishProjectTemplate=8]="PublishProjectTemplate";e[e.LaunchProjectTemplate=9]="LaunchProjectTemplate";e[e.ArchiveProject=10]="ArchiveProject";e[e.RollbackProject=11]="RollbackProject";e[e.CrossSpaceCopy=12]="CrossSpaceCopy";e[e.CrossSpaceCopyProject=13]="CrossSpaceCopyProject";e[e.Export=14]="Export";e[e.Import=15]="Import";e[e.PublishChuxProject=16]="PublishChuxProject";e[e.CopyResource=17]="CopyResource";e[e.CopyVibeProject=18]="CopyVibeProject"}(qd||(qd={})),function(e){e[e.Packing=0]="Packing";e[e.PackSuccess=1]="PackSuccess";e[e.PackFail=2]="PackFail"}(Dd||(Dd={}));class Nd{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Nd.prototype.__init.call(this),Nd.prototype.__init2.call(this),this.request=Md([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Md([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}Ping(e,t){const i=this.genBaseURL("/api/intelligence_api/ping");return this.request({url:i,method:"POST"},t)}DraftProjectCreate(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/draft_project/create"),s={space_id:i.space_id,name:i.name,description:i.description,icon_uri:i.icon_uri,monetization_conf:i.monetization_conf,create_from:i.create_from,folder_id:i.folder_id,type:i.type};return this.request({url:o,method:"POST",data:s},t)}GetDraftIntelligenceList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_list"),s={space_id:i.space_id,name:i.name,has_published:i.has_published,status:i.status,types:i.types,search_scope:i.search_scope,folder_id:i.folder_id,folder_include_children:i.folder_include_children,order_type:i.order_type,project_type:i.project_type,is_fav_filter:i.is_fav_filter,is_collaborator_filter:i.is_collaborator_filter,organization_id:i.organization_id,is_fav:i.is_fav,recently_open:i.recently_open,option:i.option,order_by:i.order_by,cursor_id:i.cursor_id,size:i.size};return this.request({url:o,method:"POST",data:s},t)}DraftProjectUpdate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/update"),s={project_id:i.project_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}GetDraftIntelligenceInfo(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_info"),s={intelligence_id:i.intelligence_id,intelligence_type:i.intelligence_type,version:i.version};return this.request({url:o,method:"POST",data:s},t)}GetUserRecentlyEditIntelligence(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/search/get_recently_edit_intelligence"),s={size:i.size,types:i.types,enterprise_id:i.enterprise_id,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}DraftProjectCopy(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/draft_project/copy"),s={project_id:i.project_id,to_space_id:i.to_space_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}ProcessEntityTask(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/entity_task/process"),s={entity_id:i.entity_id,action:i.action,task_id_list:i.task_id_list};return this.request({url:o,method:"POST",data:s},t)}DraftProjectDelete(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/delete"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}EntityTaskSearch(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/entity_task/search"),s={task_list:i.task_list};return this.request({url:o,method:"POST",data:s},t)}ListIntelligenceCollaboration(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/collaboration/list"),s={intelligence_id:i.intelligence_id,intelligence_type:i.intelligence_type};return this.request({url:o,method:"POST",data:s},t)}OceanProjectCreate(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/ocean_project/create"),s={space_id:i.space_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}OceanProjectUpdate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/ocean_project/update"),s={project_id:i.project_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}GetOceanProjectList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_list"),s={space_id:i.space_id,status:i.status,search_scope:i.search_scope,order_by:i.order_by,page_index:i.page_index,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}PublishProject(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_project"),s={project_id:i.project_id,version_number:i.version_number,description:i.description,connectors:i.connectors,connector_publish_config:i.connector_publish_config};return this.request({url:o,method:"POST",data:s},t)}GetPublishRecordDetail(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_record_detail"),s={project_id:i.project_id,publish_record_id:i.publish_record_id};return this.request({url:o,method:"POST",data:s},t)}GetPublishRecordList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_record_list"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}PublishConnectorList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/connector_list"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}CheckProjectVersionNumber(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/check_version_number"),s={project_id:i.project_id,version_number:i.version_number};return this.request({url:o,method:"POST",data:s},t)}DraftProjectInnerTaskList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/inner_task_list"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}GetOceanProjectInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_info"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}GetModelListFilterParams(e,t){const i=this.genBaseURL("/api/intelligence_api/model/get_model_list_filter_params");return this.request({url:i,method:"POST"},t)}StartEstimatedTrainingCost(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/start_estimated_training_cost"),s={base_model_id:i.base_model_id,space_id:i.space_id,training_dataset_id:i.training_dataset_id,epochs:i.epochs};return this.request({url:o,method:"POST",data:s},t)}GetModelList(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_list"),s={space_id:i.space_id,name:i.name,tag_filters:i.tag_filters,context_len_min:i.context_len_min,context_len_max:i.context_len_max,model_cost_min:i.model_cost_min,model_cost_max:i.model_cost_max,model_vendor:i.model_vendor,statusList:i.statusList,model_show_family_id:i.model_show_family_id,model_source:i.model_source,order_by:i.order_by,cursor_id:i.cursor_id,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}GetFinetuneTemplateDataset(e,t){const i=this.genBaseURL("/api/intelligence_api/model/get_finetune_template_dataset");return this.request({url:i,method:"POST"},t)}GetModelUsageData(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_usage_data"),s={space_id:i.space_id,model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}GetEstimatedTrainingCost(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_estimated_training_cost"),s={task_id:i.task_id,space_id:i.space_id,base_model_id:i.base_model_id,epochs:i.epochs};return this.request({url:o,method:"POST",data:s},t)}CreateFinetuneTask(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/create_finetune_task"),s={space_id:i.space_id,base_model_id:i.base_model_id,training_dataset_id:i.training_dataset_id,validating_dataset:i.validating_dataset,finetune_configuration:i.finetune_configuration,description:i.description,name:i.name};return this.request({url:o,method:"POST",data:s},t)}UploadFinetuneDataset(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/upload_finetune_dataset"),s={space_id:i.space_id,fileType:i.fileType,fileName:i.fileName,data:i.data,testing_data:i.testing_data};return this.request({url:o,method:"POST",data:s},t)}GetModelInfo(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_info"),s={space_id:i.space_id,model_id:i.model_id,is_finetuning:i.is_finetuning};return this.request({url:o,method:"POST",data:s},t)}GetFinetuneTrainingInfo(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_finetune_training_info"),s={space_id:i.space_id,model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}GetModelPerformanceData(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_performance_data"),s={space_id:i.space_id,model_id:i.model_id,get_pct:i.get_pct};return this.request({url:o,method:"POST",data:s},t)}OperateFinetuneTask(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/operate_finetune_task"),s={id:i.id,action:i.action};return this.request({url:o,method:"POST",data:s},t)}DeleteFinetuneModel(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/delete_finetune_model"),s={model_id:i.model_id,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetUserCompleteProfileRecord(e,t){const i=this.genBaseURL("/api/intelligence_api/user_profile/get_user_complete_profile_record");return this.request({url:i,method:"POST"},t)}DownloadUserProfile(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/user_profile/download_user_profile"),s={Cookie:i.Cookie};return this.request({url:o,method:"POST",headers:s},t)}GetProjectPublishedConnector(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/get_published_connector"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}PublishIntelligenceUnList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_intelligence_unlist"),s={intelligence_id:i.intelligence_id,connector_ids:i.connector_ids,intelligence_type:i.intelligence_type};return this.request({url:o,method:"POST",data:s},t)}PublishIntelligenceList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_publish_intelligence_list"),s={intelligence_type:i.intelligence_type,space_id:i.space_id,owner_id:i.owner_id,name:i.name,order_last_publish_time:i.order_last_publish_time,order_total_token:i.order_total_token,size:i.size,cursor_id:i.cursor_id,intelligence_ids:i.intelligence_ids};return this.request({url:o,method:"POST",data:s},t)}UpdateDiffModeInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/diff_mode/update_diff_mode_info"),s={target_type:i.target_type,target_id:i.target_id,diff_mode_info:i.diff_mode_info,exit_and_save:i.exit_and_save,exit_and_discard:i.exit_and_discard};return this.request({url:o,method:"POST",data:s},t)}GetDiffModeInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/diff_mode/get_diff_mode_info"),s={target_type:i.target_type,target_id:i.target_id};return this.request({url:o,method:"POST",data:s},t)}GetProjectPublishSummary(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_project_publish_summary"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}DraftProjectCrossSpaceCopy(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/draft_project/crossspace_copy"),s={project_id:i.project_id,to_space_id:i.to_space_id};return this.request({url:o,method:"POST",data:s},t)}EntityTaskList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/entity_task/list"),s={space_id:i.space_id,task_id_list:i.task_id_list};return this.request({url:o,method:"POST",data:s},t)}ExpansionTpm(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/expansion_tpm"),s={model_id:i.model_id,enterprise_id:i.enterprise_id,organization_id:i.organization_id,tpm_input_expansion:i.tpm_input_expansion,tpm_output_expansion:i.tpm_output_expansion,start_time:i.start_time,end_time:i.end_time};return this.request({url:o,method:"POST",data:s},t)}GetEstimatedTpmExpansionCost(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion_cost"),s={model_id:i.model_id,enterprise_id:i.enterprise_id,input_tpm:i.input_tpm,output_tpm:i.output_tpm};return this.request({url:o,method:"POST",data:s},t)}GetEstimatedTpmExpansion(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion"),s={model_id:i.model_id,enterprise_id:i.enterprise_id,estimated_rpm:i.estimated_rpm,StartTime:i.StartTime,EndTime:i.EndTime};return this.request({url:o,method:"POST",data:s},t)}FolderUpdate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/update"),s={folder_id:i.folder_id,name:i.name,description:i.description};return this.request({url:o,method:"POST",data:s},t)}GetFolderList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_folder_list"),s={space_id:i.space_id,type:i.type,name:i.name,search_scope:i.search_scope,parent_folder_id:i.parent_folder_id,parent_include_children:i.parent_include_children,order_by:i.order_by,order_type:i.order_type,size:i.size,page_num:i.page_num};return this.request({url:o,method:"POST",data:s},t)}FolderMove(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/move"),s={folder_id:i.folder_id,parent_folder_id:i.parent_folder_id};return this.request({url:o,method:"POST",data:s},t)}FolderDelete(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/delete"),s={folder_id:i.folder_id};return this.request({url:o,method:"POST",data:s},t)}FolderCreate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/create"),s={space_id:i.space_id,type:i.type,name:i.name,description:i.description,parent_folder_id:i.parent_folder_id};return this.request({url:o,method:"POST",data:s},t)}ArchiveProject(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/archive"),s={project_id:i.project_id,description:i.description,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetIntelligenceTaskInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/entity_task/task_info"),s={task_id:i.task_id};return this.request({url:o,method:"GET",params:s},t)}ProjectHistoryList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/history_list"),s={project_id:i.project_id,history_type:i.history_type,cursor:i.cursor,size:i.size};return this.request({url:o,method:"POST",data:s},t)}RollbackProject(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/rollback"),s={project_id:i.project_id,rollback_version:i.rollback_version,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetModelConcurrencyPerformanceData(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_concurrency_performance_data"),s={space_id:i.space_id,model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}UpdateModelConfigType(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/update_model_config_type"),s={space_id:i.space_id,model_id:i.model_id,config_type:i.config_type};return this.request({url:o,method:"POST",data:s},t)}GetSpaceModelUserConfig(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_space_model_user_config"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}OpenGetProjectList(e,t){const i=e||{},o=this.genBaseURL("/v1/apps"),s={workspace_id:i.workspace_id,publish_status:i.publish_status,connector_id:i.connector_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}OpenGetBotList(e,t){const i=e||{},o=this.genBaseURL("/v1/bots"),s={workspace_id:i.workspace_id,publish_status:i.publish_status,connector_id:i.connector_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}GetFolderTree(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/tree"),s={space_id:i.space_id,type:i.type};return this.request({url:o,method:"POST",data:s},t)}OpenGetSpaceFolder(e,t){const i=e||{},o=this.genBaseURL("/v1/folders"),s={workspace_id:i.workspace_id,folder_type:i.folder_type,parent_folder_id:i.parent_folder_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}MoveObjectToFolder(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/move_object"),s={dest_folder_id:i.dest_folder_id,folder_space_id:i.folder_space_id,move_objects:i.move_objects};return this.request({url:o,method:"POST",data:s},t)}GetFolderInfoByIds(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/folder/get_by_ids"),s={space_id:i.space_id,folder_ids:i.folder_ids,get_path_info:i.get_path_info};return this.request({url:o,method:"POST",data:s},t)}OpenGetFolderInfo(e,t){const i=e||{},o=this.genBaseURL(`/v1/folders/${i.folder_id}`);return this.request({url:o,method:"GET"},t)}ExportPreCheck(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/export_pre_check"),s={res_type:i.res_type,id:i.id,commit_id:i.commit_id};return this.request({url:o,method:"POST",data:s},t)}ImportPreCheck(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/import_pre_check"),s={package_uri:i.package_uri};return this.request({url:o,method:"POST",data:s},t)}GetUploadAuthToken(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/upload/auth_token"),s={scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}MarkProjectHistory(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/history_list/read"),s={project_id:i.project_id,version:i.version};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelDetail(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_detail"),s={model_id:i.model_id,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_list"),s={search_key:i.search_key,sort_field:i.sort_field,org_id:i.org_id,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetProjectHistoryNotice(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/history_list/notice"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}BindCustomModelSpace(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/bind_custom_model_space"),s={model_id:i.model_id,space_id_list:i.space_id_list,status:i.status,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelSpaceList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_space_list"),s={model_id:i.model_id,search_key:i.search_key,org_id:i.org_id,cursor_id:i.cursor_id,limit:i.limit,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelParameterTemplate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_parameter_template"),s={org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}OpenCopyTaskInfo(e,t){const i=e||{},o=this.genBaseURL(`/v1/entities/copy_tasks/${i.task_id}`);return this.request({url:o,method:"GET"},t)}OpenDuplicateDraftEntity(e,t){const i=e||{},o=this.genBaseURL("/v1/entities/copy_tasks"),s={entity_id:i.entity_id,entity_type:i.entity_type,to_workspace_id:i.to_workspace_id};return this.request({url:o,method:"POST",data:s},t)}ConvertCustomModelParameter(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/convert_custom_model_parameter"),s={parameters:i.parameters,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}CreateCustomModel(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/create_custom_model"),s={model_name:i.model_name,model_icon_uri:i.model_icon_uri,model_arch:i.model_arch,model_desc:i.model_desc,base_url:i.base_url,secret_name:i.secret_name,model_runtime_tag:i.model_runtime_tag,inputLength:i.inputLength,parameters:i.parameters,api_agreement:i.api_agreement,safety_guardrails:i.safety_guardrails,auth:i.auth,api_mode:i.api_mode,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}TerminateCustomModel(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/terminate_custom_model"),s={model_id:i.model_id,terminate_time:i.terminate_time,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCustomModel(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/update_custom_model"),s={model_name:i.model_name,model_icon_uri:i.model_icon_uri,model_arch:i.model_arch,model_desc:i.model_desc,base_url:i.base_url,secret_name:i.secret_name,model_runtime_tag:i.model_runtime_tag,inputLength:i.inputLength,parameters:i.parameters,model_id:i.model_id,api_agreement:i.api_agreement,safety_guardrails:i.safety_guardrails,auth:i.auth,api_mode:i.api_mode,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}GetModelUsageRecord(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_usage_record"),s={space_id:i.space_id,model_id:i.model_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp,order_by_type:i.order_by_type,order_by_field:i.order_by_field,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetEntityModelUsage(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_entity_model_usage"),s={space_id:i.space_id,model_id:i.model_id,entity_id:i.entity_id,entity_type:i.entity_type,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp};return this.request({url:o,method:"POST",data:s},t)}GetTypeList(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/get_type_list"),s={model:i.model,voice:i.voice,raw_model:i.raw_model,space_id:i.space_id,cur_model_id:i.cur_model_id,cur_model_ids:i.cur_model_ids,model_scene:i.model_scene,tag_filters:i.tag_filters,user_benefit_filter:i.user_benefit_filter};return this.request({url:o,method:"POST",data:s},t)}SaveModelReplacement(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/save_replacement"),s={space_id:i.space_id,old_model_id:i.old_model_id,new_model_id:i.new_model_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp};return this.request({url:o,method:"POST",data:s},t)}GetModelReplacement(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_replacement"),s={space_id:i.space_id,entity_type:i.entity_type,entity_id:i.entity_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCustomModelV2(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/update"),s={model_id:i.model_id,display_name:i.display_name,model_name:i.model_name,base_url:i.base_url,api_mode:i.api_mode,auth:i.auth,support_image_understanding:i.support_image_understanding,max_tokens:i.max_tokens};return this.request({url:o,method:"POST",data:s},t)}ListProviderModels(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/list_provider_models"),s={provider:i.provider,auth:i.auth,base_url:i.base_url,search_key:i.search_key};return this.request({url:o,method:"POST",data:s},t)}ListCustomModelV2(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/list"),s={account_type:i.account_type,coze_account_id:i.coze_account_id,enterprise_id:i.enterprise_id,search_key:i.search_key,provider:i.provider,source_type:i.source_type,sort_field:i.sort_field,sort_order:i.sort_order,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}ToggleCustomModelMemberVisibility(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/toggle_member_visibility"),s={model_id:i.model_id,member_visible:i.member_visible};return this.request({url:o,method:"POST",data:s},t)}DeleteCustomModelV2(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/delete"),s={model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}ListProviders(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/custom_model/list_providers"),s={only_enabled:i.only_enabled};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelDetailV2(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/detail"),s={model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}CreateCustomModelV2(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/custom_model/create"),s={source_type:i.source_type,provider:i.provider,display_name:i.display_name,model_name:i.model_name,base_url:i.base_url,api_mode:i.api_mode,auth:i.auth,support_image_understanding:i.support_image_understanding,max_tokens:i.max_tokens,account_type:i.account_type,coze_account_id:i.coze_account_id,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}}const Gd=new Nd({}),$d={agent:Gc.VibeProjectAgent,workflow:Gc.VibeProjectAutomation,webapp:Gc.VibeProjectWebApp,app:Gc.VibeProjectApp,skill:Gc.VibeProjectSkill,web:Gc.VibeProjectGeneralWeb,miniprogram:Gc.VibeProjectWechatMiniProgram,assistant:Gc.VibeProjectAssistantAgent},Fd={[Gc.VibeProjectAgent]:"agent",[Gc.VibeProjectAutomation]:"workflow",[Gc.VibeProjectWebApp]:"webapp",[Gc.VibeProjectApp]:"app",[Gc.VibeProjectSkill]:"skill",[Gc.VibeProjectGeneralWeb]:"web",[Gc.VibeProjectWechatMiniProgram]:"miniprogram",[Gc.VibeProjectAssistantAgent]:"assistant"};function Vd(e){if(!e)return;const t=String(e).trim();if(!t)return;const i=t.toLowerCase();return $d[i]}const Wd=e=>Fd[e],Hd=[Gc.VibeProjectAgent,Gc.VibeProjectAutomation,Gc.VibeProjectWebApp,Gc.VibeProjectApp,Gc.VibeProjectSkill,Gc.VibeProjectGeneralWeb,Gc.VibeProjectWechatMiniProgram,Gc.VibeProjectAssistantAgent].map(Wd).filter(Boolean);function Jd(e,t){return null!=e?e:t()}function Kd(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 Qd={agent:t.VibeProjectType.Agent,workflow:t.VibeProjectType.Automation,webapp:t.VibeProjectType.WebApp,app:t.VibeProjectType.App,skill:t.VibeProjectType.Skill,web:t.VibeProjectType.GeneralWeb,miniprogram:t.VibeProjectType.WechatMiniProgram,assistant:t.VibeProjectType.AssistantAgent},Yd={[t.VibeProjectType.Agent]:"agent",[t.VibeProjectType.Automation]:"workflow",[t.VibeProjectType.WebApp]:"webapp",[t.VibeProjectType.App]:"app",[t.VibeProjectType.Skill]:"skill",[t.VibeProjectType.GeneralWeb]:"web",[t.VibeProjectType.WechatMiniProgram]:"miniprogram",[t.VibeProjectType.AssistantAgent]:"assistant"};const Zd=e=>Yd[e],Xd=[t.VibeProjectType.GeneralWeb,t.VibeProjectType.App],el=Xd.map(Zd);function tl(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 il(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 ol{static getInstance(){return ol.INSTANCE||(ol.INSTANCE=new ol),ol.INSTANCE}sendMessageRunTask(e){const t=[_.resolve(__dirname,"./send-message.worker.js")],i=process.execPath;v.spawn(i,[...t,JSON.stringify(e)],{detached:!0,stdio:"ignore"}).unref()}async sendMessage(e){return await t.sendProjectChatMessage(e)}isValidType(e){return Xd.includes(e)}}const sl=ol.getInstance();function nl(e,t){return null!=e?e:t()}function rl(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 al(i){i.command("create").description("Create a new project").requiredOption("--message <message>","Description/requirements for creating the project").requiredOption("--type <type>","Project type: agent | workflow | app | skill | web | miniprogram | assistant").option("--org-id <orgId>","Organization ID (optional, will read from context automatically)").option("--space-id <spaceId>","Space ID (optional, will read from context automatically)").option("--wait","Wait for project creation to complete").config({help:{brief:"Create a new Coze Coding project",description:"Create a new Coze Coding project via natural language description. The system will automatically generate project structure and configuration based on the description, supporting multiple project types.",examples:[{desc:"Create an Agent project",cmd:'coze code project create --message "Create an intelligent customer service robot" --type agent',tags:["[RECOMMENDED]"]},{desc:"Create a Workflow project",cmd:'coze code project create --message "Create a data processing workflow" --type workflow'}],schema:{input:{message:{type:"string",required:!0,description:"Project description/requirements (natural language)"},type:{type:"string",required:!0,enum:el,description:"Project type"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{project_id:{type:"string",description:"Created project ID"},type:{type:"string",description:"Project type"}}},enums:{type:el.reduce(((e,t)=>(e[t]=`${t.toUpperCase()} project`,e)),{})},errors:[{code:e.ErrorCode.E1005,name:"INVALID_PROJECT_TYPE",desc:"Invalid project type",fix:"Please use a valid project type: agent | workflow | app | skill | web | miniprogram | assistant"},{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Missing Space ID",fix:"Please use the --space-id parameter or run `coze space use <spaceId>` first"},{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Project type is not supported for creation",fix:"Please choose a supported project type and try again"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized or project tool config is missing",fix:"Please retry and run with --debug if the issue persists"}]}}).action((async(i,o)=>{const s=o.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=nl(nl(i.spaceId,(()=>rl([s,"optionalAccess",e=>e.config,"access",e=>e.spaceId]))),(()=>"")),{message:r,type:a,wait:c}=i;rl([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e(`Resolving project type '${a}'...`)]);const d=function(e){if(!e)return;const t=String(e).trim();if(!t)return;const i=t.toLowerCase();return Qd[i]}(a);if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!d)throw new e.CozeError(e.ErrorCode.E1005,`Unknown project type: ${a}`,{type:a});if(!sl.isValidType(d))throw new e.CozeError(e.ErrorCode.E1006,`Project type ${a} is not supported for creation`,{type:a,projectType:d});rl([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching agent tools configuration...")]);const l=rl([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===d)),"optionalAccess",e=>e.tools]);if(!l||0===l.length)throw new e.CozeError(e.ErrorCode.E5000,`No tools config for projectType: ${String(a)}`,{type:a,projectType:d});const p={};l.forEach((e=>{rl([e,"optionalAccess",e=>e.name])&&(p[e.name]=Boolean(e.enabled))})),rl([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching project default skills...")]);const u={skills:nl(rl([await ua.GetProjectDefaultSkill({project_type:d,space_id:String(n)}),"access",e=>e.data,"optionalAccess",e=>e.skill_list]),(()=>[])).map((e=>({skill_id:e.skill_id,is_preload:e.is_preload}))),filter_types:[d]},_={space_id:String(n),user_query:r,project_type:d,agent_tools:p,project_settings:{model_setting:{model_name:""},skill_setting:u}};rl([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating project...")]);const h=nl((await t.IdeApi.ChatCreateVibeProject(_)).data,(()=>({}))).project_id,m=await rl([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!m)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(s.ui.success('Project created successfully, please use "coze code message status" to check the status.'),rl([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:h,type:a})]),c){const e=await sl.sendMessage({projectId:nl(h,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:m,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${h}`});s.response.print(e.lastAnswerMessage)}else sl.sendMessageRunTask({projectId:nl(h,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:m,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${h}`})}))}const cl=i=>{const o=i.command("project").alias("proj").config({help:{brief:"Manage Coze Coding projects",description:"Manage Coze Coding projects (Vibe Project). Supports creating, viewing, listing, and deleting projects, covering various project types like Agent, Workflow, Skill, Web apps, Mini-programs, etc.",examples:[{desc:"Create project",cmd:'coze code project create --message "Create a chatbot" --type web'},{desc:"List projects",cmd:"coze code project list"},{desc:"View project details",cmd:"coze code project get <projectId>"},{desc:"Delete project",cmd:"coze code project delete <projectId>"}],seeAlso:["coze code deploy","coze code skill"],schema:{input:{},output:{}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).description("Manage Coze Coding projects");al(o),function(t){t.command("list").description("List all projects").config({help:{brief:"List all projects in the current space",description:"Get the list of projects in the current space. Supports filtering by type, name, publish status, and supports pagination.",examples:[{desc:"List projects",cmd:"coze code project list",tags:["[RECOMMENDED]"]},{desc:"Filter by type",cmd:"coze code project list --type agent --type workflow"},{desc:"Search by name",cmd:'coze code project list --name "customer service"'}],schema:{input:{size:{type:"number",required:!1,description:"Number of projects to return (default: 10)"},cursorId:{type:"string",required:!1,description:"Cursor for pagination"},type:{type:"array",required:!1,description:"Project type filter (can be passed multiple times)"},name:{type:"string",required:!1,description:"Filter by project name"},hasPublished:{type:"boolean",required:!1,description:"Filter by publish status"},searchScope:{type:"number",required:!1,description:"Created by (All = 0, CreateByMe = 1)"},folderId:{type:"string",required:!1,description:"Folder ID"},orderType:{type:"number",required:!1,description:"Sort type (0 for descending, 1 for ascending)"},isFavFilter:{type:"boolean",required:!1,description:"Filter by favorite status"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Project ID"},name:{type:"string",description:"Project name"},type:{type:"string",description:"Project type"},description:{type:"string",description:"Project description"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}],enums:{type:Hd.reduce(((e,t)=>(e[t]=`${t.toUpperCase()} project`,e)),{}),"search-scope":{0:"All",1:"CreateByMe"},"order-type":{0:"Descending",1:"Ascending"},"order-by":{0:"updated_at",1:"created_at"}}}}).option("--size <size>","Number of projects to return",parseInt).option("--cursor-id <cursorId>","Cursor for pagination").option("--type <type>","Project type filter (can be passed multiple times): agent | workflow | webapp | app | web | miniprogram | assistant",((e,t=[])=>[...t,e]),[]).option("--name <name>","Filter by project name").option("--has-published","Filter by publish status").option("--search-scope <searchScope>","Created by (All = 0, CreateByMe = 1, AllWithCollaborator = 2)").option("--folder-id <folderId>","Folder ID").option("--order-type <orderType>","Sort type (0 for descending, 1 for ascending)").option("--order-by <orderBy>","Order by (0 for updated_at, 1 for created_at)").option("--is-fav-filter","Filter by favorite status (true | false)").action((async function(e,t){const i=t.getContext(),o=Jd(Kd([e,"optionalAccess",e=>e.size]),(()=>10)),s=Jd(Kd([e,"optionalAccess",e=>e.cursorId]),(()=>{})),n=Kd([e,"optionalAccess",e=>e.type,"optionalAccess",e=>e.map,"call",e=>e(Vd),"access",e=>e.filter,"call",e=>e(Boolean)]),r=Kd([e,"optionalAccess",e=>e.name]),a=Kd([e,"optionalAccess",e=>e.hasPublished])?Boolean(Kd([e,"optionalAccess",e=>e.hasPublished])):void 0,c=Number(Jd(Kd([e,"optionalAccess",e=>e.searchScope]),(()=>zd.All))),d=Jd(Kd([e,"optionalAccess",e=>e.folderId]),(()=>"0")),l=Number(Jd(Kd([e,"optionalAccess",e=>e.orderType]),(()=>Ld.Desc))),p=Boolean(Kd([e,"optionalAccess",e=>e.isFavFilter])),u=Number(Jd(Kd([e,"optionalAccess",e=>e.orderBy]),(()=>jd.UpdateTime)));let _=[];Kd([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching project list...")]);const h=await Gd.GetDraftIntelligenceList({space_id:Jd(Kd([i,"optionalAccess",e=>e.config,"access",e=>e.spaceId]),(()=>"")),size:o,cursor_id:s,types:n,name:r,has_published:a,search_scope:c,folder_id:d,order_type:l,order_by:u,is_fav_filter:p,status:[Nc.Using,Nc.Banned,Nc.MoveFailed]});_=Kd([h,"access",e=>e.data,"optionalAccess",e=>e.intelligences])||[],Kd([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetched ${_.length} projects.`)]),Kd([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(_.map((e=>({id:Kd([e,"access",e=>e.basic_info,"optionalAccess",e=>e.id]),name:Kd([e,"access",e=>e.basic_info,"optionalAccess",e=>e.name]),type:Wd(e.type),description:Kd([e,"access",e=>e.basic_info,"optionalAccess",e=>e.description])}))))])}))}(o),function(i){i.command("get <projectId>").description("View project details").config({help:{brief:"Get project details",description:"Get the detailed configuration of the specified project, including project type, settings, skill configurations, etc.",examples:[{desc:"View project details",cmd:"coze code project get <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},project_name:{type:"string",description:"Project name"},project_type:{type:"string",description:"Project type"},skills:{type:"object",description:"Project skill configurations",properties:{skills:{type:"array",items:{type:"object",properties:{skill_id:{type:"string",description:"Skill ID"},is_preload:{type:"boolean",description:"Is preloaded"}}}}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project does not exist",fix:"Please confirm if the project ID is correct, use `project list` to view available projects"}]}}).action((async function(i,o,s){const n=s.getContext();tl([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetching project details for '${i}'...`)]);const r=tl([await t.IdeApi.GetVibeProject({project_id:i}),"access",e=>e.data,"optionalAccess",e=>e.project_info]);if(!r)throw new e.CozeError(e.ErrorCode.E3001,`Project ${i} not found`,{projectId:i});tl([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Project details for '${i}':`)]),tl([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...y.omit(r,["project_settings"]),skills:y.pick(tl([r,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]),["skills"]),project_type:Zd(tl([r,"optionalAccess",e=>e.project_type]))})])}))}(o),function(i){i.command("delete <projectId>").description("Delete a project").config({help:{brief:"Delete project",description:"Delete the specified Coze Coding project. This operation cannot be undone, please use with caution.",examples:[{desc:"Delete project",cmd:"coze code project delete <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID to delete"}},output:{project_id:{type:"string",description:"Deleted project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E3005,name:"DELETE_FAILED",desc:"Failed to delete project",fix:"Please confirm if the project ID is correct and check if you have sufficient permissions"}]}}).action((async function(e,i,o){const s=o.getContext();il([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",t=>t(`Deleting project '${e}'...`)]),await t.IdeApi.DeleteVibeProject({project_id:e}),il([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Project '${e}' deleted successfully.`)]),il([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({project_id:e,message:`Project '${e}' deleted successfully.`})])}))}(o)};var dl,ll,pl,ul,_l,hl,ml,gl,fl,yl,vl,wl,bl,Sl,Pl,Cl,Tl,El,Il,kl,Al,jl,Rl,zl,Ll,Ul,Ol,xl,Bl,ql,Dl,Ml,Nl,Gl,$l,Fl,Vl,Wl,Hl,Jl,Kl,Ql,Yl,Zl,Xl,ep,tp,ip,op,sp,np,rp,ap,cp,dp,lp,pp,up,_p,hp,mp,gp,fp,yp,vp,wp,bp;function Sp(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[e.Example=0]="Example";e[e.Template=1]="Template"}(dl||(dl={})),function(e){e[e.SpaceEvent=1]="SpaceEvent"}(ll||(ll={})),function(e){e[e.Interest=1]="Interest"}(pl||(pl={})),function(e){e[e.General=0]="General";e[e.PPT=1]="PPT";e[e.Podcast=2]="Podcast";e[e.WEB=3]="WEB";e[e.ImageDoc=4]="ImageDoc";e[e.Poster=5]="Poster";e[e.Excel=6]="Excel";e[e.DesignTemplate=7]="DesignTemplate";e[e.PPTTemplate=8]="PPTTemplate";e[e.Chart=9]="Chart";e[e.Video=10]="Video";e[e.ImagePPTTemplate=11]="ImagePPTTemplate";e[e.VideoTemplate=12]="VideoTemplate"}(ul||(ul={})),function(e){e[e.Chat=1]="Chat";e[e.Fill=2]="Fill"}(_l||(_l={})),function(e){e[e.Delete=0]="Delete";e[e.Running=1]="Running";e[e.Pause=2]="Pause";e[e.TaskFinish=3]="TaskFinish";e[e.Init=4]="Init";e[e.Stop=5]="Stop";e[e.Interrupt=6]="Interrupt";e[e.IllegalContent=7]="IllegalContent";e[e.AbnormalInterrupt=8]="AbnormalInterrupt";e[e.Sleep=9]="Sleep"}(hl||(hl={})),function(e){e[e.Favorite=1]="Favorite";e[e.Template=2]="Template";e[e.TemplateCover=3]="TemplateCover";e[e.PlanTemplate=4]="PlanTemplate";e[e.Article=5]="Article"}(ml||(ml={})),function(e){e[e.General=0]="General";e[e.Product=1]="Product"}(gl||(gl={})),function(e){e[e.Unknown=0]="Unknown";e[e.Pending=1]="Pending";e[e.Running=2]="Running";e[e.Completed=3]="Completed";e[e.Failed=4]="Failed";e[e.Cancelled=5]="Cancelled"}(fl||(fl={})),function(e){e[e.HandsOff=0]="HandsOff";e[e.Cooperative=1]="Cooperative";e[e.Auto=2]="Auto"}(yl||(yl={})),function(e){e[e.Modify=1]="Modify";e[e.Clear=2]="Clear";e[e.RemoveBackground=3]="RemoveBackground";e[e.Inpainting=4]="Inpainting";e[e.TextReplacement=5]="TextReplacement"}(vl||(vl={})),function(e){e[e.Unactivated=1]="Unactivated";e[e.Activated=2]="Activated"}(wl||(wl={})),function(e){e[e.hot_city=1]="hot_city";e[e.city=2]="city"}(bl||(bl={})),function(e){e[e.PDF=1]="PDF";e[e.PPT=2]="PPT";e[e.ImageEditablePpt=3]="ImageEditablePpt"}(Sl||(Sl={})),function(e){e[e.Chinese=0]="Chinese";e[e.English=1]="English"}(Pl||(Pl={})),function(e){e[e.Review=1]="Review";e[e.Draft=2]="Draft";e[e.LawQA=3]="LawQA"}(Cl||(Cl={})),function(e){e[e.Pin=1]="Pin";e[e.UnPin=2]="UnPin";e[e.Use=3]="Use"}(Tl||(Tl={})),function(e){e[e.Init=1]="Init";e[e.Stock=2]="Stock";e[e.Sector=3]="Sector"}(El||(El={})),function(e){e[e.GeneralChat=1]="GeneralChat";e[e.Scheduled=2]="Scheduled"}(Il||(Il={})),function(e){e[e.FieldAnalysis=1]="FieldAnalysis";e[e.Upload=2]="Upload"}(kl||(kl={})),function(e){e[e.Running=1]="Running";e[e.Pause=2]="Pause";e[e.TaskFinish=3]="TaskFinish";e[e.Init=4]="Init";e[e.Stop=5]="Stop";e[e.Interrupt=6]="Interrupt";e[e.IllegalContent=7]="IllegalContent";e[e.AbnormalInterrupt=8]="AbnormalInterrupt";e[e.Sleep=9]="Sleep"}(Al||(Al={})),function(e){e[e.UNKNOWN=0]="UNKNOWN";e[e.HTML=1]="HTML";e[e.WORD=2]="WORD";e[e.PPT=3]="PPT";e[e.EXCEL=4]="EXCEL";e[e.PDF=5]="PDF";e[e.NOTE=6]="NOTE";e[e.IMAGE=7]="IMAGE";e[e.PODCAST=8]="PODCAST"}(jl||(jl={})),function(e){e[e.FavoritePage=1]="FavoritePage";e[e.TASK=2]="TASK"}(Rl||(Rl={})),function(e){e[e.UserUpload=1]="UserUpload";e[e.Explore=2]="Explore";e[e.TASK=3]="TASK"}(zl||(zl={})),function(e){e[e.PPT=1]="PPT"}(Ll||(Ll={})),function(e){e[e.Favorite=1]="Favorite";e[e.MultiDocImage=2]="MultiDocImage"}(Ul||(Ul={})),function(e){e[e.Upload=1]="Upload";e[e.Search=2]="Search";e[e.Generate=3]="Generate"}(Ol||(Ol={})),function(e){e[e.PNG=1]="PNG";e[e.JPG=2]="JPG";e[e.MP4=3]="MP4"}(xl||(xl={})),function(e){e[e.Modify=1]="Modify";e[e.Clear=2]="Clear";e[e.RemoveBackground=3]="RemoveBackground";e[e.Generate=4]="Generate";e[e.Search=5]="Search";e[e.Blur=6]="Blur"}(Bl||(Bl={})),function(e){e[e.Image=1]="Image";e[e.Html=2]="Html";e[e.Livephoto=3]="Livephoto"}(ql||(ql={})),function(e){e[e.Chat=1]="Chat";e[e.ApiTemplate=2]="ApiTemplate"}(Dl||(Dl={})),function(e){e[e.Suggest=1]="Suggest"}(Ml||(Ml={})),function(e){e[e.Unknown=0]="Unknown";e[e.Clarifying=1]="Clarifying";e[e.PendingActivation=2]="PendingActivation";e[e.Running=3]="Running";e[e.PendingConfirm=4]="PendingConfirm";e[e.Terminated=5]="Terminated"}(Nl||(Nl={})),function(e){e[e.Unknown=0]="Unknown";e[e.SystemError=1]="SystemError";e[e.InsufficientBalance=2]="InsufficientBalance";e[e.UserManual=3]="UserManual";e[e.Timeout=4]="Timeout"}(Gl||(Gl={})),function(e){e[e.DiggTypeDigg=1]="DiggTypeDigg";e[e.DiggTypeBury=2]="DiggTypeBury"}($l||($l={})),function(e){e[e.Query=1]="Query";e[e.Answer=2]="Answer";e[e.Resume=3]="Resume"}(Fl||(Fl={})),function(e){e[e.Unknown=0]="Unknown";e[e.ActivatePlan=1]="ActivatePlan";e[e.ResumePlan=2]="ResumePlan"}(Vl||(Vl={})),function(e){e[e.DocMultiImage=1]="DocMultiImage"}(Wl||(Wl={})),function(e){e[e.PDF=1]="PDF";e[e.DOCX=2]="DOCX"}(Hl||(Hl={})),function(e){e[e.DeleteCookie=1]="DeleteCookie"}(Jl||(Jl={})),function(e){e[e.POSITION=0]="POSITION";e[e.ELEMENT=1]="ELEMENT"}(Kl||(Kl={})),function(e){e[e.DiamondMatrix=1]="DiamondMatrix";e[e.BulletPoints=2]="BulletPoints";e[e.StaggeredProcessDiagram=3]="StaggeredProcessDiagram";e[e.ArrowRingDiagram=4]="ArrowRingDiagram";e[e.VerticalTimeline=5]="VerticalTimeline"}(Ql||(Ql={})),function(e){e[e.Init=1]="Init";e[e.Enabled=2]="Enabled";e[e.Disabled=3]="Disabled"}(Yl||(Yl={})),function(e){e[e.Pending=1]="Pending";e[e.Success=2]="Success";e[e.Avoid=3]="Avoid";e[e.Failed=4]="Failed"}(Zl||(Zl={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Expired=3]="Expired"}(Xl||(Xl={})),function(e){e[e.Query=1]="Query";e[e.Template=2]="Template"}(ep||(ep={})),function(e){e[e.Pause=1]="Pause";e[e.Resume=2]="Resume";e[e.Pin=3]="Pin";e[e.Unpin=4]="Unpin";e[e.DoNotDisturb=5]="DoNotDisturb";e[e.CancelDoNotDisturb=6]="CancelDoNotDisturb";e[e.Stop=7]="Stop";e[e.Read=8]="Read"}(tp||(tp={})),function(e){e[e.Init=0]="Init";e[e.Enable=1]="Enable";e[e.Disable=2]="Disable"}(ip||(ip={})),function(e){e[e.Open=1]="Open";e[e.Close=2]="Close"}(op||(op={})),function(e){e[e.Open=1]="Open";e[e.Close=2]="Close"}(sp||(sp={})),function(e){e[e.Online=1]="Online";e[e.Debug=2]="Debug"}(np||(np={})),function(e){e[e.UserCreate=0]="UserCreate";e[e.Example=1]="Example"}(rp||(rp={})),function(e){e[e.Init=0]="Init";e[e.List=1]="List";e[e.Unlist=2]="Unlist"}(ap||(ap={})),function(e){e[e.Good=1]="Good";e[e.Bad=2]="Bad"}(cp||(cp={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(dp||(dp={})),function(e){e[e.Pending=1]="Pending";e[e.Running=2]="Running";e[e.Success=3]="Success";e[e.Failed=4]="Failed";e[e.Cancel=5]="Cancel"}(lp||(lp={})),function(e){e[e.Video=1]="Video";e[e.Voice=2]="Voice";e[e.Music=3]="Music"}(pp||(pp={})),function(e){e[e.Update=1]="Update";e[e.UpdateAndAdd=2]="UpdateAndAdd";e[e.UpdateAndSync=3]="UpdateAndSync"}(up||(up={})),function(e){e[e.ChatQuery=1]="ChatQuery";e[e.VideoEdit=2]="VideoEdit"}(_p||(_p={})),function(e){e[e.Pin=1]="Pin";e[e.Unpin=2]="Unpin"}(hp||(hp={})),function(e){e[e.Valid=1]="Valid";e[e.Deleted=2]="Deleted"}(mp||(mp={})),function(e){e[e.Narration=1]="Narration";e[e.Music=2]="Music";e[e.Other=3]="Other"}(gp||(gp={})),function(e){e[e.Video=1]="Video";e[e.Image=2]="Image";e[e.Audio=3]="Audio";e[e.Combination=4]="Combination";e[e.Document=5]="Document"}(fp||(fp={})),function(e){e[e.Local=1]="Local";e[e.AiGenerated=2]="AiGenerated";e[e.Asset=3]="Asset";e[e.Search=4]="Search"}(yp||(yp={})),function(e){e[e.Role=1]="Role";e[e.Item=2]="Item";e[e.Scene=3]="Scene";e[e.Other=4]="Other"}(vp||(vp={})),function(e){e[e.VoiceSelection=1]="VoiceSelection";e[e.VoiceDescription=2]="VoiceDescription";e[e.None=3]="None"}(wp||(wp={})),function(e){e[e.NotUploaded=1]="NotUploaded";e[e.Active=2]="Active";e[e.Processing=3]="Processing";e[e.Failed=4]="Failed"}(bp||(bp={}));class Pp{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Pp.prototype.__init.call(this),Pp.prototype.__init2.call(this),this.request=Sp([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Sp([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}CreateTaskReplay(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/create_task_replay"),s={task_id:i.task_id,need_qr_code:i.need_qr_code,file_list:i.file_list,doc_multi_img_zip_uri:i.doc_multi_img_zip_uri};return this.request({url:o,method:"POST",data:s},t)}GetTaskReplay(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_replay"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}DeleteCozeSpaceTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/delete_task"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCozeSpaceTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/update_task"),s={task_id:i.task_id,task_name:i.task_name,mcp_tool_list:i.mcp_tool_list,expert_agent_config:i.expert_agent_config,scheduled_task_setting:i.scheduled_task_setting};return this.request({url:o,method:"POST",data:s},t)}CreateCozeSpaceTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/create_task"),s={task_name:i.task_name,task_type:i.task_type,file_uri_list:i.file_uri_list,mcp_tool_list:i.mcp_tool_list,agent_ids:i.agent_ids,scheduled_task_setting:i.scheduled_task_setting,source_from:i.source_from,is_debug:i.is_debug,expert_agent_config:i.expert_agent_config};return this.request({url:o,method:"POST",data:s},t)}CozeSpaceChat(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/chat"),s={task_id:i.task_id,query:i.query,files:i.files,mcp_list:i.mcp_list,chat_type:i.chat_type,pause_reason:i.pause_reason,task_run_mode:i.task_run_mode,expert_agent_run_config:i.expert_agent_run_config,scheduled_task_config:i.scheduled_task_config,disable_team_mode:i.disable_team_mode,resume_data:i.resume_data,ability_type:i.ability_type,all_authorized_mcp:i.all_authorized_mcp,reference_template_list:i.reference_template_list,agent_ids:i.agent_ids,router_control:i.router_control,favorites:i.favorites,extra_info:i.extra_info,reference_content:i.reference_content,guiding_id:i.guiding_id,skill_id_list:i.skill_id_list,is_skill_debug:i.is_skill_debug,thinking:i.thinking,reference_items:i.reference_items,plan_template_id:i.plan_template_id,action:i.action,assets:i.assets};return this.request({url:o,method:"POST",data:s},t)}PollStepList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/poll_step_list"),s={task_id:i.task_id,answer_id:i.answer_id,next_key:i.next_key};return this.request({url:o,method:"POST",data:s},t)}OperateTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_task"),s={task_id:i.task_id,operate_type:i.operate_type,pause_reason:i.pause_reason,browser:i.browser,read_progress:i.read_progress,has_unread:i.has_unread};return this.request({url:o,method:"POST",data:s},t)}GetCozeSpaceTaskList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_list"),s={cursor:i.cursor,size:i.size,long_term:i.long_term};return this.request({url:o,method:"POST",data:s},t)}GetMessageList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_message_list"),s={task_id:i.task_id,cursor:i.cursor,size:i.size,asc_mode:i.asc_mode};return this.request({url:o,method:"POST",data:s},t)}UpdateTaskPlan(e,t){const i=e,o=this.genBaseURL("/api/coze_space/update_task_plan"),s={task_id:i.task_id,action_id:i.action_id,task_plan:i.task_plan};return this.request({url:o,method:"POST",data:s},t)}GetTaskReplayById(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_replay_by_id"),s={task_share_id:i.task_share_id,secret:i.secret};return this.request({url:o,method:"POST",data:s},t)}OperateTaskReplay(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_task_replay"),s={task_id:i.task_id,task_share_id:i.task_share_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}UploadTaskFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/upload_task_file"),s={task_id:i.task_id,file_name:i.file_name,file_content:i.file_content};return this.request({url:o,method:"POST",data:s},t)}UploadUserResearchFile(e,t){const i=e,o=this.genBaseURL("/api/coze_space/upload_user_research_file"),s={task_id:i.task_id,action:i.action,file_type:i.file_type,file_name:i.file_name,file_content:i.file_content,desc:i.desc,fields:i.fields};return this.request({url:o,method:"POST",data:s},t)}LandingPageEmailSubscribe(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/landing_page/email_subscribe"),s={email:i.email};return this.request({url:o,method:"POST",data:s},t)}GetUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_url"),s={uri:i.uri,expire_seconds:i.expire_seconds,is_short_url:i.is_short_url,uri_list:i.uri_list};return this.request({url:o,method:"POST",data:s},t)}LandingPage(e,t){const i=this.genBaseURL("/api/coze_space/landing_page");return this.request({url:i,method:"POST"},t)}ExpertProductDetails(e,t){const i=e,o=this.genBaseURL("/api/coze_space/expert_product_details"),s={agent_id:i.agent_id};return this.request({url:o,method:"POST",data:s},t)}Digg(e,t){const i=e,o=this.genBaseURL("/api/coze_space/digg"),s={agent_id:i.agent_id,action_type:i.action_type,is_cancel:i.is_cancel};return this.request({url:o,method:"POST",data:s},t)}SearchStock(e,t){const i=e,o=this.genBaseURL("/api/coze_space/search_stock"),s={search_type:i.search_type,stock_search_word:i.stock_search_word,sector_search_word:i.sector_search_word};return this.request({url:o,method:"POST",data:s},t)}Text2Image(e,t){const i=e,o=this.genBaseURL("/api/coze_space/text2image"),s={prompt:i.prompt,width:i.width,height:i.height};return this.request({url:o,method:"GET",params:s},t)}GetInviteInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_invite_info");return this.request({url:i,method:"POST"},t)}CheckInviteCode(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/check_invite_code"),s={code:i.code};return this.request({url:o,method:"POST",data:s},t)}ExpertProductList(e,t){const i=this.genBaseURL("/api/coze_space/expert_product_list");return this.request({url:i,method:"POST"},t)}CheckInWaitList(e,t){const i=this.genBaseURL("/api/coze_space/check_in_wait_list");return this.request({url:i,method:"POST"},t)}JoinWaitList(e,t){const i=this.genBaseURL("/api/coze_space/join_wait_list");return this.request({url:i,method:"POST"},t)}GetSandboxToken(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_sandbox_token"),s={task_id:i.task_id,action_url_code:i.action_url_code};return this.request({url:o,method:"POST",data:s},t)}GetUserScheduledTasks(e,t){const i=this.genBaseURL("/api/coze_space/get_user_scheduled_tasks");return this.request({url:i,method:"POST"},t)}GenerateRelatedWords(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/generate_related_words"),s={original_word:i.original_word,describe:i.describe};return this.request({url:o,method:"POST",data:s},t)}CodeRepair(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/code_repair"),s={uri:i.uri,error_msg:i.error_msg};return this.request({url:o,method:"POST",data:s},t)}AuthorizedChannelMatch(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/authorized_channel_match"),s={web_rul:i.web_rul};return this.request({url:o,method:"POST",data:s},t)}UpdateTaskStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_task_status"),s={agent_id:i.agent_id,sk:i.sk,task_id:i.task_id,task_status:i.task_status,result:i.result};return this.request({url:o,method:"POST",data:s},t)}GetWebUrl(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_web_url"),s={original_url:i.original_url,exchange_for_short_url:i.exchange_for_short_url,exchange_for_qr_code:i.exchange_for_qr_code,exchange_for_long_url:i.exchange_for_long_url};return this.request({url:o,method:"POST",data:s},t)}OperateSandbox(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_sandbox"),s={task_id:i.task_id,action:i.action,delete_cookie_info:i.delete_cookie_info};return this.request({url:o,method:"POST",data:s},t)}UpdateTaskName(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_task_name"),s={agent_id:i.agent_id,sk:i.sk,task_id:i.task_id,task_name:i.task_name};return this.request({url:o,method:"POST",data:s},t)}GenDoc(e,t){const i=e,o=this.genBaseURL("/api/coze_space/gen_doc"),s={task_id:i.task_id,target_file_type:i.target_file_type,original_file_uri:i.original_file_uri,original_file_name:i.original_file_name,file_content:i.file_content};return this.request({url:o,method:"POST",data:s},t)}PreGetContractInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/pre_get_contract_info"),s={file_content:i.file_content,task_id:i.task_id,file_name:i.file_name};return this.request({url:o,method:"POST",data:s},t)}GetContractCaseInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_contract_case_info"),s={case_no:i.case_no};return this.request({url:o,method:"POST",data:s},t)}GetContractLawInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_contract_law_info"),s={law:i.law,num:i.num};return this.request({url:o,method:"POST",data:s},t)}GetCozeSpaceUserInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_user_info"),s={need_volcano_info:i.need_volcano_info,need_user_job_info:i.need_user_job_info,need_turn_off_user_data_management:i.need_turn_off_user_data_management,need_user_scenes:i.need_user_scenes,need_user_active_time:i.need_user_active_time,need_turn_off_ai_watermark:i.need_turn_off_ai_watermark,need_dnu_user:i.need_dnu_user,need_close_video_demo_project:i.need_close_video_demo_project,need_video_demo_project_account:i.need_video_demo_project_account};return this.request({url:o,method:"POST",data:s},t)}SearchCityInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/search_city_info"),s={search_type:i.search_type,keyword:i.keyword};return this.request({url:o,method:"POST",data:s},t)}UpdateScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/update_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id,task_type:i.task_type,status:i.status,scheduled_task_name:i.scheduled_task_name,trigger:i.trigger,mcp_tool_list:i.mcp_tool_list,expert_agent_config:i.expert_agent_config,task_plan:i.task_plan,is_need_try_run:i.is_need_try_run,description:i.description,task_id:i.task_id,daily_executed_at:i.daily_executed_at,task_plan_v2:i.task_plan_v2};return this.request({url:o,method:"POST",data:s},t)}GetScheduledTasks(e,t){const i=this.genBaseURL("/api/coze_space/get_scheduled_tasks");return this.request({url:i,method:"POST"},t)}TryRunScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/try_run_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id};return this.request({url:o,method:"POST",data:s},t)}DeleteScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/delete_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id};return this.request({url:o,method:"POST",data:s},t)}CreateScheduledTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/create_scheduled_task"),s={is_need_try_run:i.is_need_try_run,scheduled_task_name:i.scheduled_task_name,trigger:i.trigger,source_task_id:i.source_task_id,task_plan:i.task_plan,description:i.description,daily_executed_at:i.daily_executed_at,task_plan_v2:i.task_plan_v2};return this.request({url:o,method:"POST",data:s},t)}UpdateTeamInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_team_info"),s={switch:i.switch};return this.request({url:o,method:"POST",data:s},t)}GetTeamInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_team_info");return this.request({url:i,method:"POST"},t)}GetTaskInfo(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_task_info"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}FeelGood(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/feel_good"),s={task_id:i.task_id,answer_id:i.answer_id,feel:i.feel,content:i.content};return this.request({url:o,method:"POST",data:s},t)}GetUserScheduledTaskQuota(e,t){const i=this.genBaseURL("/api/coze_space/get_scheduled_task_quota");return this.request({url:i,method:"POST"},t)}GetSingleScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_single_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id};return this.request({url:o,method:"POST",data:s},t)}DeleteUserAuthorization(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/delete_user_authorization"),s={url:i.url,clear_arg:i.clear_arg};return this.request({url:o,method:"POST",data:s},t)}GetUserAuthorizationList(e,t){const i=this.genBaseURL("/api/coze_space/get_user_authorization_list");return this.request({url:i,method:"POST"},t)}AddUserAuthorization(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/add_user_authorization"),s={task_id:i.task_id,url:i.url,clear_arg:i.clear_arg,add_arg:i.add_arg};return this.request({url:o,method:"POST",data:s},t)}SearchFeelGood(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/search_feel_good"),s={task_id:i.task_id,answer_id:i.answer_id};return this.request({url:o,method:"POST",data:s},t)}GetAuthorizedChannelList(e,t){const i=this.genBaseURL("/api/coze_space/get_authorized_channel_list");return this.request({url:i,method:"GET"},t)}GetTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_task_example"),s={task_example_id:i.task_example_id};return this.request({url:o,method:"POST",data:s},t)}AdminListTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/list_task_example"),s={size:i.size,page:i.page,task_ids:i.task_ids,category_id:i.category_id,ability_type:i.ability_type,status:i.status};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_task_example"),s={example_id:i.example_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCozeSpaceUserInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_user_info"),s={job_id:i.job_id,turn_off_user_data_management:i.turn_off_user_data_management,scene_ids:i.scene_ids,turn_off_ai_watermark:i.turn_off_ai_watermark,close_video_demo_project:i.close_video_demo_project,video_demo_project_account:i.video_demo_project_account};return this.request({url:o,method:"POST",data:s},t)}GetTaskExampleList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_example_list"),s={category_id:i.category_id,page_size:i.page_size,page:i.page,ability_type:i.ability_type,scene_ids:i.scene_ids};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_task_example"),s={task_id:i.task_id,example_name:i.example_name,example_description:i.example_description,icon_uri:i.icon_uri,index:i.index,category_id:i.category_id,user_query:i.user_query,share_id:i.share_id,ability_type:i.ability_type,open_app_use:i.open_app_use,app_title:i.app_title,official_recommend:i.official_recommend,file_type:i.file_type,type:i.type,close_make_same:i.close_make_same,product_info:i.product_info,api_template_type:i.api_template_type,attachment_files:i.attachment_files};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_task_example"),s={example_id:i.example_id,example_name:i.example_name,example_description:i.example_description,icon_uri:i.icon_uri,index:i.index,category_id:i.category_id,user_query:i.user_query,status:i.status,ability_type:i.ability_type,open_app_use:i.open_app_use,app_title:i.app_title,official_recommend:i.official_recommend,type:i.type,close_make_same:i.close_make_same,product_info:i.product_info,file_type:i.file_type,api_template_type:i.api_template_type,attachment_files:i.attachment_files};return this.request({url:o,method:"POST",data:s},t)}GetTaskExampleCategory(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_example_category"),s={ability_type:i.ability_type};return this.request({url:o,method:"GET",params:s},t)}GetUserJobList(e,t){const i=this.genBaseURL("/api/coze_space/get_user_job_list");return this.request({url:i,method:"GET"},t)}AdminParseTaskShareURL(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/parse_task_share_url"),s={share_url:i.share_url};return this.request({url:o,method:"POST",data:s},t)}GetAppInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_app_info");return this.request({url:i,method:"GET"},t)}AdminGetTaskExampleCategory(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/get_task_example_category"),s={ability_type:i.ability_type};return this.request({url:o,method:"GET",params:s},t)}AdminUploadFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/upload_task_file"),s={file_name:i.file_name,file_content:i.file_content,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}UpdateFileContent(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_file_content"),s={task_id:i.task_id,file_uri:i.file_uri,file_content:i.file_content};return this.request({url:o,method:"POST",data:s},t)}ExportPPTAgentFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/export_ppt_agent_file"),s={source_uri:i.source_uri,task_id:i.task_id,export_type:i.export_type};return this.request({url:o,method:"POST",data:s},t)}RestoreExampleFile(e,t){const i=e,o=this.genBaseURL("/api/coze_space/restore_example_file"),s={task_id:i.task_id,example_id:i.example_id,product:i.product};return this.request({url:o,method:"POST",data:s},t)}GetHtmlHeightFix(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_html_height_fix"),s={code:i.code};return this.request({url:o,method:"POST",data:s},t)}PollMessages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/poll_messages"),s={start_next_key:i.start_next_key};return this.request({url:o,method:"GET",params:s},t)}OperatePausedTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_paused_task"),s={task_id:i.task_id,pause_reason:i.pause_reason};return this.request({url:o,method:"POST",data:s},t)}GetFrontierKey(e,t){const i=this.genBaseURL("/api/coze_space/get_frontier_key");return this.request({url:i,method:"GET"},t)}SearchImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/search_image"),s={query:i.query,count:i.count};return this.request({url:o,method:"POST",data:s},t)}GetUserExpertList(e,t){const i=this.genBaseURL("/api/coze_space/get_user_expert_list");return this.request({url:i,method:"POST"},t)}OperateUserExpert(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_user_expert"),s={agent_id:i.agent_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}GetHotQuery(e,t){const i=this.genBaseURL("/api/coze_space/get_hot_query");return this.request({url:i,method:"POST"},t)}ImageDownload(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/download_image"),s={image_infos:i.image_infos,download_type:i.download_type};return this.request({url:o,method:"POST",data:s},t)}ImageEdit(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/edit_image"),s={edit_type:i.edit_type,image_url:i.image_url,query:i.query,count:i.count,task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}CreateImageCopy(e,t){const i=e,o=this.genBaseURL("/api/coze_space/create_image_copy"),s={task_id:i.task_id,image_path:i.image_path,source_image_url:i.source_image_url};return this.request({url:o,method:"POST",data:s},t)}GetLatestImagesWithID(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_latest_images_with_id"),s={task_id:i.task_id,image_paths:i.image_paths};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTaskExampleCategory(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_task_example_category"),s={name:i.name,ability_type:i.ability_type,index:i.index,job_ids:i.job_ids,scene_ids:i.scene_ids};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteTaskExampleCategory(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_task_example_category"),s={category_id:i.category_id};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTaskExampleCategory(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_task_example_category"),s={category_id:i.category_id,name:i.name,index:i.index,job_ids:i.job_ids,scene_ids:i.scene_ids};return this.request({url:o,method:"POST",data:s},t)}BatchHtmlToImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_html_to_image"),s={task_id:i.task_id,html_uri:i.html_uri,device_info:i.device_info,screenshot_info:i.screenshot_info};return this.request({url:o,method:"POST",data:s},t)}GetAppTaskExampleList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_app_task_example_list"),s={ability_type:i.ability_type,need_official_recommended:i.need_official_recommended};return this.request({url:o,method:"POST",data:s},t)}GenCover(e,t){const i=e,o=this.genBaseURL("/api/coze_space/gen_cover"),s={task_id:i.task_id,original_file_uri:i.original_file_uri,resolution:i.resolution,mode:i.mode,selector_str:i.selector_str,task_share_url:i.task_share_url};return this.request({url:o,method:"POST",data:s},t)}CopyResource(e,t){const i=e,o=this.genBaseURL("/api/coze_space/copy_resource"),s={new_task_id:i.new_task_id,uri_list:i.uri_list};return this.request({url:o,method:"POST",data:s},t)}BatchUpdateImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_update_image"),s={task_id:i.task_id,image_info_list:i.image_info_list};return this.request({url:o,method:"POST",data:s},t)}Text2Json(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/text2json"),s={text:i.text,type:i.type};return this.request({url:o,method:"POST",data:s},t)}EditImageWithMsg(e,t){const i=e,o=this.genBaseURL("/api/coze_space/edit_image_with_msg"),s={task_id:i.task_id,source_image_info:i.source_image_info,edit_type:i.edit_type,query:i.query,edit_info:i.edit_info};return this.request({url:o,method:"POST",data:s},t)}GetASRToken(e,t){const i=this.genBaseURL("/api/coze_space/get_asr_token");return this.request({url:i,method:"GET"},t)}QueryRewriting(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/query_rewriting"),s={query:i.query};return this.request({url:o,method:"POST",data:s},t)}GetShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_shortcut_command"),s={ability_type:i.ability_type,need_general_data:i.need_general_data};return this.request({url:o,method:"POST",data:s},t)}ClickPopup(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/click_popup"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}GetPopupInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_popup_info"),s={ability_type:i.ability_type};return this.request({url:o,method:"POST",data:s},t)}AdminCreateExampleDatabaseData(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_example_database_data"),s={data:i.data};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_shortcut_command"),s={id:i.id,title:i.title,app_title:i.app_title,query:i.query,action_type:i.action_type,open_pc:i.open_pc,open_app:i.open_app,job_id:i.job_id,open_time:i.open_time,expire_time:i.expire_time};return this.request({url:o,method:"POST",data:s},t)}AdminCreateShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_shortcut_command"),s={ability_type:i.ability_type,title:i.title,app_title:i.app_title,query:i.query,action_type:i.action_type,open_pc:i.open_pc,open_app:i.open_app,job_id:i.job_id,expire_time:i.expire_time};return this.request({url:o,method:"POST",data:s},t)}AdminGetShortcutCommandList(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/get_shortcut_command_list"),s={size:i.size,ability_type:i.ability_type,page:i.page,open_pc:i.open_pc,open_app:i.open_app,job_id:i.job_id};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_shortcut_command"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}AdminSyncCrawl(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/sync_crawl"),s={req:i.req,upload:i.upload};return this.request({url:o,method:"POST",data:s},t)}AdminGetUserJobList(e,t){const i=this.genBaseURL("/api/coze_space/admin/get_user_job_list");return this.request({url:i,method:"GET"},t)}AdminListTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/list_template"),s={size:i.size,page:i.page,template_ids:i.template_ids,category_ids:i.category_ids,ability_type:i.ability_type,template_name:i.template_name};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_template"),s={ability_type:i.ability_type,category_id:i.category_id,web_template_conf:i.web_template_conf,template_labels:i.template_labels,original_query:i.original_query,query_template:i.query_template,template_words:i.template_words,open_app_use:i.open_app_use,app_template_conf:i.app_template_conf,template_files:i.template_files,reference_info:i.reference_info,api_template_type:i.api_template_type,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_template"),s={template_id:i.template_id,ability_type:i.ability_type,category_id:i.category_id,web_template_conf:i.web_template_conf,template_labels:i.template_labels,original_query:i.original_query,query_template:i.query_template,template_words:i.template_words,open_app_use:i.open_app_use,app_template_conf:i.app_template_conf,index:i.index,is_selected:i.is_selected,template_files:i.template_files,reference_info:i.reference_info,api_template_type:i.api_template_type,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_template"),s={template_id:i.template_id};return this.request({url:o,method:"POST",data:s},t)}GetTemplateList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_template_list"),s={category_id:i.category_id,page_size:i.page_size,page:i.page,ability_type:i.ability_type};return this.request({url:o,method:"POST",data:s},t)}GetAppTemplateList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_app_template_list"),s={ability_type:i.ability_type};return this.request({url:o,method:"POST",data:s},t)}GetTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_template_info"),s={template_id:i.template_id};return this.request({url:o,method:"POST",data:s},t)}GetActivityInfo(e,t){const i=this.genBaseURL("/api/coze_space/activity/info");return this.request({url:i,method:"GET"},t)}BindRelation(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/activity/bind"),s={code:i.code};return this.request({url:o,method:"POST",data:s},t)}GetInviteCode(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/activity/invite_code"),s={activity_id:i.activity_id};return this.request({url:o,method:"POST",data:s},t)}GetInviteRecords(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/activity/invite_records"),s={activity_id:i.activity_id};return this.request({url:o,method:"POST",data:s},t)}RollbackFileVersion(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/rollback_file_version"),s={task_id:i.task_id,file_name:i.file_name,target_version:i.target_version};return this.request({url:o,method:"POST",data:s},t)}GetFileVersionInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_file_version_info"),s={task_id:i.task_id,file_name:i.file_name,long_term_plan:i.long_term_plan};return this.request({url:o,method:"POST",data:s},t)}AdminMDelUri(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdel_uri"),s={uris:i.uris,urls:i.urls};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_sem_url"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}AdminCreateSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_sem_url"),s={experiment_url:i.experiment_url,compare_url:i.compare_url,description:i.description};return this.request({url:o,method:"POST",data:s},t)}AdminListSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/list_sem_url"),s={size:i.size,page:i.page};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_sem_url"),s={id:i.id,experiment_url:i.experiment_url,compare_url:i.compare_url,description:i.description};return this.request({url:o,method:"POST",data:s},t)}GetSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_sem_url"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}ClickCompetitionLikes(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/click_competition_likes"),s={competition_task_id:i.competition_task_id,is_like:i.is_like};return this.request({url:o,method:"POST",data:s},t)}SubmitCompetitionTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/submit_competition_task"),s={task_id:i.task_id,product_url:i.product_url,title:i.title,cover_uri:i.cover_uri,competition_id:i.competition_id};return this.request({url:o,method:"POST",data:s},t)}GetCompetitionInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_competition_info");return this.request({url:i,method:"POST"},t)}GetCompetitionTaskList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_competition_task_list"),s={page_size:i.page_size,cursor:i.cursor,is_create_sorted:i.is_create_sorted,search_title:i.search_title,competition_id:i.competition_id};return this.request({url:o,method:"POST",data:s},t)}FavoriteList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/list"),s={tag_ids:i.tag_ids,name:i.name,need_untagged:i.need_untagged,size:i.size,cursor:i.cursor,exclude_content_types:i.exclude_content_types};return this.request({url:o,method:"POST",data:s},t)}DeleteTags(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/delete_tags"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}DeleteFavorites(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/delete"),s={ids:i.ids,related_uris:i.related_uris};return this.request({url:o,method:"POST",data:s},t)}BatchGetFavoriteInfo(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/batch_get_info"),s={favorite_ids:i.favorite_ids};return this.request({url:o,method:"POST",data:s},t)}UpdateFavoriteInfo(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/update"),s={id:i.id,tag_ids:i.tag_ids};return this.request({url:o,method:"POST",data:s},t)}GetTagList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/get_tag_list"),s={tag_ids:i.tag_ids,tag_name:i.tag_name};return this.request({url:o,method:"POST",data:s},t)}CreateTags(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/create_tag"),s={tag_name:i.tag_name,tag_desc:i.tag_desc,favorite_info_list:i.favorite_info_list};return this.request({url:o,method:"POST",data:s},t)}AddFavorite(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/add"),s={title:i.title,content_uri:i.content_uri,content_text:i.content_text,tag_ids:i.tag_ids,source:i.source,scene:i.scene,product_type:i.product_type};return this.request({url:o,method:"POST",data:s},t)}UpdateTags(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/update_tag"),s={tag_id:i.tag_id,tag_name:i.tag_name,tag_desc:i.tag_desc};return this.request({url:o,method:"POST",data:s},t)}GetMyCompetitionTaskList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_my_competition_task_list"),s={page_size:i.page_size,cursor:i.cursor,competition_id:i.competition_id};return this.request({url:o,method:"POST",data:s},t)}AdminGetUserScenes(e,t){const i=this.genBaseURL("/api/coze_space/admin/get_user_scenes");return this.request({url:i,method:"GET"},t)}GetUserScenes(e,t){const i=this.genBaseURL("/api/coze_space/get_user_scenes");return this.request({url:i,method:"GET"},t)}GetDeepWritingConf(e,t){const i=this.genBaseURL("/api/coze_space/get_deep_writing_conf");return this.request({url:i,method:"GET"},t)}GetCompetitionTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_competition_task"),s={competition_task_id:i.competition_task_id};return this.request({url:o,method:"POST",data:s},t)}GetUnreadCount(e,t){const i=this.genBaseURL("/api/coze_space/get_unread_count");return this.request({url:i,method:"POST"},t)}BatchHtmlCodeToImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_html_code_to_image"),s={task_id:i.task_id,html_code:i.html_code,device_info:i.device_info,screenshot_info:i.screenshot_info,zip:i.zip};return this.request({url:o,method:"POST",data:s},t)}GenDocMultiImageMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/gen_doc_multi_image_material"),s={task_id:i.task_id,file_uri:i.file_uri};return this.request({url:o,method:"POST",data:s},t)}GetDerivedProduct(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_derived_product"),s={task_id:i.task_id,derived_product_type:i.derived_product_type};return this.request({url:o,method:"POST",data:s},t)}SaveDerivedProduct(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/save_derived_product"),s={task_id:i.task_id,derived_product:i.derived_product};return this.request({url:o,method:"POST",data:s},t)}TagFavorites(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/tag_favorites"),s={tag_name:i.tag_name,tag_desc:i.tag_desc};return this.request({url:o,method:"POST",data:s},t)}SuggestQuery(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/suggest_query"),s={query:i.query,image_urls:i.image_urls};return this.request({url:o,method:"POST",data:s},t)}BatchGetUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_get_url"),s={uri_list:i.uri_list,expire_seconds:i.expire_seconds,is_short_url:i.is_short_url};return this.request({url:o,method:"POST",data:s},t)}UploadFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/upload_file"),s={file_name:i.file_name,file_content:i.file_content,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}BatchGetFavorite(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/get_count"),s={file_uris:i.file_uris};return this.request({url:o,method:"POST",data:s},t)}GetEarliestQuery(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_earliest_query"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}GetMappingUri(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_mapping_uri"),s={uri:i.uri};return this.request({url:o,method:"POST",data:s},t)}ApiTemplate(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/api_template"),s={prompt:i.prompt,files:i.files,type:i.type,task_id:i.task_id,template_id:i.template_id};return this.request({url:o,method:"POST",data:s},t)}BatchGetMultiMedia(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/batch_get_multimedia"),s={media_uris:i.media_uris};return this.request({url:o,method:"POST",data:s},t)}AdminBatchGetMultiMedia(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/batch_get_multimedia"),s={media_uris:i.media_uris};return this.request({url:o,method:"POST",data:s},t)}AdminCreateMultiMedia(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_multimedia"),s={task_id:i.task_id,media_path:i.media_path,media_uri:i.media_uri,media_url:i.media_url,image_type:i.image_type,media_ext:i.media_ext};return this.request({url:o,method:"POST",data:s},t)}GetPodcastConfig(e,t){const i=this.genBaseURL("/api/coze_space/get_podcast_config");return this.request({url:i,method:"POST"},t)}IntentRecognition(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/intent_recognition"),s={task_id:i.task_id,files:i.files,ability_type:i.ability_type,query:i.query};return this.request({url:o,method:"POST",data:s},t)}ListTemplate(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/list_template"),s={size:i.size,cursor:i.cursor,tags:i.tags,ability_type:i.ability_type,api_template_type:i.api_template_type};return this.request({url:o,method:"POST",data:s},t)}AdminGetTagsByImages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/get_tags_by_images"),s={images:i.images,query:i.query,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetTagsByImages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_tags_by_images"),s={images:i.images,query:i.query,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_template_image"),s={image:i.image,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}ReportSubmit(e,t){const i=e,o=this.genBaseURL("/api/coze_space/report_submit"),s={object_type:i.object_type,object_id:i.object_id,report_detail:i.report_detail};return this.request({url:o,method:"POST",data:s},t)}ListBotChatMessages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/list_bot_chat_message"),s={bot_chat_type:i.bot_chat_type,cursor:i.cursor,size:i.size};return this.request({url:o,method:"POST",data:s},t)}BotChatWithType(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/bot_chat_with_type"),s={bot_chat_type:i.bot_chat_type,query:i.query};return this.request({url:o,method:"POST",data:s},t)}GenImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/gen_image"),s={task_id:i.task_id,project_id:i.project_id,prompt:i.prompt,count:i.count,video_project_uri:i.video_project_uri,image_url:i.image_url,base_image_urls:i.base_image_urls,skip_save_material:i.skip_save_material,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}UploadVideoResource(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/upload_video_resource"),s={task_id:i.task_id,project_id:i.project_id,file_name:i.file_name,file_content:i.file_content,video_project_uri:i.video_project_uri,skip_save_material:i.skip_save_material,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}GetVideoConfig(e,t){const i=this.genBaseURL("/api/coze_space/video/get_video_config");return this.request({url:i,method:"POST"},t)}GetCozeSpaceDeviceInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_device_info");return this.request({url:i,method:"POST"},t)}AdminMDeleteReferenceImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdelete_reference_image"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}AdminMDeleteTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdelete_template_image"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}AdminListReferenceImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_reference_image"),s={size:i.size,cursor:i.cursor,tag:i.tag};return this.request({url:o,method:"POST",data:s},t)}AdminListRewriteImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_rewrite_image"),s={size:i.size,cursor:i.cursor,tag:i.tag};return this.request({url:o,method:"POST",data:s},t)}AdminCreateReferenceImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_reference_image"),s={tag:i.tag,image:i.image};return this.request({url:o,method:"POST",data:s},t)}AdminTemplateRewrite(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/template_rewrite"),s={template_image_ids:i.template_image_ids,rewrite_image_id:i.rewrite_image_id};return this.request({url:o,method:"POST",data:s},t)}AdminMDeleteRewriteImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdelete_rewrite_image"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}AdminListTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_template_image"),s={size:i.size,cursor:i.cursor,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateRewriteImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/update_rewrite_image"),s={id:i.id,rewrite_result:i.rewrite_result};return this.request({url:o,method:"POST",data:s},t)}GetGuidingMessage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_guiding_message"),s={guiding_id:i.guiding_id};return this.request({url:o,method:"POST",data:s},t)}AdminListImageTag(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_image_tag"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}UpdateProject(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/update_project"),s={GroupId:i.GroupId,ProjectId:i.ProjectId,LatestEditParam:i.LatestEditParam,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}DescribeProject(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/describe_project"),s={GroupId:i.GroupId,ProjectId:i.ProjectId,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}SubmitEditTaskAsync(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/submit_edit_task_async"),s={GroupId:i.GroupId,ProjectId:i.ProjectId,ProjectType:i.ProjectType,EditParam:i.EditParam,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,ignore_edit_param:i.ignore_edit_param,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}BatchGetVideoPlayInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/batch_get_video_play_info"),s={vids:i.vids,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri};return this.request({url:o,method:"POST",data:s},t)}GetDirectEditProgress(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/get_direct_edit_progress"),s={ReqId:i.ReqId,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}SearchEditMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/search_edit_material"),s={ProjectId:i.ProjectId,EditMids:i.EditMids,Space:i.Space,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}ListSnapshots(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/list_snapshots"),s={ProjectId:i.ProjectId,Vid:i.Vid,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/update_reference_image"),s={id:i.id,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}VolcVodCallback(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/volc_vod_callback"),s={RequestId:i.RequestId,Version:i.Version,EventType:i.EventType,EventTime:i.EventTime};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/delete_video_text_style"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}AdminListVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_video_text_style"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}AdminSaveVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/save_video_text_style"),s={video_text_style:i.video_text_style};return this.request({url:o,method:"POST",data:s},t)}GetMusicList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/get_music_list"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}ListVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/list_video_text_style"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}GetMessageMeta(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_message_meta"),s={task_id:i.task_id};return this.request({url:o,method:"GET",params:s},t)}AdminRunWorkflow(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/run_workflow"),s={id:i.id,input:i.input};return this.request({url:o,method:"POST",data:s},t)}QueryGenResourceStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/query_gen_resource_status"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,gen_resource_task_id:i.gen_resource_task_id,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}GenResourceAsync(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/gen_resource_async"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,gen_resource_type:i.gen_resource_type,gen_video_req_payload:i.gen_video_req_payload,gen_voice_audio_req_payload:i.gen_voice_audio_req_payload,gen_music_req_payload:i.gen_music_req_payload,skip_save_material:i.skip_save_material,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}GetTaskItemList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_item_list"),s={task_id:i.task_id,item_ids:i.item_ids,start_time:i.start_time,end_time:i.end_time};return this.request({url:o,method:"POST",data:s},t)}CancelGenResourceTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/cancel_gen_resource_task"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,gen_resource_task_id:i.gen_resource_task_id,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTemplateTagsFromCSV(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/update_template_tags_from_csv"),s={is_run_wf:i.is_run_wf,is_update:i.is_update,tos_path:i.tos_path};return this.request({url:o,method:"POST",data:s},t)}GetPlanTemplates(e,t){const i=this.genBaseURL("/api/coze_space/get_plan_templates");return this.request({url:i,method:"POST"},t)}DeleteTaskFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/delete_task_file"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}ListTaskFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/list_task_file"),s={task_id:i.task_id,size:i.size,cursor:i.cursor,plan_file:i.plan_file};return this.request({url:o,method:"POST",data:s},t)}GenPodcastStream(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/gen_podcast"),s={cache_key:i.cache_key};return this.request({url:o,method:"POST",data:s},t)}AdminTemplateTypeIntentBG(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/template_type_intent_bg"),s={files:i.files};return this.request({url:o,method:"POST",data:s},t)}ExportImagePPT(e,t){const i=e,o=this.genBaseURL("/api/coze_space/export_image_ppt_agent_file"),s={task_id:i.task_id,title:i.title,pages:i.pages,export_type:i.export_type};return this.request({url:o,method:"POST",data:s},t)}ExportProject(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/export_project"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,coze_claw_session_id:i.coze_claw_session_id,coze_claw_conversion_id:i.coze_claw_conversion_id};return this.request({url:o,method:"POST",data:s},t)}GetModelConfig(e,t){const i=this.genBaseURL("/api/coze_space/get_model_config");return this.request({url:i,method:"POST"},t)}ConfirmPlan(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/confirm_plan"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}GetUserSkillAuthorizationInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/skill/get_user_skill_authorization_info"),s={credential_id:i.credential_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCozeUserNickname(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_user_nickname"),s={nickname:i.nickname};return this.request({url:o,method:"POST",data:s},t)}CreateCozeUserJobName(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/create_user_job_name"),s={job_name:i.job_name};return this.request({url:o,method:"POST",data:s},t)}EnterpriseCustomer(e,t){const i=this.genBaseURL("/api/coze_space/enterprise_customer");return this.request({url:i,method:"POST"},t)}CreateVideoAsset(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/create_video_asset"),s={base_info:i.base_info,details:i.details};return this.request({url:o,method:"POST",data:s},t)}UpdateVideoAsset(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/update_video_asset"),s={asset_id:i.asset_id,base_info:i.base_info,details:i.details};return this.request({url:o,method:"POST",data:s},t)}DeleteVideoAsset(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/asset/delete_video_asset"),s={asset_id:i.asset_id};return this.request({url:o,method:"POST",data:s},t)}UpdateVideoProduction(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/production/update_video_production"),s={video_production:i.video_production,ratio:i.ratio};return this.request({url:o,method:"POST",data:s},t)}CreateVideoProduction(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/production/create_video_production"),s={video_production:i.video_production,ratio:i.ratio};return this.request({url:o,method:"POST",data:s},t)}VideoProductionMaterialList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/video_material_list"),s={production_id:i.production_id,tag_category:i.tag_category,type_category:i.type_category,page:i.page,size:i.size,need_detail_url:i.need_detail_url,session_id:i.session_id,conversation_id:i.conversation_id,search_word:i.search_word,not_need_cvs_or_cvp:i.not_need_cvs_or_cvp};return this.request({url:o,method:"POST",data:s},t)}VideoAssetDetail(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/video_asset_detail"),s={asset_id:i.asset_id};return this.request({url:o,method:"POST",data:s},t)}VideoProductionMaterialDetail(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/video_material_detail"),s={material_id:i.material_id};return this.request({url:o,method:"POST",data:s},t)}DeleteVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/delete_video_material"),s={material_id:i.material_id};return this.request({url:o,method:"POST",data:s},t)}CreateVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/create_video_material"),s={production_id:i.production_id,base_info:i.base_info,details:i.details,asset_id:i.asset_id,session_id:i.session_id,conversation_id:i.conversation_id};return this.request({url:o,method:"POST",data:s},t)}UpdateVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/update_video_material"),s={material_id:i.material_id,material_update_type:i.material_update_type,base_info:i.base_info,details:i.details};return this.request({url:o,method:"POST",data:s},t)}DeleteVideoProduction(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/production/delete_video_production"),s={production_id:i.production_id};return this.request({url:o,method:"POST",data:s},t)}VideoAssetList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/video_asset_list"),s={tag_category:i.tag_category,type_category:i.type_category,page:i.page,size:i.size,search_word:i.search_word,need_detail_url:i.need_detail_url};return this.request({url:o,method:"POST",data:s},t)}VideoProductionList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/production/video_production_list"),s={page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}OperateVideoProduction(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/production/operate_video_production"),s={production_id:i.production_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}OperateVideoAsset(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/asset/operate_video_asset"),s={asset_id:i.asset_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}BatchParseVideoAsset(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/asset/batch_parse_video_asset"),s={vids:i.vids};return this.request({url:o,method:"POST",data:s},t)}GetFileLock(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/file_lock/get"),s={project_id:i.project_id,file_path:i.file_path};return this.request({url:o,method:"GET",params:s},t)}ReleaseFileLock(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/file_lock/release"),s={project_id:i.project_id,file_path:i.file_path,session_id:i.session_id};return this.request({url:o,method:"POST",data:s},t)}AcquireFileLock(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/file_lock/acquire"),s={project_id:i.project_id,file_path:i.file_path,session_id:i.session_id,file_name:i.file_name};return this.request({url:o,method:"POST",data:s},t)}GetOutputVideo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/get_output_video"),s={video_project_uri:i.video_project_uri,claw_share_id:i.claw_share_id};return this.request({url:o,method:"POST",data:s},t)}CloneToVideoAsset(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/clone_to_video_asset"),s={material_id:i.material_id};return this.request({url:o,method:"POST",data:s},t)}CloneToVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/clone_to_video_material"),s={asset_id:i.asset_id,production_id:i.production_id,session_id:i.session_id,conversation_id:i.conversation_id};return this.request({url:o,method:"POST",data:s},t)}}const Cp=new Pp({});var Tp,Ep,Ip,kp,Ap,jp,Rp,zp,Lp,Up,Op,xp,Bp,qp,Dp,Mp,Np,Gp,$p,Fp,Vp,Wp,Hp,Jp,Kp,Qp,Yp,Zp,Xp,eu,tu;function iu(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[e.Image=1]="Image";e[e.Android=2]="Android";e[e.IOS=3]="IOS";e[e.GitCode=4]="GitCode";e[e.FaasRuntimePkg=5]="FaasRuntimePkg";e[e.SkillPkg=6]="SkillPkg";e[e.H5=7]="H5"}(Tp||(Tp={})),function(e){e[e.Unknown=0]="Unknown";e[e.FreeCertificate=1]="FreeCertificate"}(Ep||(Ep={})),function(e){e[e.Unknown=0]="Unknown";e[e.Normal=1]="Normal"}(Ip||(Ip={})),function(e){e[e.Unknown=0]="Unknown";e[e.Existing=1]="Existing";e[e.Free=2]="Free"}(kp||(kp={})),function(e){e[e.AuditPass=1]="AuditPass";e[e.AuditUnPass=2]="AuditUnPass";e[e.Auditing=3]="Auditing";e[e.Released=11]="Released";e[e.ReleaseFailed=12]="ReleaseFailed";e[e.Running=21]="Running"}(Ap||(Ap={})),function(e){e[e.Passed=1]="Passed";e[e.UnPassed=2]="UnPassed";e[e.Auditing=3]="Auditing"}(jp||(jp={})),function(e){e[e.Official=1]="Official"}(Rp||(Rp={})),function(e){e[e.Prepare=1]="Prepare";e[e.Package=2]="Package";e[e.Build=3]="Build";e[e.Deploy=4]="Deploy";e[e.Audit=5]="Audit"}(zp||(zp={})),function(e){e[e.Pending=1]="Pending";e[e.Running=2]="Running";e[e.Succeeded=3]="Succeeded";e[e.Failed=4]="Failed";e[e.Canceled=5]="Canceled";e[e.Interrupted=6]="Interrupted"}(Lp||(Lp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Success=1]="Success";e[e.Pending=2]="Pending";e[e.Failed=3]="Failed"}(Up||(Up={})),function(e){e[e.Unknown=0]="Unknown";e[e.Default=1]="Default";e[e.Custom=2]="Custom"}(Op||(Op={})),function(e){e[e.Unknown=0]="Unknown";e[e.Active=1]="Active";e[e.Disabled=2]="Disabled";e[e.Redirected=3]="Redirected";e[e.Primary=4]="Primary"}(xp||(xp={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(Bp||(Bp={})),function(e){e[e.Agent=1]="Agent";e[e.Automation=2]="Automation";e[e.WebApp=3]="WebApp";e[e.App=4]="App";e[e.Skill=5]="Skill";e[e.GeneralWeb=6]="GeneralWeb";e[e.WechatMiniProgram=7]="WechatMiniProgram";e[e.General=9]="General"}(qp||(qp={})),function(e){e[e.Created=1]="Created";e[e.Ready=3]="Ready";e[e.Stopped=4]="Stopped";e[e.Banned=5]="Banned";e[e.Paused=6]="Paused"}(Dp||(Dp={})),function(e){e[e.Unknown=0]="Unknown";e[e.VefaasFunction=1]="VefaasFunction"}(Mp||(Mp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Dev=1]="Dev";e[e.Prod=2]="Prod";e[e.Audit=3]="Audit"}(Np||(Np={})),function(e){e[e.A=1]="A";e[e.CNAME=2]="CNAME"}(Gp||(Gp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Single=1]="Single";e[e.Wildcard=2]="Wildcard";e[e.Multi=3]="Multi"}($p||($p={})),function(e){e[e.Unknown=0]="Unknown";e[e.DV=1]="DV";e[e.OV=2]="OV";e[e.EV=3]="EV"}(Fp||(Fp={})),function(e){e[e.Unknown=0]="Unknown";e[e.NotSubmitted=1]="NotSubmitted";e[e.Pending=2]="Pending";e[e.Issued=3]="Issued";e[e.Cancelling=4]="Cancelling";e[e.Canceled=5]="Canceled";e[e.Revoking=6]="Revoking";e[e.Revoked=7]="Revoked";e[e.Failed=8]="Failed";e[e.Expired=9]="Expired"}(Vp||(Vp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Free=1]="Free";e[e.Test=2]="Test";e[e.Paid=3]="Paid";e[e.Imported=4]="Imported"}(Wp||(Wp={})),function(e){e[e.NeedAuthorize=1]="NeedAuthorize";e[e.BindSuccess=2]="BindSuccess";e[e.BoundToOtherProject=3]="BoundToOtherProject";e[e.BoundToOtherUser=4]="BoundToOtherUser"}(Hp||(Hp={})),function(e){e[e.BoundToSelf=1]="BoundToSelf";e[e.BoundToOtherUser=2]="BoundToOtherUser";e[e.NotAuthorized=3]="NotAuthorized"}(Jp||(Jp={})),function(e){e[e.Line=1]="Line"}(Kp||(Kp={})),function(e){e[e.Default=0]="Default";e[e.WechatMini=1]="WechatMini";e[e.DouyinMini=2]="DouyinMini"}(Qp||(Qp={})),function(e){e[e.Day=1]="Day";e[e.Week=2]="Week";e[e.Month=3]="Month";e[e.Yesterday=4]="Yesterday";e[e.ThreeDays=5]="ThreeDays"}(Yp||(Yp={})),function(e){e[e.InvokeQPS=1]="InvokeQPS";e[e.ErrorQPS=2]="ErrorQPS";e[e.Latency=3]="Latency";e[e.DAU=4]="DAU";e[e.DNU=5]="DNU";e[e.ActiveRetention=6]="ActiveRetention";e[e.NewUserRetention=7]="NewUserRetention"}(Zp||(Zp={})),function(e){e[e.Recorded=1]="Recorded"}(Xp||(Xp={})),function(e){e[e.Sum=1]="Sum";e[e.Avg=2]="Avg"}(eu||(eu={})),function(e){e[e.Next=1]="Next";e[e.Third=3]="Third";e[e.Seventh=7]="Seventh"}(tu||(tu={}));class ou{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){ou.prototype.__init.call(this),ou.prototype.__init2.call(this),this.request=iu([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=iu([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}PublicCreateDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/create"),s={project_id:i.project_id,is_sync_db_to_prod:i.is_sync_db_to_prod,encrypt_env_variable:i.encrypt_env_variable,table_sync_configs:i.table_sync_configs,encrypt_deploy:i.encrypt_deploy,commit_hash:i.commit_hash,connector_configs:i.connector_configs};return this.request({url:o,method:"POST",data:s},t)}PublicRollbackDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/rollback"),s={project_id:i.project_id,target_deploy_history_id:i.target_deploy_history_id,rollback_database:i.rollback_database};return this.request({url:o,method:"POST",data:s},t)}PublicCancelDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/cancel"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"POST",data:s},t)}PublicGetDeployConfig(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_config/get"),s={project_id:i.project_id,commit_hash:i.commit_hash};return this.request({url:o,method:"GET",params:s},t)}PublicListDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/list"),s={project_id:i.project_id,page_token:i.page_token,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}PublicSearchRuntimeLog(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/runtime_log/search"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id,start_time:i.start_time,end_time:i.end_time,limit:i.limit,cursor:i.cursor,query:i.query,level:i.level};return this.request({url:o,method:"GET",params:s},t)}PublicGetDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/get"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"GET",params:s},t)}PublicBindCertificate(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/bind"),s={project_id:i.project_id,certificate_id:i.certificate_id,domain:i.domain};return this.request({url:o,method:"POST",data:s},t)}PublicApplyFreeCertificate(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/apply_free"),s={project_id:i.project_id,domain:i.domain,auto_renew_free_cert:i.auto_renew_free_cert};return this.request({url:o,method:"POST",data:s},t)}PublicListDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/list"),s={project_id:i.project_id,unit_type:i.unit_type};return this.request({url:o,method:"GET",params:s},t)}PublicDeleteDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/delete"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"POST",data:s},t)}PublicCreateDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/create"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"POST",data:s},t)}PublicGetDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/get"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetCertificateDetail(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/get"),s={project_id:i.project_id,certificate_id:i.certificate_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/get"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"GET",params:s},t)}PublicListVolcanoDomain(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/volcano_domain/list"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicListVolcanoCertificate(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/list_volcano"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"GET",params:s},t)}PublicListProjectTraces(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/traces/list"),s={project_id:i.project_id,start_time:i.start_time,end_time:i.end_time,filter:i.filter,page_token:i.page_token,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}PublicDownloadProjectTraces(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/traces/download"),s={project_id:i.project_id,start_time:i.start_time,end_time:i.end_time,filter:i.filter};return this.request({url:o,method:"POST",data:s},t)}PublicGetProjectMetrics(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/metrics/get"),s={project_id:i.project_id,time_range:i.time_range,retention_days:i.retention_days};return this.request({url:o,method:"GET",params:s},t)}PublicDeleteDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/delete"),s={project_id:i.project_id,deploy_unit_id:i.deploy_unit_id};return this.request({url:o,method:"POST",data:s},t)}PublicGetHelpCenterLink(e,t){const i=this.genBaseURL("/api/coding/deployment/help_center/link");return this.request({url:i,method:"GET"},t)}PublicCheckRollbackDatabase(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/check_rollback_database"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetMiniProgramPreview(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/mini_program/preview"),s={project_id:i.project_id,app_id:i.app_id,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}PublicSubmitAuthCode(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/submit_code"),s={project_id:i.project_id,connector_id:i.connector_id,code:i.code,verify_state:i.verify_state,auth_params:i.auth_params};return this.request({url:o,method:"POST",data:s},t)}PublicGetAuthStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/status"),s={project_id:i.project_id,connector_id:i.connector_id,redirect_url:i.redirect_url};return this.request({url:o,method:"POST",data:s},t)}PublicBindAuth(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/bind"),s={project_id:i.project_id,connector_id:i.connector_id,redirect_url:i.redirect_url,auth_params:i.auth_params,override:i.override};return this.request({url:o,method:"POST",data:s},t)}PublicUnbindAuth(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/unbind"),s={project_id:i.project_id,connector_id:i.connector_id};return this.request({url:o,method:"POST",data:s},t)}PublicGetBoundProject(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/get_bound_project"),s={connector_id:i.connector_id,related_id:i.related_id};return this.request({url:o,method:"GET",params:s},t)}PublicUpdateDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/update"),s={project_id:i.project_id,domain:i.domain,auto_renew_free_cert:i.auto_renew_free_cert,visit_status:i.visit_status,next_primary_domain:i.next_primary_domain};return this.request({url:o,method:"POST",data:s},t)}PublicGetCertificateQuota(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/quota"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicListDomainCertificates(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/list"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"GET",params:s},t)}PublicUnpublishConnector(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/unpublish_project"),s={project_id:i.project_id,connector_ids:i.connector_ids};return this.request({url:o,method:"POST",data:s},t)}PublicListConnector(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/list"),s={project_id:i.project_id,project_publish_status:i.project_publish_status};return this.request({url:o,method:"GET",params:s},t)}PublicPublishConnector(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/publish_project"),s={project_id:i.project_id,connector_configs:i.connector_configs};return this.request({url:o,method:"POST",data:s},t)}PublicGetDeployCount(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/get_count"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}GetRuntimeLogCount(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/runtime_log/count"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicExchangeFeishuAuthCode(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/feishu/auth/exchange_code"),s={project_id:i.project_id,code:i.code,verify_state:i.verify_state};return this.request({url:o,method:"POST",data:s},t)}PublicRevokeFeishuAuth(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/feishu/auth/revoke"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}PublicUpdateDefaultDomainPrefix(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/update_default_prefix"),s={project_id:i.project_id,prefix:i.prefix};return this.request({url:o,method:"POST",data:s},t)}PublicFeishuWebhookEvent(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/feishu/webhook/event"),s={body:i.body};return this.request({url:o,method:"POST",data:s},t)}PublicCheckCreateDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/check_create"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetHostedUsageMonthly(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/hosted_usage/monthly"),s={project_id:i.project_id,bill_month:i.bill_month};return this.request({url:o,method:"GET",params:s},t)}PublicGetEstimateHostedCost(e,t){const i=this.genBaseURL("/api/coding/deployment/hosted_usage/estimate_cost");return this.request({url:i,method:"GET"},t)}PublicGetDeployHistoryLog(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/log"),s={deploy_history_id:i.deploy_history_id,key:i.key};return this.request({url:o,method:"GET",params:s},t)}PublicGetMPICPStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/mini_program/icp_status"),s={project_id:i.project_id,app_id:i.app_id,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetOnlineDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/get_online"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetUserAnalyticsMetrics(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/metrics/user_analytics/get"),s={project_id:i.project_id,time_range:i.time_range};return this.request({url:o,method:"GET",params:s},t)}PublicPauseDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/pause"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"POST",data:s},t)}PublicStopDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/stop"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"POST",data:s},t)}PublicResumeDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/resume"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"POST",data:s},t)}PublicReportUserAnalytics(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/analytics/report"),s={events:i.events},n={project_id:i.project_id,did:i.did};return this.request({url:o,method:"POST",data:s,params:n},t)}PublicCreateDefaultDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/create_default"),s={project_id:i.project_id,prefix:i.prefix};return this.request({url:o,method:"POST",data:s},t)}PublicGetProtectionConfig(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/protection_config/get"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicUpdateProtectionConfig(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/protection_config/update"),s={project_id:i.project_id,config:i.config};return this.request({url:o,method:"POST",data:s},t)}PublicAuthRedirect(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/redirect"),s={url:i.url};return this.request({url:o,method:"GET",params:s},t)}PublicAuthCallback(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/callback"),s={origin:i.origin,path:i.path};return this.request({url:o,method:"GET",params:s},t)}}const su=new ou({}),nu={[Lp.Pending]:"Pending",[Lp.Running]:"Running",[Lp.Succeeded]:"Succeeded",[Lp.Failed]:"Failed",[Lp.Canceled]:"Canceled",[Lp.Interrupted]:"Interrupted"},ru=[Lp.Succeeded,Lp.Failed,Lp.Canceled],au=e=>e&&nu[e]||"Unknown";function cu(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 du{static __initStatic(){this.INSTANCE=new du}static getInstance(){return du.INSTANCE||(du.INSTANCE=new du),this.INSTANCE}async pollDeployStatus(t){const{projectId:i,deployHistoryId:o,onBeforePoll:s,onStatusChange:n}=t;let r;for(;;){cu([s,"optionalCall",e=>e()]);const t=cu([await su.PublicGetDeployHistory({project_id:i,deploy_history_id:o}),"optionalAccess",e=>e.data]);if(!t)throw new e.CozeError(e.ErrorCode.E5000,"Failed to get deploy history data during polling");const a=t.status;if(a!==r&&(r=a,cu([n,"optionalCall",e=>e(t)])),ru.includes(a))return t;await new Promise((e=>setTimeout(e,3e3)))}}async getLatestDeployHistoryId(e){const{projectId:t}=e;return cu([await su.PublicListDeployHistory({page_size:1,project_id:t}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list,"optionalAccess",e=>e[0],"optionalAccess",e=>e.deploy_history_id])}async getDeployHistory(t){const{projectId:i,deployHistoryId:o}=t,s=await su.PublicGetDeployHistory({project_id:i,deploy_history_id:o});if(!cu([s,"optionalAccess",e=>e.data]))throw new e.CozeError(e.ErrorCode.E5000,"Failed to get deploy history data");return s.data}canDeploy(e){return[t.VibeProjectType.AssistantAgent,t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.Skill,t.VibeProjectType.Agent,t.VibeProjectType.Automation].includes(e)}async getCommitList({projectId:i}){const o=await t.IdeApi.ProxySandboxMessage({ProjectID:i,Method:"repo_version.commit.list",Params:JSON.stringify({project_id:i})});return e.safeJsonParse(o.data,{commits:[]}).commits||[]}}du.__initStatic();const lu=du.getInstance();function pu(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 uu(e,t){return null!=e?e:t()}function _u(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 hu(e,t){return null!=e?e:t()}function mu(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 gu=e=>{if(null==e)return null;return 0===e.trim().length?null:e},fu=i=>{i.command("send [message]").description("Send a prompt message to Coze Coding project chat").option("--wait","Wait for the chat response before returning").option("--stdin","Read additional context from stdin (pipe input)").config({help:{brief:"Send a message to project chat",description:"Send a prompt message to the specified Coze Coding project chat. The message can be provided as a positional argument. Use --stdin to pipe additional context. Use @<path> to mention and upload local files as context.",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug in auth module" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Send and wait for the response",cmd:'coze code message send "Fix the bug in auth module" -p 123456 --wait'},{desc:"Mention a file with @",cmd:'coze code message send "Refactor @src/utils.ts to use async/await" -p 123456'},{desc:"Mention multiple files",cmd:'coze code message send "Compare @src/old.ts and @src/new.ts, list the differences" -p 123456'},{desc:"Send message with stdin context",cmd:'cat error.log | coze code message send "Analyze this error" --stdin -p 123456'},{desc:"Use environment variable for project",cmd:'export COZE_PROJECT_ID=123456 && coze code message send "Hello"'}],errors:[{code:e.ErrorCode.E1000,name:"MISSING_MESSAGE",desc:"No message content provided",fix:"Provide MESSAGE argument or use --stdin with piped content",example:'coze code message send "Your question" -p 123456 # or: echo "context" | coze code message send --stdin "question" -p 123456'},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{message:{type:"string",required:!1,description:"The prompt message to send to the project chat"},wait:{type:"boolean",required:!1,description:"Wait for the chat response before returning. Without this flag, the message is sent in the background."},stdin:{type:"boolean",required:!1,description:"Read additional context from stdin (pipe input)."}},output:{type:"object",properties:{content:{type:"string",description:"The chat response content"}}}}}}).action((async(i,o,s)=>{const n=s.getContext();try{if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const r=mu([s,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),a=hu(mu([r,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!a)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");const c=await mu([n,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!c)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const{wait:d,stdin:l}=o;let p=null;l&&(p=await Pr());const u=gu(i),_=gu(p);if(!u&&!_)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin");const h=u&&_?`${u}\n\n${_}`:hu(hu(u,(()=>_)),(()=>"")),m=new Set,g=await t.sendProjectChatMessage({projectId:a,prompt:h,apiBaseUrl:n.config.apiBaseUrl,accessToken:c,xTTEnv:n.config.xTTEnv,key:`coze-coding-cli:message:${a}`,onWarn:e=>n.ui.warn(e),waitForResponse:!!d,onMessageItem:e=>{if(d&&"json"===n.format&&e.finish){const t=(e=>{const t=hu(e.msg_id,(()=>"")),i=hu(e.sequence_id,(()=>""));return`${e.type}:${t}:${String(i)}`})(e);m.has(t)||(m.add(t),n.response.print({content:e.content,role:e.role,finish:e.finish,type:e.type}))}}});if(d)"text"===n.format&&n.response.print(hu(mu([g,"access",e=>e.lastAnswerMessage,"optionalAccess",e=>e.content,"access",e=>e.answer]),(()=>"")));else{const e=`Message sent. Use \`coze code message status -p ${a}\` to check the result.`;"json"===n.format?n.response.print({status:"sent",project_id:a,message:e}):n.response.print(e),process.exit(0)}}catch(e){V(e,n)}}))};function yu(e,t){return null!=e?e:t()}function vu(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 wu(e,t){return null!=e?e:t()}function bu(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 Su=async(i,o)=>{const s=o.getContext();try{if(!s)throw new e.CozeError("E5000","CLI context is not initialized");const n=bu([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=wu(bu([n,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!r)throw new e.CozeError("E1001","Missing required option: --project-id (or env COZE_PROJECT_ID)");if(!await bu([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]))throw new e.CozeError("E2001","Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(i.after&&i.before)throw new e.CozeError("E1000","--after and --before cannot be used together. Use only one cursor at a time.");s.ui.verbose(`Fetching conversation history for project ${r}...`);const a=t.createChatCore({key:`coze-coding-cli:history:${r}`,apiBaseUrl:s.config.apiBaseUrl});try{const e=i.after?"loadNext":"loadPrev",t="loadNext"===e?"11":"10",o=await a.getHistoryMessage({limit:t,project_id:r,after:i.after,before:i.before}),n=[],c=new Map,d=new Map;o.histories.forEach((e=>{if(e.user){const t=e.user.msg_id;c.has(t)||n.push(t);const i=(e=>{const t=bu([e,"optionalAccess",e=>e.content]);return wu(wu(bu([t,"optionalAccess",e=>e.query,"optionalAccess",e=>e.prompt]),(()=>bu([t,"optionalAccess",e=>e.retry,"optionalAccess",e=>e.prompt]))),(()=>bu([t,"optionalAccess",e=>e.edit,"optionalAccess",e=>e.prompt])))})(e.user.message);c.set(t,i?(e=>e.map((e=>"text"===e.type?e.content.text:"file"===e.type?`${vu([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.path])} ${yu(vu([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.from,"optionalAccess",e=>e[0]]),(()=>""))} ${yu(vu([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.to,"optionalAccess",e=>e[0]]),(()=>""))} `:"console"===e.type?vu([e,"access",e=>e.content,"access",e=>e.console,"optionalAccess",e=>e.content]):"node"===e.type?vu([e,"access",e=>e.content,"access",e=>e.node,"optionalAccess",e=>e.node_title]):"upload_file"===e.type?vu([e,"access",e=>e.content,"access",e=>e.upload_file,"optionalAccess",e=>e.file_name]):"page"===e.type?vu([e,"access",e=>e.content,"access",e=>e.page,"optionalAccess",e=>e.page_title]):"page_elements"===e.type?vu([e,"access",e=>e.content,"access",e=>e.page_elements,"optionalAccess",e=>e[0],"optionalAccess",e=>e.path,"optionalAccess",e=>e[0],"optionalAccess",e=>e.node_name]):"wf_canvas_change"===e.type?vu([e,"access",e=>e.content,"access",e=>e.wf_canvas_change,"optionalAccess",e=>e.query]):"")).join(" "))(i):"")}if(e.assistant){const t=e.assistant.messages.find((e=>"answer"===e.type&&e.content.answer));if(!t)return;const i=t.query_msg_id,o=t.content.answer;"string"==typeof i&&"string"==typeof o&&d.set(i,o)}}));const l=n[0],p=n[n.length-1],u=n.reverse().filter((e=>d.has(e))).map((e=>({userMessage:wu(c.get(e),(()=>"")),answer:wu(d.get(e),(()=>""))}))),_={histories:u,cursor:{after:l,before:p,has_more:o.has_more,loadDirection:e}};if("json"===s.format)s.response.print(_);else{if(0===u.length)return void s.response.print("No conversation history found.");u.forEach(((e,t)=>{s.response.print(`--- #${t+1} ---\nQ: ${e.userMessage}\nA: ${e.answer}\n`)})),s.response.print(`\n[cursor] after=${l}, before=${p}, has_more=${o.has_more}, loadDirection=${e}`)}}finally{a.destroy()}}catch(e){V(e,s)}};function Pu(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 Cu=i=>{const o=i.command("message");o.description("Manage project chat messages").config({help:{brief:"Manage project chat messages",description:"Manage Coze Coding project chat messages.\n\nThis command group provides:\n- send: Send a new message to the project chat\n- status: Query the status of current chat message (auto-fetch result when completed)\n- cancel: Cancel an ongoing chat message\n- history: View conversation history",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Check message status",cmd:"coze code message status -p 123456"},{desc:"Cancel ongoing message",cmd:"coze code message cancel -p 123456"},{desc:"View conversation history",cmd:"coze code message history -p 123456"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID (can also be set via COZE_PROJECT_ID env)"}}},seeAlso:["coze code project list","coze code project create"]}}).option("-p, --project-id <id>","Coze project id (or env COZE_PROJECT_ID)"),fu(o),(i=>{i.command("status").description("Query current project chat message status and get result when completed").config({help:{brief:"Query chat message status",description:"Get the current status of the chat message for the specified project. Returns status information such as running, completed, or error. When the chat is completed, automatically fetches and returns the result.",examples:[{desc:"Check message status (auto-fetch result when completed)",cmd:"coze code message status -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message status"},{desc:"Output as JSON",cmd:"coze code message status -p 123456 --format json"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Message status (running/completed/error)"},message:{type:"string",description:"Status message or error details"},answer:{type:"string",description:"The chat answer content (only when completed)"}}}}}}).action((async(i,o)=>{const s=o.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const i=_u([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),n=uu(_u([i,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!n)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");s.ui.verbose(`Fetching chat status for project ${n}...`);const{code:r,msg:a,reply_id:c,...d}=await t.BuildAgentApi.GetChatCLIMessageStatus({project_id:n});if("done"===d.status){s.ui.verbose(`Chat completed, fetching result for project ${n}...`);const e=await t.BuildAgentApi.GetChatCLIMessageResultContent({project_id:n}),i="data"in e?e.data:e;"json"===s.format?s.response.print({...d,answer:i.answer}):s.response.print(`status: [${d.status}]\nanswer: ${uu(i.answer,(()=>""))}`)}else"json"===s.format?s.response.print(d):s.response.print(d.status)}catch(e){V(e,s)}}))})(o),function(i){i.command("cancel").description("Cancel current project chat message").config({help:{brief:"Cancel ongoing chat message",description:"Cancel the currently running chat message for the specified project. Useful for stopping long-running or stuck message generation.",examples:[{desc:"Cancel current message",cmd:"coze code message cancel -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message cancel"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Cancel operation status"},message:{type:"string",description:"Result message"}}}}}}).action((async(i,o)=>{const s=o.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const i=Pu([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=null!=(n=Pu([i,"optionalAccess",e=>e.projectId]))?n:(()=>process.env.COZE_PROJECT_ID)();if(!r)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");const{accessToken:a}=s.config;if(!a)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");s.ui.verbose(`Canceling chat message for project ${r}...`);const{message:c}=await t.BuildAgentApi.CancelChatCLIMessage({project_id:r});"json"===s.format?s.response.print({message:c}):s.response.print(c)}catch(e){V(e,s)}var n}))}(o),(e=>{e.command("history").description("View conversation history of the project chat").option("--after <msg_id>","Cursor for fetching newer messages (smaller index)").option("--before <msg_id>","Cursor for fetching older messages (larger index)").config({help:{brief:"View conversation history",description:"Retrieve and display the conversation history for the specified Coze Coding project. Shows each round of user messages and LLM responses. By default, returns the latest 10 rounds of conversation. Use --after or --before cursors for pagination.",examples:[{desc:"View latest 10 rounds of conversation history",cmd:"coze code message history -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message history"},{desc:"Output as JSON with cursor info",cmd:"coze code message history -p 123456 --format json"},{desc:"Fetch newer messages after a cursor",cmd:"coze code message history -p 123456 --after msg_xxx"},{desc:"Fetch older messages before a cursor",cmd:"coze code message history -p 123456 --before msg_yyy"}],errors:[{code:"E1000",name:"INVALID_ARGUMENT",desc:"--after and --before cannot be used together",fix:"Use only one cursor option at a time for pagination"},{code:"E1001",name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:"E2001",name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"},after:{type:"string",description:'Cursor (message ID) for fetching newer messages. Newer messages have smaller index. Use the "after" value from previous output as this parameter.'},before:{type:"string",description:'Cursor (message ID) for fetching older messages. Older messages have larger index. Use the "before" value from previous output as this parameter.'}},output:{type:"object",properties:{histories:{type:"array",items:{type:"object",properties:{userMessage:{type:"string",description:"User's message in this round"},answer:{type:"string",description:"LLM's last answer with content"}}}},cursor:{type:"object",description:"Pagination cursor info for next/prev page requests",properties:{after:{type:"string",description:"Message ID of the newest result, use as --after to fetch newer messages (loadNext)"},before:{type:"string",description:"Message ID of the oldest result, use as --before to fetch older messages (loadPrev)"},has_more:{type:"boolean",description:"Whether there are more messages available"},loadDirection:{type:"string",enum:["loadNext","loadPrev"],description:"Load direction of current request. Defaults to 'loadPrev' (load older messages). 'loadNext' when --after is used, 'loadPrev' when --before is used or on initial request."}}}}}}}}).action(Su)})(o)};function Tu(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 Eu(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 Iu(i){i.command("list").description("List project environment variables").option("--env <scope>","Environment scope: dev | prod","dev").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List project environment variables",description:"Retrieve the list of environment variables for the specified project. Supports filtering by environment (dev/prod) and displays all configured sensitive information key names.",examples:[{desc:"List dev environment variables",cmd:"coze code env list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List prod environment variables",cmd:"coze code env list -p <projectId> --env prod"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},env:{type:"string",required:!1,enum:["dev","prod"],description:"Environment scope (default: dev)"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},project_type:{type:"string",description:"Project type"},env:{type:"string",description:"Environment scope"},secrets:{type:"array",description:"Environment variable list"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action((async function(e,i){const o=i.getContext(),{projectId:s}=e,n=Eu([await t.IdeApi.GetVibeProject({project_id:s}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=(a=e.env,"prod"===String(a||"dev").toLowerCase()?so.prod:so.dev);var a;const c=Eu([await _o.ListProjectSecret({env:r,project_id:s,...n===t.VibeProjectType.Skill?{with_providers:!0}:{}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[];Eu([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secrets listed successfully.")]),Eu([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(c.map((e=>({secret_key:e.secret_key,secret_id:e.secret_id,secret_val:e.secret_val,secret_type:e.secret_type}))))])}))}function ku(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 Au=i=>{const o=i.command("env").config({help:{brief:"Manage project environment variables",description:"Manage project environment variables (Secrets). Supports setting, viewing, and deleting sensitive configuration information such as API keys and database connection strings in development and production environments.",examples:[{desc:"List environment variables",cmd:"coze code env list -p <projectId>"},{desc:"Set environment variable",cmd:"coze code env set KEY VALUE -p <projectId>"},{desc:"Delete environment variable",cmd:"coze code env delete KEY -p <projectId>"}],seeAlso:["coze code deploy","coze code project"]}}).description("Manage project environment variables");Iu(o),o.command("set <key> <value>").description("Set a project environment variable").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Set project environment variable",description:"Add or update environment variables for the project. Environment variables are securely stored and used for sensitive information like API keys, passwords, etc.",examples:[{desc:"Set environment variable",cmd:"coze code env set <KEY> <VALUE> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{key:{type:"string",required:!0,description:"Environment variable key"},value:{type:"string",required:!0,description:"Environment variable value"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},key:{type:"string",description:"Set key name"},value:{type:"string",description:"Set value"}}}}},errors:[{code:e.ErrorCode.E3008,name:"SKILL_PROJECT_NOT_SUPPORTED",desc:"Skill project secret_type logic to be supplemented",fix:"This feature is not yet supported for Skill projects"}]}}).action((async function(i,o,s,n){const r=n.getContext(),{projectId:a}=s,c=Tu([await t.IdeApi.GetVibeProject({project_id:a}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(c===t.VibeProjectType.Skill)throw new e.CozeError(e.ErrorCode.E3008,"Skill project secret_type logic to be supplemented",{projectId:a,projectType:c});await _o.InsertProjectSecret({project_id:a,insert_secrets:{secrets:[{secret_key:i,secret_val:o}]}}),Tu([r,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secret set successfully")]),Tu([r,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:a,key:i,value:o})])})),function(t){t.command("delete <key>").description("Delete a project environment variable").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete project environment variable",description:"Delete specified environment variables from the project. Supports deleting multiple variables simultaneously by passing the --key parameter multiple times.",examples:[{desc:"Delete a single environment variable",cmd:"coze code env delete <KEY> -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Delete multiple environment variables",cmd:"coze code env delete <KEY> -p <projectId>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},key:{type:"string",required:!0,description:"Environment variable key name to delete"}},output:{message:{type:"string",description:"Result message"},key:{type:"string",description:"Deleted key"}}},errors:[{code:e.ErrorCode.E3003,name:"SECRET_NOT_FOUND",desc:"The specified environment variable does not exist",fix:"Please use `env list` first to confirm if the variable name is correct"}]}}).action((async function(t,i,o){const s=o.getContext(),{projectId:n}=i,r=[t],a=ku([await _o.ListProjectSecret({env:so.dev,project_id:n}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],c=new Set(r.map((e=>String(e)))),d=a.filter((e=>c.has(String(e.secret_key||"")))).map((e=>e.secret_id)).filter(Boolean);if(0===d.length)throw new e.CozeError(e.ErrorCode.E3003,`No matched secrets by keys: ${r.join(", ")}`,{projectId:n,keys:r});await _o.DeleteProjectSecret({project_id:n,keys:d}),ku([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env has been delete successfully")]),ku([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({message:"env has been delete successfully",key:t,project_id:n,keys:r,secret_ids:d})])}))}(o)};function ju(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 Ru(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 zu(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 Lu=t=>{const i=t.command("domain").config({help:{brief:"Manage custom domains for the project",description:"Manage custom domains for deployed projects. Supports adding, listing, and removing domains associated with a project, used to access deployed applications.",examples:[{desc:"List project domains",cmd:"coze code domain list <projectId>"},{desc:"Add custom domain",cmd:"coze code domain add example.com -p <projectId>"},{desc:"Delete domain",cmd:"coze code domain remove example.com -p <projectId>"}],seeAlso:["coze code deploy"]}}).description("Manage custom domains for the project");i.command("list").description("List custom domains of the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List all domains bound to the project",description:"Retrieve a list of all custom domains bound to the specified project.",examples:[{desc:"List domains",cmd:"coze code domain list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Output in JSON format",cmd:"coze code domain list -p <projectId> --format json"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Domain ID"},domain_host:{type:"string",description:"Domain host"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action((async function(e,t){const i=t.getContext(),{projectId:o}=e,s=Ru([await su.PublicListDomainRelated({project_id:o}),"access",e=>e.data,"optionalAccess",e=>e.items])||[];Ru([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Fetched domains List successfully")]),Ru([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(s.map((e=>({id:e.id,domain_host:e.domain_host}))))])})),function(t){t.command("add <domain>").description("Add a custom domain to the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add custom domain to project",description:"Bind a custom domain to a specified project. The domain must follow standard format (e.g., example.com). Once bound, the deployed application can be accessed via this domain.",examples:[{desc:"Add domain",cmd:"coze code domain add <domain> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to add (e.g., example.com)"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},domain:{type:"string",description:"Added domain"}}}}},errors:[{code:e.ErrorCode.E1004,name:"INVALID_DOMAIN",desc:"Incorrect domain format",fix:"Please use a standard domain format, e.g., example.com"}]}}).action((async function(t,i,o){const s=o.getContext(),{projectId:n}=i;if(!/^[a-zA-Z0-9][a-zA-Z0-9-]*\.[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(t))throw new e.CozeError(e.ErrorCode.E1004,"Invalid domain",{domain:t});await su.PublicCreateDomainRelated({project_id:n,domain:t}),zu([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Domain '${t}' added.`)]),zu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,domain:t})])}))}(i),function(t){t.command("remove <domain>").description("Remove a custom domain from the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete custom domain of the project",description:"Remove a bound custom domain from the specified project.",examples:[{desc:"Delete domain",cmd:"coze code domain remove example.com -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to delete"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},domain:{type:"string",description:"Deleted domain"}}}}},errors:[{code:e.ErrorCode.E1004,name:"INVALID_DOMAIN",desc:"Incorrect domain format",fix:"Please use a standard domain format, e.g., example.com"},{code:e.ErrorCode.E3005,name:"DELETE_FAILED",desc:"Failed to remove domain",fix:"Please confirm the domain is bound to the project and you have sufficient permissions"}]}}).action((async function(e,t,i){const o=i.getContext(),{projectId:s}=t;await su.PublicDeleteDomainRelated({project_id:s,domain:e}),ju([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Domain '${e}' removed.`)]),ju([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({message:`Domain '${e}' removed.`,domain:e})])}))}(i)};function Uu(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 Ou(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 xu(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 Bu(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 qu(i){const o=i.command("deploy <projectId>").description("Deploy the project to production environment").option("--commit-id <commitId>","Commit ID (optional, queries latest if omitted)").option("--wait","Wait for deployment to complete").config({help:{brief:"Deploy the project to production environment",description:"Deploy the specified project to the production environment. Supports multiple project types (Agent, Workflow, Skill, Web, Mini-program, etc.), automatically fetches the latest commit, and triggers the deployment process.",examples:[{desc:"Deploy latest project",cmd:"coze code deploy <projectId>",tags:["[RECOMMENDED]"]},{desc:"Deploy and wait for completion",cmd:"coze code deploy <projectId> --wait"},{desc:"Deploy a specific commit",cmd:"coze code deploy <projectId> --commit-id <commitId>"},{desc:"View deployment status",cmd:"coze code deploy status <projectId>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.E3007,name:"MISSING_COMMIT_HASH",desc:"No commits found in the project",fix:"Please commit your changes first before deploying"},{code:e.ErrorCode.E2002,name:"MINIPROGRAM_NOT_AUTHORIZED",desc:"Mini-program AppID not configured",fix:"Please complete the Mini-program AppID configuration in the project settings"},{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Project type is not supported for deployment",fix:"Please confirm the project type and try again with a supported project"}]}}).description("Deploy the project to production environment").action((async function(i,o,s){const n=s.getContext(),{wait:r,commitId:a}=o,c=Bu([(await t.IdeApi.GetVibeProject({project_id:i})).data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(!lu.canDeploy(c)){const t=`Project type ${Zd(c)} is not supported for deployment`;throw new e.CozeError(e.ErrorCode.E1006,t,{projectType:c})}if(c===t.VibeProjectType.AssistantAgent){const t=await e.axiosInstance$1.post("/api/sandbox/coze_coding/devbox/open_claw/deploy",{project_id:i},{headers:{"content-type":"application/json"}});return Bu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying (AssistantAgent)...")]),void Bu([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({command:"deploy",status:"ok",data:{type:c,data:Bu([t,"optionalAccess",e=>e.data])}})])}let d=a;if(!d){Bu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching latest commit...")]);const e=await lu.getCommitList({projectId:i});d=Bu([e,"optionalAccess",e=>e[0],"optionalAccess",e=>e.id])}if(!d){const t="Missing commitHash: pass --commit-hash <commitHash>";throw new e.CozeError(e.ErrorCode.E3007,t,{projectId:i})}if(c===t.VibeProjectType.WechatMiniProgram){Bu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking Mini-program authorization...")]);if(!Bu([await su.PublicGetAuthStatus({project_id:i,connector_id:"10000127"}),"access",e=>e.data,"optionalAccess",e=>e.bound_related_id])){const t="Deployment failed, please complete the Mini-program AppID configuration";throw new e.CozeError(e.ErrorCode.E2002,t)}}Bu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking deploy config...")]),await su.PublicGetDeployConfig({project_id:i,commit_hash:d},{__disableErrorToast:!0});let l="";const p=await _o.ListProjectSecret({env:so.dev,project_id:i,with_providers:!0}),u=Bu([p,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],_=Bu([p,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_cred_providers])||[];Bu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Encrypting secrets...")]);l=Bu([await _o.EncryptProjectSecret({project_id:i,project_type:c===t.VibeProjectType.Skill?oo.skill:void 0,encrypt_secrets:{secrets:u.map((e=>({secret_key:e.secret_key||"",secret_val:e.secret_val||"",secret_id:e.secret_id||"",secret_type:e.secret_type===no.consumer?zi.consumer3:zi.user_custom2}))),...c===t.VibeProjectType.Skill?{cred_providers:_}:{}}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.sealed_secrets])||"",Bu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying...")]);const h=Bu([await su.PublicCreateDeployHistory({project_id:i,encrypt_env_variable:l,commit_hash:d}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_id]);Bu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploy started.")]),r&&h?await lu.pollDeployStatus({projectId:i,deployHistoryId:h,onBeforePoll:()=>{Bu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const t=au(e.status);Bu([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",o=>o({projectId:i,status:t,domain:Bu([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:h,commitHash:e.commit_hash})])}}):Bu([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({projectId:i,status:au(Lp.Pending),domain:"",deployHistoryId:h,commitHash:d})])}));!function(t){t.command("status <projectId>").description("Check deployment status").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest if omitted)").config({help:{brief:"Query project deployment status",description:"Query the deployment status of a specified project. If no deployment history ID is specified, it automatically queries the latest deployment record. Supports viewing deployment progress, results, and error messages.",examples:[{desc:"Query latest deployment status",cmd:"coze code deploy status <projectId>",tags:["[RECOMMENDED]"]},{desc:"Query specific deployment record",cmd:"coze code deploy status <projectId> --deploy-id <deployHistoryId>"},{desc:"Wait for deployment to complete",cmd:"coze code deploy status <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (optional, queries latest if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.E3006,name:"NO_DEPLOYMENT_HISTORY",desc:"No deployment history found for this project",fix:"Please deploy the project first using `coze code deploy <projectId>`"}]}}).action((async function(t,i,o){const s=o.getContext(),{deployId:n}=i,{wait:r}=Uu([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=n;if(!a&&(Uu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("get latest deployment record...")]),a=await lu.getLatestDeployHistoryId({projectId:t}),!a))throw new e.CozeError(e.ErrorCode.E3006,"No deployment history found for this project");if(r)await lu.pollDeployStatus({projectId:t,deployHistoryId:a,onBeforePoll:()=>{Uu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const i=au(e.status);Uu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",o=>o({projectId:t,status:i,domain:Uu([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:a,commitHash:e.commit_hash})])}});else{Uu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Querying deployment status...")]);const e=await lu.getDeployHistory({projectId:t,deployHistoryId:a}),i=au(e.status),o=e.domain_list||[];Uu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",s=>s({projectId:t,status:i,domain:o[0],deployHistoryId:a,commitHash:e.commit_hash})])}}))}(o),function(e){e.command("list <projectId>").description("List deployment history for a project").option("--page-size <pageSize>","Number of records per page","10").option("--page-token <pageToken>","Page token for pagination").config({help:{brief:"List project deployment history",description:"List the deployment history of a specified project. Supports pagination to browse historical deployment records including status, commit hash, domains and timestamps.",examples:[{desc:"List deployment history",cmd:"coze code deploy list <projectId>",tags:["[RECOMMENDED]"]},{desc:"List with custom page size",cmd:"coze code deploy list <projectId> --page-size 20"},{desc:"List next page",cmd:"coze code deploy list <projectId> --page-token <token>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},pageSize:{type:"number",required:!1,description:"Number of records per page (default: 10)"},pageToken:{type:"string",required:!1,description:"Page token for pagination"}},output:{type:"array",items:{deploy_history_id:{type:"string",description:"Deployment history ID"},status:{type:"string",description:"Deployment status"},commit_hash:{type:"string",description:"Commit hash"},domain_list:{type:"array",description:"Deployed domains"},created_at:{type:"string",description:"Creation timestamp"}}}}}}).action((async function(e,t,i){const o=i.getContext(),s=Number(t.pageSize)||10,n=(Ou([await su.PublicListDeployHistory({project_id:e,page_size:s,page_token:t.pageToken}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list])||[]).map((e=>({deploy_history_id:e.deploy_history_id,project_id:e.project_id,status:au(e.status),commit_hash:e.commit_hash_short||e.commit_hash,domain_list:e.domain_list,created_at:e.created_at,can_rollback:e.can_rollback})));Ou([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)])}))}(o),function(t){t.command("fix <projectId>").description("Fix a failed deployment by sending deploy logs to AI").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest failed if omitted)").option("--wait","Wait for fix message response").config({help:{brief:"Fix a failed deployment",description:"Diagnose and fix a failed deployment. Retrieves deploy logs and sends them to AI for analysis and automatic fix. Only works when the deployment status is Failed.",examples:[{desc:"Fix latest failed deployment",cmd:"coze code deploy fix -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Fix a specific deployment",cmd:"coze code deploy fix <projectId> --deploy-id <deployId>"},{desc:"Fix and wait for result",cmd:"coze code deploy fix <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (queries latest failed if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for fix message response"}},output:{type:"object",properties:{deploy_history_id:{type:"string"},status:{type:"string"},message:{type:"string"}}}}}}).action((async function(t,i,o){const s=o.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const{deployId:n}=i,{wait:r}=xu([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=n;if(n||(a=await lu.getLatestDeployHistoryId({projectId:t})),!a)throw new e.CozeError(e.ErrorCode.E5002,`No deploy history found for project ${t}`,{project_id:t});const c=xu([await su.PublicGetDeployHistory({project_id:t,deploy_history_id:a}),"optionalAccess",e=>e.data]);if(xu([c,"optionalAccess",e=>e.status])!==Lp.Failed){const t=au(xu([c,"optionalAccess",e=>e.status]));throw new e.CozeError(e.ErrorCode.E3009,`Deployment ${a} is not in Failed status (current: ${t}). Only failed deployments can be fixed.`,{deploy_history_id:a,status:xu([c,"optionalAccess",e=>e.status])})}const d=c.deploy_log_url;if(!d)throw new e.CozeError(e.ErrorCode.E5002,`No deploy log URL found for deployment ${a}`,{deploy_history_id:a});const l=await e.customFetch.fetch(d,{method:"GET"}),p=await l.text();if(!p)throw new e.CozeError(e.ErrorCode.E5002,`Deploy log is empty for deployment ${a}`,{deploy_history_id:a,deploy_log_url:d});const u=`修复以下部署错误:\n${p}`,_=await xu([s,"access",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!_)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(r){const e=await sl.sendMessage({projectId:t,prompt:u,apiBaseUrl:s.config.apiBaseUrl,accessToken:_,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${t}`});xu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({deploy_history_id:a,status:"fix_sent",message:e.lastAnswerMessage})])}else sl.sendMessageRunTask({projectId:t,prompt:u,apiBaseUrl:s.config.apiBaseUrl,accessToken:_,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${t}`})}))}(o)}function Du(i){const o=i.command("code").description("Coze Coding CLI utilities").config({help:{brief:"Coze Coding project management",description:"Manage Coze Coding projects, including project creation, messaging, deployment, environment variables, domains, skills, and previews.",examples:[{desc:"Create a new project",cmd:'coze code project create --message "Create a chatbot" --type web'},{desc:"Send a message",cmd:'coze code message send "Fix the bug" -p <projectId>'},{desc:"Deploy project",cmd:"coze code deploy <projectId>"},{desc:"Preview project",cmd:"coze code preview <projectId>"}],seeAlso:["coze auth","coze space","coze organization"]}});Cu(o),qu(o),cl(o),Au(o),Lu(o),(e=>{const t=e.command("skill").config({help:{brief:"Manage project skills",description:"Manage skills associated with a project. Skills are important components to extend project capabilities, supporting adding, viewing, and removing project skills.",examples:[{desc:"List project skills",cmd:"coze code skill list -p <projectId>"},{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>"},{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>"}],seeAlso:["coze code project"]}}).description("Manage project skills");hc(t),gc(t),pc(t)})(o),function(i){i.command("preview <projectId>").description("Get deployment preview info for the project").config({help:{brief:"Get project preview URL",description:"Get the sandbox preview URL for the project. Supports AssistantAgent and GeneralWeb project types, returning an accessible preview URL. Sandbox initialization takes 1-3 minutes.",examples:[{desc:"Get preview URL",cmd:"coze code preview <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:{type:"string",description:"Project type"},preview_url:{type:"string",description:"Preview URL"}}},errors:[{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Unsupported project type",fix:"Preview feature only supports AssistantAgent and GeneralWeb project types"},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Missing required argument: projectId",fix:"Pass <projectId> as the first argument: `coze code preview <projectId>`",example:"coze code preview 123456"}]}}).action((async function(i,o,s){const n=s.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E1000,"Missing projectId: pass <projectId> as argument");const r=await t.IdeApi.GetVibeProject({project_id:i}),a=pu([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=pu([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.name]),d={type:Zd(a)};if(!sl.isValidType(a))throw new e.CozeError(e.ErrorCode.E1006,"Unsupported project type",{projectId:i,type:a});if(a===t.VibeProjectType.Skill){const e=await lu.getCommitList({projectId:i});pu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating preview task...")]);const t=await Cp.CreateCozeSpaceTask({task_name:`${c}-preview-${pu([e,"access",e=>e[0],"optionalAccess",e=>e.id])}`,task_type:1,is_debug:!0,source_from:rp.UserCreate,mcp_tool_list:[]});d.preview_url=`https://www.coze.cn/task-m/${t.data.task.task_id}`,pu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Preview task created. Please access the preview URL: ${d.preview_url}`)])}else{const e=await t.IdeApi.InitSandbox({project_id:i});d.preview_url=e.token?`https://${e.project_host}?token=${e.token}`:`https://${e.project_host}`,pu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Sandbox initialization started. Please access the preview URL in 1-3 minutes,preview_url: ${d.preview_url}`)])}pu([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(d)])}))}(o)}const Mu=async e=>await new Promise((t=>setTimeout(t,e)));function Nu(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 Gu=e=>{if(!e)return;const t=e.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);if(Nu([t,"optionalAccess",e=>e[1]]))return(e=>{try{return decodeURIComponent(e)}catch(t){return URIError,e}})(t[1]);const i=e.match(/filename\s*=\s*"([^"]+)"/i);if(Nu([i,"optionalAccess",e=>e[1]]))return i[1];const o=e.match(/filename\s*=\s*([^;]+)/i);return Nu([o,"optionalAccess",e=>e[1]])?o[1].trim():void 0},$u=async({url:t,outputPath:i,fetchImpl:o=t=>e.customFetch.fetch(t)})=>{const{buffer:s,response:n}=await(async(t,i)=>{const o=await i(t);if(!o.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download session file: ${o.status} ${o.statusText}`);return{buffer:Buffer.from(await o.arrayBuffer()),response:o}})(t,o),r=i||(e=>{const t=Gu((i=e.contentDisposition,o=()=>null,null!=i?i:o()));var i,o;if(t)return t;for(const t of[e.responseUrl,e.requestUrl]){if(!t||!URL.canParse(t))continue;const e=new URL(t),i=c.basename(decodeURIComponent(e.pathname));if(i&&"/"!==i&&"."!==i)return i}return"session-file.bin"})({requestUrl:t,responseUrl:n.url,contentDisposition:n.headers.get("content-disposition")}),a=await Er(r,s);return{path:a,filename:c.basename(a),size:s.byteLength,url:t,logid:n.headers.get("x-tt-logid")||void 0}},Fu="1008033";function Vu(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 Wu=async({baseUrl:t,headers:i,xTTEnv:o})=>{const n=new URL("/api/coze_claw/resource/get_frontier_key",s.normalizeBaseUrl(t));s.appendSearchParams(n,{aid:Fu});const r={...i,...s.getPpeHeaders(o)},a=await e.customFetch.fetch(n.toString(),{method:"GET",headers:r}),c=await s.parseServiceResponseBody(a,{}),d=s.getServiceResponseLogId(a);if(!a.ok)throw new Error(s.formatServiceErrorWithLogId({fallback:`Failed to get frontier key: ${a.status} ${a.statusText}`,logId:d,message:c.msg}));const l=Vu([c,"access",e=>e.data,"optionalAccess",e=>e.access_key]),p=Vu([c,"access",e=>e.data,"optionalAccess",e=>e.device_id]);if(!l||!p)throw new Error(s.formatServiceErrorWithLogId({fallback:"Frontier key response is incomplete",logId:d,message:c.msg}));return{accessKey:l,deviceId:p}};function Hu(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 Ju=async({filePaths:t,clawId:i,sessionId:o,accessFile:s=u.access,createFileReadStream:n=l.openAsBlob,uploadFile:r})=>{const a=[];for(const d of t){try{await s(d)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${d}${t instanceof Error?` (${t.message})`:""}`)}const t=c.basename(d),l=await r({fileName:t,fileContent:await n(d),clawId:i,sessionId:o}),p=Hu([l,"access",e=>e.data,"optionalAccess",e=>e.file]);if(!Hu([p,"optionalAccess",e=>e.file_uri])||!Hu([p,"optionalAccess",e=>e.file_url]))throw new e.CozeError(e.ErrorCode.E5002,l.msg||`Failed to upload session file: ${d}`);a.push({file_name:p.file_name||t,file_uri:p.file_uri,file_url:p.file_url})}return a},Ku=async({filePaths:e,sessionId:t,apiBaseUrl:i,sessionApiBaseUrl:o,sessionSpaceWebId:n,xTTEnv:r,service:a,deps:c})=>{if(!e||0===e.length)return[];const d=Hu([c,"optionalAccess",e=>e.store])||s.createSessionConfigStore(),{sessionClawId:l}=await d.get(),p=l||(await a.getStatus()).clawId;if(!p)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const u=o||i,_=await(async({sessionSpaceWebId:e,baseUrl:t,xTTEnv:i})=>{if(e)return e;try{return(await Wu({baseUrl:t,headers:{},xTTEnv:i})).deviceId}catch(e){return}})({sessionSpaceWebId:n,baseUrl:u,xTTEnv:r}),h=(Hu([c,"optionalAccess",e=>e.createApi])||s.createSessionApiClient)({baseUrl:u,webOrigin:u,xSpaceWebId:_,xTTEnv:r}),m=Hu([c,"optionalAccess",e=>e.uploadFiles])||Ju;return await m({filePaths:e,clawId:p,sessionId:t,uploadFile:({fileName:e,fileContent:t,clawId:i,sessionId:o})=>h.uploadFile({fileName:e,fileContent:t,clawId:i,sessionId:o})})};function Qu(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 Yu=1048576,Zu=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,Xu=({absolutePath:e,root:t})=>{const i=c.relative(t,e);return Boolean(i)&&!i.startsWith("..")&&!c.isAbsolute(i)},e_=async({onWarn:e,shouldWarnInvalidMention:t=()=>!0,statFile:i=u.stat,userInput:o,workTree:s})=>{(e=>{if(e.length>Yu)throw new Error("Message input is too long: max 1048576 characters")})(o);const n=[...o.matchAll(Zu)];if(0===n.length)return[{type:"text",text:o}];const r=[],a=c.resolve(s);let d=0;for(const s of n){const n=s.index,l=s[0],p=s[1];n>d&&r.push({type:"text",text:o.slice(d,n)});const u=c.resolve(a,p);let _=!1;if(Xu({absolutePath:u,root:a}))try{(await i(u)).isFile()?_=!0:t(p)&&Qu([e,"optionalCall",e=>e(`Uploading directories is not supported: ${p}`)])}catch(i){t(p)&&Qu([e,"optionalCall",e=>e(`File not found: ${p}`)])}_?r.push({type:"file",absolutePath:u,rawMention:l,relativePath:p}):r.push({type:"text",text:l}),d=n+l.length}return d<o.length&&r.push({type:"text",text:o.slice(d)}),r};const t_=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},i_=e=>e.includes("/")||e.includes("\\")||e.includes(".")||e.startsWith("."),o_=async(e,t={})=>{const i=await(async e=>{const t=await Pr(),i=t_(e),o=t_(t);return i||o?i&&o?`${i}\n\n${o}`:(n=()=>o,null!=(s=i)?s:n()):null;var s,n})(e);if(!i)return{content:i,filePaths:[]};const o=await e_({onWarn:t.onWarn,shouldWarnInvalidMention:i_,userInput:i,workTree:t.cwd||process.cwd()}),s=[];return{content:t_(o.map((e=>"text"===e.type?e.text:(s.push(e.absolutePath),""))).join("")),filePaths:s}};const s_=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(),"access",e=>e.toLowerCase,"call",e=>e()])||"",n_=async({baseUrl:t,xTTEnv:i,fetchImpl:o=e.customFetch.fetch.bind(e.customFetch)})=>{const s={"content-type":"application/json"};i&&(s["x-use-ppe"]="1",s["x-tt-env"]=i);const n=await o(`${(e=>new URL(e).origin)(t)}/api/coze_space/get_podcast_config`,{method:"POST",headers:s,body:"{}"});if(!n.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to fetch podcast config: ${String(n.status||"")} ${String(n.statusText||"")}`.trim());const r=await n.json();if(0!==r.code&&void 0!==r.code)throw new e.CozeError(e.ErrorCode.E5002,r.msg||"Failed to fetch podcast config");return r.data||{}},r_=({config:t,mode:i,keyword:o})=>{const s=(({config:t,mode:i})=>{if(!i)return;const o=s_(i),s=(t.mode_options||[]).find((e=>s_(e.value)===o||s_(e.label)===o));if(!s)throw new e.CozeError(e.ErrorCode.E1000,`Podcast mode not found: ${i}`);return s})({config:t,mode:i}),n=s_(o);return(s?[s]:t.mode_options||[]).flatMap((e=>(e.voice_options||[]).map((t=>({mode_label:e.label,mode_value:e.value,label:t.label,value:t.value,sample:t.sample,color_code:t.color_code}))).filter((e=>!n||(s_(e.label).includes(n)||s_(e.value).includes(n))))))};
17
17
  /*! *****************************************************************************
18
18
  Copyright (c) Microsoft Corporation.
19
19
 
@@ -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())}}))};function Hg(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 Jg={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 the raw API JSON envelope. 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:"Raw API envelope with code, msg, data fields"}}},Kg=t=>{t.command("upload").description("Upload a local file to a Coze agent project as JSON").requiredOption("--project-id <projectId>","The agent project ID").requiredOption("--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:Jg}).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=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:Hg([p,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv])},{projectId:a,fileName:c.basename(d),fileContent:await l.openAsBlob(d),projectDir:t.projectDir,clawId:(n=t.clawId,r=()=>"",null!=n?n:r())});o.print(h)}catch(e){V(e,i.getContext())}var n,r}))};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:"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:"Download result with status, path, filename, size, and url"}}},Zg=(t,i)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${i}`);return t},Xg=t=>{t.command("download").description("Download a Coze agent 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("--local-dir <localDir>","Local directory where the file will be saved").config({...xg,help:Yg}).action((async(t,i)=>{const o=new Lo({format:"json"});try{const n=Bg(t.projectId),r=Zg(t.projectFilePath,"--project-file-path"),a=Zg(t.localDir,"--local-dir"),d=i.getContext(),l=await(async e=>{const t=e.getContext(),{data:i}=await po.GetUserProfile({},{baseURL:Qg([t,"optionalAccess",e=>e.config,"access",e=>e.openApiBaseUrl])});return Zg(Qg([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:Qg([d,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),xTTEnv:Qg([d,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv])},{projectId:n,projectFilePath:r,localDir:a,userId:l,accountId:Qg([d,"optionalAccess",e=>e.config,"access",e=>e.organizationId])||"0"});o.print({status:"saved",path:p.path,filename:p.filename,size:p.size,url:p.url,file_url:p.fileUrl,project_file_path:p.projectFilePath,resolved_uri:p.resolvedUri})}catch(e){V(e,i.getContext())}}))},ef={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"}]},tf={brief:"List raw Coze agent project files as JSON",description:"Lists files in a Coze agent project and outputs the raw API JSON envelope. 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:"Raw API envelope with code, msg, data fields"}}},of={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"}}},sf={brief:"Read a Coze agent project file as JSON",description:"Reads content from a file in a Coze agent project and outputs the raw API JSON envelope. 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:"Raw API envelope with code, msg, data fields"}}},nf={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"}}},rf=(t,i)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${i}`);return t},af=e=>{e.command("list").description("List raw Coze agent project files as JSON").requiredOption("--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:tf}).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(c)}catch(e){V(e,t.getContext())}}))},cf=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:of}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=rf(e.projectFilePath,"--project-file-path"),r=rf(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())}}))},df=e=>{e.command("read").description("Read 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").option("--offset <offset>","Start line (from 1)").option("--limit <limit>","Number of lines to read").config({...xg,help:sf}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=rf(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(l)}catch(e){V(e,t.getContext())}}))},lf=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:nf}).action((async(e,t)=>{const i=new Lo({format:"json"});try{const o=Bg(e.projectId),n=rf(e.projectFilePath,"--project-file-path"),r=rf(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())}}))},pf=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:ef});af(t),cf(t),df(t),lf(t),Kg(t),Xg(t)})(t)};function uf(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),pf(t),ac()}function _f(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 hf(e,t){return null!=e?e:t()}function mf(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 gf(e){const t=[];let i=e;for(;i;)i.name()&&t.unshift(i.name()),i=i.parent;return t.join(" ")}function ff(e){return e._args.map((e=>e.required?`<${e.name()}>`:`[${e.name()}]`)).join(" ")}const yf=new Set(["--version","--format","--no-color","--config","--org-id","--space-id","--verbose","--debug","--log-file","--man","--schema","--commands"]);function vf(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)||yf.has(e)||t.set(e,i)}return Array.from(t.values())}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}class bf extends b.Command{__init(){this.middlewares=[]}constructor(e){super(e),bf.prototype.__init.call(this),this.helpInformation=()=>{const e=process.argv.slice(2);if(e.includes("--schema"))return`${JSON.stringify(wf([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=mf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=gf(e);let o=`@MAN ${i}\n\n`;o+=`NAME\n ${i} — ${mf([t,"optionalAccess",e=>e.brief])||e.description()}\n\n`,o+=`SYNOPSIS\n ${i} ${ff(e)}\n`,vf(e).forEach((e=>{o+=` [${e.flags}]\n`})),o+="\n",mf([t,"optionalAccess",e=>e.description])&&(o+=`DESCRIPTION\n ${t.description.replace(/\n/g,"\n ")}\n\n`);const s=vf(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`}))),mf([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"),mf([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"),mf([t,"optionalAccess",e=>e.caveats])&&t.caveats.length>0&&(o+="CAVEATS\n",t.caveats.forEach((e=>{o+=` - ${e}\n`})),o+="\n"),mf([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=mf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=gf(e);let o=`@HELP ${i}\n\n`;return mf([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: ${gf(e.parent)}\n\n`),o+=`SYNTAX:\n ${i} ${ff(e)} [options]\n\n`,mf([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`})),vf(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",mf([t,"optionalAccess",e=>e.enums])&&(o+="ENUMS:\n",Object.keys(t.enums).forEach((e=>{o+=` --${e}:\n`;const i=hf(mf([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})));Object.keys(i).forEach((e=>{o+=` ${e.padEnd(12)} ${i[e]}\n`}))})),o+="\n"),mf([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`}))),mf([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"),mf([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=mf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=gf(e);let o=`@USAGE ${i}\n\n`;mf([t,"optionalAccess",e=>e.brief])?o+=`BRIEF: ${t.brief}\n\n`:o+=`BRIEF: ${e.description()||"No description provided."}\n\n`,o+=`SYNTAX:\n ${i} ${ff(e)} [options]\n\n`,e.commands.length>0&&(o+="ACTIONS:\n",e.commands.forEach((e=>{const t=e;if(!t._hidden){const e=mf([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"),mf([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(mf([t,"optionalAccess",e=>e.enums])){const e=Object.keys(t.enums).filter((e=>Object.keys(hf(mf([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})))).length<=7));e.length>0&&(o+="ENUMS:\n",e.forEach((e=>{const i=Object.keys(hf(mf([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 bf(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 bf&&(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=wf([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 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){e.exitOverride(),e.outputError=()=>{},e.commands.forEach((e=>Pf(e)))}async function Cf(t){const i=new bf;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"}]}}),uf(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=_f([s,"access",e=>e.getConfig,"optionalCall",e=>e()]),o=_f([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")),Pf(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=Sf([a,"access",e=>e.getConfig,"optionalCall",e=>e()]),d=Sf([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 Cf(i)}))})().catch((e=>{V(e,void 0),process.exitCode=1}));
31
+ function a_(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 c_="";function d_(e=""){const t=`${Date.now()}`,i=c_||(c_=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]=p_(t[0]+t[1]),i[1]=p_(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 l_(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function p_(e){return(Array(4).join("0")+parseInt(e,2).toString(16)).slice(-4)}function u_(e,t){const i=e.key;void 0!==i&&(L_(t,10),k_(t,i));const o=e.value;void 0!==o&&(L_(t,18),k_(t,o))}function __(e){const t={};e:for(;!P_(e);){const i=z_(e);switch(i>>>3){case 0:break e;case 1:t.key=I_(e,z_(e));break;case 2:t.value=I_(e,z_(e));break;default:f_(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 h_(e){const t=w_();return function(e,t){const i=e.SeqID;void 0!==i&&(L_(t,8),O_(t,i));const o=e.LogID;void 0!==o&&(L_(t,16),O_(t,o));const s=e.service;void 0!==s&&(L_(t,24),O_(t,y_(s)));const n=e.method;void 0!==n&&(L_(t,32),O_(t,y_(n)));const r=e.headers;if(void 0!==r)for(const e of r){L_(t,42);const i=w_();u_(e,i),L_(t,i.limit),A_(t,i),b_(i)}const a=e.payloadEncoding;void 0!==a&&(L_(t,50),k_(t,a));const c=e.payloadType;void 0!==c&&(L_(t,58),k_(t,c));const d=e.payload;void 0!==d&&(L_(t,66),L_(t,d.length),function(e,t){const i=C_(e,t.length);e.bytes.set(t,i)}(t,d));const l=e.LogIDNew;void 0!==l&&(L_(t,74),k_(t,l));const p=e.serverTiming;void 0!==p&&(L_(t,82),k_(t,p));const u=e.msgID;void 0!==u&&(L_(t,90),k_(t,u));const _=e.frameType;void 0!==_&&(L_(t,96),O_(t,y_(_)))}(e,t),function(e){const t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function m_(e){return function(e){const t={};e:for(;!P_(e);){const i=z_(e);switch(i>>>3){case 0:break e;case 1:t.SeqID=U_(e,!0);break;case 2:t.LogID=U_(e,!0);break;case 3:t.service=z_(e);break;case 4:t.method=z_(e);break;case 5:{const i=g_(e);(t.headers||(t.headers=[])).push(__(e)),e.limit=i;break}case 6:t.payloadEncoding=I_(e,z_(e));break;case 7:t.payloadType=I_(e,z_(e));break;case 8:t.payload=E_(e,z_(e));break;case 9:t.LogIDNew=I_(e,z_(e));break;case 10:t.serverTiming=I_(e,z_(e));break;case 11:t.msgID=I_(e,z_(e));break;case 12:t.frameType=z_(e);break;default:f_(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 g_(e){const t=z_(e),i=e.limit;return e.limit=e.offset+t,i}function f_(e,t){switch(t){case 0:for(;128&j_(e););break;case 2:S_(e,z_(e));break;case 5:S_(e,4);break;case 1:S_(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function y_(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}const v_=[];function w_(){const e=v_.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function b_(e){v_.push(e)}function S_(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function P_(e){return e.offset>=e.limit}function C_(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 T_(e,t){const i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function E_(e,t){const i=T_(e,t);return e.bytes.subarray(i,i+t)}function I_(e,t){const i=T_(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 k_(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}L_(e,o);let s=C_(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 A_(e,t){const i=C_(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 j_(e){return e.bytes[T_(e,1)]}function R_(e,t){const i=C_(e,1);e.bytes[i]=t}function z_(e){let t,i=0,o=0;do{t=j_(e),i<32&&(o|=(127&t)<<i),i+=7}while(128&t);return o}function L_(e,t){for(t>>>=0;t>=128;)R_(e,127&t|128),t>>>=7;R_(e,t)}function U_(e,t){let i,o=0,s=0,n=0;return i=j_(e),o=127&i,128&i&&(i=j_(e),o|=(127&i)<<7,128&i&&(i=j_(e),o|=(127&i)<<14,128&i&&(i=j_(e),o|=(127&i)<<21,128&i&&(i=j_(e),s=127&i,128&i&&(i=j_(e),s|=(127&i)<<7,128&i&&(i=j_(e),s|=(127&i)<<14,128&i&&(i=j_(e),s|=(127&i)<<21,128&i&&(i=j_(e),n=127&i,128&i&&(i=j_(e),n|=(127&i)<<7))))))))),{low:o|s<<28,high:s>>>4|n<<24,unsigned:t}}function O_(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=C_(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 x_(e){return h_(e)}const B_=4294967296,q_=0x10000000000000000,D_=q_/2,M_=String.prototype.charCodeAt;class N_{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 N_(e,t,i)}static fromBytes(e,t,i){return i?N_.fromBytesLE(e,t):N_.fromBytesBE(e,t)}static fromBytesLE(e,t){return new N_(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 N_(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?G_:new N_((M_.call(e,0)|M_.call(e,1)<<8|M_.call(e,2)<<16|M_.call(e,3)<<24)>>>0,(M_.call(e,4)|M_.call(e,5)<<8|M_.call(e,6)<<16|M_.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?$_:G_;if(t){if(e>=q_)return V_}else{if(e<=-D_)return W_;if(e+1>=D_)return F_}return N_.fromBits(e%B_|0,e/B_|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*B_+(this.low>>>0):this.high*B_+(this.low>>>0)}isZero(){return 0===this.high&&0===this.low}add(e){N_.isLong(e)||(e=N_.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,N_.fromBits(l<<16|p,c<<16|d,this.unsigned)}equals(e){return N_.isLong(e)||(e=N_.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?N_.fromBits(0,0,this.unsigned):-1===this.low?N_.fromBits(0,this.high+1,this.unsigned):N_.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 G_=new N_(0,0,!1),$_=new N_(0,0,!0),F_=N_.fromBits(-1,2147483647,!1),V_=N_.fromBits(-1,-1,!0),W_=N_.fromBits(0,-2147483648,!1);var H_;!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"}(H_||(H_={}));class J_{constructor(e){this.type=e,this.target=null}}class K_ extends J_{constructor(e,t){super(e),this.message=t&&t.message||null}}class Q_ extends J_{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||H_.NATIVE_ERROR}}class Y_ extends J_{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 Z_ extends J_{constructor(e,t){super(e),this.data=t&&t.data||null}}class X_ extends Z_{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}}class eh extends J_{constructor(e,t){super(e),this.data=t&&t.data||null}}function th(e,{message:t,code:i,error:o}){return new Q_(e,{message:t,code:i,error:o})}function ih(e,{code:t,reason:i,wasClean:o,willReconnect:s}){return new Y_(e,{code:t,reason:i,wasClean:o,willReconnect:s})}function oh(e,{message:t}){return new K_(e,{message:t})}class sh{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 nh=("undefined"!=typeof globalThis&&"Window"===globalThis.constructor.name||"undefined"!=typeof window&&"Window"===window.constructor.name)&&"undefined"!=typeof document,rh="undefined"!=typeof globalThis&&("Object"===globalThis.constructor.name||"DedicatedWorkerGlobalScope"===globalThis.constructor.name)&&"undefined"!=typeof tt,ah=("undefined"!=typeof globalThis&&"Object"===globalThis.constructor.name||"undefined"==typeof globalThis||"undefined"!=typeof globalThis&&!!globalThis.WeixinJSBridge)&&"undefined"!=typeof wx,ch="undefined"!=typeof globalThis&&("DedicatedWorkerGlobalScope"===globalThis.constructor.name||"SharedWorkerGlobalScope"===globalThis.constructor.name||"ServiceWorkerGlobalScope"===globalThis.constructor.name)&&"undefined"!=typeof self,dh="undefined"!=typeof globalThis&&"Object"===globalThis.constructor.name&&"undefined"!=typeof global&&"Object"===global.constructor.name&&"undefined"!=typeof process&&!!process.version;class lh{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 ph extends lh{constructor(e,t,i){super(),this._socket=null,ah&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:i,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),rh&&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=th("error",{message:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)});this.emit("error",t);const i=ih("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 eh(e,{data:t})}("open",Object.assign(Object.assign({},e),{data:e.errMsg||""})))})),this._socket.onClose((e=>{this.emit("close",ih("close",Object.assign({},e)))})),this._socket.onMessage((e=>{this.emit("message",function(e,{data:t,message:i}){return new X_(e,{data:t,message:i})}("message",Object.assign({},e)))})),this._socket.onError((e=>{this.emit("error",th("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",th("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",th("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 uh(e,t,i){let o=-1;!function s(n){return a_(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 _h(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 hh(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 mh(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 gh(e){return a_(this,0,void 0,(function*(){if("string"==typeof e){const t=new Uint8Array(_h(e));return mh(e,t,0),t}return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}))}class fh{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 yh(e,t,i){return!!(null==e?void 0:e.find((e=>e.key===t&&e.value===i)))}function vh(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 wh(e,t){return a_(this,0,void 0,(function*(){const{enableAutoAck:i}=this._options,o=yh(e.message.headers,"need_ack","1"),s=yh(e.message.headers,"is_ack","1"),n=yh(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 bh(e,t){return a_(this,0,void 0,(function*(){this._debug("received",e.message),t()}))}function Sh(e,t){return a_(this,0,void 0,(function*(){const i=m_(yield gh(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=hh(i.payload,0,i.payload.byteLength):i.textPayload=""}else i.textPayload=""}catch(e){i.textPayload="",console.log(e)}e.message=i,t()}))}let Ph,Ch;const Th=new WeakMap,Eh=new WeakMap,Ih=new WeakMap,kh=new WeakMap,Ah=new WeakMap;let jh={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return Eh.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Ih.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return Lh(e[t])},set:(e,t,i)=>(e[t]=i,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Rh(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Ch||(Ch=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(Uh(this),t),Lh(Th.get(this))}:function(...t){return Lh(e.apply(Uh(this),t))}:function(t,...i){const o=e.call(Uh(this),t,...i);return Ih.set(o,t.sort?t.sort():[t]),Lh(o)}}function zh(e){return"function"==typeof e?Rh(e):(e instanceof IDBTransaction&&function(e){if(Eh.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)}));Eh.set(e,t)}(e),t=e,(Ph||(Ph=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some((e=>t instanceof e))?new Proxy(e,jh):e);var t}function Lh(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(Lh(e.result)),o()},n=()=>{i(e.error),o()};e.addEventListener("success",s),e.addEventListener("error",n)}));return t.then((t=>{t instanceof IDBCursor&&Th.set(t,e)})).catch((()=>{})),Ah.set(t,e),t}(e);if(kh.has(e))return kh.get(e);const t=zh(e);return t!==e&&(kh.set(e,t),Ah.set(t,e)),t}const Uh=e=>Ah.get(e);const Oh=["get","getKey","getAll","getAllKeys","count"],xh=["put","add","delete","clear"],Bh=new Map;function qh(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Bh.get(t))return Bh.get(t);const i=t.replace(/FromIndex$/,""),o=t!==i,s=xh.includes(i);if(!(i in(o?IDBIndex:IDBObjectStore).prototype)||!s&&!Oh.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 Bh.set(t,n),n}jh=(e=>({...e,get:(t,i,o)=>qh(t,i)||e.get(t,i,o),has:(t,i)=>!!qh(t,i)||e.has(t,i)}))(jh);class Dh extends lh{constructor(e,t){super(),this._dbName=e,this._keyPath=t,this._qosDB=void 0,this._init()}openDB(){return a_(this,0,void 0,(function*(){yield this._init()}))}_init(){return a_(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=Lh(r);return o&&r.addEventListener("upgradeneeded",(e=>{o(Lh(r.result),e.oldVersion,e.newVersion,Lh(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 a_(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 a_(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 a_(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 a_(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 a_(this,0,void 0,(function*(){return null===(e=this._qosDB)||void 0===e?void 0:e.getAllKeys(this._dbName)}))}getAll(){var e;return a_(this,0,void 0,(function*(){return null===(e=this._qosDB)||void 0===e?void 0:e.getAll(this._dbName)}))}closeDB(){var e;return a_(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 Mh{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=localStorage}openDB(){return a_(this,0,void 0,(function*(){}))}get _prefix(){return`frontier_${this._DBName}`}get(e){return a_(this,0,void 0,(function*(){const t=this._qosDB.getItem(this._prefix);return JSON.parse(t||"{}")[e]}))}set(e,t){return a_(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 a_(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 a_(this,0,void 0,(function*(){return this._qosDB.clear()}))}keys(){return a_(this,0,void 0,(function*(){const e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}))}getAll(){return a_(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 Nh{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=rh?tt:ah?wx:null}openDB(){return a_(this,0,void 0,(function*(){}))}get _prefix(){return`frontier_${this._DBName}`}get(e){return a_(this,0,void 0,(function*(){const t=this._qosDB.getStorageSync(this._prefix);return JSON.parse(t||"{}")[e]}))}set(e,t){return a_(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 a_(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 a_(this,0,void 0,(function*(){return this._qosDB.clearStorageSync()}))}keys(){return a_(this,0,void 0,(function*(){const e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}))}getAll(){return a_(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 Gh(e,t){if(rh||rh)return new Nh(e,t);if((nh||ch)&&void 0!==typeof indexedDB)return new Dh(e,t);if((nh||ch)&&void 0!==typeof localStorage)return new Mh(e,t);throw new Error("init QoSDB failed")}class $h{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=Gh("qos","message_id")}_intervalFlush(){return a_(this,0,void 0,(function*(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval((()=>{this.flushExpired()}),this._interval)}))}openDB(){return a_(this,0,void 0,(function*(){yield this._qosDB.openDB().then((()=>{this._intervalFlush()}))}))}flushExpired(){var e;return a_(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 a_(this,0,void 0,(function*(){return null===(t=this._qosDB)||void 0===t?void 0:t.del(e)}))}set(e,t){var i;return a_(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 a_(this,0,void 0,(function*(){return null===(t=this._qosDB)||void 0===t?void 0:t.get(e)}))}closeDB(){var e;return a_(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 Fh(e,t){var i,o,s,n,r;return a_(this,0,void 0,(function*(){const a=yh(e.message.headers,"code","-1"),c=yh(e.message.headers,"is_ack","1"),d=vh(e.message.headers,"x_frontier_msgid"),l=Number(vh(e.message.headers,"x_frontier_ttl"))||0,p=yh(e.message.headers,"x_frontier_qos","2"),u=yh(e.message.headers,"x_frontier_qos_ack","1"),_=yh(e.message.headers,"x-msg-qos","2"),h=vh(e.message.headers,"x-msg-cursor_name"),m=Number(vh(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 $h),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 Vh(e,t){var i,o;return a_(this,0,void 0,(function*(){const s=yh(e.message.headers,"x_frontier_qos","2"),n=yh(e.message.headers,"x_frontier_is_ack","1"),r=null===(i=vh(e.message.headers,"x_frontier_ack_msgid"))||void 0===i?void 0:i.split(",");if(!s)return t();if(this._QoSManager||(this._QoSManager=new $h),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 Wh(e,t){let i=0,o=t;const s=t+4;for(;o<s;){const{value:t,offset:s}=Jh(e,o);o=s,i=i<<8>>>0,i+=t}return{value:i,offset:s}}function Hh(e,t){return{value:new N_(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 Jh(e,t){return e.readUInt8?{value:e.readUInt8(t),offset:t+1}:{value:255&e[t],offset:t+1}}function Kh(e,t,i){return t.writeUint8?t.writeUint8(e,i):t[i]=255&e,i+1}const Qh="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 Yh(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]=_h(e[o].cursor_name),t+=14+i[e[o].cursor_name];return[t,i]}(e),n=Qh(o);let r=0;return e.forEach((e=>{console.log("cursor.service",e,e.service),r=Kh(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;)Kh(255&i,e,t+o),i>>>=8,o--;return t+4}(n,r,e.service||0),console.log("service",r),r=Kh(s[e.cursor_name],n,r),console.log("service-name",r),r=function(e,t,i){return e?e.length<40?mh(e,t,i)+i:t.utf8Write?t.utf8Write(e,i)+i:t.write?t.write(e,i)+i:mh(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}(N_.fromNumber(e.cursor||t),n,r),console.log("curvalue",r)})),{frameType:32,headers:[{key:"cursor_file_name",value:i}],payload:n}}class Zh{constructor(e,t,i){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=i,this._qosDB=Gh(this._cursorNameSpace,"cursor_name")}openDB(){return a_(this,0,void 0,(function*(){yield this._qosDB.openDB()}))}getCursors(){return a_(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?Yh(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?Yh(t,0,this._cursorFileName):{frameType:32,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}}))}set(e,t,i){return a_(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 a_(this,0,void 0,(function*(){const t=function(e){let t=0;const i=[];for(;t<e.byteLength;){const{offset:o}=Jh(e,t);t=o;const s={cursor_name:"",cursor:0,service:0},{value:n,offset:r}=Wh(e,t);s.service=n,t=r;const{value:a,offset:c}=Jh(e,t);t=c,s.cursor_name=hh(e,t,t+a),t+=a;const{value:d,offset:l}=Hh(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 a_(this,0,void 0,(function*(){return null===(t=yield this._qosDB.get(e))||void 0===t?void 0:t.cursor}))}closeDB(){return a_(this,0,void 0,(function*(){yield this._qosDB.closeDB()}))}get isReady(){return this._qosDB.isReady}}function Xh(e,t){return a_(this,0,void 0,(function*(){const i=16===e.message.frameType,o=32===e.message.frameType;if(!i&&!o)return t();const s=vh(e.message.headers,"cursor_file_name"),{aID:n,fpID:r,messageStrategy:a}=this._options;if(!s)return t();if(this._cursorManager||(this._cursorManager=new Zh(`${r}_${n}_${s}`,s,a)),this._cursorManager.isReady||(yield this._cursorManager.openDB()),i){const e=yield this._cursorManager.getCursors(),t=h_({frameType:null==e?void 0:e.frameType,SeqID:N_.fromNumber(this._seqId++),LogID:N_.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 em=function(e,t){return a_(this,0,void 0,(function*(){this._isInit=!1,clearTimeout(this._connectionTimeoutId),t()}))},tm=function(e,t){var i;return a_(this,0,void 0,(function*(){const e=null===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpoint();this._debug(`open ${e}`),t()}))},im=function(e,t){var i,o;return a_(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 om extends lh{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=nh,this._isNode=dh,this._isMiniTT=rh,this._isMiniWX=ah,this._isWorker=ch,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{uh(this,e,[em,im,tm])}catch(e){const t=th("error",{message:e.message,code:H_.OPEN_ERROR,error:e});this._dispatchErrorEvent(t)}},this._onMessage=e=>a_(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{uh(this,e,[Sh,wh,Vh,Xh,Fh,bh])}catch(e){const t=th("error",{message:e.message,code:H_.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(th("error",{message:e.message,code:H_.NATIVE_ERROR,error:e}));else{const t=`connect ${s} fail, max retries reached`;this._dispatchErrorEvent(th("error",{message:t,code:H_.MAX_RETRIES_ERROR,error:e}))}},this._onClose=e=>a_(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(ih("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(ih("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 a_(this,0,void 0,(function*(){return new Promise((t=>{if(!nh)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(ih("close",{code:e.code,reason:i}));const o=`connect ${t} fail, max retries reached`;return this._dispatchErrorEvent(th("error",{message:o,code:H_.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(ih("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:l_,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||ah&&wx.connectSocket||rh&&tt.connectSocket||(nh||ch)&&"undefined"!=typeof WebSocket&&WebSocket)}(i))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new sh(o,this._options.maxRetries),this._pingLossCounter=new fh(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=oh("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 a_(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 a_(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(th("error",{message:t,code:H_.MAX_RETRIES_ERROR}))}{const t=`connect ${e} timeout, max retries reached, will use backup endpoint ${s} to retry`,i=th("error",{message:t,code:H_.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=oh("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):ah||rh?new ph(a.url,a.protocol,a.headers):(nh||ch)&&"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=x_(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(ih("close",{code:1006,reason:`connect ${e} timeout, max retries reached`,wasClean:!0}))}else{const i=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(ih("close",{code:e,reason:t,wasClean:!0,willReconnect:i})),i&&this._connect()}}else this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(ih("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(ih("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 a_(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 gh(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?d_(this._options.logIDNewConfig.userIp):"")}=t||{};if(!n)throw new Error("please provide a valid service");const p={SeqID:N_.fromNumber(this._seqId++),LogID:N_.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=x_(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 a_(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 sh(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 a_(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 sm(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 nm extends w{constructor(e,t){super((e=>{const t=new URL(e);return t.searchParams.set("aid",Fu),t.toString()})(e),"pbbp2",{headers:{...t,Origin:"https://www.coze.cn"}})}}class rm{constructor(){rm.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);sm([o,"optionalCall",t=>t(e)])},d={fpID:"1289",aID:Fu,accessKey:t.accessKey,deviceID:t.deviceId,url:"wss://frontier.coze.cn",automaticOpen:!0,enableQoS:!1,enableAutoAck:!1,ws:class extends nm{constructor(e){super(e,t.headers)}}};this.fws=new om(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=sm([t,"access",e=>e.message,"optionalAccess",e=>e.payloadType]),s=sm([t,"access",e=>e.message,"optionalAccess",e=>e.service]),n=sm([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(){sm([this,"access",e=>e.fws,"optionalAccess",e=>e.close,"call",e=>e()]),this.fws=null}}function am(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 cm=(e,t)=>{const i=t.toLowerCase(),o=Object.entries(e).find((([e])=>e.toLowerCase()===i));return am([o,"optionalAccess",e=>e[1]])},dm=e=>JSON.stringify({accessKey:e.accessKey,authorization:cm(e.headers,"authorization"),deviceId:e.deviceId,organizationId:e.organizationId,serviceId:e.serviceId,xTTEnv:cm(e.headers,"x-tt-env")}),lm=e=>"function"==typeof e.resolveConfig&&"string"==typeof e.scopeKey;class pm{__init(){this.entries=new Map}constructor(e){pm.prototype.__init.call(this),this.createClient=am([e,"optionalAccess",e=>e.createClient])||(()=>new rm),this.getScopeKey=am([e,"optionalAccess",e=>e.getScopeKey])||dm}async subscribe(e,t){const i=((e,t)=>lm(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=>lm(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)am([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 um=new pm;function _m(e,t){return null!=e?e:t()}function hm(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 mm=e=>({...e,files:e.files?[...e.files]:void 0}),gm=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 fm{constructor(){fm.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=hm([e.safeJsonParse(t.content,null),"optionalAccess",e=>e.message_data,"optionalAccess",e=>e.reply]),s=t.id,n="message"===i?hm([o,"optionalAccess",e=>e.content])||t.content:hm([o,"optionalAccess",e=>e.content]);return s&&n?{answerId:s,content:n,files:t.files,requestMessageId:hm([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:_m(s.files,(()=>hm([r,"optionalAccess",e=>e.files]))),requestMessageId:_m(s.requestMessageId,(()=>hm([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&&gm(i.files)===gm(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:mm(a)})}applySessionIdleEvent(e){const t=hm([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=>mm(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 ym(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=e=>({type:"progress_update",progress:e});class wm{constructor(){wm.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=>vm({progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:t.progressStatus}))):[]}applyFrontierEvent(e){const t=ym([e,"optionalAccess",e=>e.claw_id]),i=ym([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),vm(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(vm({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(vm({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 bm{__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}){bm.prototype.__init.call(this),bm.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 Sm{__init(){this.closed=!1}__init2(){this.error=null}__init3(){this.queue=[]}constructor(e){this.cleanup=e,Sm.prototype.__init.call(this),Sm.prototype.__init2.call(this),Sm.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 Pm(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 Cm="*";class Tm{__init(){this.connectionError=null}__init2(){this.disposed=!1}__init3(){this.replyStateStore=new fm}__init4(){this.progressStateStore=new wm}__init5(){this.sessionStreams=new Map}__init6(){this.progressStreams=new Map}constructor(e){Tm.prototype.__init.call(this),Tm.prototype.__init2.call(this),Tm.prototype.__init3.call(this),Tm.prototype.__init4.call(this),Tm.prototype.__init5.call(this),Tm.prototype.__init6.call(this),this.connectionManager=Pm([e,"optionalAccess",e=>e.connectionManager])||(Pm([e,"optionalAccess",e=>e.client])?new pm({createClient:()=>e.client}):um),this.progressPoller=new bm({emitProgressUpdate:(e,t)=>{this.emitToProgress(e,t)},globalStreamKey:Cm,hasConnectionError:()=>Boolean(this.connectionError),hasSubscribers:e=>this.hasProgressSubscribers(e),listProgresses:Pm([e,"optionalAccess",e=>e.listProgresses]),progressPollIntervalMs:Pm([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 Sm((()=>{this.removeStream(e,i),Pm([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(Pm([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),Pm([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.addEventListener,"call",e=>e("abort",o,{once:!0})]),i}watchProgress(e,t){const i=e||Cm,o=new Sm((()=>{this.removeProgressStream(i,o),Pm([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(Pm([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),Pm([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!==Cm&&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(Cm,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 Em(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 Im=({replies:e,requestMessageId:t,source:i})=>{if(0===e.length)return null;const o=Em([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:Em([e,"access",t=>t[e.length-1],"optionalAccess",e=>e.files]),requestMessageId:t,source:i}:null},km=({replies:e,replyOrder:t,reply:i})=>{e.has(i.answerId)||t.push(i.answerId),e.set(i.answerId,i)},Am=({event:e,replies:t,replyOrder:i})=>{const o=t.get(e.chunk.answerId),s={answerId:e.chunk.answerId,content:`${Em([o,"optionalAccess",e=>e.content])||""}${e.chunk.content}`,files:Em([o,"optionalAccess",e=>e.files]),requestMessageId:e.chunk.requestMessageId||Em([o,"optionalAccess",e=>e.requestMessageId])};return km({replies:t,reply:s,replyOrder:i}),s},jm=({event:e,replies:t,replyOrder:i})=>(km({replies:t,reply:e.reply,replyOrder:i}),e.reply);class Rm{constructor(e){this.watcher=Em([e,"optionalAccess",e=>e.watcher])||new Tm}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,Em([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=Im({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;Am({event:e,replies:c,replyOrder:d}),Em([t,"optionalCall",t=>t(e)]);continue}if("reply_update"===e.type){if(e.reply.requestMessageId!==s)continue;jm({event:e,replies:c,replyOrder:d}),Em([i,"optionalCall",t=>t(e)]);continue}if("session_idle"!==e.type)continue;const o=Im({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 zm={skipOrgCheck:!0,skipSpaceCheck:!0},Lm=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")},Um=async({clawId:e,sessionId:t})=>{const i=s.createSessionConfigStore();await i.save({sessionId:t,...e?{sessionClawId:e}:{}})},Om=({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)}}},xm=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)}},Bm=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},qm=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},Dm=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")},Mm=(e,t)=>{const i=Dm(t);return i?[e,"",i].join("\n"):e},Nm=({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 Wu({baseUrl:r,headers:a,xTTEnv:n}),headers:a,organizationId:i}),scopeKey:JSON.stringify({baseUrl:r,authorization:a.Authorization,organizationId:i,xTTEnv:n})}},Gm=async({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,progressPollIntervalMs:s,service:n,xTTEnv:r})=>{const a=new Tm({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(Nm({accessToken:e,apiBaseUrl:t,organizationId:i,sessionApiBaseUrl:o,xTTEnv:r})),a},$m=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"),Fm=e=>`${JSON.stringify(e)}\n`;class Vm{__init(){this.replyStates=new Map}__init2(){this.requestPrintedContent=new Map}__init3(){this.endsWithNewline=!0}__init4(){this.hasStartedReply=!1}constructor(e){Vm.prototype.__init.call(this),Vm.prototype.__init2.call(this),Vm.prototype.__init3.call(this),Vm.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(Fm({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(Fm({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=Dm(e);t&&this.writeRaw(`\n${t}\n`)}writeProgress({progress:e,sessionId:t}){"text"===this.format?(this.endsWithNewline||this.writeRaw("\n"),this.writeRaw(`\n${$m(e)}\n`)):this.write(Fm({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 Wm(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 Hm=({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${Mm(e.content,t)}`)({files:o,reply:i,source:s}))},Jm=({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});Wm([n,"optionalAccess",e=>e.get,"call",e=>e(i.answerId)])!==a&&(Wm([n,"optionalAccess",e=>e.set,"call",e=>e(i.answerId,a)]),Hm({ctx:e,files:s,reply:i,sessionId:t.sessionId,source:o}))};return{handleReplyChunk:e=>{Wm([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"})}}},Km=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",qm).option("--snapshot","Print full reply snapshots instead of streaming chunks incrementally").config({...zm,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 xm(t,(async({ctx:t,service:i})=>{const o=await Lm(e.sessionId),s={...e,sessionId:o},n=await Gm({accessToken:t.config.accessToken,apiBaseUrl:t.config.apiBaseUrl,organizationId:t.config.organizationId,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv});await Um({sessionId:o});const r=s.snapshot?null:new Vm({format:t.format,includeReplyMetadata:"text"===t.format}),a=Om({timeoutMs:s.timeout}),c=Jm({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 Qm(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 Ym=async e=>await new Promise((t=>setTimeout(t,e))),Zm=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}},Xm=e=>{const t=Zm(e);return{answer_message_id:e.answerMessageId,artifacts:Qm([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}},eg=e=>{const t=Zm(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")},tg=({ctx:e,task:t})=>{"text"!==e.format?e.response.print(Xm(t)):e.response.print(eg(t))},ig=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)),og=e=>{const t=e.command("task").description("Inspect persisted session background tasks").config({...zm,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 xm(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(eg).join("\n\n"):"No session tasks");t.response.print({items:n.map((e=>Xm(e)))})}catch(e){throw ig(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 xm(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)});tg({ctx:t,task:n})}catch(e){throw ig(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 xm(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)});tg({ctx:t,task:n})}catch(e){throw ig(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",qm).action((async(e,t,i)=>{await(async(e,t)=>{await xm(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(tg({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 Ym(i),n=await o.refreshTask(e.taskId,{includeExpired:Boolean(e.includeExpired)}),tg({ctx:t,task:n}),s.isSessionTaskTerminal(n.status))return}}catch(e){throw ig(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 xm(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=>Xm(e)))})}catch(e){throw ig(e)}}))})(t)}))},sg=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${Mm(e.content,e.files)}`,ng=async(e,t)=>{await xm(t,(async({ctx:t,service:i})=>{const o=await Lm(e.sessionId),n=await i.listRepliesByMessage({sessionId:o,messageId:e.messageId});await Um({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(sg).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 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 ag=({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(`${$m(t)}\nevent_source: ${t.eventSource}`)})({ctx:e,progress:i}))}},cg=(e,t)=>!t||e.progressId===t,dg=async(e,t)=>{await xm(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=>$m(e))).join("\n\n"):"No active progress")})({ctx:t,progresses:await i.listProgresses({size:e.size})})}))},lg=async(e,t)=>{await xm(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 Gm({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=Om({timeoutMs:e.timeout}),c=ag({ctx:t});try{await(async({clawId:e,emitProgress:t,options:i,service:o})=>{(await o.listProgresses({clawId:e})).filter((e=>cg(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}))cg(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()}}))},pg=e=>{const t=e.command("progress").description("Inspect claw background progress").config({...zm,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",Bm,100).action(dg),t.command("show <progressId>").description("Show one background progress snapshot").action((async(e,t,i)=>{await(async(e,t)=>{await xm(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:rg([o,"optionalAccess",e=>e.name]),type:rg([o,"optionalAccess",e=>e.type]),progress_status:rg([o,"optionalAccess",e=>e.progressStatus]),raw:rg([o,"optionalAccess",e=>e.raw])}):t.response.print(o?$m(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 xm(t,(async({ctx:t,service:i})=>{const o=await i.getProgress({progressId:e.progressId}),s=rg([o,"optionalAccess",e=>e.progressStatus])||"finished";"text"!==t.format?t.response.print({progress_id:e.progressId,name:rg([o,"optionalAccess",e=>e.name]),type:rg([o,"optionalAccess",e=>e.type]),progress_status:s,raw:rg([o,"optionalAccess",e=>e.raw])}):t.response.print($m({progressId:e.progressId,name:rg([o,"optionalAccess",e=>e.name]),type:rg([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",qm).action((async(e,t,i)=>{await lg({progressId:e,timeout:t.timeout},i)}))};function ug(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 _g={...zm,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"}}}}}},hg=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=s_(i),n=r_({config:t,mode:o}).filter((e=>s_(e.label)===s||s_(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 n_({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})},mg=async({ctx:t,message:i,options:o,service:s})=>{const{content:n,filePaths:r}=await o_(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 Ku({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 hg({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}},gg=async({ctx:e,options:t,service:i})=>{if(!t.wait)return{streamRenderer:null,waiter:null};const o=new Vm({format:e.format}),s=ug([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 Rm({watcher:await Gm({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})}},fg=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 Mu(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}},yg=async(e,t,i)=>{await xm(i,(async({ctx:i,service:o})=>{const n=await Lm(t.sessionId),r={...t,sessionId:n},a=await mg({ctx:i,message:e,options:r,service:o}),c=await gg({ctx:i,options:r,service:o});try{const e=await o.sendMessage({sessionId:n,content:a.content,files:a.files});if(await Um({sessionId:e.sessionId}),c.waiter){const t=await fg({...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{ug([c,"access",e=>e.waiter,"optionalAccess",e=>e.dispose,"call",e=>e()])}}))};const vg={...zm,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"}]}},wg=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},bg=(e,t)=>[...t,wg(e)],Sg=t=>{if("ppt"===t||"editable"===t)return t;throw new e.CozeError(e.ErrorCode.E1000,'Invalid value for --export-type: expected "ppt" or "editable"')},Pg=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.")},Cg=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},Tg=async({file:e,service:t})=>e.fileUrl?e.fileUrl:t.resolveFileUrl({fileUri:Cg(e)}),Eg=async(e,t)=>{await xm(t,(async({ctx:t,service:i})=>{const o=await Pg({options:e}),n=await Tg({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}))}))},Ig=t=>{const i=t.command("ppt").description("Inspect, export, share, and edit session PPT artifacts").config(vg);i.command("info").description("Get PPT metadata and page count").option("--file-uri <uri>","Specific PPT file_uri").action(((e,t)=>Eg(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",Bm).action(((e,t)=>(async(e,t)=>{await xm(t,(async({ctx:t,service:i})=>{const o=await Pg({options:e}),n=await Tg({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",Sg,"ppt").action(((e,t)=>(async(e,t)=>{await xm(t,(async({ctx:t,service:i})=>{const o=await Pg({options:e}),s=Cg(o),n=await i.exportPpt({fileUri:s,exportType:e.exportType}),r=await $u({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",bg,[]).option("--wait","Wait until the edit turn becomes idle").option("--timeout <timeoutMs>","Timeout for --wait",qm).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 yg(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 xm(t,(async({ctx:t,service:i})=>{const o=await Pg({options:e}),n=Cg(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)))},kg=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"),Ag=async(e,t)=>{await xm(t,(async({ctx:t})=>{const i=await n_({baseUrl:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,xTTEnv:t.config.xTTEnv}),o=r_({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(kg).join("\n\n"):"No podcast voices matched")}))},jg=(e,t)=>[...t,e],Rg=async(t,i,o)=>{(t=>{if(t.mode&&!t.voice)throw new e.CozeError(e.ErrorCode.E1000,"--mode requires --voice")})(i),await yg(t,(e=>({file:e.file||[],podcastMode:e.mode,podcastVoice:e.voice,sessionId:e.sessionId,timeout:e.timeout,wait:e.wait}))(i),o)},zg=e=>{const t=e.command("podcast").description("Inspect podcast config");t.config({...zm,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",qm).option("--file <path>","Local file to upload and attach (can be used multiple times)",jg,[]).config({...zm,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(Rg)})(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({...zm,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(Ag)})(t)};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 Ug=e=>{e.command("current").description("Show the current locally selected default session").config({...zm,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"===Lg([t,"optionalAccess",e=>e.format])){if(!o.sessionId)return void Lg([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 Lg([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e.join("\n"))])}Lg([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)}))},Og=e=>{e.command("use <sessionId>").description("Set the current locally selected default session").config({...zm,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 Um({sessionId:t}),Lg([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"updated",session_id:t})])})({cmd:i,sessionId:e})}))},xg=e=>{const t=e.command("session").description("Manage Coze session-based claw chat").config({...zm,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({...zm,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 xm(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({...zm,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 xm(t,(async({ctx:e,service:t})=>{const i=await t.createSession();await Um({clawId:i.clawId,sessionId:i.sessionId}),e.response.print({status:"created",claw_id:i.clawId,session_id:i.sessionId})}))}))})(t),Ug(t),Og(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",Bm,20).config({...zm,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 xm(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({...zm,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({...zm,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 xm(i,(async({ctx:i})=>{const o=await $u({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),zg(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",qm).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(_g).action(yg)})(t),Ig(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({...zm,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 ng({messageId:e,sessionId:t.sessionId},i)}))})(t),Km(t),pg(t),og(t)};function Bg(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)}}))}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 Dg=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},Mg=t=>{if(e.isHttpError(t)&&("object"==typeof(i=t.data)&&null!==i&&("code"in i||"msg"in i||"data"in i)))return t.data;var i;throw t},Ng=e=>{if(null!=e&&!1!==e)return Array.isArray(e)?e.map(String).join(","):String(e)},Gg=(e,t)=>{const i=qg([e,"optionalAccess",e=>e.get,"optionalCall",e=>e(t)]),o=Ng(i);if(o)return o;if("object"!=typeof e||null===e)return;const s=e,n=t.toLowerCase();for(const[e,t]of Object.entries(s))if(e.toLowerCase()===n)return Ng(t)},$g=t=>{return{baseURL:t.baseUrl,transformResponse:[...(i=e.axiosInstance$1.defaults.transformResponse,i?Array.isArray(i)?i:[i]:[]),(e,i)=>{const o=(e=>Gg(e,"x-tt-logid")||Gg(e,"x-tt-log-id")||Gg(e,"logid"))(i);return o&&qg([t,"access",e=>e.onGetLogId,"optionalCall",e=>e(o)]),e}]};var i},Fg=(t,i)=>{if("string"==typeof t&&t.trim())return t.trim();if("number"==typeof t&&Number.isFinite(t))return String(t);throw new e.CozeError(e.ErrorCode.E5002,`Project info response missing ${i}`)},Vg=async(t,i)=>{const o=s.createSessionApiClient({baseUrl:t.baseUrl,webOrigin:t.baseUrl,xTTEnv:t.xTTEnv}),{accountId:n,ownerUid:r}=await(async(e,t)=>{const i=qg([await s.Claw.GetProjectInfo({project_id:t},$g(e)),"access",e=>e.data,"optionalAccess",e=>e.session]);return{accountId:Fg(qg([i,"optionalAccess",e=>e.account_id]),"account_id"),ownerUid:Fg(qg([i,"optionalAccess",e=>e.owner_uid]),"owner_uid")}})(t,i.projectId),a=`${r}_${n}/project_${i.projectId}-files${i.projectFilePath}`,d=await o.getUrl({uris:[a]},{headers:s.getCozeAccountHeaders(t.organizationId),onGetLogId:t.onGetLogId}),l=qg([d,"access",e=>e.data,"optionalAccess",e=>e.urls,"optionalAccess",e=>e[0]]);if(!l)throw new e.CozeError(e.ErrorCode.E5002,d.msg||"Failed to resolve agent file URL");const p=new URL("/api/coze_claw/file/download",s.normalizeBaseUrl(t.baseUrl));p.searchParams.set("file_url",l);const u=c.basename(i.projectFilePath)||"agent-file.bin",_=await $u({url:p.toString(),outputPath:c.join(i.localDir,u)});return _.logid&&qg([t,"access",e=>e.onGetLogId,"optionalCall",e=>e(_.logid)]),{..._,fileUrl:l,projectFilePath:i.projectFilePath,resolvedUri:a}};function Wg(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 Hg={skipOrgCheck:!0,skipSpaceCheck:!0},Jg=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},Kg=e=>Wg([e,"optionalAccess",e=>e.trim,"call",e=>e()])||"/",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},Yg=t=>{if(!t)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");return t.config.sessionApiBaseUrl||t.config.apiBaseUrl},Zg=()=>{let e="";return{capture:t=>{const i=Wg([t,"optionalAccess",e=>e.trim,"call",e=>e()]);i&&(e=i)},get:()=>e}},Xg=(e,t)=>{const i=t.get();return"object"!=typeof(o=e)||null===o||Array.isArray(o)?{data:e,logid:i}:{...e,logid:i};var o};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:"Use Coze agent web tools",description:"Commands for agent-facing web search and fetch APIs.",examples:[{desc:"Search the web",cmd:"coze agent web search --agent-id <id> --query-list '[\"claude code\"]'"},{desc:"Fetch a web page",cmd:"coze agent web fetch --agent-id <id> --url https://example.com --response-length medium"}]},of={brief:"Search the web for a Coze agent as JSON",description:"Calls the agent web search API and outputs the raw API JSON envelope. Requires --agent-id and --query-list.",examples:[{desc:"Search multiple queries",cmd:'coze agent web search --agent-id 123456 --query-list \'["claude code","anthropic api"]\' --project-id 123456'}],schema:{input:{"agent-id":{type:"string",required:!0,description:"The Coze agent ID"},"query-list":{type:"string",required:!0,description:"JSON string array of search queries; empty strings are removed and only the first 5 queries are sent"},"project-id":{type:"string",required:!1,description:"Optional project ID for logging and audit context"}},output:{type:"object",description:"Raw API envelope with code, msg, data, logid fields"}}},sf={brief:"Fetch a web page for a Coze agent as JSON",description:"Calls the agent web fetch API and outputs the raw API JSON envelope. Requires --agent-id and --url.",examples:[{desc:"Fetch a page",cmd:"coze agent web fetch --agent-id 123456 --url https://example.com --response-length medium --project-id 123456"}],schema:{input:{"agent-id":{type:"string",required:!0,description:"The Coze agent ID"},url:{type:"string",required:!0,description:"HTTP or HTTPS URL to fetch"},"response-length":{type:"string",required:!1,description:"Fetch summary length: short, medium, or long"},"project-id":{type:"string",required:!1,description:"Optional project ID for logging and audit context"}},output:{type:"object",description:"Raw API envelope with code, msg, data, logid fields"}}},nf=t=>{const i=ef([t,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!i)throw new e.CozeError(e.ErrorCode.E1000,"The --agent-id option is required.");return i},rf=t=>{const i=t.command("web").description("Use Coze agent web tools").config({...Hg,help:tf});i.command("search").description("Search the web for a Coze agent as JSON").requiredOption("--agent-id <agentId>","The Coze agent ID").requiredOption("--query-list <queryList>","JSON string array of search queries, max 5").option("--project-id <projectId>","Optional project ID for audit context").config({...Hg,help:of}).action((async(t,i)=>{const o=new xo({format:"json"}),n=Zg();try{const r=nf(t.agentId),a=(t=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,"The --query-list option is required and must be a JSON string array.");const i=e.safeJsonParse(t,void 0);if(void 0===i)throw new e.CozeError(e.ErrorCode.E1000,"Invalid --query-list: expected a JSON string array.");if(!Array.isArray(i)||i.some((e=>"string"!=typeof e)))throw new e.CozeError(e.ErrorCode.E1000,"Invalid --query-list: expected a JSON string array.");const o=i.map((e=>e.trim())).filter((e=>e.length>0)).slice(0,5);if(0===o.length)throw new e.CozeError(e.ErrorCode.E1000,"Invalid --query-list: expected at least one non-empty query.");return o})(t.queryList),c=i.getContext(),d=Yg(c),l=await(async(e,t)=>{try{return await s.Claw.AgentWebSearch({agent_id:t.agentId,query_list:t.queryList,project_id:t.projectId},$g(e))}catch(e){return Mg(e)}})({baseUrl:d,onGetLogId:n.capture},{agentId:r,queryList:a,projectId:t.projectId});o.print(Xg(l,n))}catch(e){V(e,i.getContext())}})),i.command("fetch").description("Fetch a web page for a Coze agent as JSON").requiredOption("--agent-id <agentId>","The Coze agent ID").requiredOption("--url <url>","HTTP or HTTPS URL to fetch").option("--response-length <responseLength>","Fetch summary length: short, medium, or long (defaults to medium)").option("--project-id <projectId>","Optional project ID for audit context").config({...Hg,help:sf}).action((async(t,i)=>{const o=new xo({format:"json"}),n=Zg();try{const r=nf(t.agentId),a=(t=>{const i=ef([t,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!i)throw new e.CozeError(e.ErrorCode.E1000,"The --url option is required.");let o;try{o=new URL(i)}catch(t){throw new e.CozeError(e.ErrorCode.E1000,"Invalid --url: expected an http:// or https:// URL.",{reason:t instanceof Error?t.message:String(t)})}if("http:"!==o.protocol&&"https:"!==o.protocol)throw new e.CozeError(e.ErrorCode.E1000,"Invalid --url: expected an http:// or https:// URL.");return i})(t.url),c=(t=>{if(!t)return"medium";if("short"===t||"medium"===t||"long"===t)return t;throw new e.CozeError(e.ErrorCode.E1000,"Invalid --response-length: expected short, medium, or long.")})(t.responseLength),d=i.getContext(),l=Yg(d),p=await(async(e,t)=>{try{return await s.Claw.AgentWebFetch({agent_id:t.agentId,url:t.url,response_length:t.responseLength,project_id:t.projectId},$g(e))}catch(e){return Mg(e)}})({baseUrl:l,onGetLogId:n.capture},{agentId:r,url:a,responseLength:c,projectId:t.projectId});o.print(Xg(p,n))}catch(e){V(e,i.getContext())}}))},af={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>"}]},cf={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"}}},df=e=>{e.command("message").description("Manage Coze agent messages").config({...Hg,help:af}).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({...Hg,help:cf}).action((async(e,t)=>{const i=new xo({format:"json"});try{const o=Jg(e.projectId),n=e.size?Qg(e.size,"--size"):void 0,r=t.getContext(),a=Yg(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),Dg(await s.Claw.ListMessage(i,$g(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())}}))},lf=e=>{e.command("member").description("Manage Coze agent members").config({...Hg,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({...Hg,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 xo({format:"json"});try{const o=Jg(e.projectId),n=t.getContext(),r=Yg(n),a=await(async(e,t)=>Dg(await s.Claw.GetProjectMembers({project_id:t.projectId},$g(e))))({baseUrl:r},{projectId:o});i.print(a)}catch(e){V(e,t.getContext())}}))},pf=e=>{e.command("info").description("Get raw Coze agent info as JSON").requiredOption("--project-id <projectId>","The agent project ID").config({...Hg,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 xo({format:"json"});try{const o=Jg(e.projectId),n=t.getContext(),r=Yg(n),a=await(async(e,t)=>Dg(await s.Claw.GetProjectInfo({project_id:t.projectId},$g(e))))({baseUrl:r},{projectId:o});i.print(a)}catch(e){V(e,t.getContext())}}))};function uf(e,t){return null!=e?e:t()}function _f(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 hf=t=>{if(t instanceof e.CozeError)return uf(t.desc,(()=>t.message));if(t instanceof Error)return t.message;if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return String(t)}},mf=(e,t,i)=>{t.print({ok:!1,err_reason:hf(e),logid:uf(_f([i,"optionalAccess",e=>e.get,"call",e=>e()]),(()=>""))}),process.exitCode=1};function gf(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 ff={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, project_file_path, and logid fields"}}},yf=(e,t)=>{const i=gf([e,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!i||"/"===i)return`/${t}`;return`${(i.startsWith("/")?i:`/${i}`).replace(/\/+$/,"")}/${t}`},vf=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({...Hg,help:ff}).action((async(t,i)=>{const o=new xo({format:"json"}),n=Zg();try{const d=Jg(t.projectId),p=((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})`:""}`)}})(p);const _=i.getContext(),h=Yg(_),m=c.basename(p),g=Kg(t.projectDir);await(async(e,t)=>{return Dg(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())},{onGetLogId:e.onGetLogId}));var i,o})({baseUrl:h,xTTEnv:gf([_,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv]),onGetLogId:n.capture},{projectId:d,fileName:m,fileContent:await l.openAsBlob(p),projectDir:g,clawId:(r=t.clawId,a=()=>"",null!=r?r:a())}),o.print(Xg({ok:!0,project_file_path:yf(g,m)},n))}catch(e){mf(e,o,n)}var r,a}))};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}const bf={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, local_file_path, and logid fields"}}},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({...Hg,help:bf}).action((async(t,i)=>{const o=new xo({format:"json"}),s=Zg();try{const n=Jg(t.projectId),r=((t,i)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${i}`);return t})(t.projectFilePath,"--project-file-path"),a=i.getContext(),c=wf([a,"optionalAccess",e=>e.cwd])||process.cwd(),d=await Vg({baseUrl:Yg(a),organizationId:wf([a,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),xTTEnv:wf([a,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv]),onGetLogId:s.capture},{projectId:n,projectFilePath:r,localDir:c});o.print(Xg({ok:!0,local_file_path:d.path},s))}catch(e){mf(e,o,s)}}))};function Pf(e,t){return null!=e?e:t()}function Cf(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:"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"}]},Ef={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, files, and logid fields"}}},If={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, logid fields"}}},kf={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, content, and logid fields"}}},Af={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, logid fields"}}},jf=(t,i)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${i}`);return t},Rf=e=>e.startsWith("/")?e:`/${e}`,zf=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({...Hg,help:Ef}).action((async(e,t)=>{const i=new xo({format:"json"}),o=Zg();try{const n=Jg(e.projectId),r=e.depth?Qg(e.depth,"--depth"):void 0,a=t.getContext(),c=Yg(a),d=Kg(e.projectDir),l=await(async(e,t)=>Dg(await s.Claw.ListProjectFiles({project_id:t.projectId,file_path:t.filePath,depth:t.depth},$g(e))))({baseUrl:c,onGetLogId:o.capture},{projectId:n,filePath:d,depth:r});i.print(Xg((e=>({ok:!0,files:Pf(Cf([e,"access",e=>e.data,"optionalAccess",e=>e.files]),(()=>[])).map((e=>({path:Rf(e.file_path||e.name||""),type:e.is_dir?"dir":"file"})))}))(l),o))}catch(e){mf(e,i,o)}}))},Lf=e=>{e.command("write").description("Write content to 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("--content <content>","File content to write (utf-8)").config({...Hg,help:If}).action((async(e,t)=>{const i=new xo({format:"json"}),o=Zg();try{const n=Jg(e.projectId),r=jf(e.projectFilePath,"--project-file-path"),a=jf(e.content,"--content"),c=t.getContext(),d=Yg(c),l=await(async(e,t)=>Dg(await s.Claw.WriteProjectFile({project_id:t.projectId,file_path:t.filePath,content:t.content},$g(e))))({baseUrl:d,onGetLogId:o.capture},{projectId:n,filePath:r,content:a});i.print(Xg(l,o))}catch(e){mf(e,i,o)}}))},Uf=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({...Hg,help:kf}).action((async(e,t)=>{const i=new xo({format:"json"}),o=Zg();try{const n=Jg(e.projectId),r=jf(e.projectFilePath,"--project-file-path"),a=e.offset?Qg(e.offset,"--offset"):void 0,c=e.limit?Qg(e.limit,"--limit"):void 0,d=t.getContext(),l=Yg(d),p=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),Dg(await s.Claw.ReadProjectFile(i,$g(e)))})({baseUrl:l,onGetLogId:o.capture},{projectId:n,filePath:r,offset:a,limit:c});i.print(Xg({ok:!0,project_file_path:r,content:Pf(Cf([p,"access",e=>e.data,"optionalAccess",e=>e.content]),(()=>""))},o))}catch(e){mf(e,i,o)}}))},Of=e=>{e.command("edit").description("Edit 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("--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({...Hg,help:Af}).action((async(e,t)=>{const i=new xo({format:"json"}),o=Zg();try{const n=Jg(e.projectId),r=jf(e.projectFilePath,"--project-file-path"),a=jf(e.mode,"--mode"),c=t.getContext(),d=Yg(c),l=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),Dg(await s.Claw.EditProjectFile(i,$g(e)))})({baseUrl:d,onGetLogId:o.capture},{projectId:n,filePath:r,mode:a,oldString:e.oldString,newString:e.newString,appendContent:e.appendContent});i.print(Xg(l,o))}catch(e){mf(e,i,o)}}))},xf=e=>{const t=e.command("agent").description("Agent-facing Coze APIs backed by Claw project endpoints").config({...Hg,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"},{desc:"Search the web",cmd:"coze agent web search --agent-id <id> --query-list '[\"claude code\"]'"},{desc:"Fetch a web page",cmd:"coze agent web fetch --agent-id <id> --url https://example.com --response-length medium"}]}});pf(t),lf(t),df(t),(e=>{const t=e.command("file").description("Manage Coze agent project files").config({...Hg,help:Tf});zf(t),Lf(t),Uf(t),Of(t),vf(t),Sf(t)})(t),rf(t)};function Bf(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),xg(t),cc(t),Du(t),Va(t),yr(t),br(t),$a(t),Qa(t),Bg(t),xf(t),dc()}function qf(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 Df(e,t){return null!=e?e:t()}function Mf(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 Nf(e){const t=[];let i=e;for(;i;)i.name()&&t.unshift(i.name()),i=i.parent;return t.join(" ")}function Gf(e){return e._args.map((e=>e.required?`<${e.name()}>`:`[${e.name()}]`)).join(" ")}const $f=new Set(["--version","--format","--no-color","--config","--org-id","--space-id","--verbose","--debug","--log-file","--man","--schema","--commands"]);function Ff(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)||$f.has(e)||t.set(e,i)}return Array.from(t.values())}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}class Wf extends b.Command{__init(){this.middlewares=[]}constructor(e){super(e),Wf.prototype.__init.call(this),this.helpInformation=()=>{const e=process.argv.slice(2);if(e.includes("--schema"))return`${JSON.stringify(Vf([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=Mf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=Nf(e);let o=`@MAN ${i}\n\n`;o+=`NAME\n ${i} — ${Mf([t,"optionalAccess",e=>e.brief])||e.description()}\n\n`,o+=`SYNOPSIS\n ${i} ${Gf(e)}\n`,Ff(e).forEach((e=>{o+=` [${e.flags}]\n`})),o+="\n",Mf([t,"optionalAccess",e=>e.description])&&(o+=`DESCRIPTION\n ${t.description.replace(/\n/g,"\n ")}\n\n`);const s=Ff(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`}))),Mf([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"),Mf([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"),Mf([t,"optionalAccess",e=>e.caveats])&&t.caveats.length>0&&(o+="CAVEATS\n",t.caveats.forEach((e=>{o+=` - ${e}\n`})),o+="\n"),Mf([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=Mf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=Nf(e);let o=`@HELP ${i}\n\n`;return Mf([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: ${Nf(e.parent)}\n\n`),o+=`SYNTAX:\n ${i} ${Gf(e)} [options]\n\n`,Mf([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`})),Ff(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",Mf([t,"optionalAccess",e=>e.enums])&&(o+="ENUMS:\n",Object.keys(t.enums).forEach((e=>{o+=` --${e}:\n`;const i=Df(Mf([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})));Object.keys(i).forEach((e=>{o+=` ${e.padEnd(12)} ${i[e]}\n`}))})),o+="\n"),Mf([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`}))),Mf([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"),Mf([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=Mf([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=Nf(e);let o=`@USAGE ${i}\n\n`;Mf([t,"optionalAccess",e=>e.brief])?o+=`BRIEF: ${t.brief}\n\n`:o+=`BRIEF: ${e.description()||"No description provided."}\n\n`,o+=`SYNTAX:\n ${i} ${Gf(e)} [options]\n\n`,e.commands.length>0&&(o+="ACTIONS:\n",e.commands.forEach((e=>{const t=e;if(!t._hidden){const e=Mf([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"),Mf([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(Mf([t,"optionalAccess",e=>e.enums])){const e=Object.keys(t.enums).filter((e=>Object.keys(Df(Mf([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})))).length<=7));e.length>0&&(o+="ENUMS:\n",e.forEach((e=>{const i=Object.keys(Df(Mf([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 Wf(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 Wf&&(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=Vf([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 Hf(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 Kf(t){const i=new Wf;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"}]}}),Bf(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=qf([s,"access",e=>e.getConfig,"optionalCall",e=>e()]),o=qf([t,"access",e=>e.getConfig,"optionalCall",e=>e()]);t.setConfig({...i,...o}),e(t)})))}(e)}(i,[qo,_r],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=Hf([a,"access",e=>e.getConfig,"optionalCall",e=>e()]),d=Hf([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=Bo(e.cwd,(()=>process.cwd())),i=Bo(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 Oo(r,s,a),d=new xo({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 yo(l),l}({argv:e,config:await s.loadConfig(t.config),globalOptions:t});!function(e){It=e.log,kt=!0===Pt([e,"access",e=>e.globalOptions,"optionalAccess",e=>e.debug]),kt&&(At||(Ht(),Jt(),At=!0))}(i);const o=ci([vt,ti,ai,Y]);await o(i,(async()=>{await Kf(i)}))})().catch((e=>{V(e,void 0),process.exitCode=1}));