@coze/cli 0.3.2-alpha.77ac1a → 0.3.3-alpha.b7c03e

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-CgQGE-CR.js"),t=require("./index-JxWKC7px.js"),o=require("chalk"),i=require("node:child_process"),s=require("./task-worker-BJO9Ixaq.js"),n=require("node:path"),r=require("node:fs/promises"),a=require("node:fs"),c=require("node:crypto"),l=require("node:http"),d=require("node:https"),p=require("node:buffer"),u=require("undici"),m=require("path"),g=require("fs/promises"),h=require("fs"),f=require("form-data"),_=require("omelette"),y=require("node:os"),b=require("child_process"),v=require("lodash"),w=require("commander"),E=require("ws");function C(e){const t=Object.create(null);if(e)for(const o in e)if("default"!==o){const i=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,i.get?i:{enumerable:!0,get:function(){return e[o]}})}return t.default=e,Object.freeze(t)}require("crypto"),require("url"),require("https-proxy-agent"),require("http"),require("https"),require("http2"),require("util"),require("stream"),require("assert"),require("tty"),require("zlib"),require("events"),require("mitt"),require("process");const I=C(n),A=C(r);function S(e,t){return null!=e?e:t()}class k{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))},o=JSON.stringify(t,null,2);return o.endsWith("\n")?o:`${o}\n`}}function j(e,t){return null!=e?e:t()}function P(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function z(e){const t=String.fromCharCode(27),o=new RegExp(`${t}(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])`,"g");return e.replace(o,"")}function T(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 R(e){const t=z(e);if(!t)return 0;const o=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/u;let i=0;const s=Array.from(t);for(let e=0;e<s.length;e+=1){const t=j(s[e],(()=>""));if(o.test(t))continue;const n=t.codePointAt(0);void 0!==n&&(i+=T(n)?2:1)}return i}function x(e,t){const o=R(e);return o>=t?e:`${e}${" ".repeat(t-o)}`}function L(e,t){if(t<=0)return"";if(R(e)<=t)return e;if(1===t)return"…";const o=z(e),i=Array.from(o),s=Math.max(0,t-R("…"));let n="",r=0;for(let e=0;e<i.length;e+=1){const t=j(i[e],(()=>"")),o=R(t);if(r+o>s)break;n+=t,r+=o}return`${n}…`}function O(e,t={}){if(0===e.length)return"";const o=function(e,t){if(0===e.length)return[];const o=new Set,i=[],s=j(e[0],(()=>({})));for(const e of Object.keys(s))o.has(e)||(o.add(e),i.push(e));for(const t of e)for(const e of Object.keys(t))o.has(e)||(o.add(e),i.push(e));const n=[];for(const t of i){let o=R(t);for(const i of e){const e=i[t],s=void 0===e?"":String(e);o=Math.max(o,R(s))}n.push({key:t,width:o})}const r=j(t.columnGap,(()=>2)),a=j(j(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),c=Math.max(1,Math.floor((a+r)/(6+r))),l=Math.min(j(t.maxColumns,(()=>c)),c);n.length>l&&n.splice(l);const d=Math.max(0,a-r*Math.max(0,n.length-1));for(;n.reduce(((e,t)=>e+t.width),0)>d;){let e=-1,t=-1;for(let o=0;o<n.length;o+=1){const i=j(P([n,"access",e=>e[o],"optionalAccess",e=>e.width]),(()=>0));i>t&&(t=i,e=o)}if(-1===e)break;const o=j(P([n,"access",t=>t[e],"optionalAccess",e=>e.width]),(()=>0));if(o<=6)break;n[e]={...n[e],width:o-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===o.length)return"";const i=j(t.columnGap,(()=>2)),s=" ".repeat(i),n=o.map((e=>x(L(e.key,e.width),e.width))).join(s),r=o.map((e=>"-".repeat(e.width))).join(s),a=[];for(const t of e){const e=o.map((e=>{const o=t[e.key];return x(L(void 0===o?"":String(o),e.width),e.width)}));a.push(e.join(s))}return`${[n,r,...a].join("\n")}\n`}function D(e,t={}){const o=Object.entries(e);if(0===o.length)return"";let i=0;for(const[e]of o)i=Math.max(i,R(e));const s=j(j(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),n=j(t.columnGap,(()=>2)),r=j(t.minValueWidth,(()=>12));let a=Math.min(i,j(t.keyMaxWidth,(()=>32)));const c=Math.max(6,s-n-r);a=Math.min(a,c);const l=Math.max(0,s-a-n),d=" ".repeat(n);return`${o.map((([e,t])=>{const o=x(L(e,a),a),i=(void 0===t?"undefined":null===t?"null":String(t)).replace(/\s*\n\s*/g," "),s=l>0?L(i,l):"";return`${o}${d}${s}`})).join("\n")}\n`}function U(e,t="",o=0){const i={};if(null==e)return i;if("object"!=typeof(s=e)||null===s||Array.isArray(s))return i;var s;for(const[s,n]of Object.entries(e)){const e=t?`${t}.${s}`:s;if(null!=n)if(Array.isArray(n))o>=5?i[e]="[Array]":0===n.length?i[e]="[]":n.every((e=>"object"!=typeof e||null===e))?i[e]=n.map((e=>{return String((o=()=>"null",null!=(t=e)?t:o()));var t,o})).join(", "):i[e]="[Array]";else if("object"!=typeof n)i[e]=n;else if(o>=5)i[e]="[Object]";else{const t=U(n,e,o+1);Object.assign(i,t)}else i[e]=n}return i}function q(e,t){return null!=e?e:t()}function B(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class M{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(B)){return O(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(q(e,(()=>"null"))))).join("\n")}\n`:"[Array]\n"}var t;if(B(e)){const t=U(e);return 0===Object.keys(t).length?"{}\n":D(t)}return`${String(e)}\n`}formatError(e){const t=[],o=q(e.errorName,(()=>"UNKNOWN_ERROR")),i=q(e.desc,(()=>e.message));return t.push(`ERROR [${e.code}] ${o}: ${i}`),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?D(U(e)):String(e))).map((e=>`${t}- ${e.trim()}`)).join("\n")}\n`;if(B(e)){const o=U(e);return 0===Object.keys(o).length?"":`${D(o).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 N(e,t){return null!=e?e:t()}function $(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function G(e,t){if(null==e)return;const o=String(e).replace(/\s*\n\s*/g," ").replace(/\s+/g," ").trim();return o?o.length<=t?o:`${o.slice(0,Math.max(0,t-3))}...`:void 0}function F(e){const t=$([e,"optionalAccess",e=>e.help,"optionalAccess",e=>e.errors]);if(t&&t.length>0)return t;const o=$([e,"optionalAccess",e=>e.errors]);return Array.isArray(o)?o:void 0}function V(t,o){const i=N(t.trigger,(()=>function(e){if(!e||0===e.length)return;return G(("coze"===e[0]?e:["coze",...e]).join(" "),150)}($([o,"optionalAccess",e=>e.argv])))),s=$([F,"call",e=>e($([o,"optionalAccess",e=>e.commandConfig])),"optionalAccess",e=>e.find,"call",e=>e((e=>e.code===t.code))]),n=N($([s,"optionalAccess",e=>e.name]),(()=>e.ErrorNameByCode[t.code])),r=N(G(n,80),(()=>"UNKNOWN_ERROR"));let a=n;t.isMessageExplicit&&t.message.trim()?a=t.message:$([s,"optionalAccess",e=>e.desc])&&(a=s.desc);const c=N(G(a,200),(()=>"An unexpected error occurred")),l=N(G(t.fix,150),(()=>G($([s,"optionalAccess",e=>e.fix]),150))),d=N(G(t.example,150),(()=>G($([s,"optionalAccess",e=>e.example]),150)));return{code:t.code,errorName:r,desc:c,trigger:i,fix:l,example:d}}function W(e,t){const o=V(e,t);return e.errorName=o.errorName,e.desc=o.desc,e.message=o.desc,e.trigger=o.trigger,e.fix=o.fix,e.example=o.example,e}function H(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}var J;function K(o,i,s,n){if(o instanceof e.CozeError)throw o;if(e.isHttpError(o)){const e=H([o,"access",e=>e.response,"optionalAccess",e=>e.status]);if("ECONNREFUSED"===o.code||"ETIMEDOUT"===o.code||"number"==typeof e&&e>=500)throw o}if(o instanceof t.ChatCoreError&&"number"==typeof H([o,"access",e=>e.ext,"optionalAccess",e=>e.code])&&o.ext.code>=500)throw o;throw new e.CozeError(i,s,{...n,cause:o instanceof Error?o.message:String(o)})}!function(e){e[e.NOT_LOGIN=700012006]="NOT_LOGIN"}(J||(J={}));const Q=(o,i)=>{const s=W(function(o){if(o instanceof e.CozeError)return o;if(o instanceof t.ChatCoreError){const{ext:t}=o;let i=e.ErrorCode.E5000;"number"==typeof t.code&&(t.code===J.NOT_LOGIN?i=e.ErrorCode.E2001:t.code>=500&&(i=e.ErrorCode.E5002));const{message:s}=o;return new e.CozeError(i,s,t)}if(e.isHttpError(o)){const t=o.toJSON();let i=e.ErrorCode.E5000;const s=H([o,"access",e=>e.response,"optionalAccess",e=>e.status]);o.code===J.NOT_LOGIN||401===s?i=e.ErrorCode.E2001:"ECONNREFUSED"===o.code||"ETIMEDOUT"===o.code?i=e.ErrorCode.E5001:403===s?i=e.ErrorCode.E2003:404===s?i=e.ErrorCode.E3000:429===s?i=e.ErrorCode.E4001:s&&s>=500&&(i=e.ErrorCode.E5002);const n=H([o,"access",e=>e.response,"optionalAccess",e=>e.headers,"optionalAccess",e=>e["x-tt-logid"]]),{message:r}=o;return new e.CozeError(i,r,{logId:n,...t})}return o instanceof Error?new e.CozeError(e.ErrorCode.E5000,o.message,o.stack):"string"==typeof o?new e.CozeError(e.ErrorCode.E5000,o):new e.CozeError(e.ErrorCode.E5000,"An unexpected error occurred")}(o),i?{argv:i.argv,commandConfig:i.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`),i)i.response.eprint(s);else{const e=new M;process.stderr.write(e.formatError(s))}process.exit(e.exitCodeForError(s.code))};const Y="@coze/cli",Z="0.3.2-alpha.77ac1a",X=Y;function ee(){const e=[{pm:"npm",cmd:`npm ls -g ${X} --json 2>/dev/null`},{pm:"pnpm",cmd:`pnpm ls -g ${X} --json 2>/dev/null`},{pm:"yarn",cmd:"yarn global list --json 2>/dev/null"}];for(const{pm:t,cmd:o}of e)try{if(i.execSync(o,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).includes(X))return t}catch(e){}return"npm"}function te(e,t){return null!=e?e:t()}function oe(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ie=Y,se=6e5;function ne(){return Z}function re(e){const t=e.trim().replace(/^v/,"").split("+")[0],o=t.indexOf("-"),i=-1===o?t:t.slice(0,o),s=-1===o?"":t.slice(o+1),n=i.split(".");return{major:parseInt(n[0]||"0",10),minor:parseInt(n[1]||"0",10),patch:parseInt(n[2]||"0",10),prerelease:""===s?[]:s.split(".")}}function ae(e,t){const o=/^\d+$/.test(e),i=/^\d+$/.test(t);if(o&&i){const o=parseInt(e,10)-parseInt(t,10);return 0===o?0:o>0?1:-1}return o?-1:i?1:e===t?0:e>t?1:-1}function ce(e,t){const o=re(e),i=re(t);return o.major!==i.major?o.major>i.major?1:-1:o.minor!==i.minor?o.minor>i.minor?1:-1:o.patch!==i.patch?o.patch>i.patch?1:-1:function(e,t){if(0===e.length&&0===t.length)return 0;if(0===e.length)return 1;if(0===t.length)return-1;const o=Math.max(e.length,t.length);for(let i=0;i<o;i++){const o=e[i],s=t[i];if(void 0===o)return-1;if(void 0===s)return 1;const n=ae(o,s);if(0!==n)return n}return 0}(o.prerelease,i.prerelease)}function le(e,t){return ce(t,e)>0}function de(e,t){return re(t).major>re(e).major}function pe(){if(process.env.COZE_CLI_NO_UPDATE_NOTIFIER)return!0;const e=te(process.env.CI,(()=>"")).toLowerCase();return""!==e&&"false"!==e&&"0"!==e||function(e){return!e||"0.0.0"===e||/dev/i.test(e)}(ne())}function ue(e){const t=oe([e,"access",e=>e.upgrade,"optionalAccess",e=>e.mode]);return"auto"===t||"notify"===t||"off"===t?t:"auto"}function me(e){return oe([e,"access",e=>e.upgrade,"optionalAccess",e=>e.channel])||"latest"}async function ge(t,o=!1,n="latest"){const r=ne(),{config:a}=t,c=oe([a,"access",e=>e.upgrade,"optionalAccess",e=>e.cache]);if(!o&&oe([c,"optionalAccess",e=>e.latestVersion])&&c.checkedAt&&Date.now()-c.checkedAt<144e5&&te(c.channel,(()=>"latest"))===n)return{currentVersion:r,latestVersion:c.latestVersion,hasUpdate:le(r,c.latestVersion)};const l=function(){try{return i.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,o="latest"){const i=`${t}/${ie}/${o}`,s=await e.customFetch.fetch(i,{headers:{accept:"application/json"}});if(!s.ok)throw new Error(`Failed to fetch latest version: ${s.status} ${s.statusText}`);return(await s.json()).version}(l,n);return await s.saveConfig({upgrade:{cache:{latestVersion:d,checkedAt:Date.now(),channel:n}}},a.configScope),{currentVersion:r,latestVersion:d,hasUpdate:le(r,d)}}async function he(e,t){const o=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([e,"access",e=>e.config,"access",e=>e.upgrade,"optionalAccess",e=>e.cache,"optionalAccess",e=>e.lastAttempt]);if(o&&Date.now()-o<se)return;try{await s.saveConfig({upgrade:{cache:{lastAttempt:Date.now()}}},e.config.configScope)}catch(e){}const n=ee(),{command:r,args:a}=function(e,t){const o=`${X}@${t}`;switch(e){case"pnpm":return{command:"pnpm",args:["add","-g",o]};case"yarn":return{command:"yarn",args:["global","add",o]};default:return{command:"npm",args:["install","-g",o]}}}(n,t);try{i.spawn(r,a,{detached:!0,stdio:"ignore",shell:"win32"===process.platform}).unref()}catch(e){}}function fe(e,t){return null!=e?e:t()}function _e(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ye={claude:"claude-code"};let be=null;function ve(){if(be)return be;const t=function(){let e=__dirname;for(let t=0;t<12;t++){const t=n.join(e,"node_modules","skills","package.json");if(a.existsSync(t))return n.dirname(t);const o=n.dirname(e);if(o===e)break;e=o}}();if(t){const o=e.safeJsonParse(a.readFileSync(n.join(t,"package.json"),"utf8")),i="string"==typeof _e([o,"optionalAccess",e=>e.bin])?o.bin:_e([o,"optionalAccess",e=>e.bin,"optionalAccess",e=>e.skills]);if(i)return be={cmd:process.execPath,prefix:[n.join(t,i)]},be}return be={cmd:"skills",prefix:[]},be}function we(e){const{cmd:t,prefix:o}=ve(),s=i.spawnSync(t,[...o,...e],{encoding:"utf8"});return{ok:0===s.status,stdout:fe(s.stdout,(()=>"")),stderr:fe(s.stderr,(()=>"")),code:s.status}}function Ee(e,t={}){const o=["add",e];return t.global&&o.push("-g"),t.yes&&o.push("-y"),t.agents&&t.agents.length>0&&o.push("-a",...t.agents),we(o)}function Ce(e,t={}){const o=["remove",e];return t.global&&o.push("-g"),o.push("-y"),we(o)}function Ie(t={}){const o=["ls","--json"];t.global&&o.push("-g");const i=we(o);if(!i.ok)return[];const s=e.safeJsonParse(i.stdout);return Array.isArray(s)?s:[]}function Ae(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Se(){return s.getGlobalSkillLockFile()}async function ke(e){try{return await r.access(e),!0}catch(e){return!1}}async function je(){let t=__dirname;for(let o=0;o<12;o++){const o=n.join(t,"package.json");if(await ke(o)){if("@coze/cli"===Ae([e.safeJsonParse(await r.readFile(o,"utf8")),"optionalAccess",e=>e.name]))return t}const i=n.dirname(t);if(i===t)break;t=i}return n.resolve(__dirname,"..")}async function Pe(){return n.join(await je(),"skills")}async function ze(){return n.join(await je(),"docs","skills")}const Te=new Set(["SKILL.md","MODULE.md"]);function Re(e){return`sha256:${c.createHash("sha256").update(e,"utf8").digest("hex")}`}function xe(e){return Te.has(n.basename(e))}async function Le(e,t=e){const o=await r.readdir(e,{withFileTypes:!0}),i=[];for(const s of o){if(s.name.startsWith("."))continue;const o=n.join(e,s.name);s.isDirectory()?i.push(...await Le(o,t)):s.isFile()&&i.push(n.relative(t,o).split(n.sep).join("/"))}return i.sort()}function Oe(e,t){const o=Ue(e);if(void 0===o)return;const i=new RegExp(`^${t}:\\s*(.+?)\\s*$`,"m"),s=o.match(i);return s?s[1].replace(/^['"]|['"]$/g,"").trim():void 0}function De(e,t){const o=Ue(e);if(void 0===o)return e;const i=`version: ${t}`;let s;return s=/^version:\s*.+$/m.test(o)?o.replace(/^version:\s*.+$/m,i):/^name:\s*.+$/m.test(o)?o.replace(/^(name:\s*.+)$/m,`$1\n${i}`):`${i}\n${o}`,e.replace(o,s)}function Ue(e){if(!e.startsWith("---"))return;const t=e.match(/^---\n([\s\S]*?)\n---/);return t?t[1]:void 0}function qe(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function Be(){const e=await Pe();if(await ke(n.join(e,"manifest.json")))return{root:e,source:"bundled"};const t=await ze();if(await ke(t))return{root:t,source:"docs"};throw new Error(`未找到 skill 来源:既无包内 ${e}/manifest.json,也无开发态 ${t}。`)}async function Me(){const t=n.join(await je(),"package.json"),o=e.safeJsonParse(await r.readFile(t,"utf8"));return i=qe([o,"optionalAccess",e=>e.version]),s=()=>"0.0.0",null!=i?i:s();var i,s}async function Ne(){const t=await Pe(),o=n.join(t,"manifest.json");if(await ke(o)){const i=e.safeJsonParse(await r.readFile(o,"utf8")),s=(await Le(t)).filter((e=>"manifest.json"!==e)),a=[];for(const e of s)a.push({rel:e,content:await r.readFile(n.join(t,e),"utf8")});return{manifest:i,files:a,source:"bundled"}}const i=await ze();if(!await ke(i))throw new Error(`未找到 skill 来源:既无包内 ${o},也无开发态 ${i}。`);const s=await Me(),{manifest:a,files:c}=await async function(e,t){const o=await Le(e),i=[],s={};for(const l of o){const o=await r.readFile(n.join(e,l),"utf8"),d=xe(l),p=d?De(o,t):o;i.push({rel:l,content:p}),d&&(s[(a=Oe(p,"name"),c=()=>l,null!=a?a:c())]={path:l,hash:Re(p)})}var a,c;return{manifest:{cliVersion:t,skills:s},files:i}}(i,s);return{manifest:a,files:c,source:"docs"}}async function $e(){try{const t=await r.readFile(Se(),"utf8");return e.safeJsonParse(t)}catch(e){return}}function Ge(e,t){return null!=e?e:t()}function Fe(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function Ve(e){try{return Re(await r.readFile(e,"utf8"))}catch(e){return}}function We(e){return[...new Set(Object.values(e.skills).map((e=>e.path.split("/")[0])))]}function He(e){return e[0]?n.dirname(e[0].path):void 0}async function Je(e={}){const{manifest:t}=await Ne(),{root:o}=await Be(),i=We(t),s=await $e(),a=Ie({global:!0}),c=await async function(e,t,o){const i=He(t);if(!i)return[];const s=new Set(t.map((e=>e.name))),r=[];for(const[t,a]of Object.entries(e.skills)){const e=a.path.split("/")[0];if(!s.has(e))continue;const c=await Ve(n.join(i,a.path));if(void 0===c)continue;if(c===a.hash)continue;const l=Fe([o,"optionalAccess",e=>e.skills,"access",e=>e[t],"optionalAccess",e=>e.hash]);void 0!==l&&c===l||r.push(t)}return r}(t,a,s);if(c.length>0&&!e.force)return{blocked:!0,cliVersion:t.cliVersion,sourceRoot:o,linkedTargets:[],skillsOk:!1,unknownTargets:[],modifiedSkills:c};const l=e.targets&&e.targets.length>0&&!e.targets.includes("all")?Ge(e.targets,(()=>[])).map((e=>fe(ye[e],(()=>e)))):void 0;let d=!0;for(const e of i){Ee(n.join(o,e),{global:!0,yes:!0,agents:l}).ok||(d=!1)}const p=Ie({global:!0}),u=p.filter((e=>i.includes(e.name))),m=Fe([u,"access",e=>e[0],"optionalAccess",e=>e.path]),g=[...new Set(u.flatMap((e=>e.agents)))],h=(new Date).toISOString(),f=He(p),_={};for(const[e,o]of Object.entries(t.skills)){const t=f?await Ve(n.join(f,o.path)):void 0;_[e]={hash:Ge(t,(()=>o.hash)),expectedHash:o.hash,installedAt:h}}return await async function(e){const t=Se();await r.mkdir(n.dirname(t),{recursive:!0}),await r.writeFile(t,`${JSON.stringify(e,null,2)}\n`,"utf8")}({version:1,cliVersion:t.cliVersion,installedBin:Ge(process.argv[1],(()=>process.execPath)),poolPath:m,targets:g,skills:_}),{blocked:!1,cliVersion:t.cliVersion,sourceRoot:o,poolPath:m,linkedTargets:g,skillsOk:d,unknownTargets:[],modifiedSkills:[]}}function Ke(e,t,o){return void 0===e?"missing":e===t?"ok":o===e?"drift":"modified"}async function Qe(){const{manifest:e}=await Ne(),t=await $e(),o=Ge(process.argv[1],(()=>process.execPath)),i=Ie({global:!0}),s=He(i),r=new Set(i.map((e=>e.name))),a=[];for(const[o,i]of Object.entries(e.skills)){const e=i.path.split("/")[0],c=Boolean(s)&&r.has(e),l=c?await Ve(n.join(s,i.path)):void 0,d=c?Ke(l,i.hash,Fe([t,"optionalAccess",e=>e.skills,"access",e=>e[o],"optionalAccess",e=>e.hash])):"missing";a.push({name:o,path:i.path,state:d})}const c=Fe([i,"access",e=>e.find,"call",e=>e((e=>r.has(e.name))),"optionalAccess",e=>e.path]);return{lockExists:Boolean(t),cliVersion:e.cliVersion,installedVersion:Fe([t,"optionalAccess",e=>e.cliVersion]),versionMatch:Boolean(t)&&Fe([t,"optionalAccess",e=>e.cliVersion])===e.cliVersion,installedBin:Fe([t,"optionalAccess",e=>e.installedBin]),currentBin:o,binMatch:!Fe([t,"optionalAccess",e=>e.installedBin])||t.installedBin===o,poolPath:c,targets:Ge(Fe([t,"optionalAccess",e=>e.targets]),(()=>[])),skills:a}}async function Ye(){const{manifest:e}=await Ne(),t=We(e),o=Ie({global:!0}),i=[];for(const e of t){const t=o.find((t=>t.name===e));if(!t)continue;Ce(e,{global:!0}).ok&&i.push({name:e,agents:t.agents})}return await async function(){await r.rm(Se(),{force:!0})}(),{removed:i}}async function Ze(){const t=await async function(){const t=n.join(await Pe(),"manifest.json");if(await ke(t)){const o=e.safeJsonParse(await r.readFile(t,"utf8"));if(qe([o,"optionalAccess",e=>e.cliVersion]))return o.cliVersion}return Me()}(),o=await $e();return o?o.cliVersion!==t?{state:"mismatch",cliVersion:t,installedVersion:o.cliVersion,message:`Skills (${o.cliVersion}) are out of sync with CLI (${t}). Run \`coze self skill install\`.`}:{state:"ok",cliVersion:t,installedVersion:o.cliVersion}:{state:"missing",cliVersion:t,message:"Bundled skills not installed yet. Run `coze self skill install` to sync them to your AI tools."}}function Xe(e){const t={};let o;const i=[];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("-")?i.push(r):(o=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 o=e[++n];"json"!==o&&"text"!==o||(t.format=o)}else t.output=e[++n];else t.version=!0;else t.help=!0}return{globalOptions:t,commandName:o,commandArgs:i}}function et(e,t){return null!=e?e:t()}function ot(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function it(e,t){const i=await async function(e){if("self"===Xe(e.argv).commandName)return;const t=function(e){const t=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([e,"access",e=>e.skill,"optionalAccess",e=>e.mode]);return"auto"===t||"notify"===t||"off"===t?t:"auto"}(e.config);if("off"===t)return;if(function(){const e=et(process.env.CI,(()=>"")).toLowerCase();return""!==e&&"false"!==e&&"0"!==e||Boolean(process.env.COZE_CLI_NO_SKILL_NOTIFIER)}())return;try{const o=await Ze();if("ok"===o.state)return;if("auto"===t&&await async function(e){if("mismatch"!==e.state&&"missing"!==e.state)return!1;try{return!(await Je({})).blocked}catch(e){return!1}}(o))return;return"json"===e.format&&e.response.setNotice({skill:{state:o.state,cliVersion:o.cliVersion,installedVersion:o.installedVersion,message:o.message,command:"coze self skill install"}}),o}catch(e){return}}(e),s=await async function(e){if("upgrade"===Xe(e.argv).commandName)return;if(pe())return;const t=ue(e.config);if("off"===t)return;const o=ot([e,"access",e=>e.config,"access",e=>e.upgrade,"optionalAccess",e=>e.cache]),i=ot([o,"optionalAccess",e=>e.latestVersion]);if(!i)return;if(et(o.channel,(()=>"latest"))!==me(e.config))return;const s=ne();if(!le(s,i))return;const n=o.lastAttempt,r="number"==typeof n&&Date.now()-n<se;let a;"auto"===("auto"===t&&de(s,i)?"notify":t)?r?a=`Auto-upgrade to ${i} did not take effect (current ${s}). Run \`coze upgrade\` manually; on an internal network verify your npm registry.`:(a=`Coze CLI ${i} available (current ${s}). Upgrading in the background; it will take effect on next run.`,he(e,i)):a=`Coze CLI ${i} available (current ${s}). Run \`coze upgrade\` to update.`;"json"===e.format&&e.response.setNotice({update:{current:s,latest:i,message:a,command:"coze upgrade"}});return{current:s,latest:i,message:a}}(e);await t(),function(e,t){if(!ot([t,"optionalAccess",e=>e.message]))return;if("json"===e.format)return void(e.response.hasPendingNotice()&&process.stderr.write(`${t.message}\n`));e.ui.info(`\n${t.message}\n`)}(e,i),function(e,t){if(!t)return;if("json"===e.format)return void(e.response.hasPendingNotice()&&process.stderr.write(`${t.message}\n`));e.ui.info(`\n${o.gray(t.current)} → ${o.green(t.latest)} ${t.message}\n`)}(e,s),async function(e){if("upgrade"===Xe(e.argv).commandName)return;if(pe())return;const t=ue(e.config);if("off"===t)return;try{const o=await ge(e,!1,me(e.config));o.hasUpdate&&"auto"===t&&!de(o.currentVersion,o.latestVersion)&&await he(e,o.latestVersion)}catch(e){}}(e)}var st=e.requireSrc();const nt=e.getDefaultExportFromCjs(st);function rt(e){var t,o,i=e.transport,s=e.endpoint,n=e.size,r=void 0===n?10:n,a=e.wait,c=void 0===a?1e3:a,l=[],d=0;function p(){if(l.length){var e=this.getBatchData();i.post({url:s,data:e,fail:function(o){t&&t(o,e)},success:function(){o&&o(e)}}),l=[]}}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){l.push(e),l.length>=r&&p.call(this),clearTimeout(d),d=setTimeout(p.bind(this),c)},flush:function(){clearTimeout(d),p.call(this)},getBatchData:function(){return l.length?(e=l,JSON.stringify({ev_type:"batch",list:e})):"";var e},clear:function(){clearTimeout(d),l=[]},fail:function(e){t=e},success:function(e){o=e}}}
2
+ "use strict";const e=require("./fetch-client-DtaPMDxl.js"),t=require("./index-BL2IXR_e.js"),o=require("chalk"),i=require("node:child_process"),s=require("./task-worker-CkGDGYoW.js"),n=require("node:path"),r=require("node:fs/promises"),a=require("node:fs"),c=require("node:crypto"),l=require("node:http"),d=require("node:https"),p=require("node:buffer"),u=require("undici"),m=require("path"),g=require("fs/promises"),h=require("fs"),f=require("form-data"),_=require("omelette"),y=require("node:os"),b=require("child_process"),v=require("lodash"),w=require("commander"),E=require("ws");function C(e){const t=Object.create(null);if(e)for(const o in e)if("default"!==o){const i=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,i.get?i:{enumerable:!0,get:function(){return e[o]}})}return t.default=e,Object.freeze(t)}require("crypto"),require("url"),require("net"),require("tls"),require("assert"),require("tty"),require("util"),require("events"),require("http"),require("https"),require("http2"),require("stream"),require("zlib"),require("mitt"),require("process");const I=C(n),A=C(r);function S(e,t){return null!=e?e:t()}class k{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))},o=JSON.stringify(t,null,2);return o.endsWith("\n")?o:`${o}\n`}}function j(e,t){return null!=e?e:t()}function P(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function z(e){const t=String.fromCharCode(27),o=new RegExp(`${t}(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])`,"g");return e.replace(o,"")}function T(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 R(e){const t=z(e);if(!t)return 0;const o=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/u;let i=0;const s=Array.from(t);for(let e=0;e<s.length;e+=1){const t=j(s[e],(()=>""));if(o.test(t))continue;const n=t.codePointAt(0);void 0!==n&&(i+=T(n)?2:1)}return i}function x(e,t){const o=R(e);return o>=t?e:`${e}${" ".repeat(t-o)}`}function L(e,t){if(t<=0)return"";if(R(e)<=t)return e;if(1===t)return"…";const o=z(e),i=Array.from(o),s=Math.max(0,t-R("…"));let n="",r=0;for(let e=0;e<i.length;e+=1){const t=j(i[e],(()=>"")),o=R(t);if(r+o>s)break;n+=t,r+=o}return`${n}…`}function O(e,t={}){if(0===e.length)return"";const o=function(e,t){if(0===e.length)return[];const o=new Set,i=[],s=j(e[0],(()=>({})));for(const e of Object.keys(s))o.has(e)||(o.add(e),i.push(e));for(const t of e)for(const e of Object.keys(t))o.has(e)||(o.add(e),i.push(e));const n=[];for(const t of i){let o=R(t);for(const i of e){const e=i[t],s=void 0===e?"":String(e);o=Math.max(o,R(s))}n.push({key:t,width:o})}const r=j(t.columnGap,(()=>2)),a=j(j(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),c=Math.max(1,Math.floor((a+r)/(6+r))),l=Math.min(j(t.maxColumns,(()=>c)),c);n.length>l&&n.splice(l);const d=Math.max(0,a-r*Math.max(0,n.length-1));for(;n.reduce(((e,t)=>e+t.width),0)>d;){let e=-1,t=-1;for(let o=0;o<n.length;o+=1){const i=j(P([n,"access",e=>e[o],"optionalAccess",e=>e.width]),(()=>0));i>t&&(t=i,e=o)}if(-1===e)break;const o=j(P([n,"access",t=>t[e],"optionalAccess",e=>e.width]),(()=>0));if(o<=6)break;n[e]={...n[e],width:o-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===o.length)return"";const i=j(t.columnGap,(()=>2)),s=" ".repeat(i),n=o.map((e=>x(L(e.key,e.width),e.width))).join(s),r=o.map((e=>"-".repeat(e.width))).join(s),a=[];for(const t of e){const e=o.map((e=>{const o=t[e.key];return x(L(void 0===o?"":String(o),e.width),e.width)}));a.push(e.join(s))}return`${[n,r,...a].join("\n")}\n`}function D(e,t={}){const o=Object.entries(e);if(0===o.length)return"";let i=0;for(const[e]of o)i=Math.max(i,R(e));const s=j(j(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),n=j(t.columnGap,(()=>2)),r=j(t.minValueWidth,(()=>12));let a=Math.min(i,j(t.keyMaxWidth,(()=>32)));const c=Math.max(6,s-n-r);a=Math.min(a,c);const l=Math.max(0,s-a-n),d=" ".repeat(n);return`${o.map((([e,t])=>{const o=x(L(e,a),a),i=(void 0===t?"undefined":null===t?"null":String(t)).replace(/\s*\n\s*/g," "),s=l>0?L(i,l):"";return`${o}${d}${s}`})).join("\n")}\n`}function U(e,t="",o=0){const i={};if(null==e)return i;if("object"!=typeof(s=e)||null===s||Array.isArray(s))return i;var s;for(const[s,n]of Object.entries(e)){const e=t?`${t}.${s}`:s;if(null!=n)if(Array.isArray(n))o>=5?i[e]="[Array]":0===n.length?i[e]="[]":n.every((e=>"object"!=typeof e||null===e))?i[e]=n.map((e=>{return String((o=()=>"null",null!=(t=e)?t:o()));var t,o})).join(", "):i[e]="[Array]";else if("object"!=typeof n)i[e]=n;else if(o>=5)i[e]="[Object]";else{const t=U(n,e,o+1);Object.assign(i,t)}else i[e]=n}return i}function q(e,t){return null!=e?e:t()}function B(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class M{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(B)){return O(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(q(e,(()=>"null"))))).join("\n")}\n`:"[Array]\n"}var t;if(B(e)){const t=U(e);return 0===Object.keys(t).length?"{}\n":D(t)}return`${String(e)}\n`}formatError(e){const t=[],o=q(e.errorName,(()=>"UNKNOWN_ERROR")),i=q(e.desc,(()=>e.message));return t.push(`ERROR [${e.code}] ${o}: ${i}`),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?D(U(e)):String(e))).map((e=>`${t}- ${e.trim()}`)).join("\n")}\n`;if(B(e)){const o=U(e);return 0===Object.keys(o).length?"":`${D(o).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 N(e,t){return null!=e?e:t()}function $(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function G(e,t){if(null==e)return;const o=String(e).replace(/\s*\n\s*/g," ").replace(/\s+/g," ").trim();return o?o.length<=t?o:`${o.slice(0,Math.max(0,t-3))}...`:void 0}function F(e){const t=$([e,"optionalAccess",e=>e.help,"optionalAccess",e=>e.errors]);if(t&&t.length>0)return t;const o=$([e,"optionalAccess",e=>e.errors]);return Array.isArray(o)?o:void 0}function V(t,o){const i=N(t.trigger,(()=>function(e){if(!e||0===e.length)return;return G(("coze"===e[0]?e:["coze",...e]).join(" "),150)}($([o,"optionalAccess",e=>e.argv])))),s=$([F,"call",e=>e($([o,"optionalAccess",e=>e.commandConfig])),"optionalAccess",e=>e.find,"call",e=>e((e=>e.code===t.code))]),n=N($([s,"optionalAccess",e=>e.name]),(()=>e.ErrorNameByCode[t.code])),r=N(G(n,80),(()=>"UNKNOWN_ERROR"));let a=n;t.isMessageExplicit&&t.message.trim()?a=t.message:$([s,"optionalAccess",e=>e.desc])&&(a=s.desc);const c=N(G(a,200),(()=>"An unexpected error occurred")),l=N(G(t.fix,150),(()=>G($([s,"optionalAccess",e=>e.fix]),150))),d=N(G(t.example,150),(()=>G($([s,"optionalAccess",e=>e.example]),150)));return{code:t.code,errorName:r,desc:c,trigger:i,fix:l,example:d}}function W(e,t){const o=V(e,t);return e.errorName=o.errorName,e.desc=o.desc,e.message=o.desc,e.trigger=o.trigger,e.fix=o.fix,e.example=o.example,e}function H(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}var J;function K(o,i,s,n){if(o instanceof e.CozeError)throw o;if(e.isHttpError(o)){const e=H([o,"access",e=>e.response,"optionalAccess",e=>e.status]);if("ECONNREFUSED"===o.code||"ETIMEDOUT"===o.code||"number"==typeof e&&e>=500)throw o}if(o instanceof t.ChatCoreError&&"number"==typeof H([o,"access",e=>e.ext,"optionalAccess",e=>e.code])&&o.ext.code>=500)throw o;throw new e.CozeError(i,s,{...n,cause:o instanceof Error?o.message:String(o)})}!function(e){e[e.NOT_LOGIN=700012006]="NOT_LOGIN"}(J||(J={}));const Q=(o,i)=>{const s=W(function(o){if(o instanceof e.CozeError)return o;if(o instanceof t.ChatCoreError){const{ext:t}=o;let i=e.ErrorCode.E5000;"number"==typeof t.code&&(t.code===J.NOT_LOGIN?i=e.ErrorCode.E2001:t.code>=500&&(i=e.ErrorCode.E5002));const{message:s}=o;return new e.CozeError(i,s,t)}if(e.isHttpError(o)){const t=o.toJSON();let i=e.ErrorCode.E5000;const s=H([o,"access",e=>e.response,"optionalAccess",e=>e.status]);o.code===J.NOT_LOGIN||401===s?i=e.ErrorCode.E2001:"ECONNREFUSED"===o.code||"ETIMEDOUT"===o.code?i=e.ErrorCode.E5001:403===s?i=e.ErrorCode.E2003:404===s?i=e.ErrorCode.E3000:429===s?i=e.ErrorCode.E4001:s&&s>=500&&(i=e.ErrorCode.E5002);const n=H([o,"access",e=>e.response,"optionalAccess",e=>e.headers,"optionalAccess",e=>e["x-tt-logid"]]),{message:r}=o;return new e.CozeError(i,r,{logId:n,...t})}return o instanceof Error?new e.CozeError(e.ErrorCode.E5000,o.message,o.stack):"string"==typeof o?new e.CozeError(e.ErrorCode.E5000,o):new e.CozeError(e.ErrorCode.E5000,"An unexpected error occurred")}(o),i?{argv:i.argv,commandConfig:i.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`),i)i.response.eprint(s);else{const e=new M;process.stderr.write(e.formatError(s))}process.exit(e.exitCodeForError(s.code))};const Y="@coze/cli",Z="0.3.3-alpha.b7c03e",X=Y;function ee(){const e=[{pm:"npm",cmd:`npm ls -g ${X} --json 2>/dev/null`},{pm:"pnpm",cmd:`pnpm ls -g ${X} --json 2>/dev/null`},{pm:"yarn",cmd:"yarn global list --json 2>/dev/null"}];for(const{pm:t,cmd:o}of e)try{if(i.execSync(o,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).includes(X))return t}catch(e){}return"npm"}function te(e,t){return null!=e?e:t()}function oe(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ie=Y,se=6e5;function ne(){return Z}function re(e){const t=e.trim().replace(/^v/,"").split("+")[0],o=t.indexOf("-"),i=-1===o?t:t.slice(0,o),s=-1===o?"":t.slice(o+1),n=i.split(".");return{major:parseInt(n[0]||"0",10),minor:parseInt(n[1]||"0",10),patch:parseInt(n[2]||"0",10),prerelease:""===s?[]:s.split(".")}}function ae(e,t){const o=/^\d+$/.test(e),i=/^\d+$/.test(t);if(o&&i){const o=parseInt(e,10)-parseInt(t,10);return 0===o?0:o>0?1:-1}return o?-1:i?1:e===t?0:e>t?1:-1}function ce(e,t){const o=re(e),i=re(t);return o.major!==i.major?o.major>i.major?1:-1:o.minor!==i.minor?o.minor>i.minor?1:-1:o.patch!==i.patch?o.patch>i.patch?1:-1:function(e,t){if(0===e.length&&0===t.length)return 0;if(0===e.length)return 1;if(0===t.length)return-1;const o=Math.max(e.length,t.length);for(let i=0;i<o;i++){const o=e[i],s=t[i];if(void 0===o)return-1;if(void 0===s)return 1;const n=ae(o,s);if(0!==n)return n}return 0}(o.prerelease,i.prerelease)}function le(e,t){return ce(t,e)>0}function de(e,t){return re(t).major>re(e).major}function pe(){if(process.env.COZE_CLI_NO_UPDATE_NOTIFIER)return!0;const e=te(process.env.CI,(()=>"")).toLowerCase();return""!==e&&"false"!==e&&"0"!==e||function(e){return!e||"0.0.0"===e||/dev/i.test(e)}(ne())}function ue(e){const t=oe([e,"access",e=>e.upgrade,"optionalAccess",e=>e.mode]);return"auto"===t||"notify"===t||"off"===t?t:"auto"}function me(e){return oe([e,"access",e=>e.upgrade,"optionalAccess",e=>e.channel])||"latest"}async function ge(t,o=!1,n="latest"){const r=ne(),{config:a}=t,c=oe([a,"access",e=>e.upgrade,"optionalAccess",e=>e.cache]);if(!o&&oe([c,"optionalAccess",e=>e.latestVersion])&&c.checkedAt&&Date.now()-c.checkedAt<144e5&&te(c.channel,(()=>"latest"))===n)return{currentVersion:r,latestVersion:c.latestVersion,hasUpdate:le(r,c.latestVersion)};const l=function(){try{return i.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,o="latest"){const i=`${t}/${ie}/${o}`,s=await e.customFetch.fetch(i,{headers:{accept:"application/json"}});if(!s.ok)throw new Error(`Failed to fetch latest version: ${s.status} ${s.statusText}`);return(await s.json()).version}(l,n);return await s.saveConfig({upgrade:{cache:{latestVersion:d,checkedAt:Date.now(),channel:n}}},a.configScope),{currentVersion:r,latestVersion:d,hasUpdate:le(r,d)}}async function he(e,t){const o=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([e,"access",e=>e.config,"access",e=>e.upgrade,"optionalAccess",e=>e.cache,"optionalAccess",e=>e.lastAttempt]);if(o&&Date.now()-o<se)return;try{await s.saveConfig({upgrade:{cache:{lastAttempt:Date.now()}}},e.config.configScope)}catch(e){}const n=ee(),{command:r,args:a}=function(e,t){const o=`${X}@${t}`;switch(e){case"pnpm":return{command:"pnpm",args:["add","-g",o]};case"yarn":return{command:"yarn",args:["global","add",o]};default:return{command:"npm",args:["install","-g",o]}}}(n,t);try{i.spawn(r,a,{detached:!0,stdio:"ignore",shell:"win32"===process.platform}).unref()}catch(e){}}function fe(e,t){return null!=e?e:t()}function _e(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ye={claude:"claude-code"};let be=null;function ve(){if(be)return be;const t=function(){let e=__dirname;for(let t=0;t<12;t++){const t=n.join(e,"node_modules","skills","package.json");if(a.existsSync(t))return n.dirname(t);const o=n.dirname(e);if(o===e)break;e=o}}();if(t){const o=e.safeJsonParse(a.readFileSync(n.join(t,"package.json"),"utf8")),i="string"==typeof _e([o,"optionalAccess",e=>e.bin])?o.bin:_e([o,"optionalAccess",e=>e.bin,"optionalAccess",e=>e.skills]);if(i)return be={cmd:process.execPath,prefix:[n.join(t,i)]},be}return be={cmd:"skills",prefix:[]},be}function we(e){const{cmd:t,prefix:o}=ve(),s=i.spawnSync(t,[...o,...e],{encoding:"utf8"});return{ok:0===s.status,stdout:fe(s.stdout,(()=>"")),stderr:fe(s.stderr,(()=>"")),code:s.status}}function Ee(e,t={}){const o=["add",e];return t.global&&o.push("-g"),t.yes&&o.push("-y"),t.agents&&t.agents.length>0&&o.push("-a",...t.agents),we(o)}function Ce(e,t={}){const o=["remove",e];return t.global&&o.push("-g"),o.push("-y"),we(o)}function Ie(t={}){const o=["ls","--json"];t.global&&o.push("-g");const i=we(o);if(!i.ok)return[];const s=e.safeJsonParse(i.stdout);return Array.isArray(s)?s:[]}function Ae(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Se(){return s.getGlobalSkillLockFile()}async function ke(e){try{return await r.access(e),!0}catch(e){return!1}}async function je(){let t=__dirname;for(let o=0;o<12;o++){const o=n.join(t,"package.json");if(await ke(o)){if("@coze/cli"===Ae([e.safeJsonParse(await r.readFile(o,"utf8")),"optionalAccess",e=>e.name]))return t}const i=n.dirname(t);if(i===t)break;t=i}return n.resolve(__dirname,"..")}async function Pe(){return n.join(await je(),"skills")}async function ze(){return n.join(await je(),"docs","skills")}const Te=new Set(["SKILL.md","MODULE.md"]);function Re(e){return`sha256:${c.createHash("sha256").update(e,"utf8").digest("hex")}`}function xe(e){return Te.has(n.basename(e))}async function Le(e,t=e){const o=await r.readdir(e,{withFileTypes:!0}),i=[];for(const s of o){if(s.name.startsWith("."))continue;const o=n.join(e,s.name);s.isDirectory()?i.push(...await Le(o,t)):s.isFile()&&i.push(n.relative(t,o).split(n.sep).join("/"))}return i.sort()}function Oe(e,t){const o=Ue(e);if(void 0===o)return;const i=new RegExp(`^${t}:\\s*(.+?)\\s*$`,"m"),s=o.match(i);return s?s[1].replace(/^['"]|['"]$/g,"").trim():void 0}function De(e,t){const o=Ue(e);if(void 0===o)return e;const i=`version: ${t}`;let s;return s=/^version:\s*.+$/m.test(o)?o.replace(/^version:\s*.+$/m,i):/^name:\s*.+$/m.test(o)?o.replace(/^(name:\s*.+)$/m,`$1\n${i}`):`${i}\n${o}`,e.replace(o,s)}function Ue(e){if(!e.startsWith("---"))return;const t=e.match(/^---\n([\s\S]*?)\n---/);return t?t[1]:void 0}function qe(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function Be(){const e=await Pe();if(await ke(n.join(e,"manifest.json")))return{root:e,source:"bundled"};const t=await ze();if(await ke(t))return{root:t,source:"docs"};throw new Error(`未找到 skill 来源:既无包内 ${e}/manifest.json,也无开发态 ${t}。`)}async function Me(){const t=n.join(await je(),"package.json"),o=e.safeJsonParse(await r.readFile(t,"utf8"));return i=qe([o,"optionalAccess",e=>e.version]),s=()=>"0.0.0",null!=i?i:s();var i,s}async function Ne(){const t=await Pe(),o=n.join(t,"manifest.json");if(await ke(o)){const i=e.safeJsonParse(await r.readFile(o,"utf8")),s=(await Le(t)).filter((e=>"manifest.json"!==e)),a=[];for(const e of s)a.push({rel:e,content:await r.readFile(n.join(t,e),"utf8")});return{manifest:i,files:a,source:"bundled"}}const i=await ze();if(!await ke(i))throw new Error(`未找到 skill 来源:既无包内 ${o},也无开发态 ${i}。`);const s=await Me(),{manifest:a,files:c}=await async function(e,t){const o=await Le(e),i=[],s={};for(const l of o){const o=await r.readFile(n.join(e,l),"utf8"),d=xe(l),p=d?De(o,t):o;i.push({rel:l,content:p}),d&&(s[(a=Oe(p,"name"),c=()=>l,null!=a?a:c())]={path:l,hash:Re(p)})}var a,c;return{manifest:{cliVersion:t,skills:s},files:i}}(i,s);return{manifest:a,files:c,source:"docs"}}async function $e(){try{const t=await r.readFile(Se(),"utf8");return e.safeJsonParse(t)}catch(e){return}}function Ge(e,t){return null!=e?e:t()}function Fe(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function Ve(e){try{return Re(await r.readFile(e,"utf8"))}catch(e){return}}function We(e){return[...new Set(Object.values(e.skills).map((e=>e.path.split("/")[0])))]}function He(e){return e[0]?n.dirname(e[0].path):void 0}async function Je(e={}){const{manifest:t}=await Ne(),{root:o}=await Be(),i=We(t),s=await $e(),a=Ie({global:!0}),c=await async function(e,t,o){const i=He(t);if(!i)return[];const s=new Set(t.map((e=>e.name))),r=[];for(const[t,a]of Object.entries(e.skills)){const e=a.path.split("/")[0];if(!s.has(e))continue;const c=await Ve(n.join(i,a.path));if(void 0===c)continue;if(c===a.hash)continue;const l=Fe([o,"optionalAccess",e=>e.skills,"access",e=>e[t],"optionalAccess",e=>e.hash]);void 0!==l&&c===l||r.push(t)}return r}(t,a,s);if(c.length>0&&!e.force)return{blocked:!0,cliVersion:t.cliVersion,sourceRoot:o,linkedTargets:[],skillsOk:!1,unknownTargets:[],modifiedSkills:c};const l=e.targets&&e.targets.length>0&&!e.targets.includes("all")?Ge(e.targets,(()=>[])).map((e=>fe(ye[e],(()=>e)))):void 0;let d=!0;for(const e of i){Ee(n.join(o,e),{global:!0,yes:!0,agents:l}).ok||(d=!1)}const p=Ie({global:!0}),u=p.filter((e=>i.includes(e.name))),m=Fe([u,"access",e=>e[0],"optionalAccess",e=>e.path]),g=[...new Set(u.flatMap((e=>e.agents)))],h=(new Date).toISOString(),f=He(p),_={};for(const[e,o]of Object.entries(t.skills)){const t=f?await Ve(n.join(f,o.path)):void 0;_[e]={hash:Ge(t,(()=>o.hash)),expectedHash:o.hash,installedAt:h}}return await async function(e){const t=Se();await r.mkdir(n.dirname(t),{recursive:!0}),await r.writeFile(t,`${JSON.stringify(e,null,2)}\n`,"utf8")}({version:1,cliVersion:t.cliVersion,installedBin:Ge(process.argv[1],(()=>process.execPath)),poolPath:m,targets:g,skills:_}),{blocked:!1,cliVersion:t.cliVersion,sourceRoot:o,poolPath:m,linkedTargets:g,skillsOk:d,unknownTargets:[],modifiedSkills:[]}}function Ke(e,t,o){return void 0===e?"missing":e===t?"ok":o===e?"drift":"modified"}async function Qe(){const{manifest:e}=await Ne(),t=await $e(),o=Ge(process.argv[1],(()=>process.execPath)),i=Ie({global:!0}),s=He(i),r=new Set(i.map((e=>e.name))),a=[];for(const[o,i]of Object.entries(e.skills)){const e=i.path.split("/")[0],c=Boolean(s)&&r.has(e),l=c?await Ve(n.join(s,i.path)):void 0,d=c?Ke(l,i.hash,Fe([t,"optionalAccess",e=>e.skills,"access",e=>e[o],"optionalAccess",e=>e.hash])):"missing";a.push({name:o,path:i.path,state:d})}const c=Fe([i,"access",e=>e.find,"call",e=>e((e=>r.has(e.name))),"optionalAccess",e=>e.path]);return{lockExists:Boolean(t),cliVersion:e.cliVersion,installedVersion:Fe([t,"optionalAccess",e=>e.cliVersion]),versionMatch:Boolean(t)&&Fe([t,"optionalAccess",e=>e.cliVersion])===e.cliVersion,installedBin:Fe([t,"optionalAccess",e=>e.installedBin]),currentBin:o,binMatch:!Fe([t,"optionalAccess",e=>e.installedBin])||t.installedBin===o,poolPath:c,targets:Ge(Fe([t,"optionalAccess",e=>e.targets]),(()=>[])),skills:a}}async function Ye(){const{manifest:e}=await Ne(),t=We(e),o=Ie({global:!0}),i=[];for(const e of t){const t=o.find((t=>t.name===e));if(!t)continue;Ce(e,{global:!0}).ok&&i.push({name:e,agents:t.agents})}return await async function(){await r.rm(Se(),{force:!0})}(),{removed:i}}async function Ze(){const t=await async function(){const t=n.join(await Pe(),"manifest.json");if(await ke(t)){const o=e.safeJsonParse(await r.readFile(t,"utf8"));if(qe([o,"optionalAccess",e=>e.cliVersion]))return o.cliVersion}return Me()}(),o=await $e();return o?o.cliVersion!==t?{state:"mismatch",cliVersion:t,installedVersion:o.cliVersion,message:`Skills (${o.cliVersion}) are out of sync with CLI (${t}). Run \`coze self skill install\`.`}:{state:"ok",cliVersion:t,installedVersion:o.cliVersion}:{state:"missing",cliVersion:t,message:"Bundled skills not installed yet. Run `coze self skill install` to sync them to your AI tools."}}function Xe(e){const t={};let o;const i=[];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("-")?i.push(r):(o=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 o=e[++n];"json"!==o&&"text"!==o||(t.format=o)}else t.output=e[++n];else t.version=!0;else t.help=!0}return{globalOptions:t,commandName:o,commandArgs:i}}function et(e,t){return null!=e?e:t()}function ot(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function it(e,t){const i=await async function(e){if("self"===Xe(e.argv).commandName)return;const t=function(e){const t=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([e,"access",e=>e.skill,"optionalAccess",e=>e.mode]);return"auto"===t||"notify"===t||"off"===t?t:"auto"}(e.config);if("off"===t)return;if(function(){const e=et(process.env.CI,(()=>"")).toLowerCase();return""!==e&&"false"!==e&&"0"!==e||Boolean(process.env.COZE_CLI_NO_SKILL_NOTIFIER)}())return;try{const o=await Ze();if("ok"===o.state)return;if("auto"===t&&await async function(e){if("mismatch"!==e.state&&"missing"!==e.state)return!1;try{return!(await Je({})).blocked}catch(e){return!1}}(o))return;return"json"===e.format&&e.response.setNotice({skill:{state:o.state,cliVersion:o.cliVersion,installedVersion:o.installedVersion,message:o.message,command:"coze self skill install"}}),o}catch(e){return}}(e),s=await async function(e){if("upgrade"===Xe(e.argv).commandName)return;if(pe())return;const t=ue(e.config);if("off"===t)return;const o=ot([e,"access",e=>e.config,"access",e=>e.upgrade,"optionalAccess",e=>e.cache]),i=ot([o,"optionalAccess",e=>e.latestVersion]);if(!i)return;if(et(o.channel,(()=>"latest"))!==me(e.config))return;const s=ne();if(!le(s,i))return;const n=o.lastAttempt,r="number"==typeof n&&Date.now()-n<se;let a;"auto"===("auto"===t&&de(s,i)?"notify":t)?r?a=`Auto-upgrade to ${i} did not take effect (current ${s}). Run \`coze upgrade\` manually; on an internal network verify your npm registry.`:(a=`Coze CLI ${i} available (current ${s}). Upgrading in the background; it will take effect on next run.`,he(e,i)):a=`Coze CLI ${i} available (current ${s}). Run \`coze upgrade\` to update.`;"json"===e.format&&e.response.setNotice({update:{current:s,latest:i,message:a,command:"coze upgrade"}});return{current:s,latest:i,message:a}}(e);await t(),function(e,t){if(!ot([t,"optionalAccess",e=>e.message]))return;if("json"===e.format)return void(e.response.hasPendingNotice()&&process.stderr.write(`${t.message}\n`));e.ui.info(`\n${t.message}\n`)}(e,i),function(e,t){if(!t)return;if("json"===e.format)return void(e.response.hasPendingNotice()&&process.stderr.write(`${t.message}\n`));e.ui.info(`\n${o.gray(t.current)} → ${o.green(t.latest)} ${t.message}\n`)}(e,s),async function(e){if("upgrade"===Xe(e.argv).commandName)return;if(pe())return;const t=ue(e.config);if("off"===t)return;try{const o=await ge(e,!1,me(e.config));o.hasUpdate&&"auto"===t&&!de(o.currentVersion,o.latestVersion)&&await he(e,o.latestVersion)}catch(e){}}(e)}var st=e.requireSrc();const nt=e.getDefaultExportFromCjs(st);function rt(e){var t,o,i=e.transport,s=e.endpoint,n=e.size,r=void 0===n?10:n,a=e.wait,c=void 0===a?1e3:a,l=[],d=0;function p(){if(l.length){var e=this.getBatchData();i.post({url:s,data:e,fail:function(o){t&&t(o,e)},success:function(){o&&o(e)}}),l=[]}}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){l.push(e),l.length>=r&&p.call(this),clearTimeout(d),d=setTimeout(p.bind(this),c)},flush:function(){clearTimeout(d),p.call(this)},getBatchData:function(){return l.length?(e=l,JSON.stringify({ev_type:"batch",list:e})):"";var e},clear:function(){clearTimeout(d),l=[]},fail:function(e){t=e},success:function(e){o=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 at=function(){return at=Object.assign||function(e){for(var t,o=1,i=arguments.length;o<i;o++)for(var s in t=arguments[o])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},at.apply(this,arguments)};function ct(e,t){var o="function"==typeof Symbol&&e[Symbol.iterator];if(!o)return e;var i,s,n=o.call(e),r=[];try{for(;(void 0===t||t-- >0)&&!(i=n.next()).done;)r.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(o=n.return)&&o.call(n)}finally{if(s)throw s.error}}return r}function lt(e,t,o){if(2===arguments.length)for(var i,s=0,n=t.length;s<n;s++)!i&&s in t||(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return e.concat(i||Array.prototype.slice.call(t))}var dt=function(){return{}};function pt(e){return e}function ut(e){return"object"==typeof e&&null!==e}var mt=Object.prototype;function gt(e){return"[object Array]"===mt.toString.call(e)}function ht(e){return"number"==typeof e}function ft(e){return"string"==typeof e}function _t(e,t){if(!gt(e))return!1;if(0===e.length)return!1;for(var o=0;o<e.length;){if(e[o]===t)return!0;o++}return!1}var yt=function(e,t){if(!gt(e))return e;var o=e.indexOf(t);if(o>=0){var i=e.slice();return i.splice(o,1),i}return e};function bt(e){try{return ft(e)?e:JSON.stringify(e)}catch(e){return"[FAILED_TO_STRINGIFY]:"+String(e)}}var vt="".padStart?function(e,t){return void 0===t&&(t=8),e.padStart(t," ")}:function(e){return e},wt=0,Et=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,lt(["[SDK]",Date.now(),vt(""+wt++)],ct(e),!1))},Ct=0,It=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,lt(["[SDK]",Date.now(),vt(""+Ct++)],ct(e),!1))},At=function(e){return Math.random()<Number(e)},St=function(e,t){return e<Number(t)},kt=function(e){return function(t){for(var o=t,i=0;i<e.length&&o;i++)try{o=e[i](o)}catch(e){Et(e)}return o}};function jt(){var e=function(){for(var e=new Array(16),t=0,o=0;o<16;o++)3&o||(t=4294967296*Math.random()),e[o]=t>>>((3&o)<<3)&255;return e}();return e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){for(var t=[],o=0;o<256;++o)t[o]=(o+256).toString(16).substr(1);var i=0,s=t;return[s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]]].join("")}(e)}var Pt=["init","start","config","beforeDestroy","provide","beforeReport","report","beforeBuild","build","beforeSend","send","beforeConfig"];function zt(e){var t,o,i=e.builder,s=e.createSender,n=e.createDefaultConfig,r=e.createConfigManager,a=e.userConfigNormalizer,c=e.initConfigNormalizer,l=e.validateInitConfig,d={};Pt.forEach((function(e){return d[e]=[]}));var p=!1,u=!1,m=!1,g=[],h=[],f=function(){var e=!1,t={},o=function(e){e.length&&e.forEach((function(e){try{e()}catch(e){}})),e.length=0},i=function(e){t[e]&&t[e].forEach((function(e){o(e[1])})),t[e]=void 0};return{set:function(i,s,n){t[i]?t[i].push([s,n]):t[i]=[[s,n]],e&&o(n)},has:function(e){return!!t[e]},remove:i,removeByEvType:function(e){Object.keys(t).forEach((function(i){t[i]&&t[i].forEach((function(t){t[0]===e&&o(t[1])}))}))},clear:function(){e=!0,Object.keys(t).forEach((function(e){i(e)}))}}}(),_={getBuilder:function(){return i},getSender:function(){return t},getPreStartQueue:function(){return g},init:function(e){if(p)It("already inited");else{if(!(e&&ut(e)&&l(e)))throw new Error("invalid InitConfig, init failed");var i=n(e);if(!i)throw new Error("defaultConfig missing");var a=c(e);if((o=r(i)).setConfig(a),o.onChange((function(){y("config")})),!(t=s(o.getConfig())))throw new Error("sender missing");p=!0,y("init",!0)}},set:function(e){p&&e&&ut(e)&&(y("beforeConfig",!1,e),null==o||o.setConfig(e))},config:function(e){if(p)return e&&ut(e)&&(y("beforeConfig",!1,e),null==o||o.setConfig(a(e))),null==o?void 0:o.getConfig()},provide:function(e,t){_t(h,e)?It("cannot provide "+e+", reserved"):(_[e]=t,y("provide",!1,e))},start:function(){p&&(u||null==o||o.onReady((function(){u=!0,y("start",!0),function(e){var t=e.getPreStartQueue();t.forEach((function(t){return e.build(t)})),t.length=0}(_)})))},report:function(e){if(e){var t=kt(d.beforeReport)(e);if(t){var o=kt(d.report)(t);o&&(u?this.build(o):function(e,t,o){if(t.push(o),!(t.length<500)){var i=t.splice(0,50);e.savePreStartDataToDb&&e.savePreStartDataToDb(i)}}(_,g,o))}}},build:function(e){if(u){var t=kt(d.beforeBuild)(e);if(t){var o=i.build(t);if(o){var s=kt(d.build)(o);s&&this.send(s)}}}},send:function(e){if(u){var o=kt(d.beforeSend)(e);o&&(t.send(o),y("send",!1,o))}},destroy:function(){f.clear(),m=!0,g.length=0,y("beforeDestroy",!0)},on:function(e,t){if("init"===e&&p||"start"===e&&u||"beforeDestroy"===e&&m)try{t()}catch(e){}else d[e]&&d[e].push(t)},off:function(e,t){d[e]&&(d[e]=yt(d[e],t))},destroyAgent:f};return h=Object.keys(_),_;function y(e,t){void 0===t&&(t=!1);for(var o=[],i=2;i<arguments.length;i++)o[i-2]=arguments[i];d[e].forEach((function(e){try{e.apply(void 0,lt([],ct(o),!1))}catch(e){}})),t&&(d[e].length=0)}}var Tt=function(e){var t=function(){var e={},t={},o={set:function(i,s){return e[i]=s,t[i]=bt(s),o},merge:function(i){return e=at(at({},e),i),Object.keys(i).forEach((function(e){t[e]=bt(i[e])})),o},delete:function(i){return delete e[i],delete t[i],o},clear:function(){return e={},t={},o},get:function(e){return t[e]},toString:function(){return at({},t)}};return o}();e.provide("context",t),e.on("report",(function(e){return e.extra||(e.extra={}),e.extra.context=t.toString(),e}))};var Rt=function(){return Date.now()};var xt=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var o=function(e){if(e)return e.__SLARDAR_REGISTRY__||(e.__SLARDAR_REGISTRY__={Slardar:{plugins:[],errors:[],subject:{}}}),e.__SLARDAR_REGISTRY__.Slardar}(function(){if("object"==typeof window&&ut(window))return window}());o&&(o.errors||(o.errors=[]),o.errors.push(e))},Lt="custom",Ot=function(e){var t=function(o){var i=function(e){if(e&&ut(e)&&e.name&&ft(e.name)){var t={name:e.name,type:"event"};if("metrics"in e&&ut(e.metrics)){var o=e.metrics,i={};for(var s in o)ht(o[s])&&(i[s]=o[s]);t.metrics=i}if("categories"in e&&ut(e.categories)){var n=e.categories,r={};for(var s in n)r[s]=bt(n[s]);t.categories=r}return"attached_log"in e&&ft(e.attached_log)&&(t.attached_log=e.attached_log),t}}(o);if(i){var s=function(e){var t;if("object"==typeof window&&window.__perfsee__){var o={};return null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,o,e),o.stack}}(t);s&&(i.stacks=s),e.report({ev_type:Lt,payload:i,extra:{timestamp:Rt()}})}};e.provide("sendEvent",t),e.provide("sendLog",(function(t){var o=function(e){if(e&&ut(e)&&e.content&&ft(e.content)){var t={content:bt(e.content),type:"log",level:"info"};if("level"in e&&(t.level=e.level),"extra"in e&&ut(e.extra)){var o=e.extra,i={},s={};for(var n in o)ht(o[n])?i[n]=o[n]:s[n]=bt(o[n]);t.metrics=i,t.categories=s}return"attached_log"in e&&ft(e.attached_log)&&(t.attached_log=e.attached_log),t}}(t);o&&e.report({ev_type:Lt,payload:o,extra:{timestamp:Rt()}})}))},Dt=function(e,t){var o=e.common||{};return o.sample_rate=t,e.common=o,e},Ut=function(e,t,o,i,s){return e?(n=s(i,t),function(){return n}):function(){return o(t)};var n},qt=function(e,t,o,i){var s=function(e,t,o){for(var i,s=ct(t.split(".")),n=s[0],r=s.slice(1);e&&r.length>0;)e=e[n],n=(i=ct(r))[0],r=i.slice(1);if(e)return o(e,n)}(e,t,(function(e,t){return e[t]}));return void 0!==s&&function(e,t,o){switch(o){case"eq":return _t(t,e);case"neq":return!_t(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)}}))}(i,"boolean"==typeof s?"bool":ht(s)?"number":"string"),o)},Bt=function(e,t){try{return"rule"===t.type?qt(e,t.field,t.op,t.values):"and"===t.type?t.children.every((function(t){return Bt(e,t)})):t.children.some((function(t){return Bt(e,t)}))}catch(e){return xt(e),!1}},Mt=function(e,t,o,i,s){if(!t)return pt;var n=t.sample_rate,r=t.include_users,a=t.sample_granularity,c=t.rules,l=t.r,d=void 0===l?Math.random():l;if(_t(r,e))return function(e){return Dt(e,1)};var p="session"===a,u=Ut(p,n,o,d,i),m=function(e,t,o,i,s,n){var r={};return Object.keys(e).forEach((function(a){var c=e[a],l=c.enable,d=c.sample_rate,p=c.conditional_sample_rules;l?(r[a]={enable:l,sample_rate:d,effectiveSampleRate:d*o,hit:Ut(t,d,i,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:Ut(t,r,i,s,n),effectiveSampleRate:r*o,filter:a}})))):r[a]={enable:l,hit:function(){return!1},sample_rate:0,effectiveSampleRate:0}})),r}(c,p,n,o,d,i);return function(e){var t;if(!u())return p&&s[0](),!1;if(!(e.ev_type in m))return Dt(e,n);if(!m[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 o=m[e.ev_type],i=o.conditional_hit_rules;if(i)for(var r=0;r<i.length;r++)if(Bt(e,i[r].filter))return!!i[r].hit()&&Dt(e,i[r].effectiveSampleRate);return o.hit()?Dt(e,o.effectiveSampleRate):((!i||!i.length)&&p&&s[1](e.ev_type),!1)}},Nt={build:function(e){return{ev_type:e.ev_type,payload:e.payload,common:at(at({},e.extra||{}),e.overrides||{})}}},$t={sample_rate:1,include_users:[],sample_granularity:"session",rules:{}};function Gt(e){var t,o;try{for(var i=function(e){var t="function"==typeof Symbol&&Symbol.iterator,o=t&&e[t],i=0;if(o)return o.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(["userId","deviceId","sessionId","env"]),s=i.next();!s.done;s=i.next()){var n=s.value;e[n]||delete e[n]}}catch(e){t={error:e}}finally{try{s&&!s.done&&(o=i.return)&&o.call(i)}finally{if(t)throw t.error}}return e}function Ft(e){return Gt(at({},e))}function Vt(e){return ut(e)&&"bid"in e&&"transport"in e}function Wt(e){return Gt(at({},e))}var Ht=function(e,t){return void 0===t&&(t="/monitor_browser/collect/batch/"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Jt=function(e,t){return void 0===t&&(t="/monitor_web/settings/browser-settings"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Kt=function(e){var t,o,i=e,s={},n=dt,r=dt;return{getConfig:function(){return i},setConfig:function(e){return s=at(at({},s),e||{}),a(),t||(t=e,i.useLocalConfig||!i.bid?(o={},n()):function(e,t,o,i){if(!e.get)return i({});e.get({withCredentials:!0,url:Jt(t)+"?bid="+o+"&store=1",success:function(e){i(e.data||{})},fail:function(){i({sample:{sample_rate:.001}})}})}(i.transport,i.domain,i.bid,(function(e){o=function(e){if(!e)return{};var t=e.sample,o=e.timestamp,i=e.quota_rate,s=void 0===i?1:i;if(!t)return{};var n=t.sample_rate,r=t.sample_granularity,a=void 0===r?"session":r,c=t.include_users,l=t.rules;return{sample:{include_users:c,sample_rate:n*s,sample_granularity:a,rules:(void 0===l?[]:l).reduce((function(e,t){var o=t.name,i=t.enable,s=t.sample_rate,n=t.conditional_sample_rules;return e[o]={enable:i,sample_rate:s,conditional_sample_rules:n},e}),{})},serverTimestamp:o}}(e),a(),n()}))),i},onChange:function(e){r=e},onReady:function(e){n=e,o&&n()}};function a(){var t=at(at(at({},e),o||{}),s);t.sample=Qt(Qt(e.sample,null==o?void 0:o.sample),s.sample),i=t,r()}};function Qt(e,t){if(!e||!t)return e||t;var o=at(at({},e),t);return o.include_users=lt(lt([],ct(e.include_users||[]),!1),ct(t.include_users||[]),!1),o.rules=lt(lt([],ct(Object.keys(e.rules||{})),!1),ct(Object.keys(t.rules||{})),!1).reduce((function(o,i){var s,n;return i in o||(i in(e.rules||{})&&i in(t.rules||{})?(o[i]=at(at({},e.rules[i]),t.rules[i]),o[i].conditional_sample_rules=lt(lt([],ct(e.rules[i].conditional_sample_rules||[]),!1),ct(t.rules[i].conditional_sample_rules||[]),!1)):o[i]=(null===(s=e.rules)||void 0===s?void 0:s[i])||(null===(n=t.rules)||void 0===n?void 0:n[i])),o}),{}),o}var Yt=function(e){e.on("report",(function(t){return function(e,t){var o=t||{},i=o.version,s=o.name,n={url:"",protocol:"",domain:"",path:"",query:"",timestamp:Date.now(),sdk_version:i||"2.1.8",sdk_name:s||"SDK_BASE"};return at(at({},e),{extra:at(at({},n),e.extra||{})})}(t,e.config())}))},Zt=function(e){e.on("beforeBuild",(function(t){return function(e,t){var o={};return o.bid=t.bid,o.pid=t.pid,o.view_id=t.viewId,o.user_id=t.userId,o.device_id=t.deviceId,o.session_id=t.sessionId,o.release=t.release,o.env=t.env,at(at({},e),{extra:at(at({},o),e.extra||{})})}(t,e.config())}))};var Xt=function(e){return{bid:"",pid:"",viewId:(t="_",t+"_"+Date.now()),userId:jt(),deviceId:jt(),sessionId:jt(),domain:"mon.zijieapi.com",release:"",env:"production",sample:$t,plugins:{},transport:{get:dt,post:dt},useLocalConfig:!1};var t},eo=function(e){var t=void 0===e?{}:e,o=t.createSender,i=void 0===o?function(e){return function(e){return rt(e)}({size:20,endpoint:Ht(e.domain),transport:e.transport})}:o,s=t.builder,n=void 0===s?Nt:s,r=t.createDefaultConfig,a=zt({validateInitConfig:Vt,initConfigNormalizer:Ft,userConfigNormalizer:Wt,createSender:i,builder:n,createDefaultConfig:void 0===r?Xt:r,createConfigManager:Kt});return Tt(a),Zt(a),Yt(a),function(e){e.on("init",(function(){var t=[],o=function(o){o.forEach((function(o){var i=o.name;_t(t,i)||(t.push(i),o.setup(e),e.destroyAgent.set(i,i,[function(){t=yt(t,i),o.tearDown&&o.tearDown()}]))}))};e.provide("applyIntegrations",o);var i=e.config();i&&i.integrations&&o(i.integrations)}))}(a),function(e){try{"object"==typeof window&&ut(window)&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__.push(e)}catch(e){}}(a),a},to=function(e){void 0===e&&(e={});var t=eo(e);return function(e){e.on("start",(function(){var t=e.config(),o=t.userId,i=t.sample,s=Mt(o,i,At,St,[function(){e.destroy()},function(t){e.destroyAgent.removeByEvType(t)}]);e.on("build",s)}))}(t),Ot(t),t}();const oo=nt("slardar:transport"),io=()=>{};function so(e){const{url:t,method:o,data:i,success:s=io,fail:n=io,getResponseText:r=io}=e;if(oo("Making %s request to %s",o,t),i&&oo("Request data: %s",i.slice(0,200)),!t||"string"!=typeof t){const e=new Error(`Invalid URL: ${t}`);return oo("Invalid URL provided: %o",t),void n(e)}try{const e=new URL(t);oo("Parsed URL - protocol: %s, hostname: %s, port: %s, path: %s",e.protocol,e.hostname,e.port,e.pathname);const a="https:"===e.protocol,c=(a?d.request:l.request)({hostname:e.hostname,port:e.port,path:e.pathname+e.search,method:o,headers:{"Content-Type":"application/json",...i&&{"Content-Length":Buffer.byteLength(i)}}},(e=>{oo("Response callback triggered: status=%s",e.statusCode);let t="";e.on("data",(e=>{oo("Response data chunk received: %s bytes",e.length),t+=e.toString()})),e.on("end",(()=>{oo("Response end event fired"),oo("Response received: status=%s, body=%s",e.statusCode,t.slice(0,200)),r(t);try{if(e.statusCode&&e.statusCode>=400)oo("Request failed with status %s: %s",e.statusCode,t),n(new Error(t||e.statusMessage||"Request failed"));else if(t){const e=JSON.parse(t);oo("Request succeeded"),s(e)}else oo("Request succeeded with empty response"),s({})}catch(e){oo("Failed to parse response: %s",e.message),n(e)}}))}));c.on("error",(e=>{oo("Request error: %s",e.message),n(e)})),c.on("timeout",(()=>{oo("Request timeout"),c.destroy(),n(new Error("Request timeout"))})),i&&c.write(i),c.end()}catch(e){oo("Exception during request: %s",e.message),n(e)}}function no(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ro=nt("slardar:reporter");class ao{constructor(){ao.prototype.__init.call(this),ao.prototype.__init2.call(this)}__init(){this.initialized=!1}__init2(){this.client=to}setup(e){var t,o;if(this.initialized)ro("Already initialized, skipping setup");else try{ro("Initializing Slardar with config:",{bid:e.bid,release:e.release,env:e.env,userId:e.userId,projectId:e.projectId});const i={get(e){oo("Transport GET called: %s",e.url),so({method:"GET",...e})},post({url:e,data:t}){oo("Transport POST called: %s",e),so({method:"POST",url:e,data:t?"string"==typeof t?t:JSON.stringify(t):void 0})}};this.client.init({bid:e.bid,transport:i,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,o=()=>!1,null!=t?t:o()),domain:e.domain,sample:{sample_rate:1,include_users:[],sample_granularity:"session",rules:{}}}),this.client.on("send",(e=>{ro("send hook called for event: %s",no([e,"optionalAccess",e=>e.ev_type])||"unknown")})),this.client.start(),this.initialized=!0,ro("Slardar initialized successfully")}catch(e){ro("Failed to initialize:",e)}}ensureInitialized(){return!!this.initialized||(ro("Not initialized, call setup() first"),!1)}sendEvent(e,t,o){if(this.ensureInitialized())try{ro("Sending event:",{name:e,metrics:t,categories:o});const i=t?Object.fromEntries(Object.entries(t).filter((([,e])=>void 0!==e))):void 0,s=o?Object.fromEntries(Object.entries(o).filter((([,e])=>void 0!==e))):void 0;no([this,"access",e=>e.client,"access",e=>e.sendEvent,"optionalCall",t=>t({name:e,metrics:i,categories:s})])}catch(e){ro("Failed to send event:",e)}}sendLog(e,t,o){if(this.ensureInitialized())try{ro("Sending log:",{level:e,message:t,extra:o}),this.sendEvent("cli_log",void 0,{level:e,message:t,...o})}catch(e){ro("Failed to send log:",e)}}reportError(e,t,o){if(this.ensureInitialized())try{const i={ev_type:"js_error",payload:{error:{name:e.name,message:e.message,stack:e.stack},breadcrumbs:[],extra:t,source:o||{type:"manual"}}};ro("Reporting JS error:",{name:e.name,message:e.message.slice(0,100),stack:no([e,"access",e=>e.stack,"optionalAccess",e=>e.slice,"call",e=>e(0,200)]),extra:t,source:o}),this.client.report(i),ro("JS error reported successfully")}catch(e){ro("Failed to report error:",e)}}setContext(e,t){this.ensureInitialized()&&no([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.set,"call",o=>o(e,t)])}mergeContext(e){this.ensureInitialized()&&(ro("Merging context:",e),no([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.merge,"call",t=>t(e)]))}deleteContext(e){this.ensureInitialized()&&no([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.delete,"call",t=>t(e)])}clearContext(){this.ensureInitialized()&&no([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.clear,"call",e=>e()])}updateConfig(e){if(this.ensureInitialized())try{ro("Updating config:",e),this.client.config({userId:e.userId,release:e.release,sessionId:e.sessionId,env:e.env})}catch(e){ro("Failed to update config:",e)}}async flush(e=1500){this.ensureInitialized()&&(ro("Flushing Slardar data..."),no([this,"access",e=>e.client,"access",e=>e.getSender,"optionalCall",e=>e(),"optionalAccess",e=>e.flush,"call",e=>e()]),ro("Waiting %dms for events to be sent...",e),await new Promise((t=>setTimeout(t,e))),ro("Slardar data flushed"))}getRawClient(){return this.client}}const co=new ao;function lo(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const po="cli_start",uo="cli_command",mo="cli_command_complete",go="cli_error",ho="network_request",fo="file_operation",_o={cliStart:e=>({name:po,metrics:{duration:0,...e}}),cliCommand:(e,t)=>({name:uo,categories:{command:e,args:lo([t,"optionalAccess",e=>e.args]),status:"running",...lo([t,"optionalAccess",e=>e.categories])},metrics:lo([t,"optionalAccess",e=>e.metrics])}),cliCommandComplete:(e,t,o,i)=>({name:mo,categories:{command:e,args:lo([i,"optionalAccess",e=>e.args]),status:t?"success":"fail",...lo([i,"optionalAccess",e=>e.categories])},metrics:{duration:o,...lo([i,"optionalAccess",e=>e.errorCode])&&{errorCode:i.errorCode}}}),networkRequest:(e,t)=>({name:ho,categories:{url:e,method:lo([t,"optionalAccess",e=>e.method])||"GET",statusCode:lo([t,"optionalAccess",e=>e.statusCode,"optionalAccess",e=>e.toString,"call",e=>e()]),status:lo([t,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:lo([t,"optionalAccess",e=>e.duration])}}),fileOperation:(e,t,o)=>({name:fo,categories:{operation:e,filePath:t,status:lo([o,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:lo([o,"optionalAccess",e=>e.duration]),fileSize:lo([o,"optionalAccess",e=>e.fileSize])}}),cliError:(e,t)=>({name:go,categories:{errorName:e.name,errorMessage:e.message,stack:e.stack||"",...t},metrics:{errorCode:1}})};function yo(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function bo(e){return(...t)=>{try{const o=e(...t);return o instanceof Promise?o.catch((()=>{})):o}catch(e){}}}const vo=bo((()=>{var e,t;co.setup({bid:"coze_cli",release:Z,env:"production",userId:process.env.USER||"",useLocalConfig:!1,domain:"mon.zijieapi.com"}),co.mergeContext({platform:process.platform,callerPlatform:(e=process.env.COZE_CLI_PLATFORM,t=()=>"unknown",null!=e?e:t()),nodeVersion:process.version,cliVersion:Z})})),wo=bo((e=>{const t=_o.cliCommand(e);co.sendEvent(t.name,t.metrics,t.categories)})),Eo=bo(((e,t,o,i)=>{const s=_o.cliCommandComplete(e,t,o,{errorCode:yo([i,"optionalAccess",e=>e.errorCode])});co.sendEvent(s.name,s.metrics,s.categories)})),Co=bo(((e,t)=>{co.reportError(e,t,{type:"cli",data:t})})),Io=bo((async()=>{await co.flush()}));async function Ao(e,t){if(e.config.disableTelemetry)return void await t();vo();const o=function(e){if(e.commandName)return e.commandName;const t=[];for(const o of e.argv){if(o.startsWith("-"))break;t.push(o)}return t.join(" ")||"unknown"}(e);wo(o);const i=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()-i;try{n?Eo(o,!0,e):(s&&Co(s,{command:o}),Eo(o,!1,e)),await Io()}catch(e){}}}function So(e,t){return null!=e?e:t()}const ko=s.getGlobalLogsDir();class jo{__init(){this.fileStream=null}__init2(){this.writeError=!1}constructor(e={}){jo.prototype.__init.call(this),jo.prototype.__init2.call(this),this.format=So(e.format,(()=>"text")),this.printToStderr=So(e.printToStderr,(()=>!1)),this.tags=So(e.tags,(()=>({}))),this.startTime=Date.now();const t=So(e.logFile,(()=>this.getDefaultLogPath()));this.logFile=t;try{this.ensureLogDir(),this.rotateLogFiles(),this.fileStream=a.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 n.join(ko,`${e}-${t}.log`)}ensureLogDir(){a.existsSync(ko)||a.mkdirSync(ko,{recursive:!0})}rotateLogFiles(){try{const e=a.readdirSync(ko).filter((e=>e.endsWith(".log"))).map((e=>({name:e,path:n.join(ko,e),mtime:a.statSync(n.join(ko,e)).mtime.getTime()}))).sort(((e,t)=>t.mtime-e.mtime));e.length>=10&&e.slice(9).forEach((e=>{try{a.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,o,i=this.printToStderr){const s=this.formatEntry(e,t,o);if(this.fileStream)try{this.fileStream.write(`${s}\n`)}catch(e){!this.writeError&&i&&(process.stderr.write("Warning: Log write failed\n"),this.writeError=!0)}i&&process.stderr.write(`${s}\n`)}formatEntry(e,t,o){const i=(new Date).toISOString(),s=Date.now()-this.startTime;if("json"===this.format){const n={level:e,timestamp:i,delta:s,...this.tags,message:t};return o.length>0&&(n.args=o),JSON.stringify(n)}const n=Object.entries(this.tags).map((([e,t])=>`${e}=${t}`)).join(" "),r=o.length>0?` ${o.map(String).join(" ")}`:"";return`${e.toUpperCase().padEnd(7)} [${i}] +${s}ms ${n} ${t}${r}`}close(){if(this.fileStream)try{this.fileStream.end()}catch(e){}}}function Po(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const zo=new Set(["authorization","cookie","set-cookie"]),To=/(^|_|-)(token|secret|password|authorization|cookie)(_|-|$)/i,Ro=Symbol("request-debug-json-parse-fallback");let xo=null,Lo=!1,Oo=!1;const Do=e.customFetch.fetch.bind(e.customFetch),Uo=e=>"[object Object]"===Object.prototype.toString.call(e),qo=e=>{try{return JSON.stringify(e)}catch(t){return JSON.stringify(String(e))}},Bo=e=>{if("string"!=typeof e)return"***";const t=e.trim(),o=Po([/^bearer\s+/i,"access",e=>e.exec,"call",e=>e(t),"optionalAccess",e=>e[0]]);return o?`${o}***`:"***"},Mo=(e,t)=>t&&To.test(t)?Bo(e):Array.isArray(e)?e.map((e=>Mo(e))):Uo(e)?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,Mo(t,e)]))):e,No=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?No(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)])))},$o=(e,t)=>e[t.toLowerCase()],Go=(e,t,o="binary")=>{const i=(e=>"string"==typeof e?p.Buffer.byteLength(e):p.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=[o];return t&&s.push(t),"number"==typeof i&&s.push(`${i} bytes`),`[${s.join("; ")}]`},Fo=(t,o)=>{if(null==t||""===t)return"<empty>";const i=Po([$o,"call",e=>e(o,"content-type"),"optionalAccess",e=>e.toLowerCase,"call",e=>e()]);if(Po([i,"optionalAccess",e=>e.includes,"call",e=>e("multipart/form-data")]))return Go(t,i,"multipart");if(t instanceof URLSearchParams)return qo(Mo(Object.fromEntries(Array.from(t.entries()))));if(p.Buffer.isBuffer(t)||t instanceof Uint8Array||t instanceof ArrayBuffer||"undefined"!=typeof Blob&&t instanceof Blob)return Go(t,i);if("string"==typeof t){const o=(t=>{const o=e.safeJsonParse(t,Ro);if(o!==Ro)return o})(t);return void 0!==o?qo(Mo(o)):JSON.stringify(t)}return Array.isArray(t)||Uo(t)?qo(Mo(t)):Go(t,i,typeof t)},Vo=(e,t)=>{try{return new URL(e,t).toString()}catch(o){return t?`${t}${e}`:e}},Wo=e=>{const t=No(e);return t["x-tt-logid"]||t["x-tt-log-id"]||t.logid||""},Ho=e=>(e||"GET").toUpperCase(),Jo=e=>{Lo&&xo&&(xo instanceof jo?xo.debugFileOnly(e):xo.debug(e))},Ko=({method:e,url:t,headers:o,body:i})=>{const s=No(o);Jo(`[DBG][HTTP][REQ] ${e} ${t}\nheaders: ${qo((e=>Object.fromEntries(Object.entries(e).map((([e,t])=>[e,zo.has(e)?Bo(t):t]))))(s))}\nbody: ${Fo(i,s)}`)},Qo=({method:e,url:t,status:o,logId:i})=>{Jo(`[DBG][HTTP][RES] ${e} ${t} status=${o} logid=${i||"-"}`)},Yo=({method:e,url:t,status:o,logId:i,message:s})=>{const n=(a=()=>"ERR",null!=(r=o)?r:a());var r,a;const c=s?` error=${JSON.stringify(s)}`:"";Jo(`[DBG][HTTP][ERR] ${e} ${t} status=${n} logid=${i||"-"}${c}`)},Zo=(e,t)=>t&&"body"in t?t.body:"object"==typeof e&&e&&"body"in e&&null!==e.body?"[request body stream]":void 0,Xo=()=>{e.axiosInstance.interceptors.request.use((e=>((e=>{const t=Ho(e.method),o=Vo(e.url||"",e.baseURL),i=No(e.headers);Ko({method:t,url:o,headers:i,body:e.data})})(e),e))),e.axiosInstance.interceptors.response.use((e=>((e=>{const t=Ho(Po([e,"access",e=>e.config,"optionalAccess",e=>e.method])),o=Vo(Po([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",Po([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Qo({method:t,url:o,status:e.status,logId:Wo(e.headers)})})(e),e)),(e=>((e=>{const t=Ho(Po([e,"access",e=>e.config,"optionalAccess",e=>e.method])),o=Vo(Po([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",Po([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Yo({method:t,url:o,status:Po([e,"access",e=>e.response,"optionalAccess",e=>e.status]),logId:Wo(Po([e,"access",e=>e.response,"optionalAccess",e=>e.headers])),message:e.message})})(e),Promise.reject(e))))},ei=()=>{e.customFetch.fetch=async(t,o)=>{const i=((e,t)=>Po([t,"optionalAccess",e=>e.method])?Ho(t.method):"object"==typeof e&&e&&"method"in e&&"string"==typeof e.method?Ho(e.method):"GET")(t,o),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,o);Ko({method:i,url:s,headers:n,body:Zo(t,o)});try{const e=await Do(t,o);return Qo({method:i,url:s,status:e.status,logId:Wo(e.headers)}),e}catch(e){throw Yo({method:i,url:s,message:e instanceof Error?e.message:String(e)}),e}}};function ti(e,t){return null!=e?e:t()}function oi(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}var ii;!function(e){e.AUTHORIZATION_PENDING="authorization_pending";e.SLOW_DOWN="slow_down";e.ACCESS_DENIED="access_denied";e.EXPIRED_TOKEN="expired_token"}(ii||(ii={}));const si=e=>new Promise((t=>setTimeout(t,e))),ni=e.createRequestClient({baseURL:"https://api.coze.com",useDefaultPlugins:!0,plugins:[{name:"oauth-error-handler",onError:t=>{if(e.isHttpError(t))throw t;const o=t,i=ti(oi([o,"access",e=>e.response,"optionalAccess",e=>e.data]),(()=>({}))),s=i.error_description||i.error||o.message,n={status:oi([o,"access",e=>e.response,"optionalAccess",e=>e.status]),code:i.error,config:o.config,response:o.response,data:i};throw new e.HttpError(ti(s,(()=>"OAuth request failed")),n)}}]});async function ri(e){return(await ni.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 ai=async(t,o)=>{const i=process.env.HTTP_PROXY||process.env.http_proxy,s=process.env.HTTPS_PROXY||process.env.https_proxy;if(s||i){const o=new u.EnvHttpProxyAgent;e.customFetch.setDispatcher(o);const[{HttpProxyAgent:n},{HttpsProxyAgent:r}]=await Promise.all([import("http-proxy-agent"),import("https-proxy-agent")]);e.axiosInstance$1.defaults.proxy=!1,ni.defaults.proxy=!1,s&&(e.axiosInstance$1.defaults.httpsAgent=new r(s),ni.defaults.httpsAgent=new r(s),t.ui.debug(`HTTPS proxy enabled: ${s}`)),i&&(e.axiosInstance$1.defaults.httpAgent=new n(i),ni.defaults.httpAgent=new n(i),t.ui.debug(`HTTP proxy enabled: ${i}`))}await o()};let ci=()=>{},li=null;const di=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),pi=(e,t)=>{return di(o=e)&&"function"==typeof o.set?(Object.entries(t).forEach((([t,o])=>{e.set(t,o)})),e):{...di(e)?e:{},...t};var o},ui=t=>{ci=t,null===li&&(li=e.axiosInstance$1.interceptors.request.use((t=>{const o=s.getCozeAccountHeaders(ci());return 0!==Object.keys(o).length&&s.shouldInjectCozeAccountHeader((t=>{const o=t.url;if(!o)return"";try{return new URL(o,t.baseURL||e.axiosInstance$1.defaults.baseURL).toString()}catch(e){return""}})(t))?(t.headers=pi(t.headers,o),t):t})))};async function mi(t,o){ui((()=>t.config.organizationId)),s.installScopedCozeAccountFetchHeader({getOrganizationId:()=>t.config.organizationId});const i=await t.auth.getValidAccessToken();e.axiosInstance$1.defaults.baseURL=t.config.apiBaseUrl;const n=`Bearer ${i}`;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 o()}function gi(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,o){let i=-1;return function s(n){if(n<=i)return Promise.reject(new Error("next() called multiple times"));i=n;let r=e[n];n===e.length&&(r=o);if(!r)return Promise.resolve();try{return Promise.resolve(r(t,s.bind(null,n+1)))}catch(e){return Promise.reject(e)}}(0)}}var hi,fi,_i,yi,bi,vi,wi,Ei,Ci,Ii,Ai,Si,ki,ji,Pi,zi,Ti,Ri,xi,Li,Oi,Di,Ui,qi,Bi,Mi,Ni,$i,Gi,Fi,Vi,Wi,Hi,Ji,Ki,Qi,Yi,Zi,Xi,es,ts,os,is,ss,ns,rs,as,cs,ls,ds,ps,us,ms,gs,hs,fs;function _s(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e.app="app";e.pat="pat"}(hi||(hi={})),function(e){e.can_apply2="CanApply";e.already_applied2="AlreadyApplied";e.joined4="Joined";e.deny3="Deny"}(fi||(fi={})),function(e){e.processing="Processing";e.approved="Approved";e.rejected="Rejected";e.auto_approved="AutoApproved"}(_i||(_i={})),function(e){e.normal="Normal";e.connector="Connector";e.privilege="Privilege"}(yi||(yi={})),function(e){e.auth_app="AuthApp";e.on_behalf_of_user="OnBehalfOfUser"}(bi||(bi={})),function(e){e.password="Password";e.sms="Sms";e.email="Email";e.unknown3="Unknown"}(vi||(vi={})),function(e){e.email2="Email";e.phone="Phone";e.unknown4="Unknown"}(wi||(wi={})),function(e){e.authorized="authorized";e.unauthorized="unauthorized";e.expired4="expired"}(Ei||(Ei={})),function(e){e.api_key="api_key";e.wechat_official="wechat_official";e.oauth_2="oauth2"}(Ci||(Ci={})),function(e){e.noncertificated="Noncertificated";e.certificated="Certificated"}(Ii||(Ii={})),function(e){e.uncertified="Uncertified";e.personal_certification="PersonalCertification";e.enterprise_certification="EnterpriseCertification"}(Ai||(Ai={})),function(e){e.obo="Obo";e.app_auth="AppAuth";e.personal_access_token="PersonalAccessToken"}(Si||(Si={})),function(e){e.legacy="Legacy";e.web_backend="WebBackend";e.single_page_or_native="SinglePageOrNative";e.terminal="Terminal";e.service="Service"}(ki||(ki={})),function(e){e.bot_editor="BotEditor";e.bot_developer="BotDeveloper";e.bot_operator="BotOperator"}(ji||(ji={})),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"}(zi||(zi={})),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"}(Ri||(Ri={})),function(e){e._12="1";e._302="30";e._902="90";e._1802="180";e._3652="365";e.customize2="customize";e.permanent2="permanent"}(xi||(xi={})),function(e){e.aes_256_gcm="AES-256-GCM"}(Li||(Li={})),function(e){e.conversation="Conversation";e.unknown="Unknown"}(Oi||(Oi={})),function(e){e.active3="Active";e.inactive="Inactive"}(Di||(Di={})),function(e){e.cloud_kms="CloudKMS",e.default="Default";e.unknown2="Unknown"}(Ui||(Ui={})),function(e){e.user_custom2="user_custom";e.consumer3="consumer"}(qi||(qi={})),function(e){e.volcano="Volcano";e.coze_team="CozeTeam"}(Bi||(Bi={})),function(e){e.super_admin="SuperAdmin";e.admin="Admin";e.member="Member";e.guest="Guest"}(Mi||(Mi={})),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"}(Ni||(Ni={})),function(e){e.string="String";e.boolean="Boolean";e.integer="Integer";e.string_list="StringList"}($i||($i={})),function(e){e.must_handle="MustHandle";e.no_need_handle="NoNeedHandle"}(Gi||(Gi={})),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"}(Fi||(Fi={})),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"}(Vi||(Vi={})),function(e){e.confirming2="Confirming";e.joined3="Joined";e.rejected3="Rejected";e.revoked2="Revoked";e.expired3="Expired";e.deny2="Deny"}(Wi||(Wi={})),function(e){e.confirming="Confirming";e.joined2="Joined";e.rejected2="Rejected";e.revoked="Revoked";e.expired2="Expired"}(Hi||(Hi={})),function(e){e.can_join="CanJoin";e.guest_prohibited_by_enterprise="GuestProhibitedByEnterprise";e.guest_prohibited_by_invited_user_enterprise="GuestProhibitedByInvitedUserEnterprise"}(Ji||(Ji={})),function(e){e.can_apply="CanApply";e.already_applied="AlreadyApplied";e.joined="Joined";e.expired="Expired";e.deny="Deny"}(Ki||(Ki={})),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";e.coze_team_advanced="CozeTeamAdvanced";e.coze_team_pro="CozeTeamPro";e.coze_team_ultra="CozeTeamUltra"}(Qi||(Qi={})),function(e){e.user_custom_only="user_custom_only";e.all2="all"}(Yi||(Yi={})),function(e){e.system="system";e.custom="custom"}(Zi||(Zi={})),function(e){e.not_in_enterprise="NotInEnterprise";e.prohibited_by_custom_people_management2="ProhibitedByCustomPeopleManagement"}(Xi||(Xi={})),function(e){e.can_apply3="CanApply";e.already_applied3="AlreadyApplied";e.joined5="Joined";e.deny4="Deny"}(es||(es={})),function(e){e.super_admin2="SuperAdmin";e.admin2="Admin";e.member2="Member";e.guest2="Guest"}(ts||(ts={})),function(e){e.member_joining_auto_approved="MemberJoiningAutoApproved"}(os||(os={})),function(e){e.string2="String";e.boolean2="Boolean";e.integer2="Integer";e.string_list2="StringList"}(is||(is={})),function(e){e.developer="developer";e.consumer2="consumer"}(ss||(ss={})),function(e){e.all="all";e.owned="owned";e.others="others"}(ns||(ns={})),function(e){e.enterprise_member="EnterpriseMember";e.enterprise_guest="EnterpriseGuest"}(rs||(rs={})),function(e){e.not_created="NotCreated";e.enabled="Enabled";e.disabled="Disabled"}(as||(as={})),function(e){e.not_created2="NotCreated";e.not_support_not_supabase="NotSupportNotSupabase";e.enabled2="Enabled";e.disabled2="Disabled";e.not_support_project_type="NotSupportProjectType"}(cs||(cs={})),function(e){e.production="Production";e.development="Development"}(ls||(ls={})),(ds||(ds={})).skill="skill",function(e){e.dev="dev";e.prod="prod"}(ps||(ps={})),function(e){e.user_custom="user_custom";e.coze_default="coze_default";e.consumer="consumer"}(us||(us={})),function(e){e.active2="Active";e.deactive="Deactive"}(ms||(ms={})),function(e){e.active="active";e.deactivated="deactivated";e.offboarded="offboarded"}(gs||(gs={})),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";e.enterprise_member_list="enterprise_member_list";e.organization_member_list="organization_member_list"}(hs||(hs={})),function(e){e.root_user="RootUser";e.basic_user="BasicUser"}(fs||(fs={}));class ys{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){ys.prototype.__init.call(this),ys.prototype.__init2.call(this),this.request=_s([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=_s([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}CreatePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/create_personal_access_token_and_permission"),s={name:o.name,expire_at:o.expire_at,duration_day:o.duration_day,organization_id:o.organization_id,workspace_permission:o.workspace_permission,account_permission:o.account_permission,workspace_permission_v2:o.workspace_permission_v2,enterprise_permission:o.enterprise_permission},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}UpdatePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/update_personal_access_token_and_permission"),s={workspace_permission:o.workspace_permission,account_permission:o.account_permission,workspace_permission_v2:o.workspace_permission_v2,enterprise_permission:o.enterprise_permission,id:o.id,name:o.name},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}DeletePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/delete_personal_access_token_and_permission"),s={id:o.id};return this.request({url:i,method:"POST",data:s},t)}ListPersonalAccessTokens(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/pat/list_personal_access_tokens"),s={organization_id:o.organization_id,page:o.page,size:o.size,search_option:o.search_option};return this.request({url:i,method:"GET",params:s},t)}GetPersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/get_personal_access_token_and_permission"),s={id:o.id};return this.request({url:i,method:"GET",params:s},t)}ListPersonalAccessTokenSupportPermissions(e,t){const o=this.genBaseURL("/api/permission_api/pat/list_personal_access_token_support_permissions");return this.request({url:o,method:"GET"},t)}CheckPersonalAccessTokenInWorkspace(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/check_personal_access_token_in_workspace"),s={workspace_id:o.workspace_id};return this.request({url:i,method:"GET",params:s},t)}AddCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/add_collaborator"),s={collaborator_types:o.collaborator_types,principal:o.principal,resource:o.resource};return this.request({url:i,method:"POST",data:s},t)}RemoveCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/remove_collaborator"),s={principal:o.principal,resource:o.resource};return this.request({url:i,method:"POST",data:s},t)}CreateAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/create_app_meta"),s={app_type:o.app_type,client_type:o.client_type,name:o.name,description:o.description,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListAppMeta(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/list_app_meta"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}GetAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_meta"),s={appid:o.appid},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}UpdateAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/update_app_meta"),s={status:o.status,oauth2_configuration:o.oauth2_configuration,appid:o.appid,name:o.name,description:o.description,declared_permission:o.declared_permission,declared_permission_v2:o.declared_permission_v2},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}UploadPublicKey(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/upload_public_key"),s={appid:o.appid,public_key_pem:o.public_key_pem};return this.request({url:i,method:"POST",data:s},t)}DeletePublicKey(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_public_key"),s={fingerprint:o.fingerprint};return this.request({url:i,method:"POST",data:s},t)}CreateClientSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/create_client_secret"),s={appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}DeleteClientSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_client_secret"),s={appid:o.appid,client_secret_id:o.client_secret_id};return this.request({url:i,method:"POST",data:s},t)}PutOAuth2Configuration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/put_oauth2_configuration"),s={oauth2_configuration:o.oauth2_configuration,appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}AuthorizeAppWithDeclaredPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/authorize_app_with_declared_permission"),s={appid:o.appid,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListAuthorizedApps(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/list_authorized_apps"),s={page:o.page,size:o.size},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetAppAuthorizationRequestInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_authorization_request_info"),s={authorize_key:o.authorize_key},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}RevokeAppAuthorizedPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/revoke_app_authorized_permission"),s={authorization_type:o.authorization_type,appid:o.appid,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DeleteApp(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_app"),s={appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}ModifyCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/modify_collaborator"),s={principal:o.principal,resource:o.resource,collaborator_types:o.collaborator_types};return this.request({url:i,method:"POST",data:s},t)}BatchAddCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/batch_add_collaborator"),s={principal_type:o.principal_type,resource:o.resource,principal_ids:o.principal_ids,collaborator_types:o.collaborator_types};return this.request({url:i,method:"POST",data:s},t)}GetAppInstallationRequestInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_installation_request_info"),s={appid:o.appid},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}AppInstallationConsent(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/app_installation_consent"),s={appid:o.appid,installation_account_hint:o.installation_account_hint};return this.request({url:i,method:"POST",data:s},t)}ImpersonateCozeUser(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/coze_web_app/impersonate_coze_user"),s={duration_seconds:o.duration_seconds,scope:o.scope,connector_info:o.connector_info};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoConnectInfoWithInsName(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_connect_info_with_ins_name");return this.request({url:o,method:"GET"},t)}GetVolcanoMaskedMobile(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_masked_mobile");return this.request({url:o,method:"GET"},t)}BindVolcano(e,t){const o=this.genBaseURL("/api/permission_api/volcano/bind_volcano");return this.request({url:o,method:"POST"},t)}AuthorizeAppWithSpecifiedWorkspace(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/authorize_app_with_specified_permission"),s={appid:o.appid,workspace_list:o.workspace_list,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetUserProfile(e,t){const o=this.genBaseURL("/v1/users/me");return this.request({url:o,method:"GET"},t)}ListAppAuthorizations(e,t){const o=e,i=this.genBaseURL(`/v1/oauth-apps/${o.appid}/authorizations`),s={page_num:o.page_num,page_size:o.page_size},n={authorization:o.authorization};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetCertificationInfo(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/get_certification_info");return this.request({url:o,method:"GET"},t)}NeedCreateEnterprise(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/need_create_enterprise");return this.request({url:o,method:"GET"},t)}CreateEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_enterprise"),s={name:o.name,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}ListEnterprise(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/enterprise/list_enterprises"),s={contain_enterprise_of_user:o.contain_enterprise_of_user,contain_organization_of_user:o.contain_organization_of_user,contain_guest_enterprise_of_user:o.contain_guest_enterprise_of_user,contain_coze_team_of_user:o.contain_coze_team_of_user,is_space:o.is_space};return this.request({url:i,method:"GET",params:s},t)}GetEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_enterprise"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"GET",params:s},t)}UpdateEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise"),s={enterprise_id:o.enterprise_id,name:o.name,icon_uri:o.icon_uri,replace_logo:o.replace_logo};return this.request({url:i,method:"POST",data:s},t)}UpdateEnterpriseSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_settings"),s={enterprise_id:o.enterprise_id,enterprise_settings:o.enterprise_settings};return this.request({url:i,method:"POST",data:s},t)}BatchAddEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_add_enterprise_people"),s={enterprise_id:o.enterprise_id,enterprise_people:o.enterprise_people,need_check_people_valid:o.need_check_people_valid};return this.request({url:i,method:"POST",data:s},t)}RemoveEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/remove_enterprise_people"),s={enterprise_id:o.enterprise_id,user_id:o.user_id,receiver:o.receiver,sync_default_organization:o.sync_default_organization};return this.request({url:i,method:"POST",data:s},t)}UpdateEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_people"),s={enterprise_id:o.enterprise_id,user_id:o.user_id,enterprise_role_type_list:o.enterprise_role_type_list,sync_default_organization:o.sync_default_organization};return this.request({url:i,method:"POST",data:s},t)}CreateEnterpriseInviteLink(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_enterprise_invite_link"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}CreateJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_join_application"),s={key:o.key,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}GetInviteInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_invite_info"),s={invite_key:o.invite_key};return this.request({url:i,method:"GET",params:s},t)}UpdateJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_application"),s={application_status:o.application_status,enterprise_id:o.enterprise_id,join_application_id_list:o.join_application_id_list};return this.request({url:i,method:"POST",data:s},t)}ListPersonalAccessTokensByCreator(e,t){const o=e,i=this.genBaseURL("/api/permission_api/permission/list_personal_access_tokens_by_creator"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}ListAppInstallations(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/list_app_installations"),s={enterprise_id:o.enterprise_id,organization_id:o.organization_id},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetEnterpriseSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_enterprise_settings"),s={enterprise_id:o.enterprise_id,enterprise_setting_key_list:o.enterprise_setting_key_list};return this.request({url:i,method:"POST",data:s},t)}SearchCanAddEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_can_add_enterprise_people"),s={people_type:o.people_type,enterprise_id:o.enterprise_id,search_key:o.search_key};return this.request({url:i,method:"POST",data:s},t)}SearchEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_enterprise_people"),s={people_type:o.people_type,enterprise_id:o.enterprise_id,search_key:o.search_key,enterprise_role_type_list:o.enterprise_role_type_list,need_volcano_user_info:o.need_volcano_user_info,need_people_number:o.need_people_number,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}ListJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_application"),s={application_status:o.application_status,enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PostAdapterMpV1Code2Session(e,t){const o=e||{},i=this.genBaseURL("/adapter/mp/v1/code2session"),s={bot_id:o.bot_id,app_id:o.app_id,connector_id:o.connector_id,code:o.code,with_userinfo:o.with_userinfo,execute_mode:o.execute_mode,agent_type:o.agent_type,agent_version:o.agent_version};return this.request({url:i,method:"POST",data:s},t)}SubmitAppOboInstallationReview(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/submit_app_obo_installation_review"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}InstallAppObo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/install_app_obo"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}UninstallAppObo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/uninstall_app_obo"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetChecklistForWorkspaceMigration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_checklist_for_workspace_migration"),s={workspace_id_list:o.workspace_id_list};return this.request({url:i,method:"POST",data:s},t)}CheckEnterpriseExist(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/check_enterprise_exist");return this.request({url:o,method:"GET"},t)}GetSSOSetting(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_sso_setting"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}BatchMigrateAuthorization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/batch_migrate_authorization"),s={authorization_list:o.authorization_list,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_invitation"),s={invitation_status:o.invitation_status,enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}RevokeJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/revoke_join_invitation"),s={enterprise_id:o.enterprise_id,join_invitation_id:o.join_invitation_id};return this.request({url:i,method:"POST",data:s},t)}UpdateJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_invitation"),s={enterprise_id:o.enterprise_id,join_invitation_id:o.join_invitation_id,joined:o.joined};return this.request({url:i,method:"POST",data:s},t)}GetJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_join_invitation"),s={join_invitation_id:o.join_invitation_id};return this.request({url:i,method:"POST",data:s},t)}SearchPeopleInOtherEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_people_in_other_enterprise"),s={enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}CreateApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_application_for_enterprise_member"),s={enterprise_id:o.enterprise_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}GetApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_application_for_enterprise_member"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}AuthorizeAppsAndPersonalaccesstokenListWithPersonalAccountPermission(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/authorize_apps_and_patlist_with_personalaccountpermission"),s={crossaccount_authinfo_list:o.crossaccount_authinfo_list};return this.request({url:i,method:"POST",data:s},t)}RevokeAppAndPersonalaccesstokenPersonalAccountPermission(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/revoke_app_and_pat_personalaccountpermission"),s={crossaccount_authinfo:o.crossaccount_authinfo};return this.request({url:i,method:"POST",data:s},t)}GetAppsAndPersonalAccessTokenListForPersonalAccountPermissionAuthorization(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/get_apps_and_patlist_for_personalaccountpermission_authorization"),s={page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}create_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/create_service_identity"),s={name:o.name,organization_id:o.organization_id,expire_at:o.expire_at,duration_day:o.duration_day,permission:o.permission},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}get_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/get_service_identity"),s={id:o.id};return this.request({url:i,method:"GET",params:s},t)}update_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/update_service_identity"),s={permission:o.permission,id:o.id,name:o.name,expire_at:o.expire_at,duration_day:o.duration_day},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}delete_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/delete_service_identity"),s={id:o.id};return this.request({url:i,method:"POST",params:s},t)}list_service_identities(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/service/list_service_identities"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}ListEncryptionConfiguration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterpise/list_encryption_configuration"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}UpdateEncryptionConfiguration(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/enterpise/update_encryption_configuration"),s={encryption_configuration:o.encryption_configuration};return this.request({url:i,method:"POST",data:s},t)}SearchOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_organization"),s={enterprise_id:o.enterprise_id,search_key:o.search_key,joined:o.joined,need_people_number:o.need_people_number,need_workspace_number:o.need_workspace_number,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}CreateOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_organization"),s={enterprise_id:o.enterprise_id,name:o.name,icon_uri:o.icon_uri,description:o.description};return this.request({url:i,method:"POST",data:s},t)}GetOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization"),s={organization_id:o.organization_id,name:o.name,icon_uri:o.icon_uri,description:o.description};return this.request({url:i,method:"POST",data:s},t)}SearchCanAddOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_can_add_organization_people"),s={organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}SearchOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_organization_people"),s={organization_role_type:o.organization_role_type,people_type:o.people_type,organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size,organization_role_type_list:o.organization_role_type_list};return this.request({url:i,method:"POST",data:s},t)}CreateJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_join_organization_application"),s={organization_id:o.organization_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}ListJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_organization_application"),s={application_status:o.application_status,organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}UpdateJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_organization_application"),s={application_status:o.application_status,organization_id:o.organization_id,join_application_id_list:o.join_application_id_list};return this.request({url:i,method:"POST",data:s},t)}GetOrganizationApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization_application_for_enterprise_member"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}CanCustomEncryptionConfiguration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterpise/can_custom_encryption_configuration"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"GET",params:s},t)}BatchAddOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_add_organization_people"),s={organization_id:o.organization_id,organization_people:o.organization_people};return this.request({url:i,method:"POST",data:s},t)}RemoveOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/remove_organization_people"),s={organization_id:o.organization_id,user_id:o.user_id,receiver:o.receiver};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization_people"),s={organization_role_type:o.organization_role_type,organization_id:o.organization_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}DownloadRemoteAttestationEvidence(e,t){const o=e,i=this.genBaseURL("/api/permission_api/aicc/download_remote_attestation_evidence"),s={component_name:o.component_name};return this.request({url:i,method:"GET",params:s},t)}GetAgentAiccInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/aicc/get_agent_aicc_info"),s={agent_id:o.agent_id};return this.request({url:i,method:"GET",params:s},t)}CheckDeleteOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/check_delete_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DeleteOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/delete_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListProjectUsers(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/list_project_users"),s={project_id:o.project_id,page_size:o.page_size,page_number:o.page_number,environment:o.environment,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectUser(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user"),s={environment:o.environment,project_id:o.project_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}GetProjectAuthConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}UpdateProjectAuthConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config"),s={project_id:o.project_id,configuration:o.configuration};return this.request({url:i,method:"POST",data:s},t)}ListProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/list_project_secret"),s={env:o.env,project_id:o.project_id,with_providers:o.with_providers,deploy_id:o.deploy_id,option:o.option};return this.request({url:i,method:"POST",data:s},t)}UpdateProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/update_project_secret"),s={project_id:o.project_id,update_secrets:o.update_secrets,update_cred_provider:o.update_cred_provider};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/delete_project_secret"),s={project_id:o.project_id,keys:o.keys,cred_provider_ids:o.cred_provider_ids};return this.request({url:i,method:"POST",data:s},t)}EncryptProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/encrypt_project_secret"),s={project_id:o.project_id,project_type:o.project_type,encrypt_secrets:o.encrypt_secrets};return this.request({url:i,method:"POST",data:s},t)}InsertProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/insert_project_secret"),s={project_id:o.project_id,insert_secrets:o.insert_secrets};return this.request({url:i,method:"POST",data:s},t)}OutboundAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/outbound_auth/callback"),s={session_id:o.session_id,error:o.error};return this.request({url:i,method:"GET",params:s},t)}CreateAgentAccessToken(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:o.project_id,deployment_env:o.deployment_env};return this.request({url:i,method:"POST",data:s},t)}ListAgentAccessTokens(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}DeleteAgentAccessToken(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={token_id:o.token_id,project_id:o.project_id};return this.request({url:i,method:"DELETE",data:s},t)}GenerateInviteCode(e,t){const o=this.genBaseURL("/api/permission_api/coze_user/generate_invite_code");return this.request({url:o,method:"POST"},t)}GetInviteCodeInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/coze_user/get_invite_code_info"),s={invite_code:o.invite_code};return this.request({url:i,method:"GET",params:s},t)}AuthorizeCredProvider(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/authorize"),s={provider_id:o.provider_id};return this.request({url:i,method:"GET",params:s},t)}ProjectSecretAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/project_secret/callback"),s={code:o.code,state:o.state,error:o.error};return this.request({url:i,method:"GET",params:s},t)}ListAuthInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/list_auth_info"),s={credential_ids:o.credential_ids};return this.request({url:i,method:"POST",data:s},t)}RevokeAuthorization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/revoke"),s={credential_id:o.credential_id};return this.request({url:i,method:"POST",data:s},t)}UpdateProjectAuthConfigV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config_v2"),s={environment:o.environment,project_id:o.project_id,configuration:o.configuration};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectUserV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user_v2"),s={environment:o.environment,project_id:o.project_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}VisibilityConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/visibility_config"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoLoginMaskedMobile(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_login_masked_mobile");return this.request({url:o,method:"GET"},t)}ListProjectUsersV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/list_project_users_v2"),s={environment:o.environment,project_id:o.project_id,page_size:o.page_size,page_number:o.page_number,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}GetProjectAuthConfigV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config_v2"),s={environment:o.environment,project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}BatchGetPeopleJoinedOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_get_people_joined_organization"),s={enterprise_id:o.enterprise_id,user_ids:o.user_ids};return this.request({url:i,method:"POST",data:s},t)}BatchRemoveOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_remove_organization_people"),s={enterprise_id:o.enterprise_id,remove_user_list:o.remove_user_list};return this.request({url:i,method:"POST",data:s},t)}BatchRemoveEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_remove_enterprise_people"),s={enterprise_id:o.enterprise_id,remove_user_list:o.remove_user_list};return this.request({url:i,method:"POST",data:s},t)}GetOrganizationSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization_settings"),s={organization_id:o.organization_id,organization_setting_key_list:o.organization_setting_key_list};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganizationSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization_settings"),s={organization_id:o.organization_id,organization_settings:o.organization_settings};return this.request({url:i,method:"POST",data:s},t)}GithubAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/github_auth/callback"),s={code:o.code,state:o.state,error:o.error};return this.request({url:i,method:"GET",params:s},t)}BatchListOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_list_organization_people"),s={organization_ids:o.organization_ids,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}}const bs=new ys({});function vs(e,t){return null!=e?e:t()}const ws=1e3,Es=Math.floor(new Date("2000-01-01T00:00:00.000Z").getTime()/ws),Cs=e=>e instanceof Error?e.message:String(e);class Is{constructor(e){this.ctx=e,this.config=e.config}getOAuthConfig(){return{baseURL:vs(this.config.openApiBaseUrl,(()=>s.DEFAULT_CONFIG.openApiBaseUrl)),clientId:vs(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",o="win32"===process.platform?["/c","start",'""',e]:[e],s="Failed to open browser automatically. Please open the URL manually.";try{const e=i.spawn(t,o,{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:i}=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 ni.post(t,{client_id:e.clientId},{baseURL:e.baseURL})).data}({baseURL:t,clientId:i}),n=`${s.verification_uri}?user_code=${s.user_code}`;this.ctx.ui.info(`Please visit ${o.underline(n)} and authorize the application.\n\nPrivacy Policy: ${o.underline("https://docs.coze.cn/guides/privacy")}\nTerms of Service: ${o.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,o){if(!t.poll)return ri(t);let i=5e3;for(o.ui.debug("Start Polling for device token..."),o.ui.debug(`Polling interval: ${i}ms`),o.ui.debug("Polling timeout: 30000ms");;)try{o.ui.debug(`Polling for device token..., ${JSON.stringify(t)}`);const e=await ri(t);return o.ui.debug(`Polling for device token success: ${JSON.stringify(e)}`),e}catch(t){if(e.isHttpError(t)){const e=t;o.ui.debug(`Polling for device token error, the error is a HttpError.\n logid: ${oi([e,"access",e=>e.response,"optionalAccess",e=>e.headers,"access",e=>e["x-tt-logid"]])}`),o.ui.debug(`Polling for device token error: ${JSON.stringify(ti(oi([e,"access",e=>e.toJSON,"optionalCall",e=>e()]),(()=>e)))}`);const s=e.data;if(oi([s,"optionalAccess",e=>e.error])===ii.AUTHORIZATION_PENDING){o.ui.debug("Polling for device token: user has not completed authorization yet."),await si(i);continue}if(oi([s,"optionalAccess",e=>e.error])===ii.SLOW_DOWN){i<3e4&&(i+=5e3),o.ui.debug(`Polling for device token: client is polling too frequently. Increasing interval to ${i}ms`),await si(i);continue}}const s=t;throw o.ui.debug(`Polling for device token error, the error is: ${s.message}\n ${s.stack}\n `),t}}({baseURL:t,clientId:i,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: ${Cs(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,o=!!this.config.refreshToken,{data:i}=await bs.GetUserProfile({},{baseURL:this.config.openApiBaseUrl}),s={logged_in:!0,user:i,token_expires_at:t?new Date(t).toISOString():o?void 0:"Never (PAT)"};this.ctx.response.print(s)}async getValidAccessToken(){const{accessToken:e,refreshToken:t,tokenExpiresAt:o}=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})(o))return e;this.ctx.ui.verbose("Access token is expired or expiring soon, refreshing...");try{const{baseURL:e,clientId:o}=this.getOAuthConfig(),i=await async function(e){const t={};return e.clientSecret&&(t.Authorization=`Bearer ${e.clientSecret}`),(await ni.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:o,refreshToken:t});return await this.saveOAuthToken(i),this.ctx.ui.verbose("Token refreshed successfully."),i.access_token}catch(e){return this.ctx.ui.error(`Failed to refresh token: ${Cs(e)}`),void await this.clearAuthData()}}}async saveOAuthToken(e){const t=(o=e.expires_in)>=Es?o*ws:Date.now()+o*ws;var o;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 As="",Ss="",ks="",js="",Ps="",zs="",Ts="",Rs="",xs="[PROC]",Ls="[INFO]",Os="[WARN]",Ds="[ERR]",Us="[DONE]",qs="[DBG]",Bs={debug:0,verbose:1,info:2,success:3,warn:4,error:5};function Ms(e){return`${ks}${Ss}${e}${As}`}class Ns{constructor(e,t,o="info"){var i,s;this.log=e,this.silent="json"===t,this.useColor=this.detectColorSupport(),this.level=o,this.levelPriority=(s=()=>2,null!=(i=Bs[o])?i:s())}detectColorSupport(){return!0===function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([process,"access",e=>e.stderr,"optionalAccess",e=>e.isTTY])&&void 0===process.env.NO_COLOR}paint(e,t){return this.useColor?`${e}${t}${As}`:t}shouldOutput(e){return!this.silent&&Bs[e]>=this.levelPriority}verbose(e,...t){this.log.verbose(e,...t),this.shouldOutput("verbose")&&process.stderr.write(`${Ms(xs)} ${this.paint(Ts,e)}\n`)}info(e,...t){this.log.info(e,...t),this.shouldOutput("info")&&process.stderr.write(`${Ms(Ls)} ${this.paint(As,e)}\n`)}warn(e,...t){this.log.warn(e,...t),this.shouldOutput("warn")&&process.stderr.write(`${Ms(Os)} ${this.paint(zs,e)}\n`)}error(e,...t){this.log.error(e,...t),this.shouldOutput("error")&&process.stderr.write(`${Ms(Ds)} ${this.paint(js,e)}\n`)}success(e,...t){this.log.success(e,...t),this.shouldOutput("success")&&process.stderr.write(`${Ms(Us)} ${this.paint(Ps,e)}\n`)}debug(e,...t){this.log.debug(e,...t),this.shouldOutput("debug")&&process.stderr.write(`${Ms(qs)} ${this.paint(Rs,e)}\n`)}}class $s{constructor(e){const{format:t}=e;this.format=t,this.formatter=function(e){return"text"===e?new M:new k}(t)}setNotice(e){this.notice={...this.notice,...e}}hasPendingNotice(){return void 0!==this.notice}print(e){const t=this.formatter.format(this.withNotice(e));process.stdout.write(t)}withNotice(e){if("json"!==this.format||!this.notice||"object"!=typeof e||null===e||Array.isArray(e))return e;const t={...e,_notice:this.notice};return this.notice=void 0,t}eprint(e){const t=this.formatter.formatError(e);process.stderr.write(t)}}function Gs(e,t){return null!=e?e:t()}const Fs=["config.json","skills",".skill-lock.json","logs","tasks","completion.sh"];async function Vs(e){try{return await A.access(e),!0}catch(e){return!1}}async function Ws(e,t){const o=Date.now();e.ui.verbose(`[Logger] CLI start: ${e.argv.join(" ")}`);try{await t()}finally{const t=Date.now()-o;e.ui.verbose(`[Logger] CLI end (took ${t}ms)`)}}var Hs,Js,Ks,Qs,Ys,Zs,Xs,en,tn,on,sn,nn,rn,an,cn,ln,dn,pn,un,mn,gn,hn,fn,_n,yn,bn,vn,wn,En,Cn,In,An,Sn,kn,jn,Pn,zn,Tn,Rn,xn,Ln,On,Dn,Un,qn,Bn,Mn,Nn,$n,Gn,Fn,Vn,Wn,Hn,Jn,Kn,Qn,Yn,Zn,Xn,er,tr,or,ir,sr,nr,rr,ar,cr,lr,dr,pr,ur,mr,gr,hr,fr,_r,yr,br,vr,wr,Er,Cr,Ir,Ar,Sr,kr,jr,Pr,zr,Tr,Rr,xr,Lr,Or,Dr,Ur,qr,Br,Mr,Nr,$r,Gr,Fr,Vr,Wr,Hr,Jr,Kr,Qr,Yr,Zr,Xr,ea,ta,oa,ia,sa,na,ra,aa,ca,la,da,pa,ua,ma,ga,ha,fa;function _a(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!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.OldVersion=0]="OldVersion";e[e.MiddleVersion=1]="MiddleVersion";e[e.NewVersion=2]="NewVersion";e[e.MiddleVersionNotPrompt=3]="MiddleVersionNotPrompt"}(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.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Ys||(Ys={})),function(e){e[e.Current=1]="Current";e[e.Previous=2]="Previous";e[e.Start=3]="Start";e[e.MostSuitable=4]="MostSuitable"}(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.Default=0]="Default";e[e.Function=1]="Function"}(en||(en={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned"}(tn||(tn={})),function(e){e[e.LimitedReadWrite=1]="LimitedReadWrite";e[e.ReadOnly=2]="ReadOnly";e[e.UnlimitedReadWrite=3]="UnlimitedReadWrite";e[e.RWModeMax=4]="RWModeMax"}(on||(on={})),function(e){e[e.Default=0]="Default";e[e.DouyinAvatar=1]="DouyinAvatar"}(sn||(sn={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(nn||(nn={})),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"}(rn||(rn={})),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"}(an||(an={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(cn||(cn={})),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"}(ln||(ln={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(dn||(dn={})),function(e){e[e.SLM=0]="SLM";e[e.LLM=1]="LLM"}(pn||(pn={})),function(e){e[e.Pre=1]="Pre";e[e.Post=2]="Post";e[e.PreAndPost=3]="PreAndPost"}(un||(un={})),function(e){e[e.Default=0]="Default";e[e.CustomizePrompt=1]="CustomizePrompt"}(mn||(mn={})),function(e){e[e.ReplyBottom=0]="ReplyBottom";e[e.CardList=1]="CardList"}(gn||(gn={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(hn||(hn={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(fn||(fn={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(_n||(_n={})),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"}(yn||(yn={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(bn||(bn={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(vn||(vn={})),function(e){e[e.Curve=0]="Curve";e[e.Straight=1]="Straight"}(wn||(wn={})),function(e){e[e.Flow=1]="Flow";e[e.Host=2]="Host"}(En||(En={})),function(e){e[e.NO_NEED=1]="NO_NEED";e[e.USE_MANUAL=2]="USE_MANUAL";e[e.USE_LLM=3]="USE_LLM"}(Cn||(Cn={})),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"}(In||(In={})),function(e){e[e.Input=0]="Input";e[e.Variable=1]="Variable"}(An||(An={})),function(e){e[e.Default=0]="Default";e[e.FromSaas=1]="FromSaas"}(Sn||(Sn={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(kn||(kn={})),function(e){e[e.FunctionCall=1]="FunctionCall";e[e.Independent=2]="Independent"}(jn||(jn={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(Pn||(Pn={})),function(e){e[e.ManualUpdate=1]="ManualUpdate";e[e.AutoUpdate=2]="AutoUpdate"}(zn||(zn={})),function(e){e[e.SemanticSearch=0]="SemanticSearch";e[e.HybirdSearch=1]="HybirdSearch";e[e.FullTextSearch=20]="FullTextSearch"}(Tn||(Tn={})),function(e){e[e.Public=1]="Public";e[e.Anonymous=2]="Anonymous";e[e.Custom=3]="Custom"}(Rn||(Rn={})),function(e){e[e.Random=0]="Random";e[e.All=1]="All"}(xn||(xn={})),function(e){e[e.System=0]="System";e[e.Custom=1]="Custom";e[e.Disable=2]="Disable";e[e.OriBot=3]="OriBot"}(Ln||(Ln={})),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"}(On||(On={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Dn||(Dn={})),function(e){e[e.CozeOldTimeCapsule=0]="CozeOldTimeCapsule";e[e.VolcanoTimeCapsule=1]="VolcanoTimeCapsule"}(Un||(Un={})),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"}(qn||(qn={})),function(e){e[e.BotQuery=1]="BotQuery";e[e.Plugin=2]="Plugin";e[e.Workflow=3]="Workflow"}(Bn||(Bn={})),function(e){e[e.Unknown=0]="Unknown";e[e.Webhook=1]="Webhook"}(Mn||(Mn={})),function(e){e[e.Unknown=0]="Unknown";e[e.Time=1]="Time";e[e.Event=2]="Event"}(Nn||(Nn={})),function(e){e[e.NoHistory=0]="NoHistory";e[e.NeedHistory=1]="NeedHistory"}($n||($n={})),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"}(Gn||(Gn={})),function(e){e[e.Init=0]="Init";e[e.Activated=1]="Activated";e[e.Deactivated=2]="Deactivated";e[e.Suspended=3]="Suspended"}(Fn||(Fn={})),function(e){e[e.Preset=1]="Preset";e[e.UserTask=2]="UserTask";e[e.PluginRunTask=3]="PluginRunTask"}(Vn||(Vn={})),function(e){e[e.Deploying=0]="Deploying";e[e.Successful=1]="Successful";e[e.Failed=2]="Failed"}(Wn||(Wn={})),function(e){e[e.All=0]="All";e[e.Bind=1]="Bind";e[e.UnBind=2]="UnBind"}(Hn||(Hn={})),function(e){e[e.CreateTime=0]="CreateTime";e[e.UpdateTime=1]="UpdateTime"}(Jn||(Jn={})),function(e){e[e.EventMeta=1]="EventMeta";e[e.ProfileMeta=2]="ProfileMeta"}(Kn||(Kn={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Qn||(Qn={})),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"}(Yn||(Yn={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(Zn||(Zn={})),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"}(Xn||(Xn={})),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"}(er||(er={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(tr||(tr={})),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"}(or||(or={})),function(e){e[e.Upgrade=1]="Upgrade";e[e.BrowseOldNoPrompt=2]="BrowseOldNoPrompt"}(ir||(ir={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(sr||(sr={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(nr||(nr={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(rr||(rr={})),function(e){e[e.Visit=1]="Visit";e[e.Edit=2]="Edit"}(ar||(ar={})),function(e){e[e.Online=1]="Online";e[e.Offline=2]="Offline"}(cr||(cr={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online"}(lr||(lr={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(dr||(dr={})),function(e){e[e.AutoGenBeforePublish=1]="AutoGenBeforePublish"}(pr||(pr={})),function(e){e[e.CozeHome=1]="CozeHome";e[e.Space=2]="Space"}(ur||(ur={})),function(e){e[e.Undefined=0]="Undefined";e[e.PersonalDraft=1]="PersonalDraft";e[e.Base=2]="Base";e[e.Publish=3]="Publish"}(mr||(mr={})),function(e){e[e.Undefined=0]="Undefined";e[e.Committed=1]="Committed";e[e.Behind=2]="Behind";e[e.NoDraftReplica=3]="NoDraftReplica"}(gr||(gr={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(hr||(hr={})),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"}(fr||(fr={})),function(e){e[e.Personal=1]="Personal";e[e.Organization=2]="Organization"}(_r||(_r={})),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"}(yr||(yr={})),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"}(br||(br={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned";e[e.MoveFail=3]="MoveFail"}(vr||(vr={})),function(e){e[e.ByteTree=1]="ByteTree";e[e.GPTAK=2]="GPTAK";e[e.MaasAK=3]="MaasAK"}(wr||(wr={})),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"}(Er||(Er={})),function(e){e[e.BotStore=1]="BotStore"}(Cr||(Cr={})),function(e){e[e.shorcutIcon=1]="shorcutIcon"}(Ir||(Ir={})),function(e){e[e.Onboarding=0]="Onboarding";e[e.BackgroundImage=1]="BackgroundImage"}(Ar||(Ar={})),function(e){e[e.BasicUser=1]="BasicUser";e[e.ExternalUser=2]="ExternalUser";e[e.RootUser=3]="RootUser"}(Sr||(Sr={})),function(e){e[e.GetInfo=1]="GetInfo"}(kr||(kr={})),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"}(jr||(jr={})),function(e){e[e.Apply=1]="Apply";e[e.Invite=2]="Invite";e[e.EnterpriseApply=3]="EnterpriseApply"}(Pr||(Pr={})),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"}(zr||(zr={})),function(e){e[e.Douyin=1]="Douyin"}(Tr||(Tr={})),function(e){e[e.GPTOpenAPI=1]="GPTOpenAPI";e[e.Maas=2]="Maas";e[e.LLMFlow=3]="LLMFlow";e[e.Merlin=4]="Merlin"}(Rr||(Rr={})),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"}(xr||(xr={})),function(e){e[e.All=0]="All";e[e.Unread=1]="Unread"}(Lr||(Lr={})),function(e){e[e.Bot=1]="Bot"}(Or||(Or={})),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"}(Dr||(Dr={})),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"}(Ur||(Ur={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ShortcutCommand=3]="ShortcutCommand";e[e.Task=4]="Task"}(qr||(qr={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Knowledge=4]="Knowledge"}(Br||(Br={})),function(e){e[e.NoPublish=0]="NoPublish";e[e.HadPublished=1]="HadPublished"}(Mr||(Mr={})),function(e){e[e.Success=1]="Success";e[e.Failed=2]="Failed";e[e.InReview=3]="InReview"}(Nr||(Nr={})),function(e){e[e.Unread=1]="Unread";e[e.Read=2]="Read"}($r||($r={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(Gr||(Gr={})),function(e){e[e.UnLimit=1]="UnLimit";e[e.Forbidden=2]="Forbidden"}(Fr||(Fr={})),function(e){e[e.Plugin=1]="Plugin";e[e.NewBotIDEGuide=2]="NewBotIDEGuide";e[e.NewBeginnerGuide=3]="NewBeginnerGuide"}(Vr||(Vr={})),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"}(Wr||(Wr={})),function(e){e[e.All=0]="All";e[e.Self=1]="Self"}(Hr||(Hr={})),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"}(Jr||(Jr={})),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"}(Kr||(Kr={})),function(e){e[e.EnterpriseUser=1]="EnterpriseUser";e[e.ExternalUser=2]="ExternalUser"}(Qr||(Qr={})),function(e){e[e.Normal=0]="Normal";e[e.DevMode=1]="DevMode"}(Yr||(Yr={})),function(e){e[e.DraftBot=1]="DraftBot";e[e.Project=2]="Project";e[e.Space=3]="Space";e[e.DouyinAvatarBot=4]="DouyinAvatarBot"}(Zr||(Zr={})),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"}(Xr||(Xr={})),function(e){e[e.Professional=1]="Professional"}(ea||(ea={})),function(e){e[e.Personal=1]="Personal";e[e.Team=2]="Team"}(ta||(ta={})),function(e){e[e.Dark=1]="Dark";e[e.Light=2]="Light"}(oa||(oa={})),function(e){e[e.AlwaysOn=0]="AlwaysOn";e[e.AlwaysOff=1]="AlwaysOff"}(ia||(ia={})),function(e){e[e.CozeAssistantGuide=1]="CozeAssistantGuide"}(sa||(sa={})),function(e){e[e.Normal=1]="Normal";e[e.Banned=2]="Banned";e[e.Canceled=3]="Canceled"}(na||(na={})),function(e){e[e.External=0]="External";e[e.Internal=1]="Internal"}(ra||(ra={})),function(e){e[e.Invisible=0]="Invisible";e[e.Visible=1]="Visible";e[e.SocietyInvisible=2]="SocietyInvisible"}(aa||(aa={})),function(e){e[e.SingleAgent=1]="SingleAgent";e[e.MultiAgent=2]="MultiAgent";e[e.WorkflowAsAgent=3]="WorkflowAsAgent"}(ca||(ca={})),function(e){e[e.Preset=1]="Preset";e[e.Library=2]="Library"}(la||(la={})),function(e){e[e.DatasetServiceValid=0]="DatasetServiceValid";e[e.DatasetServiceInvalid=1]="DatasetServiceInvalid"}(da||(da={})),function(e){e[e.DatasetValid=0]="DatasetValid";e[e.DatasetInvalid=1]="DatasetInvalid"}(pa||(pa={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(ua||(ua={})),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"}(ma||(ma={})),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"}(ga||(ga={})),function(e){e[e.SendTypeQuery=0]="SendTypeQuery";e[e.SendTypePanel=1]="SendTypePanel"}(ha||(ha={})),function(e){e[e.ToolTypeWorkFlow=1]="ToolTypeWorkFlow";e[e.ToolTypePlugin=2]="ToolTypePlugin"}(fa||(fa={}));class ya{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){ya.prototype.__init.call(this),ya.prototype.__init2.call(this),this.request=_a([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=_a([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}GetSpaceInfoV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/info"),s={space_id:o.space_id,join_space_type:o.join_space_type};return this.request({url:i,method:"POST",data:s},t)}DeleteSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/delete"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}SaveSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/save"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri,space_type:o.space_type,space_mode:o.space_mode,space_config:o.space_config,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetSpaceListV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/list"),s={search_word:o.search_word,enterprise_id:o.enterprise_id,organization_id:o.organization_id,scope_type:o.scope_type,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}UpdateAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_agent"),s={id:o.id,reference_id:o.reference_id,current_version:o.current_version,space_id:o.space_id,bot_id:o.bot_id,base_commit_version:o.base_commit_version,name:o.name,description:o.description,position:o.position,icon_uri:o.icon_uri,intents:o.intents,work_info:o.work_info,is_delete:o.is_delete};return this.request({url:i,method:"POST",data:s},t)}BatchCreateAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/batch_create_agent"),s={space_id:o.space_id,bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,agent_cnt:o.agent_cnt,base_commit_version:o.base_commit_version,version_compat:o.version_compat};return this.request({url:i,method:"POST",data:s},t)}GetPublishBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_publish_bot_list"),s={space_id:o.space_id,bot_mode:o.bot_mode,page_num:o.page_num,page_size:o.page_size,name:o.name,login_user_create:o.login_user_create,bot_id:o.bot_id};return this.request({url:i,method:"GET",params:s},t)}MGetBotByVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/mget_bot_by_version"),s={bot_versions:o.bot_versions,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}BotLastPublishInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_last_publish_info"),s={space_id:o.space_id,bot_id:o.bot_id,bot_mode:o.bot_mode};return this.request({url:i,method:"GET",params:s},t)}ProduceBot(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/produce/create_bot"),s={space_id:o.space_id,name:o.name,description:o.description,icon_url:o.icon_url,icon_uri:o.icon_uri,prompt:o.prompt,plugin_apis:o.plugin_apis,prologue:o.prologue,suggested_questions:o.suggested_questions,bot_source:o.bot_source};return this.request({url:i,method:"POST",data:s},t)}UpdateProducedBot(e,t){const o=e,i=this.genBaseURL("/api/playground_api/produce/update_bot"),s={bot_id:o.bot_id,name:o.name,description:o.description,icon_url:o.icon_url,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetPublishedBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_version/get_published_bot_list"),s={space_id_list:o.space_id_list,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}GetBotVersionInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_version/get_bot_version_info"),s={bot_id:o.bot_id,version:o.version,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}DuplicateBotVersionToSpace(e,t){const o=e,i=this.genBaseURL("/api/playground_api/dup_bot_version"),s={target_space_id:o.target_space_id,bot_id:o.bot_id,version:o.version,name:o.name,dup_society_host:o.dup_society_host};return this.request({url:i,method:"POST",data:s},t)}UpdateUserRiskAlertInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/update_user_risk_alert_info"),s={risk_alert_type:o.risk_alert_type,switch_info:o.switch_info};return this.request({url:i,method:"POST",data:s},t)}GetUserRiskAlertInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_user_risk_alert_info"),s={risk_alert_type_list:o.risk_alert_type_list,switch_type_list:o.switch_type_list},n={Cookie:o.Cookie};return this.request({url:i,method:"POST",data:s,headers:n},t)}DraftBotCollaboration(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/collaboration"),s={space_id:o.space_id,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}BotInfoAudit(e,t){const o=e,i=this.genBaseURL("/api/playground_api/audit/bot_info"),s={bot_id:o.bot_id,bot_audit_info:o.bot_audit_info,space_id:o.space_id,bot_mode:o.bot_mode};return this.request({url:i,method:"POST",data:s},t)}TimeCapsuleInvokeEvent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/timecapsule_invoke_event"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}InviteMemberLinkV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/invite"),s={space_id:o.space_id,team_invite_link_status:o.team_invite_link_status,func:o.func};return this.request({url:i,method:"POST",data:s},t)}SpaceMemberDetailV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/detail"),s={space_id:o.space_id,search_word:o.search_word,space_role_type:o.space_role_type,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}JoinSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/join"),s={space_id:o.space_id,join_space_type:o.join_space_type,is_reject:o.is_reject};return this.request({url:i,method:"POST",data:s},t)}UpdateSpaceMemberV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/update"),s={space_id:o.space_id,user_id:o.user_id,space_role_type:o.space_role_type};return this.request({url:i,method:"POST",data:s},t)}TransferSpaceV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/transfer"),s={space_id:o.space_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}RemoveSpaceMemberV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/remove"),s={space_id:o.space_id,remove_user_id:o.remove_user_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}SearchMemberV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/member/search"),s={search_list:o.search_list,space_id:o.space_id,search_volcano_account_list:o.search_volcano_account_list,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}AddBotSpaceMemberV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/member/add"),s={member_info_list:o.member_info_list,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}ExitSpaceV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/exit"),s={space_id:o.space_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}GetBotPopupInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/operate/get_bot_popup_info"),s={bot_popup_types:o.bot_popup_types,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}UpdateBotPopupInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/operate/update_bot_popup_info"),s={bot_popup_type:o.bot_popup_type,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}GenerateDescription(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/generate_description"),s={bot_name:o.bot_name,prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}DraftBotPublishHistoryDetail(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/publish_history_detail"),s={bot_id:o.bot_id,space_id:o.space_id,publish_id:o.publish_id,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GenerateStoreCategory(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/generate_store_category"),s={bot_name:o.bot_name,bot_description:o.bot_description,prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}UpdateMultiAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_multi_agent"),s={space_id:o.space_id,bot_id:o.bot_id,session_type:o.session_type,base_commit_version:o.base_commit_version,connector_type:o.connector_type};return this.request({url:i,method:"POST",data:s},t)}SwitchAgentVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/switch_agent_version"),s={bot_id:o.bot_id,space_id:o.space_id,operate_type:o.operate_type};return this.request({url:i,method:"POST",data:s},t)}LangDetect(e,t){const o=e,i=this.genBaseURL("/api/playground_api/audio/lang/detect"),s={detect_text_list:o.detect_text_list};return this.request({url:i,method:"POST",data:s},t)}GetImagexShortUrl(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_imagex_url"),s={uris:o.uris,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetPlatformCommonConfig(e,t){const o=this.genBaseURL("/api/playground_api/get_platform_common_config");return this.request({url:o,method:"GET"},t)}CreateShortcutCommand(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/create_shortcut_command"),s={object_id:o.object_id,shortcuts:o.shortcuts};return this.request({url:i,method:"POST",data:s},t)}MGetUserBasicInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/mget_user_info"),s={user_ids:o.user_ids,need_user_status:o.need_user_status,need_enterprise_identity:o.need_enterprise_identity,need_volcano_user_name:o.need_volcano_user_name};return this.request({url:i,method:"POST",data:s},t)}BindVolcanoTrn(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/bind_volcano_trn"),s={space_id:o.space_id,trn:o.trn,account_name:o.account_name};return this.request({url:i,method:"POST",data:s},t)}UnbindVolcanoTrn(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/unbind_volcano_trn"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}RetrieveFileOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/retrieve"),s={file_id:o.file_id};return this.request({url:i,method:"GET",params:s},t)}RetrieveFileContentOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/content/retrieve"),s={file_id:o.file_id};return this.request({url:i,method:"GET",params:s},t)}UploadFileOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/upload"),s={Data:o.Data},n={"Content-Type":o["Content-Type"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}BotInfoCheck(e,t){const o=e,i=this.genBaseURL("/api/playground_api/check/bot_info_check"),s={bot_id:o.bot_id,space_id:o.space_id,bot_audit_info:o.bot_audit_info};return this.request({url:i,method:"POST",data:s},t)}SupportVoiceCall(e,t){const o=e,i=this.genBaseURL("/api/playground_api/support_voice_call"),s={voice_id_list:o.voice_id_list};return this.request({url:i,method:"POST",data:s},t)}CreateUpdateShortcutCommand(e,t){const o=e,i=this.genBaseURL("/api/playground_api/create_update_shortcut_command"),s={object_id:o.object_id,space_id:o.space_id,shortcuts:o.shortcuts};return this.request({url:i,method:"POST",data:s},t)}MoveDraftBot(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/move_draft_bot"),s={bot_id:o.bot_id,target_spaceId:o.target_spaceId,from_spaceId:o.from_spaceId,move_action:o.move_action};return this.request({url:i,method:"POST",data:s},t)}GetShortcutAvailNodes(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_shortcut_avail_nodes"),s={bot_id:o.bot_id,space_id:o.space_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}MarkReadNotice(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/mark_read_notice"),s={bot_id:o.bot_id,pic_type:o.pic_type};return this.request({url:i,method:"POST",data:s},t)}CancelGenerateGif(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/cancel_generate_gif"),s={task_id:o.task_id};return this.request({url:i,method:"POST",data:s},t)}GetPicTask(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/get_pic_task"),s={bot_id:o.bot_id,pic_type:o.pic_type};return this.request({url:i,method:"POST",data:s},t)}GeneratePic(e,t){const o=e,i=this.genBaseURL("/api/playground_api/gen_img/generate_pic"),s={gen_prompt:o.gen_prompt,image_url:o.image_url,image_uri:o.image_uri,bot_id:o.bot_id,pic_type:o.pic_type,device_id:o.device_id,bot_name:o.bot_name,bot_desc:o.bot_desc};return this.request({url:i,method:"POST",data:s},t)}GetGenPicTimes(e,t){const o=this.genBaseURL("/api/playground_api/gen_img/get_gen_pic_times");return this.request({url:o,method:"POST"},t)}ListStyle(e,t){const o=this.genBaseURL("/api/playground_api/gen_img/list_style");return this.request({url:o,method:"POST"},t)}GetFileUrls(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_file_list"),s={scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetDraftBotInfoAgw(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/get_draft_bot_info"),s={bot_id:o.bot_id,version:o.version,commit_version:o.commit_version};return this.request({url:i,method:"POST",data:s},t)}CommitDraftBotInfoAgw(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/commit_draft_bot_info"),s={bot_id:o.bot_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}UpdateDraftBotInfoAgw(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/update_draft_bot_info"),s={bot_info:o.bot_info,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}GetUserQueryCollectOption(e,t){const o=this.genBaseURL("/api/playground_api/draftbot/get_user_query_collect_option");return this.request({url:o,method:"GET"},t)}GenerateUserQueryCollectPolicy(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/generate_user_query_collect_policy"),s={bot_id:o.bot_id,developer_name:o.developer_name,contact_information:o.contact_information};return this.request({url:i,method:"POST",data:s},t)}GetCozeProRights(e,t){const o=this.genBaseURL("/api/playground_api/get_coze_pro_rights");return this.request({url:o,method:"POST"},t)}GetPolicyContent(e,t){const o=e,i=this.genBaseURL(`/api/playground_api/private_policy/${o.secret}`);return this.request({url:i,method:"GET"},t)}UpdateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_agent_v2"),s={id:o.id,reference_id:o.reference_id,current_version:o.current_version,space_id:o.space_id,bot_id:o.bot_id,base_commit_version:o.base_commit_version,name:o.name,description:o.description,position:o.position,icon_uri:o.icon_uri,intents:o.intents,is_delete:o.is_delete,prompt_info:o.prompt_info,model_info:o.model_info,plugin_info_list:o.plugin_info_list,knowledge:o.knowledge,workflow_info_list:o.workflow_info_list,jump_config:o.jump_config,suggest_reply_info:o.suggest_reply_info,hook_info:o.hook_info};return this.request({url:i,method:"POST",data:s},t)}CopyAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/copy_agent_v2"),s={bot_id:o.bot_id,agent_id:o.agent_id,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}CreateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/create_agent_v2"),s={bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}BatchCreateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/batch_create_agent_v2"),s={bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,agent_cnt:o.agent_cnt,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyGetLinkMetaInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/get_link_meta_info"),s={auth_code:o.auth_code};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyTaskConfirm(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/copy_task_confirm"),s={auth_code:o.auth_code};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyGenerateAuthLink(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/generate_auth_link"),s={copy_user_id:o.copy_user_id,target_space_id:o.target_space_id};return this.request({url:i,method:"POST",data:s},t)}GetOpVoiceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_op_voice_list"),s={voice_ids:o.voice_ids,name:o.name,style_id:o.style_id,language_code:o.language_code,status:o.status,page_index:o.page_index,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetSupportLanguage(e,t){const o=this.genBaseURL("/api/playground_api/get_support_language");return this.request({url:o,method:"GET"},t)}SynchronizeVoiceList(e,t){const o=this.genBaseURL("/api/playground_api/synchronize_voice_list");return this.request({url:o,method:"GET"},t)}CheckBotAllModelPluginIds(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/check_bot_all_model_plugin_ids"),s={bot_id:o.bot_id,commit_version:o.commit_version};return this.request({url:i,method:"POST",data:s},t)}GetBotCollaborationQuota(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/collaboration_quota"),s={bot_id:o.bot_id,only_config_item:o.only_config_item,account_type:o.account_type};return this.request({url:i,method:"POST",data:s},t)}OpenCreateSpace(e,t){const o=e||{},i=this.genBaseURL("/v1/workspaces"),s={name:o.name,description:o.description,icon_file_id:o.icon_file_id,coze_account_id:o.coze_account_id,owner_uid:o.owner_uid};return this.request({url:i,method:"POST",data:s},t)}NoticeMarkRead(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/notice/mark_read"),s={notice_ids:o.notice_ids,mark_all:o.mark_all};return this.request({url:i,method:"POST",data:s},t)}GetNoticeList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/notice/get_list"),s={cursor:o.cursor,count:o.count,notice_rank_type:o.notice_rank_type};return this.request({url:i,method:"POST",data:s},t)}GetNoticeUnreadCount(e,t){const o=this.genBaseURL("/api/playground_api/notice/get_unread_count");return this.request({url:o,method:"POST"},t)}OpenSpaceList(e,t){const o=e||{},i=this.genBaseURL("/v1/workspaces"),s={page_num:o.page_num,page_size:o.page_size,enterprise_id:o.enterprise_id,user_id:o.user_id,coze_account_id:o.coze_account_id,scope:o.scope};return this.request({url:i,method:"GET",params:s},t)}ReportUserBehavior(e,t){const o=e,i=this.genBaseURL("/api/playground_api/report_user_behavior"),s={resource_id:o.resource_id,resource_type:o.resource_type,behavior_type:o.behavior_type,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_user_config"),s={risk_alert_type_list:o.risk_alert_type_list,switch_type_list:o.switch_type_list},n={Cookie:o.Cookie};return this.request({url:i,method:"POST",data:s,headers:n},t)}UpdateUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/update_user_config"),s={risk_alert_type:o.risk_alert_type,switch_info:o.switch_info};return this.request({url:i,method:"POST",data:s},t)}GetRecentDraftBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/get_recent_draft_bot"),s={behavior_type:o.behavior_type,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}GetPromptResourceInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_prompt_resource_info"),s={prompt_resource_id:o.prompt_resource_id};return this.request({url:i,method:"GET",params:s},t)}UpsertPromptResource(e,t){const o=e,i=this.genBaseURL("/api/playground_api/upsert_prompt_resource"),s={prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}DeletePromptResource(e,t){const o=e,i=this.genBaseURL("/api/playground_api/delete_prompt_resource"),s={prompt_resource_id:o.prompt_resource_id};return this.request({url:i,method:"POST",data:s},t)}GetPromptReferenceInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_prompt_reference_info"),s={space_id:o.space_id,reference_id:o.reference_id,reference_type:o.reference_type,api_id:o.api_id,project_id:o.project_id,avatar_bot_id:o.avatar_bot_id};return this.request({url:i,method:"POST",data:s},t)}GetOfficialPromptResourceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_official_prompt_list"),s={keyword:o.keyword};return this.request({url:i,method:"POST",data:s},t)}GetByteTreeByName(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/search_byte_tree"),s={name:o.name},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}CreatePrivateModel(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/create_private_model"),s={space_id:o.space_id,model_vendor:o.model_vendor,model_show_name:o.model_show_name,model_arch:o.model_arch,ak:o.ak,token_limit:o.token_limit,upper_limit_of_max_token:o.upper_limit_of_max_token,function_call:o.function_call,multimodal:o.multimodal,multimodal_types:o.multimodal_types,form_detail:o.form_detail,record_id:o.record_id,maas_model_name:o.maas_model_name,maas_model_version:o.maas_model_version,maas_model_customer_id:o.maas_model_customer_id,model_family:o.model_family,space_id_i18n:o.space_id_i18n,operator:o.operator,email:o.email,employee_id:o.employee_id,presence_penalty_config:o.presence_penalty_config,frequency_penalty_config:o.frequency_penalty_config,temperature_config:o.temperature_config,top_p_config:o.top_p_config},n={"x-inner-auth":o["x-inner-auth"],"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}CheckExemptFormInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/check_exempt_form_info"),s={exempt_form_type:o.exempt_form_type,space_id:o.space_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}SetByteTreeForSpace(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/set_byte_tree_for_space"),s={space_id:o.space_id,byte_tree_node_id:o.byte_tree_node_id,byte_tree_node_name:o.byte_tree_node_name,form_detail:o.form_detail,record_id:o.record_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetModelCapability(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bpm/get_model_capability"),s={vendor:o.vendor,model_arch:o.model_arch,maas_model_name:o.maas_model_name,maas_model_version:o.maas_model_version,maas_customer_id:o.maas_customer_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetSpaceDetail(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/detail"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}RevocateSpaceInvite(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/revocate_invite"),s={space_id:o.space_id,invite_user_id:o.invite_user_id};return this.request({url:i,method:"GET",params:s},t)}SaveVolcanoUserManageInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/save_volcano_user_manage_info"),s={volcano_basic_user_config:o.volcano_basic_user_config};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoUserManageInfo(e,t){const o=this.genBaseURL("/api/playground_api/coze_pro/get_volcano_user_manage_info");return this.request({url:o,method:"POST"},t)}GetSpaceInviteManageList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/invite_manage_list"),s={space_id:o.space_id,space_invite_status:o.space_invite_status,search_word:o.search_word,page:o.page,size:o.size};return this.request({url:i,method:"GET",params:s},t)}DebugDouYin(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/debug"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}GetDouYinAuthCode(e,t){const o=this.genBaseURL("/api/playground_api/douyin/get_auth_qr_code");return this.request({url:o,method:"GET"},t)}GetDouyinAvatarInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/douyin/v1/get_avatar_info"),s={is_draft:o.is_draft,body:o.body},n={"Open-Platform-App-ID":o["Open-Platform-App-ID"],"Byte-Signature":o["Byte-Signature"],"Byte-Timestamp":o["Byte-Timestamp"],"Byte-Nonce-Str":o["Byte-Nonce-Str"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}DouYinAuthUserList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/auth_user_list"),s={page_index:o.page_index,page_size:o.page_size,bind_status:o.bind_status,order_by:o.order_by};return this.request({url:i,method:"POST",data:s},t)}GetDebugDouYinStatus(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/get_debug_status"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}CanUserApplyClose(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/coze_pro/can_user_apply_close"),s={AccountId:o.AccountId,EventName:o.EventName,Action:o.Action,Version:o.Version},n={"X-Tt-Logid":o["X-Tt-Logid"],"X-Top-Service":o["X-Top-Service"],"X-Top-Region":o["X-Top-Region"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}CreateRoom(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/create_room"),s={bot_id:o.bot_id,conversation_id:o.conversation_id,scene:o.scene,voice_id:o.voice_id,video_config:o.video_config};return this.request({url:i,method:"POST",data:s},t)}GetVoiceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_list"),s={page_index:o.page_index,page_size:o.page_size,language_code:o.language_code};return this.request({url:i,method:"POST",data:s},t)}GetVoiceByIds(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_by_ids"),s={voice_id_map:o.voice_id_map,voice_type:o.voice_type,space_id:o.space_id,emotion_config:o.emotion_config,voice_biz_scene:o.voice_biz_scene};return this.request({url:i,method:"POST",data:s},t)}GrayVoice(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gray_voice"),s={bot_id:o.bot_id,language_to_voice_id:o.language_to_voice_id};return this.request({url:i,method:"POST",data:s},t)}GetSpaceApplyManageList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/apply_manage_list"),s={space_id:o.space_id,space_apply_status:o.space_apply_status,search_word:o.search_word,page:o.page,size:o.size};return this.request({url:i,method:"GET",params:s},t)}DraftBotCrossSpaceCopy(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/crossspace_copy"),s={bot_id:o.bot_id,to_space_id:o.to_space_id};return this.request({url:i,method:"POST",data:s},t)}RemovePublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/remove_publish_member"),s={space_id:o.space_id,member_list:o.member_list};return this.request({url:i,method:"POST",data:s},t)}AddPublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/add_publish_member"),s={space_id:o.space_id,member_list:o.member_list};return this.request({url:i,method:"POST",data:s},t)}SearchAddablePublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/search_addable_publish_member"),s={space_id:o.space_id,search_word:o.search_word,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}PublishMemberList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/publish_member_list"),s={space_id:o.space_id,search_word:o.search_word,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}OperateSpaceApply(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/operate_apply"),s={space_id:o.space_id,enterprise_id:o.enterprise_id,organization_id:o.organization_id,apply_id_list:o.apply_id_list,space_apply_status:o.space_apply_status};return this.request({url:i,method:"POST",data:s},t)}ImportSpaceConfirm(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/confirm"),s={space_id_list:o.space_id_list,enterprise_id:o.enterprise_id,organization_id:o.organization_id,personal_space_new_name:o.personal_space_new_name,user_id_list:o.user_id_list};return this.request({url:i,method:"POST",data:s},t)}ImportSpaceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/list"),s={enterprise_id:o.enterprise_id,organization_id:o.organization_id,search_word:o.search_word};return this.request({url:i,method:"GET",params:s},t)}ImportSpaceUserList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/user_list"),s={space_id_list:o.space_id_list,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetDouYinInfo(e,t){const o=this.genBaseURL("/api/playground_api/douyin/get_douyin_info");return this.request({url:o,method:"POST"},t)}LongTermMemoryList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/list"),s={bot_id:o.bot_id,connector_id:o.connector_id,offset:o.offset,limit:o.limit,time_capsule_item_type:o.time_capsule_item_type};return this.request({url:i,method:"GET",params:s},t)}LongTermMemoryUpdate(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/update"),s={bot_id:o.bot_id,connector_id:o.connector_id,biz_id:o.biz_id,new_content:o.new_content,event_ms:o.event_ms,ext:o.ext,tags:o.tags,time_capsule_item_type:o.time_capsule_item_type,iid:o.iid,meta_type:o.meta_type,memory_type:o.memory_type};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryClearAll(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/clear_all"),s={bot_id:o.bot_id,connector_id:o.connector_id,time_capsule_item_type:o.time_capsule_item_type};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryDelete(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/delete"),s={bot_id:o.bot_id,connector_id:o.connector_id,biz_ids:o.biz_ids,time_capsule_item_type:o.time_capsule_item_type,iids:o.iids,memory_meta_type_map:o.memory_meta_type_map};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/version"),s={bot_id:o.bot_id};return this.request({url:i,method:"GET",params:s},t)}GetVoiceListV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_list_v2"),s={language_code:o.language_code,space_id:o.space_id,voice_type:o.voice_type,page_size:o.page_size,next_cursor:o.next_cursor};return this.request({url:i,method:"POST",data:s},t)}GetUserUpdateProfileTag(e,t){const o=this.genBaseURL("/api/playground_api/get_user_update_profile_tag");return this.request({url:o,method:"GET"},t)}OpenRemoveSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={user_ids:o.user_ids};return this.request({url:i,method:"DELETE",data:s},t)}OpenSpaceMemberList(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}OpenAddSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={users:o.users};return this.request({url:i,method:"POST",data:s},t)}OpenGetBotInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}`),s={is_published:o.is_published,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}OpenApplyJoinSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members/apply`),s={user_ids:o.user_ids};return this.request({url:i,method:"POST",data:s},t)}OpenRemoveSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}`);return this.request({url:i,method:"DELETE"},t)}GetTypeList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_type_list"),s={model:o.model,voice:o.voice,raw_model:o.raw_model,space_id:o.space_id,cur_model_id:o.cur_model_id,cur_model_ids:o.cur_model_ids,model_scene:o.model_scene,tag_filters:o.tag_filters};return this.request({url:i,method:"POST",data:s},t)}GetCozeLaneInfo(e,t){const o=this.genBaseURL("/api/playground_api/get_coze_lane_info");return this.request({url:o,method:"POST"},t)}OpenUpdateSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members/${o.user_id}`),s={role_type:o.role_type};return this.request({url:i,method:"PUT",data:s},t)}OpenListBotVersions(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}/versions`),s={page_num:o.page_num,page_size:o.page_size,publish_status:o.publish_status,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}OpenSwitchBotDevelopMode(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}/collaboration_mode`),s={collaboration_mode:o.collaboration_mode};return this.request({url:i,method:"POST",data:s},t)}OpenUpdateSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}`),s={name:o.name,description:o.description};return this.request({url:i,method:"PUT",data:s},t)}MGetUserDefaultSpace(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/default/mget"),s={organization_ids:o.organization_ids,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}SetDefaultSpace(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/default/set"),s={space_id:o.space_id,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}}const ba=new ya({});function va(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function wa(t,o){if(va([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"});if(va([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipOrgCheck]))return void await o();const i=await async function(t){const o=t.config.organizationId;if(!o)return!1;const{data:i}=await bs.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0}),s=i.enterprise_info_list||[];if(!s.some((e=>va([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>"});return!1}(t);if(va([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipSpaceCheck]))return i&&await Ea(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId}),void await o();const s=await async function(t){const o=t.config.organizationId,{enterpriseId:i}=t.config;let{spaceId:s}=t.config,n=!1;try{if(s){const{data:t}=await ba.GetSpaceListV2({organization_id:o,enterprise_id:i}),n=va([t,"optionalAccess",e=>e.bot_space_list])||[];if(!n.some((e=>e.id===s))){const t=o?`[Context] Space ID ${s} is invalid or not found in organization ${o}.`:`[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 ba.GetSpaceListV2({organization_id:o,enterprise_id:i,page:1,size:1}),a=va([r,"optionalAccess",e=>e.bot_space_list,"optionalAccess",e=>e[0]]);if(!a){const t=o?`[Context] No spaces found in organization ${o}. 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 o=t instanceof e.CozeError?t:new e.CozeError(e.ErrorCode.E5000,t.message,t instanceof Error?t.stack:t);throw o.fix??="Switch organization or space using `coze organization use <organization_id>` or `coze space use <space_id>`",o.example??="coze organization list",o}return n}(t);await Ca(t),(i||s)&&await Ea(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId,spaceId:t.config.spaceId,billingProjectId:t.config.billingProjectId}),await o()}async function Ea(e,t){try{await s.saveConfig(t)}catch(t){e.ui.warn(`Failed to save auto-initialized context: ${t}`)}}const Ca=async o=>{const{spaceId:i}=o.config;try{const{data:s}=await t.IdeApi.GetOrCreateBillingProject({space_id:i});if(!va([s,"optionalAccess",e=>e.project_id]))throw new e.CozeError(e.ErrorCode.E5002,"[Context] Failed to get billing project ID from response.",s);o.config.billingProjectId=s.project_id,o.ui.success(`[Context] Billing Project: ${s.project_id} (space: ${i})`)}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 Ia(e,t){return null!=e?e:t()}function Aa(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Sa=t=>{const o=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");o.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"}}}}},errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Not logged in or credentials have expired",fix:"Run `coze auth login` to authenticate first.",example:"coze auth login"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server failed to fetch the space list",fix:"Retry later; run with --debug for details if the issue persists"}],seeAlso:["coze space use","coze organization list"]}}).action((async(e,t)=>{const o=t.getContext(),i=e.orgId||Aa([o,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),s=Aa([o,"optionalAccess",e=>e.config,"access",e=>e.enterpriseId]);Aa([o,"optionalAccess",e=>e.ui,"access",e=>e.verbose,"call",e=>e(`Fetching spaces for organization '${i}'...`)]);const n=await async function(e){const{data:t}=await ba.GetSpaceListV2({organization_id:e.orgId,enterprise_id:e.enterpriseId,page:1,size:100});return Ia(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([t,"optionalAccess",e=>e.bot_space_list]),(()=>[])).map((t=>({id:Ia(t.id,(()=>"")),name:Ia(t.name,(()=>"")),org_id:Ia(e.orgId,(()=>""))})))}({orgId:i,enterpriseId:s});Aa([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Spaces:")]),Aa([o,"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>"];Aa([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(r.join("\n"))])})),o.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",description:"Operation result status"},message:{type:"string",description:"Human-readable result message"}}},errors:[{code:e.ErrorCode.E1102,name:"MISSING_ARGUMENT",desc:"Required argument <space_id> is not provided",fix:"Pass the space ID as the first argument; run `coze space list` to find it.",example:"coze space use 7349123847123"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to write the local configuration file",fix:"Check file permissions of the local config directory and retry"}],seeAlso:["coze space list","coze organization use"]}}).action((async(t,o,i)=>{const n=i.getContext();Aa([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(o){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set default space to '${t}': ${o.message}`,o.stack)}}(t),Aa([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default space set to '${t}' successfully.`)]),"json"===Aa([n,"optionalAccess",e=>e.format])&&Aa([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default space set to '${t}'.`})])}))};function ka(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ja=async e=>{ka([e,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switching to personal account...")]),await async function(){const e=!!(await s.loadConfig()).organizationId;await s.saveConfig({organizationId:void 0,enterpriseId:void 0,...e?{spaceId:void 0}:{}})}(),ka([e,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switched to personal account successfully.")]),"json"===ka([e,"optionalAccess",e=>e.format])&&ka([e,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:"Switched to personal account."})])},Pa=t=>{const o=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");o.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"}}}}},seeAlso:["coze organization use","coze space list"]}}).action((async(e,t)=>{const o=t.getContext();ka([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching organizations...")]);const i=await async function(){const{data:e}=await bs.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})))))}();ka([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Organizations (Teams):")]),ka([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(i)]);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>"];ka([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])})),o.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 (or pass an empty string) to switch to personal account mode.",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.E3000,name:"RESOURCE_NOT_FOUND",desc:"Organization not found",fix:"Run `coze organization list` to see available organizations."}],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)"}}},seeAlso:["coze organization list","coze space use"]}}).action((async(t,o,i)=>{const n=i.getContext();if(!t)return void await ja(n);ka([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to organization '${t}'...`)]);const{enterpriseId:r}=await async function(t){const[o,{data:i}]=await Promise.all([s.loadConfig(),bs.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);let n="",r=!1;for(const e of i.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=o.organizationId!==t;return await s.saveConfig({organizationId:t,enterpriseId:n,...a?{spaceId:void 0}:{}}),{enterpriseId:n}}(t);ka([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Organization '${t}' found in enterprise '${r}'. Config saved.`)]),ka([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default organization set to '${t}' successfully.`)]),"json"===ka([n,"optionalAccess",e=>e.format])&&ka([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})])})),o.command("unset").alias("reset").description("Clear the organization context (switch to personal account)").config({help:{brief:"Clear organization context",description:"Clear the saved organizationId / enterpriseId (and spaceId) from the local configuration, switching back to personal account mode. Equivalent to `coze organization use` with no org_id.",examples:[{desc:"Clear organization context",cmd:"coze organization unset",tags:["[RECOMMENDED]"]},{desc:"Clear organization context (alias)",cmd:"coze org reset"}],schema:{output:{status:{type:"string",description:"Operation result status"},message:{type:"string",description:"Human-readable result message"}}},seeAlso:["coze organization use","coze organization list"]}}).action((async(e,t)=>{const o=t.getContext();await ja(o)}))};function za(e,t){return null!=e?e:t()}const Ta=async(e={})=>{const t=za(e.stdin,(()=>process.stdin));return!0===za(e.isTTY,(()=>t.isTTY))?null:await(async e=>{let t="";e.setEncoding("utf-8");for await(const o of e)t+=o;return t})(t)},Ra=e=>{process.stdout.write(e.endsWith("\n")?e:`${e}\n`)},xa=e=>{Ra(JSON.stringify(e))},La=async(e,t)=>{const o=n.resolve(e),i=n.dirname(o);if(await r.mkdir(i,{recursive:!0}),t instanceof Blob){const e=Buffer.from(await t.arrayBuffer());await r.writeFile(o,e)}else Buffer.isBuffer(t)?await r.writeFile(o,t):t instanceof ArrayBuffer?await r.writeFile(o,Buffer.from(t)):await r.writeFile(o,String(t));return o};const Oa=e=>"object"==typeof e&&null!==e,Da=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},Ua=e=>Oa(e)&&"data"in e&&void 0!==e.data?e.data:e,qa=(e,t)=>{try{const{pathname:o}=new URL(e);return n.extname(o)||t}catch(e){return t}},Ba=()=>{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")}`},Ma=e=>{const{outputPath:t,type:o,index:i,ext:s,timestamp:r}=e,a=`${o}_${r}_${i}${s}`;return n.join(t,a)},Na=async(t,o={})=>{let i=null;o.stdin&&(i=await Ta());const s=Da(t),n=Da(i),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},$a="720p",Ga="16:9",Fa=!0,Va=!0,Wa=!1,Ha=!1;function Ja(e,t){return null!=e?e:t()}function Ka(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Qa=(e,t)=>{if(null==e)return 5;const o=Number(e);if(!Number.isFinite(o))return Ka([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --duration '${String(e)}', falling back to 5`)]),5;const i=Math.floor(o);return i<4||i>12?(Ka([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):i},Ya=(e,t)=>{if(null==e)return;const o=Number(e);if(Number.isSafeInteger(o)&&o>=0)return o;Ka([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --seed '${String(e)}', this parameter will be ignored`)])},Za=e=>{const{content:t,options:o,ctx:i}=e,s=(e=>{if("string"!=typeof e)return null;const t=e.trim(),o=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(t);if(!o)return null;const i=Number(o[1]),s=Number(o[2]);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=0)return null;const n=((e,t)=>{let o=Math.abs(e),i=Math.abs(t);for(;0!==i;){const e=o%i;o=i,i=e}return o})(i,s)||1,r=`${Math.round(i/n)}:${Math.round(s/n)}`,a=Math.max(i,s);return{ratio:r,resolution:a<=854?"480p":a<=1280?"720p":"1080p"}})(o.size),n=((e,t)=>"480p"===e||"720p"===e||"1080p"===e?e:(void 0!==e&&Ka([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --resolution '${String(e)}', falling back to '${$a}'`)]),$a))(Ja(o.resolution,(()=>Ka([s,"optionalAccess",e=>e.resolution]))),i),r=((e,t)=>{if("string"==typeof e){const t=e.trim();if(t.length>0)return t}return void 0!==e&&Ka([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --ratio '${String(e)}', falling back to '${Ga}'`)]),Ga})(Ja(o.ratio,(()=>Ka([s,"optionalAccess",e=>e.ratio]))),i);return{model:"doubao-seedance-1-5-pro-251215",content:t,callback_url:Ja(Da(o.callbackUrl),(()=>{})),return_last_frame:"boolean"==typeof o.returnLastFrame?o.returnLastFrame:Ha,resolution:n,ratio:r,duration:Qa(o.duration,i),watermark:"boolean"==typeof o.watermark?o.watermark:Fa,seed:Ya(o.seed,i),camerafixed:"boolean"==typeof o.camerafixed?o.camerafixed:Wa,generate_audio:"boolean"==typeof o.generateAudio?o.generateAudio:Va}},Xa={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',tags:["[RECOMMENDED]"]},{desc:"Save result into a directory",cmd:'coze generate video create "A dancing kitten" --wait --output-path ./videos'},{desc:"Animate an image as the first frame",cmd:'coze generate video create "Camera slowly zooms in" --first-frame https://example.com/cat.png --wait'},{desc:"Read prompt from a pipe",cmd:"cat prompt.txt | coze generate video create --stdin --wait",tags:["[PIPELINE]"]}],enums:{resolution:{"480p":"Standard definition output","720p":"High definition output (default)","1080p":"Full high definition output"}},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.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Configure billing project ID and retry"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid access token",fix:"Run `coze auth login` 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)"},callbackUrl:{type:"string",required:!1,description:"Callback URL for task status changes"},returnLastFrame:{type:"boolean",required:!1,default:Ha,description:"Return last frame URL"},resolution:{type:"string",required:!1,enum:["480p","720p","1080p"],default:$a,description:"Video resolution"},ratio:{type:"string",required:!1,default:Ga,description:"Aspect ratio"},size:{type:"string",required:!1,description:"Derive ratio/resolution from WIDTHxHEIGHT (lower priority than explicit --ratio/--resolution)"},duration:{type:"number",required:!1,default:5,description:"Duration in seconds (4..12; out-of-bounds fallback -1)"},watermark:{type:"boolean",required:!1,default:Fa,description:"Add watermark (disable with --no-watermark)"},seed:{type:"number",required:!1,description:"Random seed (safe integer)"},camerafixed:{type:"boolean",required:!1,default:Wa,description:"Fixed camera position"},generateAudio:{type:"boolean",required:!1,default:Va,description:"Generate accompanying audio (disable with --no-generate-audio)"},firstFrame:{type:"string",required:!1,description:"First frame image URL"},lastFrame:{type:"string",required:!1,description:"Last frame image URL"},stdin:{type:"boolean",required:!1,description:"Read prompt from stdin (pipe input)"},wait:{type:"boolean",required:!1,description:"Wait for task completion by polling; by default the command returns taskId immediately"}},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"}}}}},caveats:["Without --wait the command only submits the task; query progress with `coze generate video status <taskId>`","--wait polls every 2 seconds and fails with E5003 after 5 minutes; the task keeps running server-side, so query it later with `coze generate video status <taskId>`","--output-path only takes effect together with --wait and must be a directory; files are saved inside it as video_<timestamp>_0.<ext> (plus last_frame_<timestamp>_0.<ext> with --return-last-frame)","--size has lower priority than explicit --ratio/--resolution; explicit values win when both are given","An out-of-bounds --duration (outside 4..12) falls back to -1 (the model decides) with a warning","Each task is billed to the configured billing project"],seeAlso:["coze generate video status","coze generate image","coze generate audio"]},ec={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",tags:["[RECOMMENDED]"]},{desc:"Output full response as JSON",cmd:"coze generate video status task_123 --format 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.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Configure billing project ID and retry"},{code:e.ErrorCode.E3000,name:"RESOURCE_NOT_FOUND",desc:"The task ID does not exist or has expired",fix:"Check the task ID returned by `coze generate video create`",example:"coze generate video status <taskId>"},{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"}],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"}}}},caveats:["Task IDs are not kept forever; an unknown or expired task ID fails with E3000"],seeAlso:["coze generate video create"]},tc=async t=>{const o=await e.customFetch.fetch(t);if(!o.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download generated resource: ${o.status} ${o.statusText}`,{url:t});return Buffer.from(await o.arrayBuffer())},oc=async e=>{const{outputPath:t,videoUrl:o,lastFrameUrl:i,shouldSaveLastFrame:s}=e,r=qa(o,".mp4"),a=Ba(),c=Ma({outputPath:t,type:"video",index:0,ext:r,timestamp:a}),l=await tc(o),d=[await La(c,l)];if(s&&"string"==typeof i&&i.length>0){const e=(e=>{const{outputPath:t,ext:o,timestamp:i}=e,s=`last_frame_${i}_0${o}`;return n.join(t,s)})({outputPath:t,ext:qa(i,".png"),timestamp:a}),o=await tc(i),s=await La(e,o);d.push(s)}return d};var ic,sc,nc,rc,ac,cc,lc,dc,pc,uc,mc,gc,hc,fc,_c,yc,bc,vc,wc;function Ec(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInputTokens=2]="TotalInputTokens";e[e.TotalOutputTokens=3]="TotalOutputTokens"}(ic||(ic={})),function(e){e[e.ASC=1]="ASC";e[e.DESC=2]="DESC"}(sc||(sc={})),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"}(nc||(nc={})),function(e){e[e.Free=1]="Free";e[e.Trial=2]="Trial";e[e.Paid=3]="Paid"}(rc||(rc={})),function(e){e[e.Inactive=1]="Inactive";e[e.Active=2]="Active"}(ac||(ac={})),function(e){e[e.CNY=1]="CNY";e[e.ResourcePoint=2]="ResourcePoint"}(cc||(cc={})),function(e){e[e.Cancellable=0]="Cancellable";e[e.NoCancellable=1]="NoCancellable";e[e.AlwaysDefault=2]="AlwaysDefault"}(lc||(lc={})),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"}(dc||(dc={})),function(e){e[e.Internal=1]="Internal";e[e.External=2]="External";e[e.Infra=3]="Infra"}(pc||(pc={})),function(e){e[e.Text=1]="Text";e[e.Image=2]="Image";e[e.Video=3]="Video";e[e.Audio=4]="Audio"}(uc||(uc={})),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"}(mc||(mc={})),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"}(gc||(gc={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online";e[e.GradualRollout=2]="GradualRollout";e[e.ReadyToOffline=3]="ReadyToOffline"}(hc||(hc={})),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"}(fc||(fc={})),function(e){e[e.Install=1]="Install";e[e.Uninstall=2]="Uninstall"}(_c||(_c={})),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"}(yc||(yc={})),function(e){e[e.Scene=1]="Scene";e[e.Type=2]="Type"}(bc||(bc={})),function(e){e[e.Official=1]="Official";e[e.Community=2]="Community"}(vc||(vc={})),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"}(wc||(wc={}));class Cc{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Cc.prototype.__init.call(this),Cc.prototype.__init2.call(this),this.request=Ec([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Ec([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}ListIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/list"),s={space_id:o.space_id,project_id:o.project_id,integration_type:o.integration_type,integration_id:o.integration_id,filter_installed:o.filter_installed,org_id:o.org_id,search_words:o.search_words,page_num:o.page_num,page_size:o.page_size,project_type:o.project_type};return this.request({url:i,method:"POST",data:s},t)}SetIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/update"),s={integration_id:o.integration_id,space_id:o.space_id,auth_schema_value:o.auth_schema_value};return this.request({url:i,method:"POST",data:s},t)}DeleteIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/delete"),s={integration_id:o.integration_id,space_id:o.space_id,project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}AuthIntegrationStatus(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/auth/status"),s={integration_id:o.integration_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}ManageSpaceIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/space/manage"),s={space_ids:o.space_ids,integration_ids:o.integration_ids,op_type:o.op_type};return this.request({url:i,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}FlashASR(e,t){const o=e||{},i=this.genBaseURL("/api/v3/auc/bigmodel/recognize/flash"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}ListModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/list"),s={model_type:o.model_type,current_model_ids:o.current_model_ids,integration_ids:o.integration_ids,need_model_config_param:o.need_model_config_param,page_size:o.page_size,offset:o.offset};return this.request({url:i,method:"POST",data:s},t)}ChatCompletions(e,t){const o=e||{},i=this.genBaseURL("/api/v3/chat/completions"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CreateResponses(e,t){const o=e||{},i=this.genBaseURL("/api/v3/responses"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}GenerateImages(e,t){const o=e||{},i=this.genBaseURL("/api/v3/images/generations"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const o=e||{},i=this.genBaseURL("/api/v3/tts/unidirectional"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}GetIntegrationOauthConfig(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/auth/oauth_config"),s={integration_id:o.integration_id,space_id:o.space_id,project_id:o.project_id,session_id:o.session_id};return this.request({url:i,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks/:id"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"GET",data:s,params:n},t)}WebSearch(e,t){const o=e||{},i=this.genBaseURL("/api/search_api/web_search"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}WebSearch(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/search_api/web_search"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CreateResponses(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/responses"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks/:id"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"GET",data:s,params:n},t)}FlashASR(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/auc/bigmodel/recognize/flash"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}GenerateImages(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/images/generations"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/tts/unidirectional"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}ChatCompletions(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/chat/completions"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CancelIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/cancel"),s={integration_id:o.integration_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}Embeddings(e,t){const o=e||{},i=this.genBaseURL("/api/v3/embeddings/multimodal"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}Embeddings(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/embeddings/multimodal"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}VideoEditingUtils(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/video_editing_utils"),s={Body:o.Body},n={tool_name:o.tool_name};return this.request({url:i,method:"POST",data:s,params:n},t)}GetProjectDefaultSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/default"),s={project_type:o.project_type,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillByIDs(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/by_ids"),s={project_type:o.project_type,skill_ids:o.skill_ids,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillCategoryList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/category/list"),s={project_type:o.project_type};return this.request({url:i,method:"POST",data:s},t)}UploadSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload"),s={data:o.data},n={"Content-Type":o["Content-Type"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetUserSkillList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/user/list"),s={page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}DeleteSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/delete"),s={skill_id:o.skill_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/list"),s={project_type:o.project_type,category_type_list:o.category_type_list,space_id:o.space_id,source_list:o.source_list};return this.request({url:i,method:"POST",data:s},t)}UploadSkillConfirm(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload/confirm"),s={preview_skill_key:o.preview_skill_key};return this.request({url:i,method:"POST",data:s},t)}FetchTool(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/fetch_tool"),s={url:o.url};return this.request({url:i,method:"POST",data:s},t)}GetModelSwitchStatus(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/status"),s={model_id:o.model_id,project_ids:o.project_ids,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}StartSwitchModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/start"),s={space_id:o.space_id,project_ids:o.project_ids,current_model:o.current_model,target_model:o.target_model};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageList(e,t){const o=e||{},i=this.genBaseURL("/v1/model/usage/list"),s={space_id:o.space_id,model_id:o.model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp,order_by_field:o.order_by_field,order_by_type:o.order_by_type,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetModelDetails(e,t){const o=e||{},i=this.genBaseURL("/v1/model/details"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageDetail(e,t){const o=e||{},i=this.genBaseURL("/v1/model/usage/details"),s={space_id:o.space_id,model_id:o.model_id,project_id:o.project_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}RollbackSwitchModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/rollback"),s={space_id:o.space_id,project_ids:o.project_ids,current_model:o.current_model};return this.request({url:i,method:"POST",data:s},t)}TextEmbeddings(e,t){const o=e||{},i=this.genBaseURL("/api/v3/embeddings"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}TextEmbeddings(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/embeddings"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CheckModelReadyToOffline(e,t){const o=e||{},i=this.genBaseURL("/v1/model/ready_to_offline/check"),s={model_type:o.model_type};return this.request({url:i,method:"POST",data:s},t)}Audit(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/audit"),s={content:o.content};return this.request({url:i,method:"POST",data:s},t)}}Cc.prototype.UploadSkill=function(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload"),s=o.body;return this.request({url:i,method:"POST",data:s},t)},Cc.prototype.GenerateImages=function(e,t){const o=e||{},i=this.genBaseURL("/api/v3/images/generations"),s=o.Body;return this.request({url:i,method:"POST",data:s},t)},Cc.prototype.SubmitVideoGenerationsTasks=function(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks"),s=o;return this.request({url:i,method:"POST",data:s},t)},Cc.prototype.GetVideoGenerationsTasks=function(e,t){const o=e||{},i=this.genBaseURL(`/api/v3/contents/generations/tasks/${o.id}`);return this.request({url:i,method:"GET"},t)};const Ic=new Cc({});const Ac=async e=>await new Promise((t=>setTimeout(t,e))),Sc=async e=>{const{taskId:t,baseURL:o,accessToken:i,projectId:s}=e,n=await Ic.GetVideoGenerationsTasks({id:t},{baseURL:o,headers:{Authorization:`Bearer ${i}`},params:{project_id:s}});return Ua(n)};function kc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const jc=e=>`coze generate video status ${e}`,Pc=e=>{const{ctx:t,response:o}=e;"json"!==kc([t,"optionalAccess",e=>e.format])?Ra((e=>{const t=[e.status],o=kc([e,"access",e=>e.content,"optionalAccess",e=>e.video_url]),i=kc([e,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);return"succeeded"===e.status?("string"==typeof o&&o.length>0&&t.push(o),"string"==typeof i&&i.length>0&&t.push(i),t.join("\n")):("string"==typeof e.error_message&&e.error_message&&t.push(e.error_message),t.join("\n"))})(o)):xa(o)},zc=t=>{const o=t.getContext(),{outputPath:i}=t.optsWithGlobals(),n=(r=kc([o,"optionalAccess",e=>e.config,"optionalAccess",e=>e.integrationApiBaseUrl]),a=()=>s.DEFAULT_CONFIG.integrationApiBaseUrl,null!=r?r:a());var r,a;const c=kc([o,"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` first");return{accessToken:c,ctx:o,integrationApiBaseUrl:n,outputPath:i}},Tc=async(t,o,i)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:r,outputPath:a}=zc(i);let c=null;o.stdin&&(c=await Ta());const{content:l}=(t=>{const{prompt:o,stdinPrompt:i,options:s}=t,n=Ja(Da(o),(()=>Da(i))),r=Da(s.firstFrame),a=Da(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 l=[];return n&&l.push({type:"text",text:n}),r&&l.push({type:"image_url",image_url:{url:r},role:"first_frame"}),a&&l.push({type:"image_url",image_url:{url:a},role:"last_frame"}),{content:l}})({prompt:t,stdinPrompt:c,options:o}),d=Za({content:l,options:o,ctx:n}),p=n.format,u=kc([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!u)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const{createResp:m,taskId:g}=await(async t=>{const{requestBody:o,baseURL:i,accessToken:s,projectId:n}=t,r=await Ic.SubmitVideoGenerationsTasks(o,{baseURL:i,headers:{Authorization:`Bearer ${s}`},params:{project_id:n}}),a=Ua(r),c=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([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:d,baseURL:r,accessToken:s,projectId:u});if(!o.wait)return"json"===p?void xa({query_command:jc(g),response:m,task_id:g}):void Ra((e=>["Video generation task created successfully.",`taskId: ${e}`,`Use \`${jc(e)}\` to query status.`].join("\n"))(g));const h=await(async t=>{const{taskId:o,baseURL:i,accessToken:s,pollIntervalMs:n,pollTimeoutMs:r,projectId:a}=t,c=Date.now();for(;;){const t=await Sc({taskId:o,baseURL:i,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}): ${l=t.error_message,d=()=>"unknown",null!=l?l:d()}`,t);if(Date.now()-c>r)throw new e.CozeError(e.ErrorCode.E5003,[`Video generation timed out after ${r}ms.`,`taskId: ${o}`,`Use \`coze generate video status ${o}\` to query status.`].join("\n"),{task_id:o,last_status:t.status});await Ac(n)}var l,d})({taskId:g,baseURL:r,accessToken:s,pollIntervalMs:2e3,pollTimeoutMs:3e5,projectId:u}),f=kc([h,"access",e=>e.content,"optionalAccess",e=>e.video_url]),_=kc([h,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);if(!f||"string"!=typeof f)throw new e.CozeError(e.ErrorCode.E5002,"Video generated successfully but video_url was not returned");if(a){const e=await oc({outputPath:a,videoUrl:f,lastFrameUrl:_,shouldSaveLastFrame:!0===o.returnLastFrame});return"json"===p?void xa({task_id:g,request:d,response:h,saved_paths:e}):void Ra(e.join("\n"))}if("json"===p)return void xa({task_id:g,request:d,response:h});const y=[f];!0===o.returnLastFrame&&"string"==typeof _&&_.length>0&&y.push(_),Ra(y.join("\n"))},Rc=async(t,o,i)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:r}=zc(i),a=kc([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!a)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");let c;try{c=await Sc({taskId:t,baseURL:r,accessToken:s,projectId:a})}catch(o){if((e=>404===kc([e,"optionalAccess",e=>e.response,"optionalAccess",e=>e.status]))(o))throw new e.CozeError(e.ErrorCode.E3000,`Video generation task '${t}' not found`,{taskId:t},{trigger:"The task ID does not exist or has expired",fix:"Check the task ID returned by `coze generate video create`",example:"coze generate video status <taskId>"});throw o}Pc({ctx:n,response:c})},xc=(e,t)=>{const o=t.getContext();Q(e,o)},Lc=e=>{var t;t=e.command("create [prompt]").description("Create a video generation task").config({help:Xa}).action((async(e,t,o)=>{try{await Tc(e,t,o)}catch(e){xc(e,o)}})),t.option("--callback-url <url>","Callback URL for task status changes").option("--return-last-frame","Return last frame URL (default: disabled)",Ha).option("--resolution <res>","Resolution: 480p|720p|1080p",$a).option("--ratio <ratio>",`Aspect ratio (default: ${Ga})`,Ga).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)",Wa).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")},Oc=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);Lc(t),(e=>{e.command("status <taskId>").description("Query video generation task status by task ID").config({help:ec}).action((async(e,t,o)=>{try{await Rc(e,0,o)}catch(e){xc(e,o)}}))})(t)},Dc="2K",Uc=!0,qc="url",Bc="standard",Mc="disabled",Nc={brief:"Generate images from text",description:"Generate images from a text prompt, optionally guided by reference images. Requires login and a configured billing project; each call is billed to that project. Without --output-path the command prints image URLs (or base64 data); with --output-path it downloads the images into the given directory.",examples:[{desc:"Generate image",cmd:'coze generate image "A futuristic city"',tags:["[RECOMMENDED]"]},{desc:"Save into a directory",cmd:'coze generate image "A cat" --output-path ./images'},{desc:"Specify size",cmd:'coze generate image "A dog" --size 2048x2048'},{desc:"Use a reference image",cmd:'coze generate image "Make it watercolor style" --image https://example.com/cat.png'},{desc:"Read prompt from a pipe",cmd:"cat prompt.txt | coze generate image --stdin --output-path ./images",tags:["[PIPELINE]"]}],enums:{"response-format":{url:"Return a temporary download URL for each generated image",b64_json:"Return each generated image inline as base64-encoded data"},sequential:{auto:"Let the model decide whether to generate a group of related images (up to --max-images)",disabled:"Generate a single image only (default)"}},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)"},outputPath:{type:"string",description:"Directory path to save the generated image files (inherited from `coze generate --output-path`)"},size:{type:"string",default:Dc,description:"Image size: 2K|4K or WIDTHxHEIGHT"},watermark:{type:"boolean",default:Uc,description:"Add watermark (disable with --no-watermark)"},image:{type:"array",items:{type:"string"},description:"Reference image URL (can be used multiple times)"},responseFormat:{type:"string",enum:["url","b64_json"],default:qc,description:"Response format"},optimizePromptMode:{type:"string",default:Bc,description:"Prompt optimization mode"},sequential:{type:"string",enum:["auto","disabled"],default:Mc,description:"Group image generation mode"},maxImages:{type:"number",default:15,description:"Maximum number of group images (1-15)"},stdin:{type:"boolean",description:"Read prompt from stdin (pipe input)"}},output:{type:"object",description:"Without --output-path, prints the ImageData array (url/b64_json/size per item). With --output-path, prints an object { created, image_0..image_N, saved_paths }.",properties:{created:{type:"number"},image_0:{type:"object",description:"ImageData of the Nth image (image_0..image_N)"},saved_paths:{type:"array",items:{type:"string"}}}}},caveats:["--output-path must be a directory; files are saved inside it as image_<timestamp>_<index>.<ext>","Invalid --response-format, --sequential, or --max-images values fall back to defaults with a warning; an invalid --size fails with E1000 instead of falling back","With --sequential auto the model may return multiple images in one call (capped by --max-images)","Each call is billed to the configured billing project"],seeAlso:["coze generate audio","coze generate video create","coze file upload"]};function $c(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Gc=3686400,Fc=16777216,Vc=e=>"object"==typeof e&&null!==e,Wc=(t,o)=>new e.CozeError(e.ErrorCode.E1000,`Invalid --size '${t}': ${o}`,{size:t},{trigger:"The --size value failed local validation",fix:"Use 2K/4K or WIDTHxHEIGHT with total pixels in [3686400, 16777216] and aspect ratio in [1:16, 16:1]",example:'coze generate image "A dog" --size 2048x2048'}),Hc=e=>{if("string"==typeof e){const t=e.trim();return t.length?t:Bc}return Bc},Jc=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},Kc=t=>{t.command("image [prompt]").description("Generate images from text prompts").config({help:Nc}).option("--size <size>","Image size: 2K|4K or WIDTHxHEIGHT (local validation)",Dc).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",qc).option("--optimize-prompt-mode <mode>",`Prompt optimization mode (default: ${Bc})`,Bc).option("--sequential <mode>","Group image generation mode: auto|disabled",Mc).option("--max-images <n>","Maximum number of group images (1-15)",String(15)).option("--stdin","Read prompt from stdin (pipe input)").action((async(t,o,i)=>{const n=i.getContext(),{outputPath:r}=i.optsWithGlobals(),a=await Na(t,{stdin:o.stdin}),c=$c([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const l=(e=>{if(null==e)return{value:Dc};if("string"!=typeof e)throw Wc(String(e),"expected 2K/4K or WIDTHxHEIGHT");const t=e.trim();if("2K"===t||"4K"===t)return{value:t};const o=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(t);if(!o)throw Wc(t,"expected 2K/4K or WIDTHxHEIGHT");const i=Number(o[1]),s=Number(o[2]),n=i*s,r=i/s;if(!(Number.isFinite(i)&&Number.isFinite(s)&&i>0&&s>0&&n>=Gc&&n<=Fc&&r>=.0625&&r<=16))throw Wc(t,"total pixels must be in [3686400, 16777216], aspect ratio must be in [1:16, 16:1]");return{value:`${i}x${s}`}})(o.size),d="url"===(p=o.responseFormat)||"b64_json"===p?{value:p}:void 0!==p?{value:qc,warning:`Invalid --response-format '${String(p)}', falling back to '${qc}'`}:{value:qc};var p;const u=(e=>"auto"===e||"disabled"===e?{value:e}:void 0!==e?{value:Mc,warning:`Invalid --sequential '${String(e)}', falling back to '${Mc}'`}:{value:Mc})(o.sequential),m=(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'`}})(o.maxImages);l.warning&&$c([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(l.warning)]),d.warning&&$c([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(d.warning)]),u.warning&&$c([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(u.warning)]),m.warning&&$c([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(m.warning)]);const g={model:"doubao-seedream-4-5-251128",prompt:a,size:l.value,watermark:"boolean"==typeof o.watermark?o.watermark:Uc,image:Jc(o.image),response_format:d.value,optimize_prompt_options:{mode:Hc(o.optimizePromptMode)},sequential_image_generation:u.value,sequential_image_generation_options:{max_images:m.value}},h=(t=>{const o=Vc(t)&&"data"in t?t.data:t;if(Vc(i=o)&&"string"==typeof i.model&&"number"==typeof i.created&&Array.isArray(i.data))return o;var i;throw new e.CozeError(e.ErrorCode.E5002,"Image generation API returned an unexpected response format",t)})(await Ic.GenerateImages({Body:g},{baseURL:s.DEFAULT_CONFIG.integrationApiBaseUrl,params:{project_id:c}}));if(h.error)throw new e.CozeError(e.ErrorCode.E5002,"Image generation failed (top-level error)",h.error);const f=(y=()=>qc,null!=(_=g.response_format)?_:y());var _,y;const b=h.data.filter((e=>!e.error&&("url"===f?"string"==typeof e.url&&e.url.length>0:"string"==typeof e.b64_json&&e.b64_json.length>0)));if(0===b.length)throw new e.CozeError(e.ErrorCode.E5002,"Image generation succeeded but no valid image data was returned",h);if(r){const t=[],o=Ba();for(const[i,s]of b.entries()){const n="url"===f&&s.url?qa(s.url,".png"):".png",a=Ma({outputPath:r,type:"image",index:i,ext:n,timestamp:o});let c;if("url"===f){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 l=await La(a,c);t.push(l)}const{model:i,usage:s,HttpHeader:a,...c}=(e=>{const{data:t,...o}=e,i=Object.fromEntries(t.map(((e,t)=>[`image_${t}`,e])));return{...o,...i}})(h);$c([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...c,saved_paths:t})])}else $c([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(h.data)])}))},Qc="cli_user",Yc="zh_female_xiaohe_uranus_bigtts",Zc="mp3",Xc=24e3,el={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"',tags:["[RECOMMENDED]"]},{desc:"Save into a directory",cmd:'coze generate audio "Hello" --output-path ./out'},{desc:"Pipe SSML input from stdin",cmd:'echo "<speak>Hello</speak>" | coze generate audio --ssml --stdin',tags:["[PIPELINE]"]},{desc:"Specify audio encoding",cmd:'coze generate audio "Hello" --audio-format ogg_opus'}],enums:{"audio-format":{pcm:"Raw PCM audio frames without a container header (for further processing)",mp3:"MP3 encoded audio, playable by most players (default)",ogg_opus:"Opus audio in an OGG container, smaller at comparable quality"}},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` 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)"},outputPath:{type:"string",description:"Directory path to save the generated audio file (inherited from `coze generate --output-path`)"},uid:{type:"string",default:Qc,description:"User UID"},speaker:{type:"string",default:Yc,description:"Speaker voice"},audioFormat:{type:"string",enum:["pcm","mp3","ogg_opus"],default:Zc,description:"Audio encoding format"},sampleRate:{type:"number",default:Xc,description:"Sample rate"},speechRate:{type:"number",default:0,description:"Speech rate (-50..100)"},loudnessRate:{type:"number",default:0,description:"Loudness (-50..100)"},ssml:{type:"boolean",default:!1,description:"Treat input as SSML (defaults to plain text)"},stdin:{type:"boolean",description:"Read prompt from stdin (pipe input)"}},output:{type:"object",description:"Applies to `--format json` only; in text mode the command prints a plain string (saved path or audio URL)",properties:{request:{type:"object"},url:{type:"string",description:"Audio download URL"},saved_path:{type:"string",description:"Local path if saved"}}}},caveats:["--output-path must be a directory; the audio file is saved inside it as audio_<timestamp>_0.<ext>","Plain text and SSML are mutually exclusive: with --ssml the whole input is sent as SSML, otherwise it is sent as plain text","pcm output has no container header; most players require mp3 or ogg_opus","Each call is billed to the configured billing project"],seeAlso:["coze generate image","coze generate video create","coze file upload"]};function tl(e,t){return null!=e?e:t()}function ol(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const il=(e,t)=>"pcm"===e||"mp3"===e||"ogg_opus"===e?e:(void 0!==e&&ol([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --audio-format '${String(e)}', falling back to '${Zc}'`)]),Zc),sl=(e,t,o,i)=>{if(null==e)return t;const s=Number(e);return Number.isFinite(s)?Math.floor(s):(ol([i,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",i=>i(`Invalid --${o} '${String(e)}', falling back to ${t}`)]),t)},nl=t=>{const o=t.trim();if(0===o.length)return null;const i=o.startsWith("data:")?o.slice(5).trim():o;if(0===i.length)return null;const s=i[0];if("{"!==s&&"["!==s)return null;const n=e.safeJsonParse(i,void 0,{onError:t=>{const i=t instanceof Error?t.message:String(t);throw new e.CozeError(e.ErrorCode.E5002,`Failed to parse response: ${i}`,{line:o})}});return void 0===n?null:Oa(n)&&"number"==typeof n.code?n:null},rl=t=>{const o=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. All subcommands require login and a configured billing project, and the generation cost is billed to that project. Use the shared --output-path option to download generated files into a local directory; without it, commands print result URLs or data.",examples:[{desc:"Generate image",cmd:'coze generate image "A cat"',tags:["[RECOMMENDED]"]},{desc:"Generate audio",cmd:'coze generate audio "Hello world"'},{desc:"Generate video",cmd:'coze generate video create "A dancing dog"'},{desc:"Save generated files into a directory",cmd:'coze generate image "A cat" --output-path ./out'}],seeAlso:["coze file upload","coze auth login"]}}).option("--output-path <path>","Directory path to save the generated media files");Kc(o),(t=>{t.command("audio [prompt]").description("Synthesize speech from text or SSML (streaming)").config({help:el}).option("--uid <uid>",`User UID (default: ${Qc})`,Qc).option("--speaker <speaker>",`Speaker (default: ${Yc})`,Yc).option("--audio-format <format>","Audio encoding: pcm|mp3|ogg_opus",Zc).option("--sample-rate <n>","Sample rate (default: 24000)",String(Xc)).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,o,i)=>{const s=i.getContext();try{const{outputPath:n}=i.optsWithGlobals(),r=ol([s,"optionalAccess",e=>e.config,"access",e=>e.integrationApiBaseUrl]);if(!ol([s,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]))throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login` first");const a=await Na(t,{stdin:o.stdin}),c=ol([s,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const l={user:{uid:tl(Da(o.uid),(()=>Qc))},req_params:{speaker:tl(Da(o.speaker),(()=>Yc)),audio_params:{format:il(o.audioFormat,s),sample_rate:sl(o.sampleRate,Xc,"sample-rate",s),speech_rate:sl(o.speechRate,0,"speech-rate",s),loudness_rate:sl(o.loudnessRate,0,"loudness-rate",s)}}};o.ssml?l.req_params={...l.req_params,ssml:a}:l.req_params={...l.req_params,text:a};const d=new URL("/api/v3/tts/unidirectional",r);d.searchParams.append("project_id",c);const p=await e.customFetch.fetch(d.toString(),{method:"POST",body:JSON.stringify(l)});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"),m=p.body.getReader(),g=[];let h;const f=t=>{if(0===t.code)return n&&"string"==typeof t.data&&g.push(Buffer.from(t.data,"base64")),!1;if(2e7===t.code)return"string"==typeof t.url&&t.url.length>0&&(h=t.url),!0;throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis failed (code=${t.code}): ${tl(t.message,(()=>"unknown"))}`,t)};let _="";for(;;){const{done:e,value:t}=await m.read();if(e)break;_+=u.decode(t,{stream:!0});const o=_.split(/\r?\n/);_=tl(o.pop(),(()=>""));for(const e of o){const t=nl(e);if(t&&f(t)){await m.cancel();break}}if(h)break}if(!h){_+=u.decode();const e=_.split(/\r?\n/);_="";for(const t of e){const e=nl(t);if(e&&f(e))break}}if(n){const t=tl(ol([l,"access",e=>e.req_params,"optionalAccess",e=>e.audio_params,"optionalAccess",e=>e.format]),(()=>Zc)),o="pcm"===t?".pcm":"ogg_opus"===t?".ogg":".mp3",i=Ba(),r=Ma({outputPath:n,type:"audio",index:0,ext:o,timestamp:i});let a=null;if(g.length>0)a=await La(r,Buffer.concat(g));else if(h){const t=await e.customFetch.fetch(h);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=qa(h,o),c=Ma({outputPath:n,type:"audio",index:0,ext:r,timestamp:i});a=await La(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:h});return"json"===ol([s,"optionalAccess",e=>e.format])?void xa({request:l,url:h,saved_path:a}):void Ra(a)}if("json"===ol([s,"optionalAccess",e=>e.format]))return void xa({request:l,url:h});if(h)return void Ra(h);Ra("Speech synthesis completed, but no audio download URL was returned; you can use --format json to view details.")}catch(e){Q(e,s)}}))})(o),Oc(o)};function al(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const cl=o=>{(o=>{o.command("upload <path>").description("Upload a local file").config({help:{brief:"Upload a local file",description:"Upload a local file to Coze and get an online URL back. The file can be used as an attachment or context in projects. In text mode the command prints only the file URL, which makes it easy to embed in other commands.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf",tags:["[RECOMMENDED]"]},{desc:"Get the full result as JSON (file_url and file_uri)",cmd:"coze file upload ./screenshot.png --format json"},{desc:"Upload and reference the URL in a project message",cmd:'coze code message send "Use this asset: $(coze file upload ./logo.png)" -p 123456',tags:["[PIPELINE]"]}],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"},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The given path points to a directory, not a file",fix:"Pass a path to a single file; uploading directories is not supported",example:"coze file upload ./document.pdf"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed during upload",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Upload API returned an error",fix:"Please retry later. Use --debug for more details"}],schema:{input:{path:{type:"string",required:!0,description:"Local file path to upload"}},output:{type:"object",description:"In `--format json` mode prints the upload result object; in text mode prints the uploaded file URL string",properties:{file_url:{type:"string",description:"Uploaded file URL"},file_uri:{type:"string",description:"Uploaded file URI"}}}},caveats:["Uploading directories is not supported; pass a single file path","Uploaded files are stored as temporary CLI attachments and the returned URL expires after a retention period (about 24 hours); re-upload when the link expires"],seeAlso:["coze code message send","coze generate image"]}}).action((async(o,i,s)=>{let n;try{let i;n=s.getContext();try{i=await g.stat(o)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${o}`,{filePath:o})}if(!i.isFile())throw new e.CozeError(e.ErrorCode.E1000,`Not a file: ${o}. Uploading directories is not supported`,{filePath:o},{trigger:"The given path points to a directory",fix:"Pass a path to a single file",example:"coze file upload ./document.pdf"});const r=m.basename(o),a=m.extname(o),c=a?r.slice(0,-a.length):r,l=a.slice(1),d=new f;d.append("file_name",c),d.append("file_extension",l),d.append("file_content",h.createReadStream(o)),d.append("biz_type","cli_attachment");const p=await t.IdeApi.UploadFile({data:d},{headers:{...d.getHeaders()}});"json"===al([n,"optionalAccess",e=>e.format])?al([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(p.data)]):al([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(al([p,"access",e=>e.data,"optionalAccess",e=>e.file_url]))])}catch(e){Q(e,n)}}))})(o.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. Uploading returns an online URL for the file.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf",tags:["[RECOMMENDED]"]},{desc:"Get the upload result as JSON",cmd:"coze file upload ./screenshot.png --format json"}],seeAlso:["coze code message send","coze generate image"]}}))};function ll(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function dl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function pl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function ul(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ml=t=>{const o=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. Effective configuration is merged from environment variables, the local `.cozerc.json` in the current directory, and the global `~/.coze/cli/config.json` (environment variables take the highest priority). No authentication is required for any config subcommand.",examples:[{desc:"List all configurations",cmd:"coze config list",tags:["[RECOMMENDED]"]},{desc:"Get a configuration value",cmd:"coze config get spaceId"},{desc:"Set a configuration value",cmd:"coze config set spaceId 123456789"},{desc:"Delete a configuration value",cmd:"coze config delete spaceId"}],seeAlso:["coze auth status","coze space use","coze organization use"]}});(t=>{t.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 and source of the specified configuration keys. Values are resolved from environment variables, the local `.cozerc.json`, the global `~/.coze/cli/config.json`, and built-in defaults, in that priority order. If a key does not exist, a warning is printed and the command still exits with code 0.",examples:[{desc:"Get default Space ID",cmd:"coze config get spaceId",tags:["[RECOMMENDED]"]},{desc:"Get API base URL",cmd:"coze config get apiBaseUrl"},{desc:"Get multiple configurations",cmd:"coze config get spaceId organizationId"},{desc:"Read a value in a script",cmd:"coze config get spaceId --format json",tags:["[PIPELINE]"]}],schema:{input:{keys:{type:"array",items:{type:"string"},required:!0,description:"Configuration key names (e.g. spaceId, organizationId, apiBaseUrl)",example:["spaceId"]}},output:{key:{type:"string",description:"Configuration key name",example:"spaceId"},value:{type:"any",description:"Configuration value",example:"123456789"},source:{type:"string",enum:["env","env-file","local","global","default"],description:"Where the effective value comes from",example:"global"}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Unexpected failure while reading configuration files",fix:"Retry with --debug to see details; check that config files are readable",example:"coze config get spaceId --debug"}],seeAlso:["coze config list","coze config set","coze config delete"],caveats:["A missing key only prints a warning; it does not fail the command"]}}).action((async(e,t,o)=>{const i=o.getContext(),n=await s.listConfigs();for(const t of e){const e=n.find((e=>e.key===t));ll(e?[i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)]:[i,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Configuration '${t}' not found.`)])}}))})(o),(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 configuration key-value pair. Nested keys use dot paths, e.g. `upgrade.mode`. The value is persisted in the global configuration file `~/.coze/cli/config.json` (or the file pointed to by the COZE_CONFIG_FILE environment variable, if set). The key is free-form, but only known keys (see the `key` enum below) affect CLI behavior; internal state paths (e.g. `upgrade.cache.*`) cannot be set.",examples:[{desc:"Set default workspace",cmd:"coze config set spaceId 123456789",tags:["[RECOMMENDED]"]},{desc:"Set default organization",cmd:"coze config set organizationId 987654321"},{desc:"Switch upgrade strategy to notify-only",cmd:"coze config set upgrade.mode notify"},{desc:"Switch upgrade channel to beta",cmd:"coze config set upgrade.channel beta"},{desc:"Set then verify in a script",cmd:"coze config set spaceId 123456789 && coze config get spaceId --format json",tags:["[PIPELINE]"]}],enums:{key:{spaceId:"Default Space ID used when --space-id is not passed",organizationId:"Default Organization ID used when --org-id is not passed",apiBaseUrl:"Base URL of the Coze Coding API",openApiBaseUrl:"Base URL of the Coze Open API",defaultOutputFormat:"Default output format when --format is not passed","upgrade.mode":"Auto-upgrade strategy: auto (silent background upgrade, default) / notify (prompt only) / off (disabled)","upgrade.channel":"npm dist-tag used for upgrades: latest (default), beta, alpha, ...","skill.mode":"Bundled-skill consistency strategy: auto (silently run `coze self skill install` on mismatch, default) / notify (prompt only) / off (disabled)",disableTelemetry:"Whether to disable anonymous usage statistics (true/false)"}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to write the configuration file (e.g. directory not writable)",fix:"Please check the key/value and file permissions, then retry. Use --debug for more details.",example:"coze config set spaceId 123456789 --debug"}],schema:{input:{key:{type:"string",required:!0,description:"Configuration key name",example:"spaceId"},value:{type:"string",required:!0,description:"New configuration value",example:"123456789"}},output:{key:{type:"string",description:"Configuration key name",example:"spaceId"},value:{type:"string",description:"Saved configuration value",example:"123456789"},scope:{type:"string",enum:["global"],description:"Scope the value was written to (always global)",example:"global"},status:{type:"string",enum:["updated"],description:"Operation result",example:"updated"},message:{type:"string",description:"Human-readable result message",example:"Configuration 'spaceId' updated successfully in global scope."}}},seeAlso:["coze config get","coze config list","coze config delete"],caveats:["Always writes to the global scope; the local `.cozerc.json` is never modified by this command","Unknown keys are saved as-is without validation"]}}).action((async(t,o,i,n)=>{const r=n.getContext();try{if(s.isInternalConfigPath(t))throw new e.CozeError(e.ErrorCode.E5000,`'${t}' is internal state managed by the CLI and cannot be set.`);const i=s.buildPatchByPath(t,o),n="global";await s.saveConfig(i,n);const a={key:t,value:o,scope:n,status:"updated",message:`Configuration '${t}' updated successfully in ${n} scope.`};if(dl([r,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(a.message)]),"json"===dl([r,"optionalAccess",e=>e.format]))return void dl([r,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])}catch(i){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set '${t}' to '${o}': ${i.message}`,i.stack)}}))})(o),(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 keys from the configuration files. For each key, the local `.cozerc.json` in the current directory is checked first; if the key is not there, it is removed from the global `~/.coze/cli/config.json`. Deleting a key that does not exist is a no-op and still reports success.",examples:[{desc:"Delete a specific configuration key",cmd:"coze config delete spaceId",tags:["[RECOMMENDED]"]},{desc:"Delete multiple configuration keys",cmd:"coze config delete spaceId organizationId"},{desc:"Delete then verify in a script",cmd:"coze config delete spaceId && coze config get spaceId --format json",tags:["[PIPELINE]"]}],errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to write the configuration file when removing the key",fix:"Please check the configuration key and file permissions, then retry. Use --debug for more details.",example:"coze config delete spaceId --debug"}],schema:{input:{keys:{type:"array",items:{type:"string"},required:!0,description:"Configuration key names to delete",example:["spaceId"]}},output:{key:{type:"string",description:"Deleted configuration key name",example:"spaceId"},status:{type:"string",enum:["deleted"],description:"Operation result",example:"deleted"},message:{type:"string",description:"Human-readable result message",example:"Configuration 'spaceId' has been removed."}}},seeAlso:["coze config list","coze config get","coze config set"],caveats:["Built-in defaults and environment variables cannot be deleted; only values stored in config files are removed"]}}).action((async(t,o,i)=>{const n=i.getContext();for(const o of t)try{await s.deleteConfig(o);const e={key:o,status:"deleted",message:`Configuration '${o}' has been removed.`};pl([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleted ${o} from configuration file successfully.`)]),"json"===pl([n,"optionalAccess",e=>e.format])&&pl([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)])}catch(t){const i=t;throw new e.CozeError(e.ErrorCode.E5000,`Failed to delete config '${o}': ${i.message}`,i.stack)}}))})(o),(t=>{t.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 every effective configuration item with its value and source. Items are merged from environment variables, the local `.cozerc.json`, the global `~/.coze/cli/config.json`, and built-in defaults (environment variables take the highest priority). The command is read-only and requires no authentication.",examples:[{desc:"List configurations",cmd:"coze config list",tags:["[RECOMMENDED]"]},{desc:"List configurations as JSON for scripts",cmd:"coze config list --format json",tags:["[PIPELINE]"]},{desc:"Inspect merge result with debug logs",cmd:"coze config list --debug"}],schema:{output:{type:"array",description:"All effective configuration items",items:{key:{type:"string",description:"Configuration key name",example:"spaceId"},value:{type:"any",description:"Effective configuration value",example:"123456789"},source:{type:"string",enum:["env","env-file","local","global","default"],description:"Where the effective value comes from",example:"global"}}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Unexpected failure while reading configuration files",fix:"Retry with --debug to see details; check that config files are readable",example:"coze config list --debug"}],seeAlso:["coze config get","coze config set","coze config delete"]}}).action((async(e,t)=>{const o=t.getContext(),i=(await s.listConfigs()).map((({key:e,value:t,source:o})=>({key:e,value:t,source:o})));ul([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Configurations found:")]),ul([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(i)])}))})(o)},gl="__COZE_FILE_COMP__";function hl(){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 fl(e){const t=y.homedir();switch(e){case"bash":return n.join(t,"darwin"===process.platform?".bash_profile":".bashrc");case"zsh":return n.join(t,".zshrc");case"fish":return n.join(t,".config/fish/config.fish");case"powershell":return function(){const e=["pwsh","powershell"];for(const t of e)try{const e=i.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 _l(){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]}" == "${gl}" ]]; 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" == "${gl}" ]]; 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(y.EOL)}function yl(e){switch(e){case"bash":return`\n# begin coze completion\nsource ${s.getGlobalCompletionFile()}\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 '${gl}') {\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 bl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}let vl,wl,El=!1,Cl=!1;function Il(e){const t=(o=e._args,i=()=>[],null!=o?o:i());var o,i;if(0===t.length)return!1;const s=/path|file|dir|folder/i;return t.some((e=>s.test(e._name)))}function Al(){const e=hl();if(!e)return!1;const t=fl(e);if(!t)return!1;if("bash"===e){const e=s.getGlobalConfigDir(),t=n.join(e,"completion.sh");a.existsSync(e)||a.mkdirSync(e,{recursive:!0}),a.writeFileSync(t,_l())}const o=n.dirname(t);a.existsSync(o)||a.mkdirSync(o,{recursive:!0});const i=yl(e);return!!i&&(a.appendFileSync(t,i),!0)}async function Sl(e){if(!e.completionInstalled&&process.stdout.isTTY&&!process.env.CI&&!(process.argv.includes("--compzsh")||process.argv.includes("--compbash")||process.argv.includes("--compfish")||process.argv.includes("--comppwsh")||El||Cl))if(function(){try{const e=hl();if(!e)return!1;const t=fl(e);return!(!t||!a.existsSync(t))&&a.readFileSync(t,"utf8").includes("begin coze completion")}catch(e){return!1}}())try{await s.saveConfig({completionInstalled:!0})}catch(e){}else try{Al()&&(await s.saveConfig({completionInstalled:!0}),console.log("Shell auto-completion has been configured. Restart your terminal to activate."))}catch(e){}}function kl(t){wl=t,function(){const e=process.argv.indexOf("--completion");e>-1&&(El=!0,process.argv.splice(e,1));const t=process.argv.indexOf("--completion-fish");t>-1&&(Cl=!0,process.argv.splice(t,1))}(),vl=_("coze"),vl.on("complete",((e,o)=>{const i=o.line.trimStart().split(/\s+/);i.length>0&&(i[0].endsWith("coze")||i[0].endsWith("bin/main"))&&i.shift();let s="";o.line.endsWith(" ")?(s="",""===i[i.length-1]&&i.pop()):s=i.pop()||"";const n=function(e,t,o){let i=e;for(const e of t){const t=i.commands.find((t=>t.name()===e||t.alias()===e));if(t)i=t;else if(!e.startsWith("-"))return Il(i)?[gl]:[]}const s=[];i.commands.length>0&&i.commands.forEach((e=>{s.push(e.name())})),i.options.forEach((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))})),i!==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(o)));return 0===n.length&&Il(i)?[gl]:n}(t,i,s);o.reply(n)})),t.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). The shell type is auto-detected and the completion block is written to its startup script (.bashrc / .zshrc / fish config / $PROFILE). Running the command without options behaves the same as --setup; when --setup and --cleanup are both passed, --cleanup wins. A terminal restart (or sourcing the startup script) is required for changes to take effect.",examples:[{desc:"Install completion for the detected shell (minimal)",cmd:"coze completion",tags:["[RECOMMENDED]"]},{desc:"Install completion script explicitly",cmd:"coze completion --setup"},{desc:"Remove completion script",cmd:"coze completion --cleanup"}],schema:{input:{setup:{type:"boolean",required:!1,default:!0,description:"Install shell completion into the startup script (default behavior when no option is passed)"},cleanup:{type:"boolean",required:!1,default:!1,description:"Remove shell completion from the startup script (takes precedence over --setup)"}},output:{message:{type:"string",description:"Plain-text result message printed to stdout (no JSON output)",example:"Shell completion (zsh) setup successful! Please restart your terminal or source your config file."}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Shell type could not be detected, or writing the completion block to the startup script failed (exit code 1)",fix:"Use a supported shell (bash, zsh, fish, powershell) and ensure the startup script is writable",example:"coze completion --setup"}],seeAlso:["coze upgrade","coze config list"],caveats:["Completion is also auto-installed on the first interactive run of the CLI (skipped in CI or non-TTY environments)","Changes only take effect after restarting the terminal or sourcing the shell startup script","For bash, an extra completion script is written to the `~/.coze/cli/` directory"]}}).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=hl();if(!e)return;const t=fl(e);if(!t||!a.existsSync(t))return;const o=yl(e);if(o){const e=a.readFileSync(t,"utf8").replace(new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"");a.writeFileSync(t,e)}if("bash"===e){const e=s.getGlobalConfigDir(),t=n.join(e,"completion.sh");a.existsSync(t)&&a.unlinkSync(t),a.existsSync(e)&&0===a.readdirSync(e).length&&a.rmdirSync(e)}}(),await s.saveConfig({completionInstalled:!1}),console.log("Shell completion removed! Please restart your terminal.");else{const e=hl();if(!e)return console.error("Could not detect your shell type. Supported shells: bash, zsh, fish, powershell."),void(process.exitCode=1);Al()?(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 jl(){return El?(console.log(_l()),void process.exit()):Cl?(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]" = "${gl}"`," return"," end"," for c in $completions"," echo $c"," end","end","complete -c coze -a '(_coze_completion)' -n '_coze_completion'","### coze completion - end ###"].join(y.EOL)),void process.exit()):void(process.argv.includes("--comppwsh")?function(){if(!wl)return void process.exit();const e=process.argv.indexOf("--comppwsh"),t=process.argv.slice(e+1);let o=wl;const i=[];for(const e of t){const t=bl([o,"access",e=>e.commands,"optionalAccess",e=>e.find,"call",t=>t((t=>t.name()===e||t.alias()===e))]);t?o=t:i.push(e)}const s=[];bl([o,"access",e=>e.commands,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{s.push(e.name())}))]),bl([o,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}))]),o!==wl&&bl([wl,"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=i[i.length-1]||"",r=Array.from(new Set(s)).filter((e=>e.startsWith(n)));0===r.length&&Il(o)?console.log(gl):r.length>0&&console.log(r.join("\n")),process.exit()}():vl&&vl.init())}class Pl{static getInstance(){return Pl.INSTANCE||(Pl.INSTANCE=new Pl),Pl.INSTANCE}async getDefaultConversation(e){return(await t.BuildAgentApi.GetProjectDefaultConversation({project_id:e})).Data}async updateConversationSetting(e,o,i){await t.BuildAgentApi.UpdateConversationSetting({project_id:e,conversation_id:o,...void 0!==i.modelSetting?{model_setting:i.modelSetting}:{},...void 0!==i.skillSetting?{skill_setting:i.skillSetting}:{},...void 0!==i.mode?{mode:i.mode}:{},...void 0!==i.agentTools?{agent_tools:i.agentTools}:{}})}}const zl=Pl.getInstance();function Tl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Rl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function xl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ll=o=>{const i=o.command("tools").config({help:{brief:"Manage project tools",description:"Manage tools associated with a project. Tools extend project capabilities such as web search, image generation, etc.",examples:[{desc:"List project tools",cmd:"coze code tools list -p <projectId>"},{desc:"Enable a tool",cmd:"coze code tools enable enable_image_gen -p <projectId>"},{desc:"Disable a tool",cmd:"coze code tools disable enable_image_gen -p <projectId>"}],seeAlso:["coze code project","coze code model"]}}).description("Manage project tools");!function(o){o.command("list").description("List available tools for the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List available tools for the project",description:"List all available tools for the specified project type, with enabled status indicating current configuration.",examples:[{desc:"List project tools",cmd:"coze code tools list -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:"array",items:{type:"object",properties:{tool_name:{type:"string",description:"Tool name"},description:{type:"string",description:"Tool description"},enabled:{type:"boolean",description:"Whether the tool is enabled"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Check the project ID, run `coze code project list` to view available projects"},{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"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server failed to fetch the tool list or conversation settings",fix:"Retry later; run with --debug for details if the issue persists"}],seeAlso:["coze code tools enable","coze code tools disable"]}}).action((async function(e,o){const i=o.getContext(),{projectId:s}=e,n=Tl([await t.IdeApi.GetVibeProject({project_id:s}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=Tl([await zl.getDefaultConversation(s),"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools]),a=Tl([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===n)),"optionalAccess",e=>e.tools]);if(!a||0===a.length)return Tl([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("No tools available for this project type.")]),void Tl([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e([])]);const c=a.map((e=>({tool_name:e.name,description:e.description||e.display_name,enabled:Tl([r,"optionalAccess",t=>t[e.name]])})));Tl([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${c.length} tools.`)]),Tl([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(c)])}))}(i),function(o){o.command("enable <toolName>").description("Enable a conversation tool").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Enable a conversation tool",description:"Enable a specified tool in the default conversation settings.",examples:[{desc:"Enable image generation",cmd:"coze code tools enable enable_image_gen -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{toolName:{type:"string",required:!0,description:"Tool name to enable"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},enable_tool_name:{type:"string",description:"Enabled tool name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified tool is not available for this project type",fix:"Use 'coze code tools list -p <projectId>' to see available tools"}],seeAlso:["coze code tools list","coze code tools disable"]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=Rl([await t.IdeApi.GetVibeProject({project_id:r}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=Rl([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===a)),"optionalAccess",e=>e.tools]);if(!Rl([c,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Tool '${o}' is not available for this project type`,{toolName:o,projectId:r});const l=await zl.getDefaultConversation(r),d=Rl([l,"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools])||{};await zl.updateConversationSetting(r,l.id,{agentTools:{...d,[o]:!0}}),Rl([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Tool '${o}' enabled.`)]),Rl([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,enable_tool_name:o,message:`Tool '${o}' has been enabled successfully`})])}))}(i),function(o){o.command("disable <toolName>").description("Disable a conversation tool").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Disable a conversation tool",description:"Disable a specified tool in the default conversation settings.",examples:[{desc:"Disable image generation",cmd:"coze code tools disable enable_image_gen -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{toolName:{type:"string",required:!0,description:"Tool name to disable"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},disable_tool_name:{type:"string",description:"Disabled tool name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified tool is not available for this project type",fix:"Use 'coze code tools list -p <projectId>' to see available tools"}],seeAlso:["coze code tools list","coze code tools enable"]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=xl([await t.IdeApi.GetVibeProject({project_id:r}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=xl([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===a)),"optionalAccess",e=>e.tools]);if(!xl([c,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Tool '${o}' is not available for this project type`,{toolName:o,projectId:r});const l=await zl.getDefaultConversation(r),d=xl([l,"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools])||{};await zl.updateConversationSetting(r,l.id,{agentTools:{...d,[o]:!1}}),xl([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Tool '${o}' disabled.`)]),xl([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,disable_tool_name:o,message:`Tool '${o}' has been disabled successfully`})])}))}(i)};function Ol(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Dl(e,t){return null!=e?e:t()}function Ul(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function ql(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Bl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Ml(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Nl=o=>{const i=o.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");!function(o){o.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)").option("--my","List personal skills only").option("--page <page>","Page number (for personal skills)").option("--size <size>","Page size (for personal skills)").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]"]},{desc:"List personal skills",cmd:"coze code skill list -p <projectId> --my"},{desc:"List personal skills with pagination",cmd:"coze code skill list -p <projectId> --my --page 1 --size 10"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"},my:{type:"boolean",required:!1,description:"List personal skills only"},page:{type:"number",required:!1,description:"Page number (for personal skills, default: 1)"},size:{type:"number",required:!1,description:"Page size (for personal skills, default: 20)"}},output:{type:"object",properties:{items:{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"}}}},total:{type:"number",description:"Total number of records (only present for --my mode)"}}}},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"}],seeAlso:["coze code skill add","coze code skill remove"]}}).action((async function(o,i){const s=i.getContext(),{projectId:n}=o;if(o.my){const e=o.page?parseInt(o.page,10):1,t=o.size?parseInt(o.size,10):20,i=await Ic.GetUserSkillList({page:e,size:t});return Ul([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${Ul([i,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} personal skills.`)]),void Ul([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({items:Ul([i,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({skill_id:Ul([e,"optionalAccess",e=>e.skill_id]),name:Ul([e,"optionalAccess",e=>e.name]),description:Ul([e,"optionalAccess",e=>e.description]),icon:Ul([e,"optionalAccess",e=>e.icon]),is_installed:!1})))])||[],total:Dl(Ul([i,"access",e=>e.data,"optionalAccess",e=>e.total]),(()=>0))})])}const r=Dl(Dl(o.spaceId,(()=>Ul([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=Ul([await zl.getDefaultConversation(n),"access",e=>e.conversation_setting,"optionalAccess",e=>e.skill_setting,"optionalAccess",e=>e.skills])||[],l=new Set(c.map((e=>e.skill_id)).filter(Boolean)),d=Ul([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),p=await Ic.GetSkillList({project_type:d,space_id:r,category_type_list:[d]});Ul([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${Ul([p,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} skills.`)]),Ul([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({items:Ul([p,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({description:Ul([e,"optionalAccess",e=>e.description]),skill_id:Ul([e,"optionalAccess",e=>e.skill_id]),name:Ul([e,"optionalAccess",e=>e.name]),icon:Ul([e,"optionalAccess",e=>e.icon]),is_installed:l.has(e.skill_id||"")})))])||[]})])}))}(i),function(t){t.command("add <skillId>").description("Add skills to the conversation").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add skill to conversation",description:"Add a specified skill to the default conversation. Skills can extend 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:{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 (returned by the API layer, not thrown by the CLI itself)",fix:"Please use `skill list` to confirm available skills"}],seeAlso:["coze code skill list","coze code skill remove"]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t,n=[e],r=await zl.getDefaultConversation(s);await zl.updateConversationSetting(s,r.id,{skillSetting:{add_skills:n.map((e=>({skill_id:String(e),is_preload:!0})))}}),ql([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skills added successfully.")]),ql([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,added_skill_ids:n,message:"added Skills successfully."})])}))}(i),function(t){t.command("remove <skillId>").description("Remove skills from the conversation").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Remove skill from conversation",description:"Remove a configured skill from the default conversation.",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:{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 conversation (returned by the API layer, not thrown by the CLI itself)",fix:"Please use `skill list` to confirm installed skills"}],seeAlso:["coze code skill list","coze code skill add"]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t,n=[e],r=await zl.getDefaultConversation(s);await zl.updateConversationSetting(s,r.id,{skillSetting:{remove_skills:n.map((e=>({skill_id:String(e),is_preload:!0})))}}),Ol([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill removed.")]),Ol([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,removed_skill_ids:n,message:"removed Skills successfully."})])}))}(i),function(t){t.command("upload <filePath>").description("Upload a personal skill").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Upload a personal skill",description:"Upload a .skill file as a personal skill. If a naming conflict exists, it will be automatically confirmed to overwrite.",examples:[{desc:"Upload a skill file",cmd:'coze code skill upload "./my-skill.skill" -p <projectId>',tags:["[RECOMMENDED]"]}],schema:{input:{filePath:{type:"string",required:!0,description:"Path to the .skill file"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"File not found at the specified path",fix:"Please provide a valid path to a .skill file"}],seeAlso:["coze code skill list","coze code skill delete"]}}).action((async function(t,o,i){const s=i.getContext(),{projectId:n}=o,r=m.resolve(t);if(!h.existsSync(r))throw new e.CozeError(e.ErrorCode.E1000,`File not found: ${r}`,{filePath:r});const a=m.basename(r),c=h.createReadStream(r);Bl([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Uploading skill ${a}...`)]);const l=await Ic.UploadSkill({body:{file_content:c,file_name:a}},{headers:{"Content-Type":"multipart/form-data"}});if(Bl([l,"access",e=>e.data,"optionalAccess",e=>e.naming_conflict])){const e=Bl([l,"access",e=>e.data,"optionalAccess",e=>e.conflict_info,"optionalAccess",e=>e.preview_skill_key]);Bl([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Naming conflict detected, auto-confirming overwrite...")]),await Ic.UploadSkillConfirm({preview_skill_key:e})}Bl([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill uploaded successfully.")]),Bl([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,message:"Skill uploaded successfully"})])}))}(i),function(t){t.command("delete <skillId>").description("Delete a personal skill").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete a personal skill",description:"Permanently delete a personal skill. This is different from skill remove which only unlinks a skill from the project.",examples:[{desc:"Delete a skill",cmd:"coze code skill delete <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{skillId:{type:"string",required:!0,description:"Skill ID to delete"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Skill not found or invalid skill ID",fix:"Use 'coze code skill list -p <projectId> --my' to see available skills"}],seeAlso:["coze code skill list","coze code skill upload"]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t;await Ic.DeleteSkill({skill_id:e}),Ml([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Skill '${e}' deleted.`)]),Ml([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({project_id:s,message:`Skill '${e}' has been permanently deleted`})])}))}(i)};var $l,Gl,Fl,Vl,Wl,Hl,Jl,Kl,Ql,Yl,Zl,Xl,ed,td,od,id,sd,nd,rd,ad,cd,ld,dd,pd,ud,md,gd,hd,fd,_d,yd,bd,vd,wd,Ed,Cd,Id,Ad,Sd,kd,jd,Pd,zd,Td,Rd,xd,Ld,Od,Dd,Ud,qd,Bd,Md,Nd,$d,Gd,Fd,Vd,Wd,Hd,Jd,Kd,Qd,Yd,Zd,Xd,ep,tp,op,ip,sp,np,rp,ap,cp,lp,dp;function pp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}($l||($l={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(Gl||(Gl={})),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"}(Fl||(Fl={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(Vl||(Vl={})),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"}(Wl||(Wl={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(Hl||(Hl={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(Jl||(Jl={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(Kl||(Kl={})),function(e){e[e.Official=1]="Official";e[e.Public=2]="Public";e[e.Custom=3]="Custom";e[e.Others=101]="Others"}(Ql||(Ql={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(Yl||(Yl={})),function(e){e[e.App=1]="App";e[e.Resource=2]="Resource"}(Zl||(Zl={})),function(e){e[e.CozeModel=1]="CozeModel";e[e.VolcAccount=2]="VolcAccount";e[e.SelfAccount=3]="SelfAccount";e[e.SelfModel=4]="SelfModel"}(Xl||(Xl={})),function(e){e[e.Asc=1]="Asc";e[e.Desc=2]="Desc"}(ed||(ed={})),function(e){e[e.NoDetail=1]="NoDetail";e[e.Detail=2]="Detail";e[e.Operate=3]="Operate"}(td||(td={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(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.Prompt=6]="Prompt";e[e.Database=7]="Database";e[e.Variable=8]="Variable"}(id||(id={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi";e[e.MessagesApi=2]="MessagesApi"}(sd||(sd={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(nd||(nd={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(rd||(rd={})),function(e){e[e.Provider=1]="Provider";e[e.Custom=2]="Custom"}(ad||(ad={})),function(e){e[e.CozeAccountTypeUnknown=0]="CozeAccountTypeUnknown";e[e.CozeAccountTypePersonal=1]="CozeAccountTypePersonal";e[e.CozeAccountTypeOrganization=2]="CozeAccountTypeOrganization"}(cd||(cd={})),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"}(ld||(ld={})),function(e){e[e.Mobile=1]="Mobile";e[e.Web=2]="Web"}(dd||(dd={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(pd||(pd={})),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"}(ud||(ud={})),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"}(md||(md={})),function(e){e[e.DEFAULT=0]="DEFAULT";e[e.Chux=1]="Chux"}(gd||(gd={})),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"}(hd||(hd={})),function(e){e[e.PromptDiff=1]="PromptDiff";e[e.ModelDiff=2]="ModelDiff"}(fd||(fd={})),function(e){e[e.DraftBot=1]="DraftBot"}(_d||(_d={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(yd||(yd={})),function(e){e[e.Archive=1]="Archive";e[e.Rollback=2]="Rollback"}(bd||(bd={})),function(e){e[e.ProjectCopyCancel=1]="ProjectCopyCancel";e[e.ProjectCopyRetry=2]="ProjectCopyRetry"}(vd||(vd={})),function(e){e[e.ProjectCopy=1]="ProjectCopy";e[e.BotCopy=2]="BotCopy";e[e.VibeProjectCopy=3]="VibeProjectCopy"}(wd||(wd={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Ed||(Ed={})),function(e){e[e.Bot=1]="Bot";e[e.Workflow=2]="Workflow";e[e.Application=3]="Application"}(Cd||(Cd={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(Id||(Id={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(Ad||(Ad={})),function(e){e[e.BatchSize=1]="BatchSize";e[e.LearningRate=2]="LearningRate";e[e.Epochs=3]="Epochs"}(Sd||(Sd={})),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"}(kd||(kd={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(jd||(jd={})),function(e){e[e.Douyin=1]="Douyin"}(Pd||(Pd={})),function(e){e[e.Terminating=1]="Terminating";e[e.Terminated=2]="Terminated"}(zd||(zd={})),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"}(Td||(Td={})),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"}(Rd||(Rd={})),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"}(xd||(xd={})),function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInput=2]="TotalInput";e[e.TotalOutput=3]="TotalOutput"}(Ld||(Ld={})),function(e){e[e.stop=1]="stop";e[e.resume=2]="resume",e[e.delete=3]="delete"}(Od||(Od={})),function(e){e[e.Recommend=1]="Recommend"}(Dd||(Dd={})),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"}(qd||(qd={})),function(e){e[e.upload=1]="upload";e[e.TrainingSetSplit=2]="TrainingSetSplit"}(Bd||(Bd={})),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"}(Nd||(Nd={})),function(e){e[e.Publish=0]="Publish";e[e.Archive=1]="Archive"}($d||($d={})),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"}(Vd||(Vd={})),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"}(Wd||(Wd={})),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"}(Hd||(Hd={})),function(e){e[e.Normal=0]="Normal";e[e.InReview=1]="InReview";e[e.Offline=2]="Offline"}(Jd||(Jd={})),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"}(Kd||(Kd={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Authorizing=3]="Authorizing"}(Qd||(Qd={})),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"}(Yd||(Yd={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Zd||(Zd={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.Name=2]="Name"}(Xd||(Xd={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime"}(ep||(ep={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.PublishTime=2]="PublishTime";e[e.OpenTime=3]="OpenTime"}(tp||(tp={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(op||(op={})),function(e){e[e.All=0]="All";e[e.CreateByMe=1]="CreateByMe";e[e.AllWithCollaborator=2]="AllWithCollaborator";e[e.CanImportToSpace=3]="CanImportToSpace"}(ip||(ip={})),function(e){e[e.Desc=0]="Desc";e[e.Asc=1]="Asc"}(sp||(sp={})),function(e){e[e.Copy=1]="Copy";e[e.Move=2]="Move";e[e.Publish=3]="Publish";e[e.ImportExport=4]="ImportExport"}(np||(np={})),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"}(rp||(rp={})),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"}(ap||(ap={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(cp||(cp={})),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"}(lp||(lp={})),function(e){e[e.Packing=0]="Packing";e[e.PackSuccess=1]="PackSuccess";e[e.PackFail=2]="PackFail"}(dp||(dp={}));class up{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){up.prototype.__init.call(this),up.prototype.__init2.call(this),this.request=pp([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=pp([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}Ping(e,t){const o=this.genBaseURL("/api/intelligence_api/ping");return this.request({url:o,method:"POST"},t)}DraftProjectCreate(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/create"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri,monetization_conf:o.monetization_conf,create_from:o.create_from,folder_id:o.folder_id,type:o.type};return this.request({url:i,method:"POST",data:s},t)}GetDraftIntelligenceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_list"),s={space_id:o.space_id,name:o.name,has_published:o.has_published,status:o.status,types:o.types,search_scope:o.search_scope,folder_id:o.folder_id,folder_include_children:o.folder_include_children,order_type:o.order_type,project_type:o.project_type,is_fav_filter:o.is_fav_filter,is_collaborator_filter:o.is_collaborator_filter,organization_id:o.organization_id,is_fav:o.is_fav,recently_open:o.recently_open,option:o.option,order_by:o.order_by,cursor_id:o.cursor_id,size:o.size};return this.request({url:i,method:"POST",data:s},t)}DraftProjectUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/update"),s={project_id:o.project_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetDraftIntelligenceInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_info"),s={intelligence_id:o.intelligence_id,intelligence_type:o.intelligence_type,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GetUserRecentlyEditIntelligence(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/search/get_recently_edit_intelligence"),s={size:o.size,types:o.types,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DraftProjectCopy(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/copy"),s={project_id:o.project_id,to_space_id:o.to_space_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}ProcessEntityTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/entity_task/process"),s={entity_id:o.entity_id,action:o.action,task_id_list:o.task_id_list};return this.request({url:i,method:"POST",data:s},t)}DraftProjectDelete(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/delete"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}EntityTaskSearch(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/entity_task/search"),s={task_list:o.task_list};return this.request({url:i,method:"POST",data:s},t)}ListIntelligenceCollaboration(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/collaboration/list"),s={intelligence_id:o.intelligence_id,intelligence_type:o.intelligence_type};return this.request({url:i,method:"POST",data:s},t)}OceanProjectCreate(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/ocean_project/create"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}OceanProjectUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/ocean_project/update"),s={project_id:o.project_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetOceanProjectList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_list"),s={space_id:o.space_id,status:o.status,search_scope:o.search_scope,order_by:o.order_by,page_index:o.page_index,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PublishProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_project"),s={project_id:o.project_id,version_number:o.version_number,description:o.description,connectors:o.connectors,connector_publish_config:o.connector_publish_config};return this.request({url:i,method:"POST",data:s},t)}GetPublishRecordDetail(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_record_detail"),s={project_id:o.project_id,publish_record_id:o.publish_record_id};return this.request({url:i,method:"POST",data:s},t)}GetPublishRecordList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_record_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublishConnectorList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/connector_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}CheckProjectVersionNumber(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/check_version_number"),s={project_id:o.project_id,version_number:o.version_number};return this.request({url:i,method:"POST",data:s},t)}DraftProjectInnerTaskList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/inner_task_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}GetOceanProjectInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_info"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}GetModelListFilterParams(e,t){const o=this.genBaseURL("/api/intelligence_api/model/get_model_list_filter_params");return this.request({url:o,method:"POST"},t)}StartEstimatedTrainingCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/start_estimated_training_cost"),s={base_model_id:o.base_model_id,space_id:o.space_id,training_dataset_id:o.training_dataset_id,epochs:o.epochs};return this.request({url:i,method:"POST",data:s},t)}GetModelList(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_list"),s={space_id:o.space_id,name:o.name,tag_filters:o.tag_filters,context_len_min:o.context_len_min,context_len_max:o.context_len_max,model_cost_min:o.model_cost_min,model_cost_max:o.model_cost_max,model_vendor:o.model_vendor,statusList:o.statusList,model_show_family_id:o.model_show_family_id,model_source:o.model_source,order_by:o.order_by,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}GetFinetuneTemplateDataset(e,t){const o=this.genBaseURL("/api/intelligence_api/model/get_finetune_template_dataset");return this.request({url:o,method:"POST"},t)}GetModelUsageData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_usage_data"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTrainingCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_training_cost"),s={task_id:o.task_id,space_id:o.space_id,base_model_id:o.base_model_id,epochs:o.epochs};return this.request({url:i,method:"POST",data:s},t)}CreateFinetuneTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/create_finetune_task"),s={space_id:o.space_id,base_model_id:o.base_model_id,training_dataset_id:o.training_dataset_id,validating_dataset:o.validating_dataset,finetune_configuration:o.finetune_configuration,description:o.description,name:o.name};return this.request({url:i,method:"POST",data:s},t)}UploadFinetuneDataset(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/upload_finetune_dataset"),s={space_id:o.space_id,fileType:o.fileType,fileName:o.fileName,data:o.data,testing_data:o.testing_data};return this.request({url:i,method:"POST",data:s},t)}GetModelInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_info"),s={space_id:o.space_id,model_id:o.model_id,is_finetuning:o.is_finetuning};return this.request({url:i,method:"POST",data:s},t)}GetFinetuneTrainingInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_finetune_training_info"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetModelPerformanceData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_performance_data"),s={space_id:o.space_id,model_id:o.model_id,get_pct:o.get_pct};return this.request({url:i,method:"POST",data:s},t)}OperateFinetuneTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/operate_finetune_task"),s={id:o.id,action:o.action};return this.request({url:i,method:"POST",data:s},t)}DeleteFinetuneModel(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/delete_finetune_model"),s={model_id:o.model_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetUserCompleteProfileRecord(e,t){const o=this.genBaseURL("/api/intelligence_api/user_profile/get_user_complete_profile_record");return this.request({url:o,method:"POST"},t)}DownloadUserProfile(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/user_profile/download_user_profile"),s={Cookie:o.Cookie};return this.request({url:i,method:"POST",headers:s},t)}GetProjectPublishedConnector(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/get_published_connector"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublishIntelligenceUnList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_intelligence_unlist"),s={intelligence_id:o.intelligence_id,connector_ids:o.connector_ids,intelligence_type:o.intelligence_type};return this.request({url:i,method:"POST",data:s},t)}PublishIntelligenceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_publish_intelligence_list"),s={intelligence_type:o.intelligence_type,space_id:o.space_id,owner_id:o.owner_id,name:o.name,order_last_publish_time:o.order_last_publish_time,order_total_token:o.order_total_token,size:o.size,cursor_id:o.cursor_id,intelligence_ids:o.intelligence_ids};return this.request({url:i,method:"POST",data:s},t)}UpdateDiffModeInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/diff_mode/update_diff_mode_info"),s={target_type:o.target_type,target_id:o.target_id,diff_mode_info:o.diff_mode_info,exit_and_save:o.exit_and_save,exit_and_discard:o.exit_and_discard};return this.request({url:i,method:"POST",data:s},t)}GetDiffModeInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/diff_mode/get_diff_mode_info"),s={target_type:o.target_type,target_id:o.target_id};return this.request({url:i,method:"POST",data:s},t)}GetProjectPublishSummary(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_project_publish_summary"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}DraftProjectCrossSpaceCopy(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/crossspace_copy"),s={project_id:o.project_id,to_space_id:o.to_space_id};return this.request({url:i,method:"POST",data:s},t)}EntityTaskList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/entity_task/list"),s={space_id:o.space_id,task_id_list:o.task_id_list};return this.request({url:i,method:"POST",data:s},t)}ExpansionTpm(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/expansion_tpm"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,organization_id:o.organization_id,tpm_input_expansion:o.tpm_input_expansion,tpm_output_expansion:o.tpm_output_expansion,start_time:o.start_time,end_time:o.end_time};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTpmExpansionCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion_cost"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,input_tpm:o.input_tpm,output_tpm:o.output_tpm};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTpmExpansion(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,estimated_rpm:o.estimated_rpm,StartTime:o.StartTime,EndTime:o.EndTime};return this.request({url:i,method:"POST",data:s},t)}FolderUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/update"),s={folder_id:o.folder_id,name:o.name,description:o.description};return this.request({url:i,method:"POST",data:s},t)}GetFolderList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_folder_list"),s={space_id:o.space_id,type:o.type,name:o.name,search_scope:o.search_scope,parent_folder_id:o.parent_folder_id,parent_include_children:o.parent_include_children,order_by:o.order_by,order_type:o.order_type,size:o.size,page_num:o.page_num};return this.request({url:i,method:"POST",data:s},t)}FolderMove(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/move"),s={folder_id:o.folder_id,parent_folder_id:o.parent_folder_id};return this.request({url:i,method:"POST",data:s},t)}FolderDelete(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/delete"),s={folder_id:o.folder_id};return this.request({url:i,method:"POST",data:s},t)}FolderCreate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/create"),s={space_id:o.space_id,type:o.type,name:o.name,description:o.description,parent_folder_id:o.parent_folder_id};return this.request({url:i,method:"POST",data:s},t)}ArchiveProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/archive"),s={project_id:o.project_id,description:o.description,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetIntelligenceTaskInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/entity_task/task_info"),s={task_id:o.task_id};return this.request({url:i,method:"GET",params:s},t)}ProjectHistoryList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list"),s={project_id:o.project_id,history_type:o.history_type,cursor:o.cursor,size:o.size};return this.request({url:i,method:"POST",data:s},t)}RollbackProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/rollback"),s={project_id:o.project_id,rollback_version:o.rollback_version,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetModelConcurrencyPerformanceData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_concurrency_performance_data"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}UpdateModelConfigType(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/update_model_config_type"),s={space_id:o.space_id,model_id:o.model_id,config_type:o.config_type};return this.request({url:i,method:"POST",data:s},t)}GetSpaceModelUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_space_model_user_config"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}OpenGetProjectList(e,t){const o=e||{},i=this.genBaseURL("/v1/apps"),s={workspace_id:o.workspace_id,publish_status:o.publish_status,connector_id:o.connector_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}OpenGetBotList(e,t){const o=e||{},i=this.genBaseURL("/v1/bots"),s={workspace_id:o.workspace_id,publish_status:o.publish_status,connector_id:o.connector_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}GetFolderTree(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/tree"),s={space_id:o.space_id,type:o.type};return this.request({url:i,method:"POST",data:s},t)}OpenGetSpaceFolder(e,t){const o=e||{},i=this.genBaseURL("/v1/folders"),s={workspace_id:o.workspace_id,folder_type:o.folder_type,parent_folder_id:o.parent_folder_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}MoveObjectToFolder(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/move_object"),s={dest_folder_id:o.dest_folder_id,folder_space_id:o.folder_space_id,move_objects:o.move_objects};return this.request({url:i,method:"POST",data:s},t)}GetFolderInfoByIds(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/folder/get_by_ids"),s={space_id:o.space_id,folder_ids:o.folder_ids,get_path_info:o.get_path_info};return this.request({url:i,method:"POST",data:s},t)}OpenGetFolderInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/folders/${o.folder_id}`);return this.request({url:i,method:"GET"},t)}ExportPreCheck(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/export_pre_check"),s={res_type:o.res_type,id:o.id,commit_id:o.commit_id};return this.request({url:i,method:"POST",data:s},t)}ImportPreCheck(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/import_pre_check"),s={package_uri:o.package_uri};return this.request({url:i,method:"POST",data:s},t)}GetUploadAuthToken(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/upload/auth_token"),s={scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}MarkProjectHistory(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list/read"),s={project_id:o.project_id,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelDetail(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_detail"),s={model_id:o.model_id,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_list"),s={search_key:o.search_key,sort_field:o.sort_field,org_id:o.org_id,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetProjectHistoryNotice(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list/notice"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}BindCustomModelSpace(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/bind_custom_model_space"),s={model_id:o.model_id,space_id_list:o.space_id_list,status:o.status,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelSpaceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_space_list"),s={model_id:o.model_id,search_key:o.search_key,org_id:o.org_id,cursor_id:o.cursor_id,limit:o.limit,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelParameterTemplate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_parameter_template"),s={org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}OpenCopyTaskInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/entities/copy_tasks/${o.task_id}`);return this.request({url:i,method:"GET"},t)}OpenDuplicateDraftEntity(e,t){const o=e||{},i=this.genBaseURL("/v1/entities/copy_tasks"),s={entity_id:o.entity_id,entity_type:o.entity_type,to_workspace_id:o.to_workspace_id};return this.request({url:i,method:"POST",data:s},t)}ConvertCustomModelParameter(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/convert_custom_model_parameter"),s={parameters:o.parameters,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}CreateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/create_custom_model"),s={model_name:o.model_name,model_icon_uri:o.model_icon_uri,model_arch:o.model_arch,model_desc:o.model_desc,base_url:o.base_url,secret_name:o.secret_name,model_runtime_tag:o.model_runtime_tag,inputLength:o.inputLength,parameters:o.parameters,api_agreement:o.api_agreement,safety_guardrails:o.safety_guardrails,auth:o.auth,api_mode:o.api_mode,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}TerminateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/terminate_custom_model"),s={model_id:o.model_id,terminate_time:o.terminate_time,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}UpdateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/update_custom_model"),s={model_name:o.model_name,model_icon_uri:o.model_icon_uri,model_arch:o.model_arch,model_desc:o.model_desc,base_url:o.base_url,secret_name:o.secret_name,model_runtime_tag:o.model_runtime_tag,inputLength:o.inputLength,parameters:o.parameters,model_id:o.model_id,api_agreement:o.api_agreement,safety_guardrails:o.safety_guardrails,auth:o.auth,api_mode:o.api_mode,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageRecord(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_usage_record"),s={space_id:o.space_id,model_id:o.model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp,order_by_type:o.order_by_type,order_by_field:o.order_by_field,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetEntityModelUsage(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_entity_model_usage"),s={space_id:o.space_id,model_id:o.model_id,entity_id:o.entity_id,entity_type:o.entity_type,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}GetTypeList(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/get_type_list"),s={model:o.model,voice:o.voice,raw_model:o.raw_model,space_id:o.space_id,cur_model_id:o.cur_model_id,cur_model_ids:o.cur_model_ids,model_scene:o.model_scene,tag_filters:o.tag_filters,user_benefit_filter:o.user_benefit_filter};return this.request({url:i,method:"POST",data:s},t)}SaveModelReplacement(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/save_replacement"),s={space_id:o.space_id,old_model_id:o.old_model_id,new_model_id:o.new_model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}GetModelReplacement(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_replacement"),s={space_id:o.space_id,entity_type:o.entity_type,entity_id:o.entity_id};return this.request({url:i,method:"POST",data:s},t)}UpdateCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/update"),s={model_id:o.model_id,display_name:o.display_name,model_name:o.model_name,base_url:o.base_url,api_mode:o.api_mode,auth:o.auth,support_image_understanding:o.support_image_understanding,max_tokens:o.max_tokens};return this.request({url:i,method:"POST",data:s},t)}ListProviderModels(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/list_provider_models"),s={provider:o.provider,auth:o.auth,base_url:o.base_url,search_key:o.search_key};return this.request({url:i,method:"POST",data:s},t)}ListCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/list"),s={account_type:o.account_type,coze_account_id:o.coze_account_id,enterprise_id:o.enterprise_id,search_key:o.search_key,provider:o.provider,source_type:o.source_type,sort_field:o.sort_field,sort_order:o.sort_order,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}ToggleCustomModelMemberVisibility(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/toggle_member_visibility"),s={model_id:o.model_id,member_visible:o.member_visible};return this.request({url:i,method:"POST",data:s},t)}DeleteCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/delete"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}ListProviders(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/custom_model/list_providers"),s={only_enabled:o.only_enabled};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelDetailV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/detail"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}CreateCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/create"),s={source_type:o.source_type,provider:o.provider,display_name:o.display_name,model_name:o.model_name,base_url:o.base_url,api_mode:o.api_mode,auth:o.auth,support_image_understanding:o.support_image_understanding,max_tokens:o.max_tokens,account_type:o.account_type,coze_account_id:o.coze_account_id,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}}const mp=new up({}),gp={agent:md.VibeProjectAgent,workflow:md.VibeProjectAutomation,webapp:md.VibeProjectWebApp,app:md.VibeProjectApp,skill:md.VibeProjectSkill,web:md.VibeProjectGeneralWeb,miniprogram:md.VibeProjectWechatMiniProgram,assistant:md.VibeProjectAssistantAgent},hp={[md.VibeProjectAgent]:"agent",[md.VibeProjectAutomation]:"workflow",[md.VibeProjectWebApp]:"webapp",[md.VibeProjectApp]:"app",[md.VibeProjectSkill]:"skill",[md.VibeProjectGeneralWeb]:"web",[md.VibeProjectWechatMiniProgram]:"miniprogram",[md.VibeProjectAssistantAgent]:"assistant"};function fp(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return gp[o]}const _p=e=>hp[e],yp=[md.VibeProjectAgent,md.VibeProjectAutomation,md.VibeProjectWebApp,md.VibeProjectApp,md.VibeProjectSkill,md.VibeProjectGeneralWeb,md.VibeProjectWechatMiniProgram,md.VibeProjectAssistantAgent].map(_p).filter(Boolean);function bp(e,t){return null!=e?e:t()}function vp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function wp(e,t){return null!=e?e:t()}const Ep=["ecs","vefaas"],Cp=new Set([t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.WechatMiniProgram]),Ip=(e,t)=>{const o=void 0!==e?(e=>void 0!==e&&Cp.has(e))(e):Ep.includes(wp(process.env.COZE_CLI_PLATFORM,(()=>"")).trim().toLowerCase());return o?"https://www.coze.cn/":wp(t,(()=>s.DEFAULT_CONFIG.apiBaseUrl))},Ap=(e,t,o)=>`${Ip(t,o)}p/${e}`;class Sp{static getInstance(){return Sp.INSTANCE||(Sp.INSTANCE=new Sp),Sp.INSTANCE}sendMessageRunTask(e){const t=[m.resolve(__dirname,"./send-message.worker.js")],o=process.execPath;b.spawn(o,[...t,JSON.stringify(e)],{detached:!0,stdio:"ignore"}).unref()}async sendMessage(e){return await t.sendProjectChatMessage(e)}}const kp=Sp.getInstance();function jp(e,t){return null!=e?e:t()}function Pp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const zp=["github","local"],Tp="按标准流程初始化当前项目";async function Rp(t,o){if(o)try{const i=await Pp([t,"access",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!i)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const s=await zl.getDefaultConversation(o);kp.sendMessageRunTask({projectId:o,prompt:Tp,apiBaseUrl:t.config.apiBaseUrl,accessToken:i,xTTEnv:t.config.xTTEnv,conversationId:s.id,key:`coze-coding-cli:message:${o}`}),t.ui.info(` Initial query sent. Use \`coze code message status -p ${o}\` to check the result.`)}catch(e){t.ui.warn(`Failed to send initial query: ${e instanceof Error?e.message:String(e)}. You can send it manually: coze code message send "${Tp}" -p ${o}`)}}const xp={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},Lp={[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"};function Op(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return xp[o]}const Dp=e=>Lp[e],Up={ask:t.ProjectMode.Ask,agent:t.ProjectMode.Agent,dangerous_confirm:t.ProjectMode.DangerousConfirm,plan:t.ProjectMode.Plan};t.ProjectMode.Ask,t.ProjectMode.Agent,t.ProjectMode.DangerousConfirm,t.ProjectMode.Plan;const qp={[t.ConversationMode.Ask]:"ask",[t.ConversationMode.Agent]:"agent",[t.ConversationMode.DangerousConfirm]:"dangerous_confirm",[t.ConversationMode.Plan]:"plan"};function Bp(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return Up[o]}function Mp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Np(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const $p={project_id:"7603316828982525988",icon_uri:"gen_project_icon/2026-02-06/7603316828982525988_1770308040.png",name:"OpenClaw助手(副本)",description:"OpenClaw智能代理:提供多场景AI服务,自动化处理任务,提升工作效率。"};function Gp(e,t){return null!=e?e:t()}function Fp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Vp=new Set([t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.WechatMiniProgram]);function Wp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Hp=o=>{const i=o.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");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 | webapp | 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").option("--chat-mode <chatMode>","Chat mode: ask | agent | dangerous_confirm | plan").option("--model-name <modelName>","Model name for the project").option("--tool-name <toolName>","Tool names to enable (can specify multiple times)",((e,t)=>t.concat(e)),[]).option("--design","Enable design wizard (auto-enabled when --chat-mode is plan)").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:Object.keys(xp),description:"Project type: agent | workflow | app | skill | web | webapp | miniprogram | assistant"},orgId:{type:"string",required:!1,description:"Organization ID (optional, reads from context)"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"},chatMode:{type:"string",enum:Object.keys(Up),required:!1,description:'Chat mode: ask (对话模式) | agent (Agent模式, default) | dangerous_confirm (危险操作需确认) | plan (计划模式). When set to "plan", --design is auto-enabled.'},modelName:{type:"string",required:!1,description:"Model name for the project"},toolName:{type:"array",required:!1,description:"Tool names to enable (can specify multiple times with --tool-name)"},design:{type:"boolean",required:!1,description:"Enable design wizard. Auto-enabled when --chat-mode is plan. Only supported for web/app/miniprogram project types."}},output:{project_id:{type:"string",description:"Created project ID"},type:{type:"string",description:"Project type"},project_url:{type:"string",description:"Web URL to open the project conversation page directly"}}},enums:{type:Object.keys(xp).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 | webapp | 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"},{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"}],seeAlso:["coze code project list","coze code project get"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Gp(Gp(o.spaceId,(()=>Fp([s,"optionalAccess",e=>e.config,"access",e=>e.spaceId]))),(()=>"")),{message:r,type:a,wait:c,chatMode:l,modelName:d,toolName:p,design:u}=o,m=Boolean(u)||"plan"===l;Fp([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e(`Resolving project type '${a}'...`)]);const g=Op(a);if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!g)throw new e.CozeError(e.ErrorCode.E1005,`Unknown project type: ${a}`,{type:a});Fp([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching agent tools configuration...")]);const h=Fp([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===g)),"optionalAccess",e=>e.tools]);if(!h||0===h.length)throw new e.CozeError(e.ErrorCode.E5000,`No tools config for projectType: ${String(a)}`,{type:a,projectType:g});const f={};h.forEach((e=>{Fp([e,"optionalAccess",e=>e.name])&&(f[e.name]=Gp(Fp([p,"optionalAccess",e=>e.includes,"call",t=>t(e.name)]),(()=>Boolean(e.enabled))))})),Fp([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching project default skills...")]);const _={skills:Gp(Fp([await Ic.GetProjectDefaultSkill({project_type:g,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:[g]};let y;if(g===t.VibeProjectType.AssistantAgent){Fp([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating assistant project via template copy...")]);const e=await t.IdeApi.CopyVibeProject({...$p,target_space_id:String(n)});y=Fp([e,"access",e=>e.data,"optionalAccess",e=>e.basic_info,"optionalAccess",e=>e.project_id])}else{Fp([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating project...")]);const e=Gp((await t.IdeApi.ChatCreateVibeProject({space_id:String(n),user_query:r,project_type:g,project_settings:{...Vp.has(g)?{project_symbol:t.ProjectSymbol.ProjectSymbolVersion3}:{},model_setting:{model_name:d||""},agent_tools:f,skill_setting:_,...l?{project_mode:Bp(l)}:{},...m?{wizards:{design:!0}}:{}}})).data,(()=>({})));y=e.project_id}const b=await Fp([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!b)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const v=y?Ap(y,g,s.config.apiBaseUrl):"";s.ui.success(`Project created successfully, please use "coze code message status -p ${y}" to check the status. Open the project: ${v}`),Fp([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:y,type:a,project_url:v})]);const w=await zl.getDefaultConversation(Gp(y,(()=>"")));if(c){const e=await kp.sendMessage({projectId:Gp(y,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:b,xTTEnv:s.config.xTTEnv,conversationId:w.id,key:`coze-coding-cli:message:${y}`});s.response.print(e.lastAnswerMessage)}else kp.sendMessageRunTask({projectId:Gp(y,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:b,xTTEnv:s.config.xTTEnv,conversationId:w.id,key:`coze-coding-cli:message:${y}`})})),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, AllWithCollaborator = 2)"},folderId:{type:"string",required:!1,description:"Folder ID"},orderType:{type:"number",required:!1,description:"Sort type (0 for descending, 1 for ascending)"},orderBy:{type:"number",required:!1,description:"Order by (0 for updated_at, 1 for created_at)"},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:yp.reduce(((e,t)=>(e[t]=`${t.toUpperCase()} project`,e)),{}),"search-scope":{0:"All",1:"CreateByMe",2:"AllWithCollaborator"},"order-type":{0:"Descending",1:"Ascending"},"order-by":{0:"updated_at",1:"created_at"}},seeAlso:["coze code project get","coze code project create"]}}).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 o=t.getContext(),i=bp(vp([e,"optionalAccess",e=>e.size]),(()=>10)),s=bp(vp([e,"optionalAccess",e=>e.cursorId]),(()=>{})),n=vp([e,"optionalAccess",e=>e.type,"optionalAccess",e=>e.map,"call",e=>e(fp),"access",e=>e.filter,"call",e=>e(Boolean)]),r=vp([e,"optionalAccess",e=>e.name]),a=vp([e,"optionalAccess",e=>e.hasPublished])?Boolean(vp([e,"optionalAccess",e=>e.hasPublished])):void 0,c=Number(bp(vp([e,"optionalAccess",e=>e.searchScope]),(()=>ip.All))),l=bp(vp([e,"optionalAccess",e=>e.folderId]),(()=>"0")),d=Number(bp(vp([e,"optionalAccess",e=>e.orderType]),(()=>sp.Desc))),p=Boolean(vp([e,"optionalAccess",e=>e.isFavFilter])),u=Number(bp(vp([e,"optionalAccess",e=>e.orderBy]),(()=>tp.UpdateTime)));let m=[];vp([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching project list...")]);const g=await mp.GetDraftIntelligenceList({space_id:bp(vp([o,"optionalAccess",e=>e.config,"access",e=>e.spaceId]),(()=>"")),size:i,cursor_id:s,types:n,name:r,has_published:a,search_scope:c,folder_id:l,order_type:d,order_by:u,is_fav_filter:p,status:[ud.Using,ud.Banned,ud.MoveFailed]});m=vp([g,"access",e=>e.data,"optionalAccess",e=>e.intelligences])||[],vp([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetched ${m.length} projects.`)]),vp([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(m.map((e=>({id:vp([e,"access",e=>e.basic_info,"optionalAccess",e=>e.id]),name:vp([e,"access",e=>e.basic_info,"optionalAccess",e=>e.name]),type:_p(e.type),description:vp([e,"access",e=>e.basic_info,"optionalAccess",e=>e.description])}))))])}))}(i),function(o){o.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"},type:{type:"string",description:"Human-readable project type string"},tools:{type:"object",description:"Project tool configurations (Record<string, boolean>)"},chat_mode:{type:"string",description:"Human-readable chat mode string"},model_name:{type:"string",description:"Current model name used by the project"},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"}],seeAlso:["coze code project list","coze code project create"]}}).action((async function(o,i,s){const n=s.getContext();Mp([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetching project details for '${o}'...`)]);try{const[i,s]=await Promise.all([t.IdeApi.GetVibeProject({project_id:o}),zl.getDefaultConversation(o)]),r=Mp([i,"access",e=>e.data,"optionalAccess",e=>e.project_info]);if(!r)throw new e.CozeError(e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o});const a=s.conversation_setting;Mp([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Project details for '${o}':`)]),Mp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>{return e({...v.omit(r,["project_settings"]),type:Dp(Mp([r,"optionalAccess",e=>e.project_type])),tools:Mp([a,"optionalAccess",e=>e.agent_tools]),chat_mode:(t=Mp([a,"optionalAccess",e=>e.mode]),qp[t]),model_name:Mp([a,"optionalAccess",e=>e.model_setting,"optionalAccess",e=>e.model_name]),skills:v.pick(Mp([a,"optionalAccess",e=>e.skill_setting]),["skills"])});var t}])}catch(t){K(t,e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o})}}))}(i),function(o){o.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"}],seeAlso:["coze code project list"]}}).action((async function(o,i,s){const n=s.getContext();Np([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleting project '${o}'...`)]);try{await t.IdeApi.DeleteVibeProject({project_id:o})}catch(t){K(t,e.ErrorCode.E3005,`Failed to delete project '${o}': project not found or no permission`,{projectId:o})}Np([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Project '${o}' deleted successfully.`)]),Np([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:o,message:`Project '${o}' deleted successfully.`})])}))}(i),function(o){o.command("db").description("Manage project databases").command("list").description("List project database tables").requiredOption("-p, --project-id <projectId>","Project ID").option("--schema <schema>","Schema name (knowledge or public)").option("--env <env>","Environment: dev | prod (default: dev)").config({help:{brief:"List project database tables",description:"List all database tables for the specified project, grouped by schema.",examples:[{desc:"List all tables",cmd:"coze code project db list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List knowledge schema tables",cmd:"coze code project db list -p <projectId> --schema knowledge"},{desc:"List prod tables",cmd:"coze code project db list -p <projectId> --env prod"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},schema:{type:"string",required:!1,description:"Schema name filter"},env:{type:"string",required:!1,description:"Environment (dev or prod)"}},output:{type:"array",items:{type:"object",properties:{schema:{type:"string",description:"Schema name"},table_name:{type:"string",description:"Table name"}}}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid or missing project ID",fix:"Provide a valid project ID with -p <projectId>"}],seeAlso:["coze code db","coze code project get"]}}).action((async function(e,o){const i=o.getContext(),{projectId:s,env:n}=e,r="prod"===n?t.MemoryEnv.product:t.MemoryEnv.develop,a=[];await Promise.all(["knowledge","public"].map((async e=>{((await t.IdeApi.GetSchemaTables({project_id:s,database_env:r,schema:e})).table_names||[]).forEach((t=>{a.push({schema:e,table_name:t})}))}))),Wp([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${a.length} tables.`)]),Wp([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])}))}(i),function(o){o.command("import").description("Import a project from a remote repo or local zip file").requiredOption("-s, --source <source>","Import source: github / local").option("-r, --repo <fullName>","Remote repo full name (e.g. user/repo), required for --source github").option("-f, --file <path>","Local zip file path, required for --source local").config({help:{brief:"Import a project from a remote repo or local zip file",description:"Create a new project by importing from a remote Git repository or uploading a local zip file. Remote import requires prior OAuth authorization via `coze code git auth login`. Imported remote projects will be automatically bound to the source repo. Local uploads must be zip format and no more than 500MB.",examples:[{desc:"Import from GitHub (minimal)",cmd:"coze code project import --source github --repo user/my-app"},{desc:"Import from GitHub",cmd:"coze code project import -s github -r user/my-app",tags:["[RECOMMENDED]"]},{desc:"Upload local zip file",cmd:"coze code project import --source local --file ./project.zip"},{desc:"[PIPELINE] Import and check status",cmd:"ID=$(coze code project import -s github -r user/app --format json | jq -r .project_id) && coze code project get $ID",tags:["[PIPELINE]"]},{desc:"[TEMPLATE] Import from any source",cmd:"coze code project import --source <github|local> [--repo <owner/name>] [--file <path>]",tags:["[TEMPLATE]"]}],schema:{input:{source:{type:"string",required:!0,enum:["github","local"],description:"Import source type",example:"github"},repo:{type:"string",required:!1,description:"Remote repo full name (owner/name)",example:"user/my-app"},file:{type:"string",required:!1,description:"Local zip file path",example:"./project.zip"}},output:{project_id:{type:"string",description:"Created project ID",example:"proj_abc123"},source:{type:"string",description:"Import source type",example:"github"},repo:{type:"string",description:"Remote repo full name (if applicable)",example:"user/my-app"},project_url:{type:"string",description:"Web URL of the created project",example:"https://code.coze.cn/p/proj_abc123"}}},enums:{source:{github:"Import from a GitHub repository",local:"Upload a local zip file"}},errors:[{code:e.ErrorCode.E1008,name:"MISSING_IMPORT_SOURCE",desc:"Missing import source",fix:"Use --source github or --source local"},{code:e.ErrorCode.E1009,name:"MISSING_REPO",desc:"Missing --repo for github import",fix:"Add --repo <owner/name>"},{code:e.ErrorCode.E1010,name:"MISSING_FILE",desc:"Missing --file for local import",fix:"Add --file <path>"},{code:e.ErrorCode.E1011,name:"INVALID_FILE_FORMAT",desc:"File is not zip format",fix:"Only .zip files are supported"},{code:e.ErrorCode.E1012,name:"FILE_TOO_LARGE",desc:"File exceeds 500MB",fix:"Reduce file size and retry"},{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Missing Space ID",fix:"Run `coze space use <spaceId>` first"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and run with --debug if the issue persists"}],seeAlso:["coze code project create","coze code repo bind","coze code git auth login"],caveats:["Remote import requires prior OAuth authorization via `coze code git auth login`","Local upload only supports .zip format, max 500MB","Remote imported projects are automatically bound to the source repo"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=jp(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or run `coze space use <spaceId>` first");const{source:r,repo:a,file:c}=o;if(!r||!zp.includes(r))throw new e.CozeError(e.ErrorCode.E1008,`Invalid or missing import source: "${r}". Use --source github or --source local`);if("github"===r){if(!a)throw new e.CozeError(e.ErrorCode.E1009,"Missing --repo: required when --source is github");s.ui.info(`Importing from GitHub: ${a}...`);const o=jp(Pp([await t.IdeApi.ImportProject({space_id:n,import_source:2,git_url:`https://github.com/${a}.git`,git_repo_name:a}),"access",e=>e.data,"optionalAccess",e=>e.vibe_project_id]),(()=>"")),i=o?Ap(o,t.VibeProjectType.General,s.config.apiBaseUrl):"";s.ui.success("Project imported successfully."),s.ui.info(` Project ID: ${o}`),s.ui.info(` Source: github (${a})`),s.ui.info(` Project URL: ${i}`),await Rp(s,o),s.response.print({project_id:o,source:"github",repo:a,project_url:i})}else if("local"===r){if(!c)throw new e.CozeError(e.ErrorCode.E1010,"Missing --file: required when --source is local");if(!c.endsWith(".zip"))throw new e.CozeError(e.ErrorCode.E1011,`Invalid file format: "${c}". Only .zip files are supported`);if(!h.existsSync(c))throw new e.CozeError(e.ErrorCode.E1011,`File not found: "${c}"`);const o=h.statSync(c);if(o.size>524288e3)throw new e.CozeError(e.ErrorCode.E1012,`File too large: ${Math.round(o.size/1024/1024)}MB. Maximum is 500MB`);s.ui.info(`Uploading local file: ${c}...`);const i=new f;i.append("space_id",n),i.append("import_source","1"),i.append("data",h.createReadStream(c),m.basename(c));const r=jp(Pp([await e.axiosInstance.post("/api/ideserver_api/project/import_project",i,{headers:{...i.getHeaders(),"agw-js-conv":"str"}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.vibe_project_id]),(()=>"")),a=r?Ap(r,t.VibeProjectType.General,s.config.apiBaseUrl):"";s.ui.success("Project imported successfully."),s.ui.info(` Project ID: ${r}`),s.ui.info(` Source: local (${c})`),s.ui.info(` Project URL: ${a}`),await Rp(s,r),s.response.print({project_id:r,source:"local",project_url:a})}}))}(i)};function Jp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Kp=new Set([t.VibeProjectType.WechatMiniProgram,t.VibeProjectType.Agent,t.VibeProjectType.Automation,t.VibeProjectType.Skill,t.VibeProjectType.AssistantAgent]);function Qp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Yp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Zp=o=>{const i=o.command("model").config({help:{brief:"Manage project models",description:"Manage models for Coze Coding projects. List available models and set the active model for a project.",examples:[{desc:"List available models",cmd:"coze code model list -p <projectId>"},{desc:"Set project model",cmd:"coze code model set doubao-dev-0213 -p <projectId>"}],seeAlso:["coze code project","coze code tools"]}}).description("Manage project models");!function(o){o.command("list").description("List available models").option("-p, --project-id <projectId>","Project ID").option("--type <type>","Project type (web, app, agent, etc.)").config({help:{brief:"List available models",description:"List all available models for the specified project or project type.",examples:[{desc:"List models for a project",cmd:"coze code model list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List models by type",cmd:"coze code model list --type web"}],schema:{input:{projectId:{type:"string",required:!1,description:"Project ID"},type:{type:"string",required:!1,description:"Project type"}},output:{type:"array",items:{type:"object",properties:{model_name:{type:"string",description:"Model name"},display_name:{type:"string",description:"Display name"},enable:{type:"boolean",description:"Whether this model is currently set for the project (only available when using -p)"}}}}},enums:{type:{agent:"AGENT project",workflow:"WORKFLOW project",webapp:"WEBAPP project",app:"APP project",skill:"SKILL project",web:"WEB project",miniprogram:"MINIPROGRAM project",assistant:"ASSISTANT project"}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Project type is required when project ID is not provided",fix:"Provide --type <type> or -p <projectId> to specify the project"}],seeAlso:["coze code model set"]}}).action((async function(o,i){const s=i.getContext(),{projectId:n}=o;let r,a,c;if(n){const e=await t.IdeApi.GetVibeProject({project_id:n});r=Yp([e,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),a=Yp([e,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.space_id]);const o=await zl.getDefaultConversation(n);c=Yp([o,"access",e=>e.conversation_setting,"optionalAccess",e=>e.model_setting,"optionalAccess",e=>e.model_name])}else{const t=o.type;if(!t)throw new e.CozeError(e.ErrorCode.E1000,"Project type is required",{projectId:n});r=Op(t)}if(!r)throw new e.CozeError(e.ErrorCode.E1000,"Project type is required",{projectId:n});const l=Yp([await t.BuildAgentApi.GetModelList({project_id:n,project_type:r,space_id:a}),"access",e=>e.model_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({model_name:e.name,display_name:e.display_name,enable:n?c===e.name:void 0})))]);Yp([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${Yp([l,"optionalAccess",e=>e.length])||0} models.`)]),Yp([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(l)])}))}(i),function(o){o.command("set <modelName>").description("Set conversation model").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Set conversation model",description:"Set the model used by the default conversation. Use model list to see available models.",examples:[{desc:"Set conversation model",cmd:"coze code model set doubao-dev-0213 -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{modelName:{type:"string",required:!0,description:"Model name"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},model_name:{type:"string",description:"Model name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified model is not available for this project",fix:"Use 'coze code model list -p <projectId>' to see available models"}],seeAlso:["coze code model list"]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=await t.IdeApi.GetVibeProject({project_id:r}),c=Qp([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),l=Qp([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.space_id]);if(!Qp([await t.BuildAgentApi.GetModelList({project_id:r,project_type:c,space_id:l}),"access",e=>e.model_list,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Model '${o}' is not available. Use 'coze code model list' to see available models.`,{modelName:o,projectId:r});const d=await zl.getDefaultConversation(r);await zl.updateConversationSetting(r,d.id,{modelSetting:{model_name:o}}),Qp([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Model set to '${o}'.`)]),Qp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,model_name:o,message:`Model has been set to '${o}' successfully`})])}))}(i)};function Xp(e,t){return null!=e?e:t()}function eu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function tu(e,t){return null!=e?e:t()}function ou(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const iu=e=>{if(null==e)return null;return 0===e.trim().length?null:e},su=o=>{o.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"},{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",description:'Output depends on mode. Without --wait (json): { status: "sent", project_id, message } is printed immediately. With --wait (json): one NDJSON line per finished message item, each shaped as { content, role, finish, type }. With --wait (text): the final answer text is printed.',properties:{content:{type:"string",description:"The chat response content (per NDJSON line in --wait json mode)"},role:{type:"string",description:"Message role (--wait json mode)"},finish:{type:"boolean",description:"Whether the message item finished (--wait json mode)"},type:{type:"string",description:"Message item type (--wait json mode)"},status:{type:"string",description:'Send status, e.g. "sent" (non --wait json mode)'},project_id:{type:"string",description:"Project ID (non --wait json mode)"},message:{type:"string",description:"Hint message (non --wait json mode)"}}}},seeAlso:["coze code message status","coze code message history"]}}).action((async(o,i,s)=>{const n=s.getContext();try{if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const r=ou([s,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),a=tu(ou([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 ou([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:l,stdin:d}=i;let p=null;d&&(p=await Ta());const u=iu(o),m=iu(p);if(!u&&!m)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin");const g=u&&m?`${u}\n\n${m}`:tu(tu(u,(()=>m)),(()=>"")),h=await zl.getDefaultConversation(a),f=new Set,_=await t.sendProjectChatMessage({projectId:a,conversationId:h.id,prompt:g,apiBaseUrl:n.config.apiBaseUrl,accessToken:c,xTTEnv:n.config.xTTEnv,key:`coze-coding-cli:message:${a}`,onWarn:e=>n.ui.warn(e),waitForResponse:!!l,onMessageItem:e=>{if(l&&"json"===n.format&&e.finish){const t=(e=>{const t=tu(e.msg_id,(()=>"")),o=tu(e.sequence_id,(()=>""));return`${e.type}:${t}:${String(o)}`})(e);f.has(t)||(f.add(t),n.response.print({content:e.content,role:e.role,finish:e.finish,type:e.type}))}}});if(l)"text"===n.format&&n.response.print(tu(ou([_,"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){Q(e,n)}}))};function nu(e,t){return null!=e?e:t()}function ru(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function au(e,t){return null!=e?e:t()}function cu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const lu=async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError("E5000","CLI context is not initialized");const n=cu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=au(cu([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 cu([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(o.after&&o.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=await zl.getDefaultConversation(r),c=t.createChatCore({key:`coze-coding-cli:history:${r}`,apiBaseUrl:s.config.apiBaseUrl});try{const e=o.after?"loadNext":"loadPrev",t="loadNext"===e?"11":"10",i=await c.getHistoryMessage({limit:t,project_id:r,conversation_id:a.id,after:o.after,before:o.before}),n=[],l=new Map,d=new Map;i.histories.forEach((e=>{if(e.user){const t=e.user.msg_id;l.has(t)||n.push(t);const o=(e=>{const t=cu([e,"optionalAccess",e=>e.content]);return au(au(cu([t,"optionalAccess",e=>e.query,"optionalAccess",e=>e.prompt]),(()=>cu([t,"optionalAccess",e=>e.retry,"optionalAccess",e=>e.prompt]))),(()=>cu([t,"optionalAccess",e=>e.edit,"optionalAccess",e=>e.prompt])))})(e.user.message);l.set(t,o?(e=>e.map((e=>"text"===e.type?e.content.text:"file"===e.type?`${ru([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.path])} ${nu(ru([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.from,"optionalAccess",e=>e[0]]),(()=>""))} ${nu(ru([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.to,"optionalAccess",e=>e[0]]),(()=>""))} `:"console"===e.type?ru([e,"access",e=>e.content,"access",e=>e.console,"optionalAccess",e=>e.content]):"node"===e.type?ru([e,"access",e=>e.content,"access",e=>e.node,"optionalAccess",e=>e.node_title]):"upload_file"===e.type?ru([e,"access",e=>e.content,"access",e=>e.upload_file,"optionalAccess",e=>e.file_name]):"page"===e.type?ru([e,"access",e=>e.content,"access",e=>e.page,"optionalAccess",e=>e.page_title]):"page_elements"===e.type?ru([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?ru([e,"access",e=>e.content,"access",e=>e.wf_canvas_change,"optionalAccess",e=>e.query]):"")).join(" "))(o):"")}if(e.assistant){const t=e.assistant.messages.find((e=>"answer"===e.type&&e.content.answer));if(!t)return;const o=t.query_msg_id,i=t.content.answer;"string"==typeof o&&"string"==typeof i&&d.set(o,i)}}));const p=n[0],u=n[n.length-1],m=n.reverse().filter((e=>d.has(e))).map((e=>({userMessage:au(l.get(e),(()=>"")),answer:au(d.get(e),(()=>""))}))),g={histories:m,cursor:{after:p,before:u,has_more:i.has_more,loadDirection:e}};if("json"===s.format)s.response.print(g);else{if(0===m.length)return void s.response.print("No conversation history found.");m.forEach(((e,t)=>{s.response.print(`--- #${t+1} ---\nQ: ${e.userMessage}\nA: ${e.answer}\n`)})),s.response.print(`\n[cursor] after=${p}, before=${u}, has_more=${i.has_more}, loadDirection=${e}`)}}finally{c.destroy()}}catch(e){Q(e,s)}};function du(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const pu=o=>{const i=o.command("message");i.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"}],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)"),su(i),(o=>{o.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)"}}}},seeAlso:["coze code message send","coze code message cancel"]}}).action((async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const o=eu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),n=Xp(eu([o,"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 r=await zl.getDefaultConversation(n),{code:a,msg:c,reply_id:l,...d}=await t.BuildAgentApi.GetChatCLIMessageStatus({project_id:n,conversation_id:r.id});if("done"===d.status){s.ui.verbose(`Chat completed, fetching result for project ${n}...`);const e=await t.BuildAgentApi.GetChatCLIMessageResultContent({project_id:n,conversation_id:r.id}),o="data"in e?e.data:e;"json"===s.format?s.response.print({...d,answer:o.answer}):s.response.print(`status: [${d.status}]\nanswer: ${Xp(o.answer,(()=>""))}`)}else"json"===s.format?s.response.print(d):s.response.print(d.status)}catch(e){Q(e,s)}}))})(i),function(o){o.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:{message:{type:"string",description:"Result message"}}}},seeAlso:["coze code message status","coze code message send"]}}).action((async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const o=du([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=null!=(n=du([o,"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 c=await zl.getDefaultConversation(r),{message:l}=await t.BuildAgentApi.CancelChatCLIMessage({project_id:r,conversation_id:c.id});"json"===s.format?s.response.print({message:l}):s.response.print(l)}catch(e){Q(e,s)}var n}))}(i),(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."}}}}}},seeAlso:["coze code message send","coze code message status"]}}).action(lu)})(i)};function uu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function mu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function gu(o){o.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:{type:"array",items:{type:"object",properties:{secret_key:{type:"string",description:"Environment variable key"},secret_id:{type:"string",description:"Secret ID"},secret_val:{type:"string",description:"Environment variable value"},secret_type:{type:"string",description:"Secret type"}}}}},enums:{env:{dev:"Development environment variables",prod:"Production environment variables"}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}],seeAlso:["coze code env set","coze code env delete"]}}).action((async function(e,o){const i=o.getContext(),{projectId:s}=e,n=mu([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()?ps.prod:ps.dev);var a;const c=mu([await bs.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])||[];mu([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secrets listed successfully.")]),mu([i,"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 hu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const fu=o=>{const i=o.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");gu(i),i.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:{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"}],seeAlso:["coze code env list","coze code env delete"]}}).action((async function(o,i,s,n){const r=n.getContext(),{projectId:a}=s,c=uu([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 bs.InsertProjectSecret({project_id:a,insert_secrets:{secrets:[{secret_key:o,secret_val:i}]}}),uu([r,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secret set successfully")]),uu([r,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:a,key:o,value:i})])})),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 a specified environment variable from the project by its key name.",examples:[{desc:"Delete an environment variable",cmd:"coze code env delete <KEY> -p <projectId>",tags:["[RECOMMENDED]"]}],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"},project_id:{type:"string",description:"Project ID"},keys:{type:"array",description:"Deleted environment variable key names"},secret_ids:{type:"array",description:"Deleted secret IDs"}}},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"}],seeAlso:["coze code env list","coze code env set"]}}).action((async function(t,o,i){const s=i.getContext(),{projectId:n}=o,r=[t],a=hu([await bs.ListProjectSecret({env:ps.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)))),l=a.filter((e=>c.has(String(e.secret_key||"")))).map((e=>e.secret_id)).filter(Boolean);if(0===l.length)throw new e.CozeError(e.ErrorCode.E3003,`No matched secrets by keys: ${r.join(", ")}`,{projectId:n,keys:r});await bs.DeleteProjectSecret({project_id:n,keys:l}),hu([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env has been delete successfully")]),hu([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:l})])}))}(i)};var _u,yu,bu,vu,wu,Eu,Cu,Iu,Au,Su,ku,ju,Pu,zu,Tu,Ru,xu,Lu,Ou,Du,Uu,qu,Bu,Mu,Nu,$u,Gu,Fu,Vu,Wu,Hu;function Ju(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!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"}(_u||(_u={})),function(e){e[e.Unknown=0]="Unknown";e[e.FreeCertificate=1]="FreeCertificate"}(yu||(yu={})),function(e){e[e.Unknown=0]="Unknown";e[e.Normal=1]="Normal"}(bu||(bu={})),function(e){e[e.Unknown=0]="Unknown";e[e.Existing=1]="Existing";e[e.Free=2]="Free"}(vu||(vu={})),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"}(wu||(wu={})),function(e){e[e.Passed=1]="Passed";e[e.UnPassed=2]="UnPassed";e[e.Auditing=3]="Auditing"}(Eu||(Eu={})),function(e){e[e.Official=1]="Official"}(Cu||(Cu={})),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"}(Iu||(Iu={})),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"}(Au||(Au={})),function(e){e[e.Unknown=0]="Unknown";e[e.Success=1]="Success";e[e.Pending=2]="Pending";e[e.Failed=3]="Failed"}(Su||(Su={})),function(e){e[e.Unknown=0]="Unknown";e[e.Default=1]="Default";e[e.Custom=2]="Custom"}(ku||(ku={})),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"}(ju||(ju={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(Pu||(Pu={})),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"}(zu||(zu={})),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"}(Tu||(Tu={})),function(e){e[e.Unknown=0]="Unknown";e[e.VefaasFunction=1]="VefaasFunction"}(Ru||(Ru={})),function(e){e[e.Unknown=0]="Unknown";e[e.Dev=1]="Dev";e[e.Prod=2]="Prod";e[e.Audit=3]="Audit"}(xu||(xu={})),function(e){e[e.A=1]="A";e[e.CNAME=2]="CNAME"}(Lu||(Lu={})),function(e){e[e.Unknown=0]="Unknown";e[e.Single=1]="Single";e[e.Wildcard=2]="Wildcard";e[e.Multi=3]="Multi"}(Ou||(Ou={})),function(e){e[e.Unknown=0]="Unknown";e[e.DV=1]="DV";e[e.OV=2]="OV";e[e.EV=3]="EV"}(Du||(Du={})),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"}(Uu||(Uu={})),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"}(qu||(qu={})),function(e){e[e.NeedAuthorize=1]="NeedAuthorize";e[e.BindSuccess=2]="BindSuccess";e[e.BoundToOtherProject=3]="BoundToOtherProject";e[e.BoundToOtherUser=4]="BoundToOtherUser"}(Bu||(Bu={})),function(e){e[e.BoundToSelf=1]="BoundToSelf";e[e.BoundToOtherUser=2]="BoundToOtherUser";e[e.NotAuthorized=3]="NotAuthorized"}(Mu||(Mu={})),function(e){e[e.Line=1]="Line"}(Nu||(Nu={})),function(e){e[e.Default=0]="Default";e[e.WechatMini=1]="WechatMini";e[e.DouyinMini=2]="DouyinMini"}($u||($u={})),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"}(Gu||(Gu={})),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"}(Fu||(Fu={})),function(e){e[e.Recorded=1]="Recorded"}(Vu||(Vu={})),function(e){e[e.Sum=1]="Sum";e[e.Avg=2]="Avg"}(Wu||(Wu={})),function(e){e[e.Next=1]="Next";e[e.Third=3]="Third";e[e.Seventh=7]="Seventh"}(Hu||(Hu={}));class Ku{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Ku.prototype.__init.call(this),Ku.prototype.__init2.call(this),this.request=Ju([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Ju([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}PublicCreateDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/create"),s={project_id:o.project_id,is_sync_db_to_prod:o.is_sync_db_to_prod,encrypt_env_variable:o.encrypt_env_variable,table_sync_configs:o.table_sync_configs,encrypt_deploy:o.encrypt_deploy,commit_hash:o.commit_hash,connector_configs:o.connector_configs};return this.request({url:i,method:"POST",data:s},t)}PublicRollbackDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/rollback"),s={project_id:o.project_id,target_deploy_history_id:o.target_deploy_history_id,rollback_database:o.rollback_database};return this.request({url:i,method:"POST",data:s},t)}PublicCancelDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/cancel"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_config/get"),s={project_id:o.project_id,commit_hash:o.commit_hash};return this.request({url:i,method:"GET",params:s},t)}PublicListDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/list"),s={project_id:o.project_id,page_token:o.page_token,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}PublicSearchRuntimeLog(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/runtime_log/search"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id,start_time:o.start_time,end_time:o.end_time,limit:o.limit,cursor:o.cursor,query:o.query,level:o.level};return this.request({url:i,method:"GET",params:s},t)}PublicGetDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"GET",params:s},t)}PublicBindCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/bind"),s={project_id:o.project_id,certificate_id:o.certificate_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicApplyFreeCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/apply_free"),s={project_id:o.project_id,domain:o.domain,auto_renew_free_cert:o.auto_renew_free_cert};return this.request({url:i,method:"POST",data:s},t)}PublicListDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/list"),s={project_id:o.project_id,unit_type:o.unit_type};return this.request({url:i,method:"GET",params:s},t)}PublicDeleteDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/delete"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicCreateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/create"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/get"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetCertificateDetail(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/get"),s={project_id:o.project_id,certificate_id:o.certificate_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/get"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicListVolcanoDomain(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/volcano_domain/list"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicListVolcanoCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/list_volcano"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicListProjectTraces(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/traces/list"),s={project_id:o.project_id,start_time:o.start_time,end_time:o.end_time,filter:o.filter,page_token:o.page_token,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PublicDownloadProjectTraces(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/traces/download"),s={project_id:o.project_id,start_time:o.start_time,end_time:o.end_time,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}PublicGetProjectMetrics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/metrics/get"),s={project_id:o.project_id,time_range:o.time_range,retention_days:o.retention_days};return this.request({url:i,method:"GET",params:s},t)}PublicDeleteDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/delete"),s={project_id:o.project_id,deploy_unit_id:o.deploy_unit_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetHelpCenterLink(e,t){const o=this.genBaseURL("/api/coding/deployment/help_center/link");return this.request({url:o,method:"GET"},t)}PublicCheckRollbackDatabase(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/check_rollback_database"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetMiniProgramPreview(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/mini_program/preview"),s={project_id:o.project_id,app_id:o.app_id,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}PublicSubmitAuthCode(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/submit_code"),s={project_id:o.project_id,connector_id:o.connector_id,code:o.code,verify_state:o.verify_state,auth_params:o.auth_params};return this.request({url:i,method:"POST",data:s},t)}PublicGetAuthStatus(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/status"),s={project_id:o.project_id,connector_id:o.connector_id,redirect_url:o.redirect_url};return this.request({url:i,method:"POST",data:s},t)}PublicBindAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/bind"),s={project_id:o.project_id,connector_id:o.connector_id,redirect_url:o.redirect_url,auth_params:o.auth_params,override:o.override};return this.request({url:i,method:"POST",data:s},t)}PublicUnbindAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/unbind"),s={project_id:o.project_id,connector_id:o.connector_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetBoundProject(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/get_bound_project"),s={connector_id:o.connector_id,related_id:o.related_id};return this.request({url:i,method:"GET",params:s},t)}PublicUpdateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/update"),s={project_id:o.project_id,domain:o.domain,auto_renew_free_cert:o.auto_renew_free_cert,visit_status:o.visit_status,next_primary_domain:o.next_primary_domain};return this.request({url:i,method:"POST",data:s},t)}PublicGetCertificateQuota(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/quota"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicListDomainCertificates(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/list"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicUnpublishConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/unpublish_project"),s={project_id:o.project_id,connector_ids:o.connector_ids};return this.request({url:i,method:"POST",data:s},t)}PublicListConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/list"),s={project_id:o.project_id,project_publish_status:o.project_publish_status};return this.request({url:i,method:"GET",params:s},t)}PublicPublishConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/publish_project"),s={project_id:o.project_id,connector_configs:o.connector_configs};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployCount(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get_count"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}GetRuntimeLogCount(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/runtime_log/count"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicExchangeFeishuAuthCode(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/auth/exchange_code"),s={project_id:o.project_id,code:o.code,verify_state:o.verify_state};return this.request({url:i,method:"POST",data:s},t)}PublicRevokeFeishuAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/auth/revoke"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublicUpdateDefaultDomainPrefix(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/update_default_prefix"),s={project_id:o.project_id,prefix:o.prefix};return this.request({url:i,method:"POST",data:s},t)}PublicFeishuWebhookEvent(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/webhook/event"),s={body:o.body};return this.request({url:i,method:"POST",data:s},t)}PublicCheckCreateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/check_create"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetHostedUsageMonthly(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/hosted_usage/monthly"),s={project_id:o.project_id,bill_month:o.bill_month};return this.request({url:i,method:"GET",params:s},t)}PublicGetEstimateHostedCost(e,t){const o=this.genBaseURL("/api/coding/deployment/hosted_usage/estimate_cost");return this.request({url:o,method:"GET"},t)}PublicGetDeployHistoryLog(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/log"),s={deploy_history_id:o.deploy_history_id,key:o.key};return this.request({url:i,method:"GET",params:s},t)}PublicGetMPICPStatus(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/mini_program/icp_status"),s={project_id:o.project_id,app_id:o.app_id,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetOnlineDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get_online"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetUserAnalyticsMetrics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/metrics/user_analytics/get"),s={project_id:o.project_id,time_range:o.time_range};return this.request({url:i,method:"GET",params:s},t)}PublicPauseDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/pause"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicStopDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/stop"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicResumeDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/resume"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicReportUserAnalytics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/analytics/report"),s={events:o.events},n={project_id:o.project_id,did:o.did};return this.request({url:i,method:"POST",data:s,params:n},t)}PublicCreateDefaultDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/create_default"),s={project_id:o.project_id,prefix:o.prefix};return this.request({url:i,method:"POST",data:s},t)}PublicGetProtectionConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/protection_config/get"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicUpdateProtectionConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/protection_config/update"),s={project_id:o.project_id,config:o.config};return this.request({url:i,method:"POST",data:s},t)}PublicAuthRedirect(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/redirect"),s={url:o.url};return this.request({url:i,method:"GET",params:s},t)}PublicAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/callback"),s={redirect_url:o.redirect_url};return this.request({url:i,method:"GET",params:s},t)}}const Qu=new Ku({});function Yu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Zu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Xu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const em=t=>{const o=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 -p <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");o.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"}],seeAlso:["coze code domain add","coze code domain remove"]}}).action((async function(e,t){const o=t.getContext(),{projectId:i}=e,s=Zu([await Qu.PublicListDomainRelated({project_id:i}),"access",e=>e.data,"optionalAccess",e=>e.items])||[];Zu([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Fetched domains List successfully")]),Zu([o,"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:{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"}],seeAlso:["coze code domain list","coze code domain remove"]}}).action((async function(t,o,i){const s=i.getContext(),{projectId:n}=o;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 Qu.PublicCreateDomainRelated({project_id:n,domain:t}),Xu([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Domain '${t}' added.`)]),Xu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,domain:t})])}))}(o),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:{message:{type:"string",description:"Result message"},domain:{type:"string",description:"Deleted domain"}}},errors:[{code:e.ErrorCode.E3000,name:"RESOURCE_NOT_FOUND",desc:"Domain is not bound to the project",fix:"Use `coze code domain list -p <projectId>` to view bound domains"},{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"}],seeAlso:["coze code domain list","coze code domain add"]}}).action((async function(t,o,i){const s=i.getContext(),{projectId:n}=o;try{await Qu.PublicDeleteDomainRelated({project_id:n,domain:t})}catch(o){K(o,e.ErrorCode.E3000,`Domain '${t}' is not bound to project '${n}'`,{domain:t,projectId:n})}Yu([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Domain '${t}' removed.`)]),Yu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({message:`Domain '${t}' removed.`,domain:t})])}))}(o)},tm={[Au.Pending]:"Pending",[Au.Running]:"Running",[Au.Succeeded]:"Succeeded",[Au.Failed]:"Failed",[Au.Canceled]:"Canceled",[Au.Interrupted]:"Interrupted"},om=[Au.Succeeded,Au.Failed,Au.Canceled],im=e=>e&&tm[e]||"Unknown";function sm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class nm{static __initStatic(){this.INSTANCE=new nm}static getInstance(){return nm.INSTANCE||(nm.INSTANCE=new nm),this.INSTANCE}async pollDeployStatus(t){const{projectId:o,deployHistoryId:i,onBeforePoll:s,onStatusChange:n}=t;let r;for(;;){sm([s,"optionalCall",e=>e()]);const t=sm([await Qu.PublicGetDeployHistory({project_id:o,deploy_history_id:i}),"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,sm([n,"optionalCall",e=>e(t)])),om.includes(a))return t;await new Promise((e=>setTimeout(e,3e3)))}}async getLatestDeployHistoryId(e){const{projectId:t}=e;return sm([await Qu.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:o,deployHistoryId:i}=t,s=await Qu.PublicGetDeployHistory({project_id:o,deploy_history_id:i});if(!sm([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.WechatMiniProgram,t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.Skill,t.VibeProjectType.Agent,t.VibeProjectType.Automation].includes(e)}async getCommitList({projectId:o}){const i=await t.IdeApi.ProxySandboxMessage({ProjectID:o,Method:"repo_version.commit.list",Params:JSON.stringify({project_id:o})});return e.safeJsonParse(i.data,{commits:[]}).commits||[]}}nm.__initStatic();const rm=nm.getInstance();function am(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function cm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function lm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function dm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function pm(o){const i=o.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").option("--table-name <tableName...>","Database table names to sync to production",((e,t)=>t.concat(e)),[]).option("--encrypt-deploy <encrypt_deploy>","Pre-encrypted environment variable string (for Skill projects)").option("--connector-id <connectorId>","Connector IDs for mini-program deployment channels (can specify multiple times, e.g. 10000127 for WeChat, 10000126 for TikTok)",((e,t)=>t.concat(e)),[]).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"},commitId:{type:"string",required:!1,description:"Commit ID (optional, queries latest if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"},tableName:{type:"array",required:!1,description:"Database table names to sync to production (can specify multiple times)"},encryptDeploy:{type:"string",required:!1,description:"Pre-encrypted environment variable string (for Skill projects)"},connectorId:{type:"array",required:!1,description:"Connector IDs for mini-program channels (10000127=WeChat, 10000126=TikTok). If omitted, auto-detects authorized channels."}},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.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Check the project ID, run `coze code project list` to view available projects"},{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"}],seeAlso:["coze code deploy status","coze code deploy list","coze code deploy fix"]}}).description("Deploy the project to production environment").action((async function(o,i,s){const n=s.getContext(),{wait:r,commitId:a,tableName:c,encryptDeploy:l,connectorId:d}=i;let p;try{p=await t.IdeApi.GetVibeProject({project_id:o})}catch(t){K(t,e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o})}const u=dm([p.data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(!rm.canDeploy(u)){const t=`Project type ${Dp(u)} is not supported for deployment`;throw new e.CozeError(e.ErrorCode.E1006,t,{projectType:u})}if(u===t.VibeProjectType.AssistantAgent)return dm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying (AssistantAgent)...")]),await e.axiosInstance$1.post("api/sandbox/coze_coding/devbox/open_claw/deploy",{project_id:o}),void dm([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"ok",type:u,message:`Assistant project deployment successfully, Please access the ${Ap(o,u,dm([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))} to view the project`})]);let m,g=a;if(!g){dm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching latest commit...")]);const e=await rm.getCommitList({projectId:o});g=dm([e,"optionalAccess",e=>e[0],"optionalAccess",e=>e.id])}if(!g){const t="No commits found: commit your changes first, or pass --commit-id <commitId>";throw new e.CozeError(e.ErrorCode.E3007,t,{projectId:o})}if(u===t.VibeProjectType.WechatMiniProgram)if(d&&d.length>0)m=d.map((e=>({connector_id:e})));else{dm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking Mini-program authorization...")]);const t=[{name:"WeChat",id:"10000127"},{name:"TikTok",id:"10000126"}],i=(await Promise.all(t.map((async e=>{const t=await Qu.PublicGetAuthStatus({project_id:o,connector_id:e.id});return{...e,authorized:Boolean(dm([t,"access",e=>e.data,"optionalAccess",e=>e.bound_related_id]))}})))).filter((e=>e.authorized));if(0===i.length){const t=`Deployment failed, no authorized Mini-program channels found. Please visit ${Ap(o,u,dm([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))} to complete WeChat or TikTok AppID configuration.`;throw new e.CozeError(e.ErrorCode.E2002,t)}m=i.map((e=>({connector_id:e.id})))}dm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking deploy config...")]),await Qu.PublicGetDeployConfig({project_id:o,commit_hash:g},{__disableErrorToast:!0});let h="";const f=await bs.ListProjectSecret({env:ps.dev,project_id:o,with_providers:!0}),_=dm([f,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],y=dm([f,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_cred_providers])||[];dm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Encrypting secrets...")]);h=dm([await bs.EncryptProjectSecret({project_id:o,project_type:u===t.VibeProjectType.Skill?ds.skill:void 0,encrypt_secrets:{secrets:_.map((e=>({secret_key:e.secret_key||"",secret_val:e.secret_val||"",secret_id:e.secret_id||"",secret_type:e.secret_type===us.consumer?qi.consumer3:qi.user_custom2}))),cred_providers:y}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.sealed_secrets])||"",dm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying...")]);const b={project_id:o,encrypt_env_variable:h,commit_hash:g,encrypt_deploy:u===t.VibeProjectType.Skill?Boolean(l):void 0,connector_configs:m};if(c&&c.length>0){const e=new Map,i=["knowledge","public"];await Promise.all(i.map((async i=>{((await t.IdeApi.GetSchemaTables({project_id:o,database_env:t.MemoryEnv.develop,schema:i})).table_names||[]).forEach((t=>{e.set(t,i)}))}))),b.table_sync_configs=c.map((t=>({table_name:t,schema:e.get(t)||"",sync_data:!0})))}const v=dm([await Qu.PublicCreateDeployHistory(b),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_id]);dm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploy started.")]),r&&v?await rm.pollDeployStatus({projectId:o,deployHistoryId:v,onBeforePoll:()=>{dm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const t=im(e.status);dm([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",i=>i({projectId:o,status:t,domain:dm([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:v,commitHash:e.commit_hash})])}}):dm([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({projectId:o,status:im(Au.Pending),domain:"",deployHistoryId:v,commitHash:g})])}));!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>`"}],seeAlso:["coze code deploy","coze code deploy fix"]}}).action((async function(t,o,i){const s=i.getContext(),{deployId:n}=o,{wait:r}=am([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=n;if(!a&&(am([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("get latest deployment record...")]),a=await rm.getLatestDeployHistoryId({projectId:t}),!a))throw new e.CozeError(e.ErrorCode.E3006,"No deployment history found for this project");if(r)await rm.pollDeployStatus({projectId:t,deployHistoryId:a,onBeforePoll:()=>{am([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const o=im(e.status);am([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",i=>i({projectId:t,status:o,domain:am([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:a,commitHash:e.commit_hash})])}});else{am([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Querying deployment status...")]);const e=await rm.getDeployHistory({projectId:t,deployHistoryId:a}),o=im(e.status),i=e.domain_list||[];am([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",s=>s({projectId:t,status:o,domain:i[0],deployHistoryId:a,commitHash:e.commit_hash})])}}))}(i),function(t){t.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:"object",properties:{items:{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"}}},next_page_token:{type:"string",description:"Token for fetching the next page, empty if no more pages"},has_more:{type:"boolean",description:"Whether there are more records"}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Check the project ID, run `coze code project list` to view available projects"},{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"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server failed to fetch the deployment history",fix:"Retry later; run with --debug for details if the issue persists"}],seeAlso:["coze code deploy","coze code deploy status"]}}).action((async function(e,t,o){const i=o.getContext(),s=Number(t.pageSize)||10,n=await Qu.PublicListDeployHistory({project_id:e,page_size:s,page_token:t.pageToken}),r=(cm([n,"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:im(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})));cm([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>{return e({items:r,next_page_token:cm([n,"optionalAccess",e=>e.data,"optionalAccess",e=>e.next_page_token])||"",has_more:(t=cm([n,"optionalAccess",e=>e.data,"optionalAccess",e=>e.has_more]),o=()=>!1,null!=t?t:o())});var t,o}])}))}(i),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 <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",description:"Structured output is only printed with --wait. Without --wait the fix request is sent in the background and no structured output is produced.",properties:{deploy_history_id:{type:"string"},status:{type:"string"},message:{type:"object",description:"Last answer message object (ServerMessageRaw); the answer text is in message.content.answer"}}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and run with --debug if the issue persists"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"No deploy history or deploy log found",fix:"Please confirm the project has deployment records and retry"},{code:e.ErrorCode.E3009,name:"CONFLICT",desc:"Deployment is not in Failed status",fix:"Only failed deployments can be fixed. Check the deployment status first"},{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"}],seeAlso:["coze code deploy status","coze code deploy list"]}}).action((async function(t,o,i){const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const{deployId:n}=o,r=null!=(a=o.wait)?a:(()=>lm([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"optionalAccess",e=>e.wait]))();var a;let c=n;if(n||(c=await rm.getLatestDeployHistoryId({projectId:t})),!c)throw new e.CozeError(e.ErrorCode.E5002,`No deploy history found for project ${t}`,{project_id:t});const l=lm([await Qu.PublicGetDeployHistory({project_id:t,deploy_history_id:c}),"optionalAccess",e=>e.data]);if(lm([l,"optionalAccess",e=>e.status])!==Au.Failed){const t=im(lm([l,"optionalAccess",e=>e.status]));throw new e.CozeError(e.ErrorCode.E3009,`Deployment ${c} is not in Failed status (current: ${t}). Only failed deployments can be fixed.`,{deploy_history_id:c,status:lm([l,"optionalAccess",e=>e.status])})}const d=l.deploy_log_url;if(!d)throw new e.CozeError(e.ErrorCode.E5002,`No deploy log URL found for deployment ${c}`,{deploy_history_id:c});const p=await e.customFetch.fetch(d,{method:"GET"}),u=await p.text();if(!u)throw new e.CozeError(e.ErrorCode.E5002,`Deploy log is empty for deployment ${c}`,{deploy_history_id:c,deploy_log_url:d});const m=`修复以下部署错误:\n${u}`,g=await lm([s,"access",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!g)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const h=await zl.getDefaultConversation(t);if(r){const e=await kp.sendMessage({projectId:t,prompt:m,apiBaseUrl:s.config.apiBaseUrl,accessToken:g,xTTEnv:s.config.xTTEnv,conversationId:h.id,key:`coze-coding-cli:message:${t}`});lm([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({deploy_history_id:c,status:"fix_sent",message:e.lastAnswerMessage})])}else kp.sendMessageRunTask({projectId:t,prompt:m,apiBaseUrl:s.config.apiBaseUrl,accessToken:g,xTTEnv:s.config.xTTEnv,conversationId:h.id,key:`coze-coding-cli:message:${t}`})}))}(i)}function um(e,t){return null!=e?e:t()}function mm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class gm{static getInstance(){return gm.INSTANCE||(gm.INSTANCE=new gm),gm.INSTANCE}async createSpaceDatabase(o){const i=await t.IdeApi.CreateSpaceDatabase({space_id:o},{});if(!i.database)throw new e.CozeError(e.ErrorCode.E5000,"Failed to create database");return i.database}async listSpaceDatabases(e,o){const i=await t.IdeApi.ListSpaceDatabase({space_id:e,cursor_id:mm([o,"optionalAccess",e=>e.cursor_id]),limit:um(mm([o,"optionalAccess",e=>e.limit]),(()=>20))},{});return{databases:um(mm([i,"optionalAccess",e=>e.databases]),(()=>[])),next_cursor_id:i.next_cursor_id}}async getSpaceDatabase(o,i){let s;try{s=await t.IdeApi.GetSpaceDatabase({space_id:o,database_id:i},{})}catch(t){K(t,e.ErrorCode.E3010,`Database '${i}' not found or no permission`,{databaseId:i})}if(!s.database)throw new e.CozeError(e.ErrorCode.E3010,`Database '${i}' not found or no permission`,{databaseId:i});return s.database}async deleteSpaceDatabase(e,o){await t.IdeApi.DeleteSpaceDatabase({space_id:e,database_id:o},{})}async rollbackSpaceDatabase(e,o,i){return await t.IdeApi.RollbackSpaceDatabase({space_id:e,database_id:o,timestamp:i},{})}async getSpaceDatabaseStatus(e,o){return await t.IdeApi.GetSpaceDatabaseStatus({space_id:e,database_id:o},{})}}const hm=gm.getInstance(),fm={0:"active",1:"creating"},_m={0:"dev",1:"prod"},ym={0:"restoring",1:"success",2:"failed"},bm=e=>e&&"0"!==e?new Date(Number(e)).toLocaleString():"-",vm=e=>e?e.length<=4?"***":`${e.slice(0,4)}***`:"-";function wm(e,t){return null!=e?e:t()}function Em(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Cm(e,t){return null!=e?e:t()}function Im(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Am(t){t.command("rollback").description("Rollback database to a specific timestamp").requiredOption("--db-id <dbId>","Database ID").requiredOption("--timestamp <timestamp>","Target timestamp in milliseconds (Int64)").option("--confirm","Confirm rollback (required)").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Rollback database",description:"Rollback a database to a specific point in time using PITR (Point-in-Time Recovery). The --confirm flag is required. Use `coze code db status` to check the rollback progress.",examples:[{desc:"Rollback database",cmd:"coze code db rollback --db-id <id> --timestamp 1713254400000 --confirm",tags:["[RECOMMENDED]"]},{desc:"Check rollback status",cmd:"coze code db status --db-id <id>"}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},timestamp:{type:"string",required:!0,description:"Target timestamp in milliseconds (Int64 string)"},confirm:{type:"boolean",required:!0,description:"Must be set to confirm rollback"}},output:{restore_history_id:{type:"string",description:"Restore history ID"}}},errors:[{code:e.ErrorCode.E1007,name:"DB_SQL_DANGEROUS",desc:"Rollback requires --confirm flag",fix:"Add --confirm flag to proceed",example:"coze code db rollback --db-id <id> --timestamp <ts> --confirm"},{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E3012,name:"DB_RESTORE_WINDOW_EXCEEDED",desc:"Rollback time exceeds recovery window",fix:"Use `coze code db status` to check earliest_restore_time"},{code:e.ErrorCode.E3013,name:"DB_RESTORE_IN_PROGRESS",desc:"A rollback is already in progress",fix:"Wait for the current rollback to complete"}],seeAlso:["coze code db query","coze code db status"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!t.confirm)throw new e.CozeError(e.ErrorCode.E1007,"Rollback requires --confirm flag to proceed",{databaseId:t.dbId,timestamp:t.timestamp},{trigger:"Rollback is a potentially destructive operation",fix:"Add --confirm flag to confirm rollback",example:`coze code db rollback --db-id ${t.dbId} --timestamp ${t.timestamp} --confirm`});((t,o=Date.now())=>{if(!/^\d+$/.test(t)||!Number.isSafeInteger(Number(t)))throw new e.CozeError(e.ErrorCode.E1000,`Invalid --timestamp '${t}': expected an integer millisecond timestamp`,{timestamp:t},{trigger:"Timestamp must be a millisecond Unix timestamp (Int64)",fix:"Pass the target time in milliseconds, e.g. 1713254400000",example:"coze code db rollback --db-id <id> --timestamp 1713254400000 --confirm"});const i=Number(t);if(i<1e12)throw new e.CozeError(e.ErrorCode.E1000,`Invalid --timestamp '${t}': value looks like seconds, expected milliseconds`,{timestamp:t},{trigger:"Timestamp unit looks like seconds instead of milliseconds",fix:"Multiply the value by 1000, e.g. --timestamp "+1e3*i,example:"coze code db rollback --db-id <id> --timestamp 1713254400000 --confirm"});if(i>o)throw new e.CozeError(e.ErrorCode.E1000,`Invalid --timestamp '${t}': target time is in the future`,{timestamp:t},{trigger:"PITR can only restore to a past point in time",fix:"Pass a millisecond timestamp earlier than now"})})(t.timestamp);const s=Cm(Cm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Rolling back database '${t.dbId}' to ${new Date(Number(t.timestamp)).toLocaleString()}...`);const n=await hm.rollbackSpaceDatabase(s,t.dbId,t.timestamp);i.ui.success(`Rollback initiated. Use 'coze code db status --db-id ${t.dbId}' to check progress.`),i.response.print({restore_history_id:Im([n,"optionalAccess",e=>e.restore_history_id])})}))}const Sm=[{pattern:/\bDROP\s+(TABLE|INDEX|SCHEMA|DATABASE|VIEW|FUNCTION|TRIGGER)\b/i,level:"critical",reason:"Contains DROP statement that permanently removes database objects"},{pattern:/\bTRUNCATE\s+(TABLE\s+)?\w/i,level:"critical",reason:"Contains TRUNCATE statement that removes all rows from a table"},{pattern:/\bALTER\s+TABLE\b/i,level:"warning",reason:"Contains ALTER TABLE statement that may cause data loss"},{pattern:/\bDELETE\s+FROM\s+\w+\s*(?:;?\s*$)/im,level:"critical",reason:"Contains DELETE without WHERE clause that removes all rows"},{pattern:/\bUPDATE\s+\w+\s+SET\s+(?!.*\bWHERE\b).*$/im,level:"critical",reason:"Contains UPDATE without WHERE clause that modifies all rows"}];function km(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function jm(e,t){return null!=e?e:t()}function Pm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const zm=async(t,o,i,s)=>{const n=`${t}/api/platform/pg-meta/default/query`,r=Buffer.from(`${o}:${i}`).toString("base64"),a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${r}`},body:JSON.stringify({query:s})});if(!a.ok){const t=await a.text(),o=e.safeJsonParse(t,void 0),i=jm(jm(Pm([o,"optionalAccess",e=>e.message]),(()=>Pm([o,"optionalAccess",e=>e.error,"optionalAccess",e=>e.message]))),(()=>`pg-meta request failed: ${a.status}`));throw new Error(i)}const c=await a.json();return Array.isArray(c)?c:[]};function Tm(e,t){return null!=e?e:t()}function Rm(t){t.command("query").description("Execute SQL query on a database").requiredOption("--db-id <dbId>","Database ID").option("--sql <sql>","Inline SQL to execute").option("--file <path>","Read SQL from file").option("--confirm","Confirm execution of dangerous SQL").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Execute SQL query",description:"Execute SQL on a database. Supports inline SQL (--sql), file input (--file), or stdin pipe. Dangerous operations (DROP, TRUNCATE, DELETE/UPDATE without WHERE) require --confirm flag. In JSON mode, dangerous SQL without --confirm returns an error.",examples:[{desc:"Execute inline SQL",cmd:'coze code db query --db-id <id> --sql "SELECT * FROM users LIMIT 10"',tags:["[RECOMMENDED]"]},{desc:"Execute SQL from file",cmd:"coze code db query --db-id <id> --file ./query.sql"},{desc:"Pipe SQL via stdin",cmd:'echo "SELECT 1" | coze code db query --db-id <id>'},{desc:"Execute with confirmation",cmd:'coze code db query --db-id <id> --sql "DROP TABLE old_data" --confirm'}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},sql:{type:"string",required:!1,description:"Inline SQL (highest priority)"},file:{type:"string",required:!1,description:"Path to SQL file"},confirm:{type:"boolean",required:!1,description:"Confirm dangerous operations"}},output:{result:{type:"array",description:"Query results (SELECT)"},rows_affected:{type:"number",description:"Rows affected (DML)"},command:{type:"string",description:"SQL command type"},warnings:{type:"array",description:"Security warnings"}}},errors:[{code:e.ErrorCode.E1007,name:"DB_SQL_DANGEROUS",desc:"SQL contains dangerous operation",fix:"Add --confirm flag or modify the SQL",example:'coze code db query --db-id <id> --sql "DROP TABLE t" --confirm'},{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E5004,name:"DB_SQL_EXECUTION_FAILED",desc:"SQL execution failed",fix:"Check SQL syntax and table structure"},{code:e.ErrorCode.E5005,name:"DB_CONNECTION_FAILED",desc:"Cannot connect to database service",fix:"Check database status and network"}],seeAlso:["coze code db rollback","coze code db dump"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Tm(Tm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const n=t.sql||t.file?void 0:await async function(e,t){return null!=e?e:await t()}(await Ta(),(async()=>{}));let r;try{r=await(async e=>{if(km([e,"optionalAccess",e=>e.sql]))return e.sql.trim();if(km([e,"optionalAccess",e=>e.file])){const t=m.resolve(e.file),o=(await g.readFile(t,"utf-8")).trim();if(!o)throw new Error(`SQL file is empty: ${t}`);return o}if(km([e,"optionalAccess",e=>e.stdin])){const t=e.stdin.trim();if(!t)throw new Error("SQL input from stdin is empty");return t}throw new Error("No SQL provided. Use --sql, --file, or pipe SQL via stdin.")})({sql:t.sql,file:t.file,stdin:n})}catch(t){throw new e.CozeError(e.ErrorCode.E1000,t instanceof Error?t.message:String(t),void 0,{trigger:"No usable SQL input",fix:"Provide SQL via --sql, --file, or stdin pipe",example:'coze code db query --db-id <id> --sql "SELECT 1"'})}const a=(e=>{const t=[];let o="safe";const i=e.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const{pattern:e,level:s,reason:n}of Sm)e.test(i)&&(t.push(n),"critical"===s?o="critical":"safe"===o&&(o="warning"));return{isDangerous:"safe"!==o,level:o,reasons:t}})(r);if(a.isDangerous&&!t.confirm){const o="json"===i.format,s=!0===process.stdin.isTTY;if(o||!s)throw new e.CozeError(e.ErrorCode.E1007,`SQL contains dangerous operation: ${a.reasons.join(", ")}`,{sql:r.substring(0,200),analysis:a},{trigger:"Dangerous SQL detected without --confirm",fix:"Add --confirm flag to proceed, or modify the SQL to remove dangerous operations",example:`coze code db query --db-id ${t.dbId} --sql "..." --confirm`});i.ui.info(`⚠ Warning: SQL contains dangerous operation:\n ${a.reasons.join("\n ")}`);const{confirm:n}=await import("@inquirer/prompts").then((e=>({confirm:e.confirm})));if(!await n({message:"Are you sure you want to execute this SQL?",default:!1}))return void i.ui.info("Operation cancelled.")}i.ui.info("Fetching database connection info...");const c=await hm.getSpaceDatabase(s,t.dbId);if(!c.supabase_url)throw new e.CozeError(e.ErrorCode.E5005,"Database does not have supabase_url. Cannot execute SQL via pg-meta.",{databaseId:t.dbId});if(!c.super_user||!c.super_user_password)throw new e.CozeError(e.ErrorCode.E5005,"Database does not have super_user credentials. Cannot authenticate against pg-meta.",{databaseId:t.dbId});let l;i.ui.info("Executing SQL...");try{l=await zm(c.supabase_url,c.super_user,c.super_user_password,r)}catch(t){throw new e.CozeError(e.ErrorCode.E5004,`SQL execution failed: ${t.message}`,{sql:r.substring(0,200)})}const d=Tm(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([r,"access",e=>e.trim,"call",e=>e(),"access",e=>e.split,"call",e=>e(/\s+/),"access",e=>e[0],"optionalAccess",e=>e.toUpperCase,"call",e=>e()]),(()=>"UNKNOWN")),p="SELECT"===d,u=a.isDangerous?a.reasons:[],h=l.length>0,f=p||h?l.length:null;p||h?i.response.print("json"===i.format?{result:l,rows_affected:f,command:d,warnings:u}:l):(i.ui.success("SQL executed successfully (rows_affected unavailable from pg-meta)."),i.response.print("json"===i.format?{result:[],rows_affected:null,command:d,warnings:u,note:"pg-meta does not expose rows_affected for DDL/DML without RETURNING"}:{command:d,message:"SQL executed successfully."}))}))}function xm(e,t){return null!=e?e:t()}function Lm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Om=e=>({database_id:e.database_id,name:e.name,status:xm(fm[xm(e.status,(()=>0))],(()=>String(e.status))),database_env:xm(_m[xm(e.database_env,(()=>0))],(()=>String(e.database_env))),created_at:bm(e.created_at)});async function Dm(t,o){const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=xm(xm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const n=xm(t.limit,(()=>20)),r="json"!==i.format;if(r||!0===t.all){const e=xm(t.maxPages,(()=>10)),o=[];let a,c=t.cursor,l=0;for(i.ui.info("Fetching databases...");l<e;){const e=await hm.listSpaceDatabases(s,{cursor_id:c,limit:n});if(o.push(...xm(e.databases,(()=>[])).map(Om)),l+=1,i.ui.verbose(`Page ${l}: ${xm(Lm([e,"access",e=>e.databases,"optionalAccess",e=>e.length]),(()=>0))} item(s)`),a=e.next_cursor_id,!a||"0"===a){a=void 0;break}c=a}return a&&i.ui.info(`Reached --max-pages=${e}. More results available (cursor: ${a}). Pass --max-pages to fetch more.`),i.ui.info(`Fetched ${o.length} database(s).`),void(r?i.response.print(o):i.response.print({databases:o,next_cursor_id:xm(a,(()=>"0"))}))}const a=await hm.listSpaceDatabases(s,{cursor_id:t.cursor,limit:n});i.response.print({databases:xm(a.databases,(()=>[])).map(Om),next_cursor_id:a.next_cursor_id})}function Um(e,t){return null!=e?e:t()}function qm(e,t){return null!=e?e:t()}async function Bm(t,o){const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=qm(qm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const a=t.includeSchema&&t.includeSchema.length>0?t.includeSchema:["public"];i.ui.info("Fetching database connection info...");const c=await hm.getSpaceDatabase(s,t.dbId);if(!c.supabase_url)throw new e.CozeError(e.ErrorCode.E5006,"Database does not have supabase_url. Cannot generate types via PostgREST OpenAPI.",{databaseId:t.dbId},{fix:"Check database is in active status. Run `coze code db status --db-id <id>`."});if(!c.anon_key)throw new e.CozeError(e.ErrorCode.E5006,"Database does not have anon_key. Cannot authenticate with PostgREST.",{databaseId:t.dbId});i.ui.info("Fetching OpenAPI schema from PostgREST...");const l=`${c.supabase_url}/rest/v1/`;let d,p;try{const e=await fetch(l,{headers:{apikey:c.anon_key}});if(!e.ok)throw new Error(`PostgREST returned ${e.status}`);const t=await e.json();d=await async function(e){if("string"==typeof e.openapi)return e;if("string"==typeof e.swagger){const{convertObj:t}=await import("swagger2openapi");return(await t(e,{patch:!0,warnOnly:!0})).openapi}return e}(t)}catch(o){throw new e.CozeError(e.ErrorCode.E5006,`Failed to fetch OpenAPI schema: ${o.message}`,{databaseId:t.dbId})}i.ui.info("Generating TypeScript types...");try{const e=await import("openapi-typescript"),t=await e.default(d,{exportType:!0});p="string"==typeof t?t:e.astToString(t)}catch(o){throw new e.CozeError(e.ErrorCode.E5006,`Type generation failed: ${o.message}`,{databaseId:t.dbId},{fix:"The CLI auto-converts PostgREST Swagger 2.0 to OpenAPI 3.0 before generation. If it still fails, the schema may use constructs the generator cannot map — re-run with --debug for the underlying error."})}const u=n.resolve(qm(t.output,(()=>"types/database.ts")));await r.mkdir(n.dirname(u),{recursive:!0}),await r.writeFile(u,"// Auto-generated by coze code db gen-types\n// Do not edit manually\n\n"+p,"utf-8"),i.ui.success(`Types generated: ${u}`),i.response.print({output_path:u,schemas:a})}function Mm(e,t){return null!=e?e:t()}const Nm=/^[a-zA-Z_][a-zA-Z0-9_$]{0,62}$/,$m=e=>{let t=` ${e.column_name} ${e.data_type}`;return e.character_maximum_length&&(t=` ${e.column_name} ${e.data_type}(${e.character_maximum_length})`),"NO"===e.is_nullable&&(t+=" NOT NULL"),e.column_default&&(t+=` DEFAULT ${e.column_default}`),t};async function Gm(e,t){const[o,i,s,n]=await Promise.all([zm(e.supabaseUrl,e.username,e.password,t.tables),zm(e.supabaseUrl,e.username,e.password,t.columns),zm(e.supabaseUrl,e.username,e.password,t.constraints),zm(e.supabaseUrl,e.username,e.password,t.indexes)]),r=(e=>{const t=new Map;for(const o of e){const e=`${o.table_schema}.${o.table_name}`,i=t.get(e);i?i.push(o):t.set(e,[o])}return t})(i);let a="";for(const e of o){const t=`${e.table_schema}.${e.table_name}`,o=Mm(r.get(t),(()=>[]));a+=`CREATE TABLE IF NOT EXISTS ${e.table_schema}.${e.table_name} (\n`,a+=o.map($m).join(",\n"),a+="\n);\n\n"}for(const e of s){const t=e.constraint_type;("p"===t||"u"===t||"f"===t||"c"===t)&&e.definition&&(a+=`ALTER TABLE ${e.schema_name}.${e.table_name} ADD CONSTRAINT ${e.constraint_name} ${e.definition};\n`)}s.length>0&&(a+="\n");const c=new Set(s.filter((e=>"p"===e.constraint_type||"u"===e.constraint_type)).map((e=>`${e.schema_name}.${e.constraint_name}`)));for(const e of n){const t=`${e.schemaname}.${e.indexname}`;!c.has(t)&&e.indexdef&&(a+=`${e.indexdef};\n`)}return n.length>0&&(a+="\n"),a}async function Fm(t,o){const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Mm(Mm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!0===t.schemaOnly&&!0===t.dataOnly)throw new e.CozeError(e.ErrorCode.E1000,"--schema-only and --data-only are mutually exclusive");const a=!t.dataOnly,c=!0===t.dataOnly,l=c?"data-only":"schema-only",d=(t=>{const o=t&&t.length>0?Array.from(new Set(t)):["public"];for(const t of o)if(!Nm.test(t))throw new e.CozeError(e.ErrorCode.E1000,`Invalid schema name '${t}'. Must be a plain PostgreSQL identifier (letters, digits, underscore, $; max 63 chars; starts with letter or underscore).`);return o})(t.includeSchema),p=(e=>{const t=e.map((e=>`'${e}'`)).join(", ");return{tables:`\n SELECT table_name, table_schema\n FROM information_schema.tables\n WHERE table_schema IN (${t})\n AND table_type = 'BASE TABLE'\n ORDER BY table_schema, table_name;\n `,columns:`\n SELECT table_name, table_schema, column_name, data_type,\n is_nullable, column_default, character_maximum_length,\n numeric_precision, numeric_scale\n FROM information_schema.columns\n WHERE table_schema IN (${t})\n ORDER BY table_schema, table_name, ordinal_position;\n `,constraints:`\n SELECT n.nspname AS schema_name,\n cl.relname AS table_name,\n c.conname AS constraint_name,\n c.contype AS constraint_type,\n pg_get_constraintdef(c.oid) AS definition\n FROM pg_catalog.pg_constraint c\n JOIN pg_catalog.pg_class cl ON c.conrelid = cl.oid\n JOIN pg_catalog.pg_namespace n ON cl.relnamespace = n.oid\n WHERE n.nspname IN (${t})\n ORDER BY n.nspname, cl.relname,\n CASE c.contype WHEN 'p' THEN 1 WHEN 'u' THEN 2 WHEN 'f' THEN 3 ELSE 4 END,\n c.conname;\n `,indexes:`\n SELECT schemaname, tablename, indexname, indexdef\n FROM pg_indexes\n WHERE schemaname IN (${t})\n ORDER BY schemaname, tablename, indexname;\n `}})(d);i.ui.info("Fetching database connection info...");const u=await hm.getSpaceDatabase(s,t.dbId);if(!u.supabase_url)throw new e.CozeError(e.ErrorCode.E5007,"Database does not have supabase_url. Cannot access pg-meta.",{databaseId:t.dbId});if(!u.super_user||!u.super_user_password)throw new e.CozeError(e.ErrorCode.E5007,"Database does not have super_user credentials. Cannot authenticate against pg-meta.",{databaseId:t.dbId});const m={supabaseUrl:u.supabase_url,username:u.super_user,password:u.super_user_password};let g="";g+="-- Dump generated by coze code db dump\n",g+=`-- Database: ${t.dbId}\n`,g+=`-- Mode: ${l}\n`,g+=`-- Schemas: ${d.join(", ")}\n`,g+=`-- Date: ${(new Date).toISOString()}\n\n`;try{a&&(i.ui.info("Exporting schema..."),g+=await Gm(m,p)),c&&(i.ui.info("Exporting data..."),g+=await async function(e,t){const o=await zm(e.supabaseUrl,e.username,e.password,t.tables);let i="";for(const t of o){const o=`SELECT * FROM ${t.table_schema}.${t.table_name};`,s=await zm(e.supabaseUrl,e.username,e.password,o);if(0===s.length)continue;const n=Object.keys(s[0]);for(const e of s){const o=n.map((t=>{return null==(o=e[t])?"NULL":"number"==typeof o?Number.isFinite(o)?String(o):"NULL":"boolean"==typeof o?o?"TRUE":"FALSE":"bigint"==typeof o?String(o):o instanceof Date?`'${o.toISOString()}'`:"object"==typeof o?`'${JSON.stringify(o).replace(/'/g,"''")}'`:`'${String(o).replace(/'/g,"''")}'`;var o}));i+=`INSERT INTO ${t.table_schema}.${t.table_name} (${n.join(", ")}) VALUES (${o.join(", ")});\n`}i+="\n"}return i}(m,p))}catch(o){throw new e.CozeError(e.ErrorCode.E5007,`Dump failed: ${o.message}`,{databaseId:t.dbId})}const h=n.resolve(Mm(t.output,(()=>"db/schema.sql")));await r.mkdir(n.dirname(h),{recursive:!0}),await r.writeFile(h,g,"utf-8"),i.ui.success(`Dump completed: ${h}`),i.response.print({output_path:h,mode:l,schemas:d})}function Vm(e,t){return null!=e?e:t()}function Wm(e,t){return null!=e?e:t()}const Hm=t=>{const o=t.command("db").description("Manage Coze space databases").config({help:{brief:"Database management for Coze spaces",description:"Create, query, and manage Supabase-backed databases in your Coze space. Supports database lifecycle management, SQL execution, TypeScript type generation, and schema export.",examples:[{desc:"Create a new database",cmd:"coze code db create",tags:["[RECOMMENDED]"]},{desc:"List all databases",cmd:"coze code db list"},{desc:"Execute SQL query",cmd:'coze code db query --db-id <id> --sql "SELECT 1"'},{desc:"Generate TypeScript types",cmd:"coze code db gen-types --db-id <id>"},{desc:"Export database schema",cmd:"coze code db dump --db-id <id>"}],seeAlso:["coze code project","coze code env"],schema:{input:{},output:{}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found or no permission",fix:"Check --db-id is correct, run `coze code db list`"}]}});o.command("create").description("Create a new database in current space").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Create a new database",description:"Create a new Supabase database in the current space. The database name and credentials are auto-generated. Use `coze code db get` to retrieve connection info.",examples:[{desc:"Create a database",cmd:"coze code db create",tags:["[RECOMMENDED]"]}],schema:{input:{spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{database_id:{type:"string",description:"Created database ID"},status:{type:"string",description:"Database status"},database_env:{type:"string",description:"Environment"}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Use --space-id or run `coze space use <spaceId>` first"},{code:e.ErrorCode.E4002,name:"DB_QUOTA_EXCEEDED",desc:"Space database quota exceeded",fix:"Delete unused databases with `coze code db delete`"}],seeAlso:["coze code db list","coze code db get"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Wm(Wm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info("Creating database in space...");const n=await hm.createSpaceDatabase(s);i.ui.success("Database created successfully!"),i.response.print({database_id:n.database_id,database_url:n.database_url,status:Wm(fm[Wm(n.status,(()=>0))],(()=>n.status)),database_env:Wm(_m[Wm(n.database_env,(()=>0))],(()=>n.database_env)),created_at:bm(n.created_at)})})),function(t){t.command("list").description("List databases in current space").option("--space-id <spaceId>","Space ID (optional, reads from context)").option("--limit <limit>","Number of databases per page (1-100)",parseInt).option("--cursor <cursorId>","Cursor for pagination").option("--all","Fetch all databases across pages").option("--max-pages <maxPages>","Max pages to fetch in text mode (default: 10)",parseInt).config({help:{brief:"List databases",description:"List all databases in the current space. Supports cursor-based pagination. Use --all to fetch all databases at once.",examples:[{desc:"List databases",cmd:"coze code db list",tags:["[RECOMMENDED]"]},{desc:"List all databases",cmd:"coze code db list --all"},{desc:"Paginated listing",cmd:"coze code db list --limit 5 --cursor <cursorId>"}],schema:{input:{limit:{type:"number",required:!1,description:"Items per page (1-100, default: 20)"},cursor:{type:"string",required:!1,description:"Pagination cursor"},all:{type:"boolean",required:!1,description:"Fetch all databases"}},output:{type:"array",items:{type:"object",properties:{database_id:{type:"string",description:"Database ID"},name:{type:"string",description:"Database name"},status:{type:"string",description:"Status"},database_env:{type:"string",description:"Environment"},created_at:{type:"string",description:"Creation time"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Use --space-id or run `coze space use <spaceId>` first"}],seeAlso:["coze code db create","coze code db get"]}}).action(Dm)}(o),function(t){t.command("get").description("Get database details").requiredOption("--db-id <dbId>","Database ID").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Get database details",description:"Get detailed information about a specific database, including connection URLs and credentials. The console URL can be constructed from supabase_url.",examples:[{desc:"Get database details",cmd:"coze code db get --db-id <databaseId>",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{database_id:{type:"string",description:"Database ID"},database_name:{type:"string",description:"Database name"},database_url:{type:"string",description:"Connection URL"},supabase_url:{type:"string",description:"Supabase URL"},super_user:{type:"string",description:"Super user name"},super_user_password:{type:"string",description:"Super user password"},service_role_key:{type:"string",description:"Supabase service role key"},anon_key:{type:"string",description:"Supabase anon key"},status:{type:"string",description:"Status"},database_env:{type:"string",description:"Database environment (e.g. develop / production)"},created_at:{type:"string",description:"Creation time (formatted timestamp)"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found or no permission",fix:"Check --db-id is correct, run `coze code db list`"}],seeAlso:["coze code db list","coze code db status"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Um(Um(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Fetching database '${t.dbId}'...`);const n=await hm.getSpaceDatabase(s,t.dbId);i.ui.success("Database details:");const r="json"===i.format;var a;r||i.ui.info("Credentials are masked in text output. Use --format json to get full values."),i.response.print({database_id:n.database_id,database_name:n.name,database_url:r?n.database_url:(a=n.database_url,a?a.replace(/^([a-z+]+:\/\/[^:/@]+):[^@]+@/i,"$1:****@"):"-"),supabase_url:n.supabase_url,super_user:n.super_user,super_user_password:r?n.super_user_password:vm(n.super_user_password),service_role_key:r?n.service_role_key:vm(n.service_role_key),anon_key:n.anon_key,status:Um(fm[Um(n.status,(()=>0))],(()=>n.status)),database_env:Um(_m[Um(n.database_env,(()=>0))],(()=>n.database_env)),created_at:bm(n.created_at)})}))}(o),function(t){t.command("delete").description("Delete a database").requiredOption("--db-id <dbId>","Database ID").option("--confirm","Confirm deletion (required)").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Delete a database",description:"Delete a database from the current space. This operation cannot be undone. The --confirm flag is required to proceed.",examples:[{desc:"Delete a database",cmd:"coze code db delete --db-id <databaseId> --confirm",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID to delete"},confirm:{type:"boolean",required:!1,description:"Confirm deletion. Required in JSON mode or non-interactive (non-TTY) terminals; in interactive terminals an interactive confirmation prompt is shown if omitted"}},output:{deleted:{type:"boolean",description:"Deletion status"},database_id:{type:"string",description:"Deleted database ID"}}},errors:[{code:e.ErrorCode.E1007,name:"DB_SQL_DANGEROUS",desc:"Deletion requires --confirm flag",fix:"Add --confirm flag to proceed with deletion",example:"coze code db delete --db-id <id> --confirm"},{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct, run `coze code db list`"}],seeAlso:["coze code db list","coze code db create"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!t.confirm){const o="json"===i.format,s=!0===process.stdin.isTTY;if(o||!s)throw new e.CozeError(e.ErrorCode.E1007,"Deletion requires --confirm flag to proceed",{databaseId:t.dbId},{trigger:"Database deletion is a destructive operation",fix:"Add --confirm flag to confirm deletion",example:`coze code db delete --db-id ${t.dbId} --confirm`});i.ui.warn(`⚠ You are about to delete database '${t.dbId}'. This operation cannot be undone.`);const{confirm:n}=await import("@inquirer/prompts").then((e=>({confirm:e.confirm})));if(!await n({message:`Are you sure you want to delete database '${t.dbId}'?`,default:!1}))return void i.ui.info("Operation cancelled.")}const s=Vm(Vm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Deleting database '${t.dbId}'...`),await hm.deleteSpaceDatabase(s,t.dbId),i.ui.success(`Database '${t.dbId}' deleted successfully.`),i.response.print({deleted:!0,database_id:t.dbId})}))}(o),Rm(o),Am(o),function(t){t.command("status").description("Get database status and restore info").requiredOption("--db-id <dbId>","Database ID").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Check database status",description:"Get the status of a database including restore/rollback information. Shows whether the database can be rolled back, current restore status, and earliest restore time.",examples:[{desc:"Check database status",cmd:"coze code db status --db-id <databaseId>",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"}},output:{can_restore:{type:"boolean",description:"Whether PITR restore is available"},is_restoring:{type:"boolean",description:"Whether a restore is in progress"},latest_restore_status:{type:"string",description:"Latest restore status"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"}],seeAlso:["coze code db get","coze code db rollback"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=wm(wm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Fetching status for database '${t.dbId}'...`);const n=await hm.getSpaceDatabaseStatus(s,t.dbId);i.ui.success("Database status:"),i.response.print({can_restore:Em([n,"optionalAccess",e=>e.can_restore]),is_restoring:Em([n,"optionalAccess",e=>e.is_restoring]),earliest_restore_time:bm(Em([n,"optionalAccess",e=>e.earliest_restore_time])),latest_restore_status:wm(ym[wm(Em([n,"optionalAccess",e=>e.latest_restore_status]),(()=>-1))],(()=>Em([n,"optionalAccess",e=>e.latest_restore_status]))),latest_restore_error:Em([n,"optionalAccess",e=>e.latest_restore_error]),latest_restore_start_time:bm(Em([n,"optionalAccess",e=>e.latest_restore_start_time])),latest_restore_end_time:bm(Em([n,"optionalAccess",e=>e.latest_restore_end_time]))})}))}(o),function(t){t.command("gen-types").description("Generate TypeScript types from database schema").requiredOption("--db-id <dbId>","Database ID").option("--output <path>","Output file path","types/database.ts").option("--include-schema <name>","Schema name (can be specified multiple times)",((e,t=[])=>[...t,e]),[]).option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Generate TypeScript types",description:"Generate TypeScript type definitions from database schema using PostgREST OpenAPI. The generated types follow the Supabase database type format.",examples:[{desc:"Generate types for public schema",cmd:"coze code db gen-types --db-id <id>",tags:["[RECOMMENDED]"]},{desc:"Generate types for multiple schemas",cmd:"coze code db gen-types --db-id <id> --include-schema public --include-schema auth"},{desc:"Custom output path",cmd:"coze code db gen-types --db-id <id> --output src/types/db.ts"}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},output:{type:"string",required:!1,description:"Output file path (default: types/database.ts)"},includeSchema:{type:"array",required:!1,description:"Schema names (default: public)"}},output:{output_path:{type:"string",description:"Generated file path"},schemas:{type:"array",description:"Generated schemas"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E5006,name:"DB_GEN_TYPES_FAILED",desc:"Type generation failed",fix:"Ensure the database is active. PostgREST Swagger 2.0 is auto-converted to OpenAPI 3.0; re-run with --debug to see the underlying generator error."}],seeAlso:["coze code db dump","coze code db query"]}}).action(Bm)}(o),function(t){t.command("dump").description("Export database schema or data").requiredOption("--db-id <dbId>","Database ID").option("--output <path>","Output file path","db/schema.sql").option("--schema-only","Export schema only (default if neither flag set)").option("--data-only","Export data only").option("--include-schema <name>","Schema name to dump (repeatable, default: public)",((e,t=[])=>[...t,e]),[]).option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Export database schema or data",description:"Export database schema (DDL) or data as SQL. Uses pg-meta API to query information_schema. Default mode is schema-only, default schema is public. Pass --include-schema multiple times to include additional schemas (e.g. auth, storage).",examples:[{desc:"Export public schema",cmd:"coze code db dump --db-id <id>",tags:["[RECOMMENDED]"]},{desc:"Export data only",cmd:"coze code db dump --db-id <id> --data-only"},{desc:"Include multiple schemas",cmd:"coze code db dump --db-id <id> --include-schema public --include-schema auth"},{desc:"Custom output path",cmd:"coze code db dump --db-id <id> --output backups/schema.sql"}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},output:{type:"string",required:!1,description:"Output file path (default: db/schema.sql)"},schemaOnly:{type:"boolean",required:!1,description:"Export schema only (default: true)"},dataOnly:{type:"boolean",required:!1,description:"Export data only"},includeSchema:{type:"array",required:!1,description:"Schema name(s) to include (repeatable, default: public)"}},output:{output_path:{type:"string",description:"Output file path"},mode:{type:"string",description:"Export mode"},schemas:{type:"array",description:"Schemas included in the dump"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E5007,name:"DB_DUMP_FAILED",desc:"Schema export failed",fix:"Check database status and permissions"}],seeAlso:["coze code db query","coze code db gen-types"]}}).action(Fm)}(o)};function Jm(e,t){return null!=e?e:t()}function Km(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Qm=["github","gitlab"];function Ym(e,t){return null!=e?e:t()}function Zm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Xm=["github","gitlab"];async function eg(t){const{ctx:o,force:i,warning:s,message:n,errorMessage:r,errorData:a,errorDetail:c}=t;if(i)return!0;const l="json"===o.format,d=!0===process.stdin.isTTY;if(l||!d)throw new e.CozeError(e.ErrorCode.E1000,r,a,c);o.ui.warn(s);const{confirm:p}=await import("@inquirer/prompts");return!!await p({message:n,default:!1})||(o.ui.info("Operation cancelled."),!1)}function tg(e,t){return null!=e?e:t()}function og(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ig=["github","gitlab"];const sg=o=>{const i=o.command("auth").description("Git platform OAuth authorization management").config({help:{brief:"Manage Git platform OAuth authorization",description:"Manage OAuth authorization for Git platforms. Supports login, status check, and logout.",examples:[{desc:"Login",cmd:"coze code git auth login"},{desc:"Check status",cmd:"coze code git auth status"},{desc:"Logout",cmd:"coze code git auth logout"}],seeAlso:["coze code git search"]}});i.command("login").description("Authorize a Git platform via OAuth").config({help:{brief:"Authorize a Git platform via OAuth",description:"Initiate OAuth authorization flow for a Git platform. Opens a browser for the user to complete authorization. The authorization is stored at the space level and can be reused across projects. Defaults to GitHub if --provider is not specified.",examples:[{desc:"Authorize GitHub (minimal)",cmd:"coze code git auth login"},{desc:"Authorize GitHub explicitly",cmd:"coze code git auth login --provider github",tags:["[RECOMMENDED]"]},{desc:"[TEMPLATE] Authorize any provider",cmd:"coze code git auth login --provider <github|gitlab>",tags:["[TEMPLATE]"]}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",description:"Authorization status",example:"authorized"},user:{type:"string",description:"Authorized user name",example:"octocat"}}},enums:{provider:{github:"GitHub OAuth authorization",gitlab:"GitLab OAuth authorization (future)"}},errors:[{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"},{code:e.ErrorCode.E2005,name:"OAUTH_TIMEOUT",desc:"OAuth authorization timed out",fix:"Re-run `coze code git auth login`"}],seeAlso:["coze code git auth status","coze code git auth logout"],caveats:["Authorization requires a browser. In headless environments, copy the URL from terminal output and open it manually","Authorization is stored at the space level, not per-project"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Jm(Jm(o.provider,(()=>Km([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!Qm.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${Qm.join(", ")}`);const r=Jm(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or run `coze space use <spaceId>` first");s.ui.info("Fetching integration list...");const a=Jm(Km([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>Km([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=Jm(Km([a,"optionalAccess",e=>e.id]),(()=>""));if(!c)throw new e.CozeError(e.ErrorCode.E5000,`No integration found for provider: ${n}`);s.ui.info(`Initiating OAuth for ${n}...`);const l=Jm(Km([await t.IdeApi.GetOauthConfig({integration_id:c,space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.auth_url]),(()=>""));if(!l)throw new e.CozeError(e.ErrorCode.E5000,"Failed to get OAuth authorization URL");s.ui.info(`Opening browser for ${n} authorization...`),s.ui.info(`Authorization URL: ${l}`),s.ui.info("Waiting for authorization... (timeout: 120s)");const d=Date.now();let p=!1;for(;Date.now()-d<12e4;)if(await new Promise((e=>setTimeout(e,2e3))),Km([await t.IdeApi.GetOauthStatus({integration_id:c,space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.success])){p=!0;break}if(!p)throw new e.CozeError(e.ErrorCode.E2005,"OAuth authorization timed out after 120 seconds");const u=await t.IdeApi.GetUser({space_id:r,integration_id:c}),m=Jm(Jm(Km([u,"access",e=>e.data,"optionalAccess",e=>e.login]),(()=>Km([u,"access",e=>e.data,"optionalAccess",e=>e.name]))),(()=>"unknown"));s.ui.success(`${n} authorized successfully.`),s.ui.info(` User: ${m}`),s.response.print({provider:n,status:"authorized",user:m})})),function(o){o.command("status").description("Check the Git platform OAuth authorization status").config({help:{brief:"Check the Git platform OAuth authorization status",description:"Display the current OAuth authorization status and user info for the specified Git platform.",examples:[{desc:"Check GitHub auth status (minimal)",cmd:"coze code git auth status",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Check if authorized",cmd:"coze code git auth status --format json | jq .status",tags:["[PIPELINE]"]}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",enum:["authorized","not-authorized"],description:"Authorization status",example:"authorized"},user:{type:"object",description:"Authorized user info"}}},errors:[{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"}],seeAlso:["coze code git auth login","coze code git auth logout"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Ym(Ym(o.provider,(()=>Zm([i,"access",e=>e.parent,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!Xm.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${Xm.join(", ")}`);const r=Ym(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");const a=Ym(Zm([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>Zm([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=Ym(Zm([a,"optionalAccess",e=>e.id]),(()=>""));if(2!==Zm([a,"optionalAccess",e=>e.status])||!c)return s.ui.info("Git Authorization:"),s.ui.info(` Provider: ${n}`),s.ui.info(" Status: not-authorized"),void s.response.print({provider:n,status:"not-authorized"});const l=(await t.IdeApi.GetUser({space_id:r,integration_id:c})).data;s.ui.info("Git Authorization:"),s.ui.info(` Provider: ${n}`),s.ui.info(" Status: authorized"),s.ui.info(` User: ${Ym(Ym(Zm([l,"optionalAccess",e=>e.login]),(()=>Zm([l,"optionalAccess",e=>e.name]))),(()=>"unknown"))}`),Zm([l,"optionalAccess",e=>e.avatar_url])&&s.ui.info(` Avatar: ${l.avatar_url}`),s.response.print({provider:n,status:"authorized",user:{login:Ym(Ym(Zm([l,"optionalAccess",e=>e.login]),(()=>Zm([l,"optionalAccess",e=>e.name]))),(()=>"unknown")),avatar_url:Ym(Zm([l,"optionalAccess",e=>e.avatar_url]),(()=>""))}})}))}(i),function(o){o.command("logout").description("Revoke OAuth authorization for a Git platform").option("--force","Skip confirmation and revoke directly",!1).config({help:{brief:"Revoke OAuth authorization for a Git platform",description:"Cancel the OAuth authorization for the specified Git platform in the current space. This will revoke access for all projects in the space that use this provider. Use --force to skip the confirmation prompt.",examples:[{desc:"Logout GitHub (minimal)",cmd:"coze code git auth logout"},{desc:"Force logout without confirmation",cmd:"coze code git auth logout --force",tags:["[RECOMMENDED]"]},{desc:"Logout a specific provider",cmd:"coze code git auth logout --provider gitlab"}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"},force:{type:"boolean",required:!1,description:"Skip confirmation",example:!1}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",description:"Result status",example:"deauthorized"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Revoking requires --force in JSON mode or non-interactive terminals",fix:"Add --force flag to revoke without confirmation",example:"coze code git auth logout --force"},{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"},{code:e.ErrorCode.E2007,name:"NOT_AUTHORIZED",desc:"Git service is not authorized",fix:"Use `coze code git auth status` to check status"}],seeAlso:["coze code git auth login","coze code git auth status"],caveats:["Revoking authorization affects ALL projects in the current space that use this provider","Projects bound to repos via this provider will lose sync capability until re-authorized"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=tg(tg(o.provider,(()=>og([i,"access",e=>e.parent,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!ig.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${ig.join(", ")}`);if(!await eg({ctx:s,force:o.force,warning:`⚠ You are about to revoke ${n} authorization for the current space. All projects using this provider will lose sync capability until re-authorized.`,message:`Are you sure you want to revoke ${n} authorization?`,errorMessage:"Revoking authorization requires --force flag to proceed",errorData:{provider:n},errorDetail:{trigger:"Revoking Git authorization affects all projects in the current space",fix:"Add --force flag to revoke without confirmation",example:"coze code git auth logout --force"}}))return;const r=tg(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");const a=tg(og([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>og([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=tg(og([a,"optionalAccess",e=>e.id]),(()=>""));if(2!==og([a,"optionalAccess",e=>e.status])||!c)throw new e.CozeError(e.ErrorCode.E2007,`${n} is not currently authorized`);await t.IdeApi.CancelOauth({integration_id:c,space_id:r}),s.ui.success(`${n} authorization revoked successfully.`),s.response.print({provider:n,status:"deauthorized"})}))}(i)};function ng(e,t){return null!=e?e:t()}function rg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ag=["github","gitlab"];const cg=o=>{const i=o.command("git").description("Git platform integration management").option("--provider <provider>","Git service provider: github / gitlab","github").config({help:{brief:"Manage Git platform integrations (OAuth authorization and repository search)",description:"Manage Git platform integrations including OAuth authorization and repository search. Use --provider to specify the Git service provider (default: github).",examples:[{desc:"Authorize GitHub",cmd:"coze code git auth login"},{desc:"Search repos",cmd:"coze code git search --keyword react"}],seeAlso:["coze code repo"]}});sg(i),i.command("search").description("Search repositories on the authorized Git platform").option("-k, --keyword <keyword>","Search keyword").option("--page <page>","Page number",parseInt).option("--page-size <size>","Results per page",parseInt).config({help:{brief:"Search repositories on the authorized Git platform",description:"Search through repositories accessible to the authorized Git user. Supports keyword filtering and pagination. Requires prior OAuth authorization.",examples:[{desc:"List all repos (minimal)",cmd:"coze code git search"},{desc:"Search by keyword",cmd:"coze code git search --keyword react",tags:["[RECOMMENDED]"]},{desc:"Paginated search",cmd:"coze code git search -k react --page 2 --page-size 10"},{desc:"[PIPELINE] Find empty repos for binding",cmd:'coze code git search -k my-repo --format json | jq ".items[] | select(.size == 0)"',tags:["[PIPELINE]"]}],schema:{input:{keyword:{type:"string",required:!1,description:"Search keyword",example:"react"},page:{type:"number",required:!1,description:"Page number",example:1},pageSize:{type:"number",required:!1,description:"Results per page",example:20},provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider (inherited from the `git` parent command --provider option, default: github)",example:"github"}},output:{items:{type:"array",description:"Matching repositories"},total_count:{type:"number",description:"Total matching count",example:15}}},errors:[{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"}],seeAlso:["coze code repo bind","coze code repo create"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=ng(ng(o.provider,(()=>rg([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!ag.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}`);const r=ng(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");s.ui.info("Searching repositories...");const a=await t.IdeApi.SearchRepo({space_id:r,name_search:ng(o.keyword,(()=>"")),per_page:ng(o.pageSize,(()=>20)),page:ng(o.page,(()=>1))}),c=ng(rg([a,"access",e=>e.data,"optionalAccess",e=>e.items]),(()=>[])),l=ng(rg([a,"access",e=>e.data,"optionalAccess",e=>e.total_count]),(()=>0));if(0===c.length)s.ui.info("No repositories found.");else{s.ui.info(`Found ${l} repositories:`);for(const e of c){const t=e.private?"private":"public";s.ui.info(` ${e.full_name} (${t})`)}}s.response.print({items:c.map((e=>({full_name:e.full_name,private:ng(e.private,(()=>!1)),size:ng(e.size,(()=>0)),updated_at:ng(e.updated_at,(()=>""))}))),total_count:l})}))};function lg(e,t){return null!=e?e:t()}function dg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function pg(e,t){return null!=e?e:t()}function ug(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const mg={brief:"Bind a remote repository to a project",description:"Bind an empty remote repository to the specified project. The repository must be empty (non-empty repo binding is not supported in this version). Requires prior Git OAuth authorization.",examples:[{desc:"Bind a repo (minimal)",cmd:"coze code repo bind -p proj_abc -r user/my-repo"},{desc:"Bind after creating a new repo",cmd:"coze code repo create --name my-repo && coze code repo bind -p proj_abc -r user/my-repo",tags:["[RECOMMENDED]"]},{desc:"[ERROR RECOVERY] E3015: Repo not empty",cmd:"coze code repo create --name my-new-repo --private && coze code repo bind -p proj_abc -r user/my-new-repo",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},repo:{type:"string",required:!0,description:"Remote repo full name (must be empty)",example:"user/my-repo"}},output:{project_id:{type:"string",description:"Project ID",example:"proj_abc123"},repo_full_name:{type:"string",description:"Bound repo full name",example:"user/my-repo"},status:{type:"string",description:"Binding result",example:"bound"}}},errors:[{code:e.ErrorCode.E1013,name:"MISSING_REPO_NAME",desc:"Missing repo name",fix:"Use --repo <owner/name>"},{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"},{code:e.ErrorCode.E3015,name:"REPO_NOT_EMPTY",desc:"Repo not empty (returned by the API layer, not thrown by the CLI itself)",fix:"Use `coze code repo create` to create an empty repo"},{code:e.ErrorCode.E3016,name:"REPO_ALREADY_BOUND",desc:"Project already bound",fix:"Run `coze code repo unbind -p <id>` first"}],seeAlso:["coze code repo unbind","coze code repo create","coze code repo status"],caveats:["Only empty repositories are supported for binding in this version","A project can only be bound to one repository at a time"]};function gg(e,t){return null!=e?e:t()}function hg(e,t){return null!=e?e:t()}function fg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const _g=o=>{const i=o.command("repo").description("Manage remote repositories for projects").option("--provider <provider>","Git service provider: github / gitlab","github").config({help:{brief:"Manage remote repository bindings for Coze Coding projects",description:"Manage remote repository bindings and sync operations for Coze Coding projects. Supports creating, binding, unbinding, pushing, pulling, and checking status of remote repositories.",examples:[{desc:"Bind repo",cmd:"coze code repo bind -p proj_abc -r user/my-repo"},{desc:"Push changes",cmd:"coze code repo push -p proj_abc"},{desc:"Check status",cmd:"coze code repo status -p proj_abc"}],seeAlso:["coze code git"]}});i.command("create").description("Create a new repository on the remote Git platform").option("-n, --name <name>","Repository name").option("--private","Create as private repository",!1).config({help:{brief:"Create a new repository on the remote Git platform",description:"Create a new empty repository under the authorized user account on the Git platform. The created repo can then be bound to a project using `coze code repo bind`.",examples:[{desc:"Create a public repo (minimal)",cmd:"coze code repo create --name my-app"},{desc:"Create a private repo",cmd:"coze code repo create -n my-app --private",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Create and bind",cmd:"coze code repo create -n my-repo --private && coze code repo bind -p proj_abc -r user/my-repo",tags:["[PIPELINE]"]}],schema:{input:{name:{type:"string",required:!0,description:"Repository name",example:"my-new-repo"},private:{type:"boolean",required:!1,description:"Create as private [RECOMMENDED]",example:!0}},output:{full_name:{type:"string",description:"Created repo full name",example:"user/my-new-repo"},html_url:{type:"string",description:"Repository URL",example:"https://github.com/user/my-new-repo"},private:{type:"boolean",description:"Visibility",example:!0}}},errors:[{code:e.ErrorCode.E1014,name:"MISSING_REPO_CREATION_NAME",desc:"Missing repo name",fix:"Use --name <name>"},{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"},{code:e.ErrorCode.E3009,name:"CONFLICT",desc:"Repository name already exists",fix:"Use a different name"}],seeAlso:["coze code repo bind","coze code git search"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=lg(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");if(!o.name)throw new e.CozeError(e.ErrorCode.E1014,"Missing repository name: use --name <name>");s.ui.info(`Creating repository "${o.name}"...`);const r=(await t.IdeApi.CreateRepo({space_id:n,name:o.name,private:lg(o.private,(()=>!1))})).data;s.ui.success("Repository created successfully."),s.ui.info(` Name: ${lg(dg([r,"optionalAccess",e=>e.full_name]),(()=>o.name))}`),s.ui.info(` URL: ${lg(dg([r,"optionalAccess",e=>e.html_url]),(()=>""))}`),s.ui.info(" Visibility: "+(o.private?"private":"public")),s.response.print({full_name:lg(dg([r,"optionalAccess",e=>e.full_name]),(()=>o.name)),html_url:lg(dg([r,"optionalAccess",e=>e.html_url]),(()=>"")),private:lg(o.private,(()=>!1))})})),function(o){o.command("bind").description("Bind a remote repository to a project").requiredOption("-p, --project-id <projectId>","Project ID").option("-r, --repo <fullName>","Remote repo full name (e.g. user/repo)").config({help:mg}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=pg(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");if(!o.repo)throw new e.CozeError(e.ErrorCode.E1013,"Missing repository full name: use --repo <owner/name>");const r=pg(ug([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]),(()=>1));if(3===r)throw new e.CozeError(e.ErrorCode.E3016,"Project is already bound to a remote repository. Run `coze code repo unbind -p <projectId>` first.");if(1===r)throw new e.CozeError(e.ErrorCode.E2004,"Git service is not authorized. Run `coze code git auth login` first.");const a=pg(ug([await t.IdeApi.ListIntegration({space_id:n}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])),c=pg(pg(o.provider,(()=>ug([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github")),l=a.find((e=>ug([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===c)),d=pg(ug([l,"optionalAccess",e=>e.id]),(()=>""));s.ui.info(`Binding repository "${o.repo}" to project "${o.projectId}"...`),await t.IdeApi.AddRemote({project_id:o.projectId,repo_full_name:o.repo,integration_id:d}),s.ui.success("Repository bound successfully."),s.ui.info(` Project: ${o.projectId}`),s.ui.info(` Repository: ${o.repo}`),s.response.print({project_id:o.projectId,repo_full_name:o.repo,status:"bound"})}))}(i),function(o){o.command("unbind").description("Unbind the remote repository from a project").requiredOption("-p, --project-id <projectId>","Project ID").option("--force","Skip confirmation and unbind directly",!1).config({help:{brief:"Unbind the remote repository from a project",description:"Remove the remote repository binding from the specified project. This operation does not delete the remote repository itself. Use --force to skip confirmation.",examples:[{desc:"Unbind repo (minimal)",cmd:"coze code repo unbind -p proj_abc"},{desc:"Force unbind",cmd:"coze code repo unbind -p proj_abc --force",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},force:{type:"boolean",required:!1,description:"Skip confirmation",example:!1}},output:{project_id:{type:"string",description:"Project ID",example:"proj_abc123"},status:{type:"string",description:"Result status",example:"unbound"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Unbinding requires --force in JSON mode or non-interactive terminals",fix:"Add --force flag to unbind without confirmation",example:"coze code repo unbind -p <projectId> --force"},{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Use `coze code repo status -p <id>` to check status"}],seeAlso:["coze code repo bind","coze code repo status"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!await eg({ctx:s,force:o.force,warning:`⚠ You are about to unbind the remote repository from project '${o.projectId}'.`,message:`Are you sure you want to unbind the remote repository from project '${o.projectId}'?`,errorMessage:"Unbinding requires --force flag to proceed",errorData:{projectId:o.projectId},errorDetail:{trigger:"Unbinding removes the remote repository binding from the project",fix:"Add --force flag to unbind without confirmation",example:`coze code repo unbind -p ${o.projectId} --force`}}))return;var n;if(3!==(null!=(n=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]))?n:(()=>1)()))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Use `coze code repo status -p <projectId>` to check status.");s.ui.info(`Unbinding remote repository from project "${o.projectId}"...`),await t.IdeApi.RemoveRemote({project_id:o.projectId}),s.ui.success("Repository unbound successfully."),s.ui.info(` Project: ${o.projectId}`),s.response.print({project_id:o.projectId,status:"unbound"})}))}(i),function(o){o.command("push").description("Push local commits to the bound remote repository").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Push local commits to the bound remote repository",description:"Push local commits to the bound remote repository. Requires the project to be bound to a remote repository. If the remote has new commits, you must pull first before pushing.",examples:[{desc:"Push changes (minimal)",cmd:"coze code repo push -p proj_abc",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Push and check status",cmd:"coze code repo push -p proj_abc && coze code repo status -p proj_abc",tags:["[PIPELINE]"]},{desc:"[ERROR RECOVERY] E3018: Pull first",cmd:"coze code repo pull -p proj_abc && coze code repo push -p proj_abc",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"}},output:{status:{type:"string",enum:["success","failed"],description:"Push result",example:"success"},pushed_commits:{type:"number",description:"Number of commits pushed",example:2}}},errors:[{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Bind a repo first"},{code:e.ErrorCode.E3017,name:"NOTHING_TO_PUSH",desc:"Nothing to push (not triggered in current placeholder implementation)",fix:"Already in sync with remote"},{code:e.ErrorCode.E3018,name:"REMOTE_HAS_UPDATES",desc:"Remote has updates (not triggered in current placeholder implementation)",fix:"Run `coze code repo pull -p <id>` first"}],seeAlso:["coze code repo pull","coze code repo status"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");var n;if(3!==(null!=(n=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]))?n:(()=>1)()))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Run `coze code repo bind` first.");s.ui.info("Pushing to remote..."),s.ui.success("Push completed successfully."),s.response.print({status:"success",pushed_commits:0})}))}(i),function(o){o.command("pull").description("Pull remote changes from the bound repository").requiredOption("-p, --project-id <projectId>","Project ID").option("--conflict-strategy <strategy>","Auto conflict resolution strategy: ours / theirs").config({help:{brief:"Pull remote changes from the bound repository",description:"Pull the latest changes from the bound remote repository. If conflicts occur and --conflict-strategy is provided, conflicts will be auto-resolved. Without --conflict-strategy, the command will fail on conflict with exit code 1.",examples:[{desc:"Pull changes (minimal)",cmd:"coze code repo pull -p proj_abc"},{desc:"Auto-resolve keeping local",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours",tags:["[RECOMMENDED]"]},{desc:"Auto-resolve using remote",cmd:"coze code repo pull -p proj_abc --conflict-strategy theirs"},{desc:"[PIPELINE] Pull then push",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours && coze code repo push -p proj_abc",tags:["[PIPELINE]"]},{desc:"[ERROR RECOVERY] E3019: Resolve conflict",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},conflictStrategy:{type:"string",required:!1,enum:["ours","theirs"],description:"Auto conflict resolution strategy",example:"ours"}},output:{status:{type:"string",enum:["success","conflict_resolved","failed"],description:"Pull result",example:"success"},conflict_resolved:{type:"boolean",description:"Whether conflicts were resolved",example:!1},conflict_strategy:{type:"string",description:"Strategy used",example:"ours"},conflict_files:{type:"array",items:{type:"string"},description:"Conflicting files",example:["src/index.ts"]}}},enums:{"conflict-strategy":{ours:"Keep local version for all conflicting files",theirs:"Use remote version for all conflicting files"}},errors:[{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Bind a repo first"},{code:e.ErrorCode.E3019,name:"MERGE_CONFLICT",desc:"Merge conflict without strategy (not triggered in current placeholder implementation)",fix:"Use --conflict-strategy ours or theirs"},{code:e.ErrorCode.E3020,name:"WOULD_OVERWRITE",desc:"Local changes would be overwritten (not triggered in current placeholder implementation)",fix:"Commit local changes first"}],seeAlso:["coze code repo push","coze code repo status"],caveats:["Without --conflict-strategy, conflicts will cause the command to fail","Conflict resolution applies to ALL conflicting files (no per-file selection in CLI)"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(3!==gg(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]),(()=>1)))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Run `coze code repo bind` first.");s.ui.info("Pulling from remote..."),s.ui.success("Pull completed successfully."),s.response.print({status:"success",conflict_resolved:!1,conflict_strategy:gg(o.conflictStrategy,(()=>null)),conflict_files:[]})}))}(i),function(o){o.command("status").description("Show remote repository binding and sync status for a project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Show remote repository binding and sync status for a project",description:"Display the current remote repository binding status of a project, including the bind status and (when bound) the repository full name and URL.",examples:[{desc:"Check repo status (minimal)",cmd:"coze code repo status -p proj_abc"},{desc:"JSON output for scripting",cmd:"coze code repo status -p proj_abc --format json",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Check binding status",cmd:"coze code repo status -p proj_abc --format json | jq .bind_status",tags:["[PIPELINE]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"}},output:{bind_status:{type:"string",enum:["unauth","not-bound","bound"],description:"Binding status",example:"bound"},repo_full_name:{type:"string",description:"Remote repo full name",example:"user/my-app"},html_url:{type:"string",description:"Repository URL",example:"https://github.com/user/my-app"}}},errors:[],seeAlso:["coze code repo bind","coze code repo push","coze code repo pull"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");s.ui.info("Fetching remote repository status...");const n=await t.IdeApi.GetRemote({project_id:o.projectId}),{data:r}=n,a=hg(fg([r,"optionalAccess",e=>e.status]),(()=>1)),c=hg({1:"unauth",2:"not-bound",3:"bound"}[a],(()=>"unauth"));if(3!==a)return s.ui.info("Remote Repository:"),s.ui.info(` Status: ${c}`),void s.response.print({bind_status:c});const l=fg([r,"optionalAccess",e=>e.basic_info]),d=hg(fg([l,"optionalAccess",e=>e.full_name]),(()=>"")),p=hg(fg([l,"optionalAccess",e=>e.html_url]),(()=>""));s.ui.info("Remote Repository:"),s.ui.info(` Status: ${c}`),s.ui.info(` Repository: ${d}`),s.ui.info(` URL: ${p}`),s.response.print({bind_status:c,repo_full_name:d,html_url:p})}))}(i)};function yg(o){const i=o.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"]}});pu(i),pm(i),Hp(i),fu(i),em(i),Nl(i),function(o){o.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. Supported for general Web/App project types, returning an accessible preview URL. Sandbox initialization takes 1-3 minutes. WechatMiniProgram, Agent, Automation, Skill, and AssistantAgent projects are not previewable from the CLI.",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 (only for previewable project types)"},message:{type:"string",description:"Hint message returned instead of preview_url when the project type does not support CLI preview"}}},errors:[{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Unsupported project type for CLI preview",fix:`Preview is not available for MiniProgram, Agent, Automation, Skill, or AssistantAgent projects. Use the Web dashboard: ${Ip().replace(/\/$/,"")}`},{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"}],seeAlso:["coze code deploy","coze code project get"]}}).action((async function(o,i,s){const n=s.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E1000,"Missing projectId: pass <projectId> as argument");const r=Jp([await t.IdeApi.GetVibeProject({project_id:o}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),a={type:Dp(r)};if(Kp.has(r))return void Jp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({type:a.type,message:`Project type '${a.type}' does not support CLI preview. Please visit the Web dashboard: ${Ap(o,r,Jp([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))}`})]);const c=await t.IdeApi.InitSandbox({project_id:o});a.preview_url=c.token?`https://${c.project_host}?token=${c.token}`:`https://${c.project_host}`,Jp([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: ${a.preview_url}`)]),Jp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])}))}(i),Hm(i),Ll(i),Zp(i),cg(i),_g(i)}const bg=async e=>await new Promise((t=>setTimeout(t,e)));function vg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const wg=e=>{if(!e)return;const t=e.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);if(vg([t,"optionalAccess",e=>e[1]]))return(e=>{try{return decodeURIComponent(e)}catch(t){return URIError,e}})(t[1]);const o=e.match(/filename\s*=\s*"([^"]+)"/i);if(vg([o,"optionalAccess",e=>e[1]]))return o[1];const i=e.match(/filename\s*=\s*([^;]+)/i);return vg([i,"optionalAccess",e=>e[1]])?i[1].trim():void 0},Eg=async({url:t,outputPath:o,fetchImpl:i=t=>e.customFetch.fetch(t)})=>{const{buffer:s,response:r}=await(async(t,o)=>{const i=await o(t);if(!i.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download session file: ${i.status} ${i.statusText}`);return{buffer:Buffer.from(await i.arrayBuffer()),response:i}})(t,i),a=o||(e=>{const t=wg((o=e.contentDisposition,i=()=>null,null!=o?o:i()));var o,i;if(t)return t;for(const t of[e.responseUrl,e.requestUrl]){if(!t||!URL.canParse(t))continue;const e=new URL(t),o=n.basename(decodeURIComponent(e.pathname));if(o&&"/"!==o&&"."!==o)return o}return"session-file.bin"})({requestUrl:t,responseUrl:r.url,contentDisposition:r.headers.get("content-disposition")}),c=await La(a,s);return{path:c,filename:n.basename(c),size:s.byteLength,url:t,logid:r.headers.get("x-tt-logid")||void 0}},Cg="1008033";function Ig(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ag=async({baseUrl:t,headers:o,xTTEnv:i})=>{const n=new URL("/api/coze_claw/resource/get_frontier_key",s.normalizeBaseUrl(t));s.appendSearchParams(n,{aid:Cg});const r={...o,...s.getPpeHeaders(i)},a=await e.customFetch.fetch(n.toString(),{method:"GET",headers:r}),c=await s.parseServiceResponseBody(a,{}),l=s.getServiceResponseLogId(a);if(!a.ok)throw new Error(s.formatServiceErrorWithLogId({fallback:`Failed to get frontier key: ${a.status} ${a.statusText}`,logId:l,message:c.msg}));const d=Ig([c,"access",e=>e.data,"optionalAccess",e=>e.access_key]),p=Ig([c,"access",e=>e.data,"optionalAccess",e=>e.device_id]);if(!d||!p)throw new Error(s.formatServiceErrorWithLogId({fallback:"Frontier key response is incomplete",logId:l,message:c.msg}));return{accessKey:d,deviceId:p}};function Sg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const kg=async({filePaths:t,clawId:o,sessionId:i,accessFile:s=r.access,createFileReadStream:c=a.openAsBlob,uploadFile:l})=>{const d=[];for(const r of t){try{await s(r)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${r}${t instanceof Error?` (${t.message})`:""}`)}const t=n.basename(r),a=await l({fileName:t,fileContent:await c(r),clawId:o,sessionId:i}),p=Sg([a,"access",e=>e.data,"optionalAccess",e=>e.file]);if(!Sg([p,"optionalAccess",e=>e.file_uri])||!Sg([p,"optionalAccess",e=>e.file_url]))throw new e.CozeError(e.ErrorCode.E5002,a.msg||`Failed to upload session file: ${r}`);d.push({file_name:p.file_name||t,file_uri:p.file_uri,file_url:p.file_url})}return d},jg=async({filePaths:e,sessionId:t,apiBaseUrl:o,sessionApiBaseUrl:i,sessionSpaceWebId:n,xTTEnv:r,service:a,deps:c})=>{if(!e||0===e.length)return[];const l=Sg([c,"optionalAccess",e=>e.store])||s.createSessionConfigStore(),{sessionClawId:d}=await l.get(),p=d||(await a.getStatus()).clawId;if(!p)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const u=i||o,m=await(async({sessionSpaceWebId:e,baseUrl:t,xTTEnv:o})=>{if(e)return e;try{return(await Ag({baseUrl:t,headers:{},xTTEnv:o})).deviceId}catch(e){return}})({sessionSpaceWebId:n,baseUrl:u,xTTEnv:r}),g=(Sg([c,"optionalAccess",e=>e.createApi])||s.createSessionApiClient)({baseUrl:u,webOrigin:u,xSpaceWebId:m,xTTEnv:r}),h=Sg([c,"optionalAccess",e=>e.uploadFiles])||kg;return await h({filePaths:e,clawId:p,sessionId:t,uploadFile:({fileName:e,fileContent:t,clawId:o,sessionId:i})=>g.uploadFile({fileName:e,fileContent:t,clawId:o,sessionId:i})})};function Pg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const zg=1048576,Tg=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,Rg=({absolutePath:e,root:t})=>{const o=n.relative(t,e);return Boolean(o)&&!o.startsWith("..")&&!n.isAbsolute(o)},xg=async({onWarn:e,shouldWarnInvalidMention:t=()=>!0,statFile:o=r.stat,userInput:i,workTree:s})=>{(e=>{if(e.length>zg)throw new Error("Message input is too long: max 1048576 characters")})(i);const a=[...i.matchAll(Tg)];if(0===a.length)return[{type:"text",text:i}];const c=[],l=n.resolve(s);let d=0;for(const s of a){const r=s.index,a=s[0],p=s[1];r>d&&c.push({type:"text",text:i.slice(d,r)});const u=n.resolve(l,p);let m=!1;if(Rg({absolutePath:u,root:l}))try{(await o(u)).isFile()?m=!0:t(p)&&Pg([e,"optionalCall",e=>e(`Uploading directories is not supported: ${p}`)])}catch(o){t(p)&&Pg([e,"optionalCall",e=>e(`File not found: ${p}`)])}m?c.push({type:"file",absolutePath:u,rawMention:a,relativePath:p}):c.push({type:"text",text:a}),d=r+a.length}return d<i.length&&c.push({type:"text",text:i.slice(d)}),c};const Lg=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},Og=e=>e.includes("/")||e.includes("\\")||e.includes(".")||e.startsWith("."),Dg=async(e,t={})=>{const o=await(async e=>{const t=await Ta(),o=Lg(e),i=Lg(t);return o||i?o&&i?`${o}\n\n${i}`:(n=()=>i,null!=(s=o)?s:n()):null;var s,n})(e);if(!o)return{content:o,filePaths:[]};const i=await xg({onWarn:t.onWarn,shouldWarnInvalidMention:Og,userInput:o,workTree:t.cwd||process.cwd()}),s=[];return{content:Lg(i.map((e=>"text"===e.type?e.text:(s.push(e.absolutePath),""))).join("")),filePaths:s}};const Ug=e=>function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([e,"optionalAccess",e=>e.trim,"call",e=>e(),"access",e=>e.toLowerCase,"call",e=>e()])||"",qg=async({baseUrl:t,xTTEnv:o,fetchImpl:i=e.customFetch.fetch.bind(e.customFetch)})=>{const s={"content-type":"application/json"};o&&(s["x-use-ppe"]="1",s["x-tt-env"]=o);const n=await i(`${(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||{}},Bg=({config:t,mode:o,keyword:i})=>{const s=(({config:t,mode:o})=>{if(!o)return;const i=Ug(o),s=(t.mode_options||[]).find((e=>Ug(e.value)===i||Ug(e.label)===i));if(!s)throw new e.CozeError(e.ErrorCode.E1000,`Podcast mode not found: ${o}`);return s})({config:t,mode:o}),n=Ug(i);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||(Ug(e.label).includes(n)||Ug(e.value).includes(n))))))};
16
+ ***************************************************************************** */var at=function(){return at=Object.assign||function(e){for(var t,o=1,i=arguments.length;o<i;o++)for(var s in t=arguments[o])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},at.apply(this,arguments)};function ct(e,t){var o="function"==typeof Symbol&&e[Symbol.iterator];if(!o)return e;var i,s,n=o.call(e),r=[];try{for(;(void 0===t||t-- >0)&&!(i=n.next()).done;)r.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(o=n.return)&&o.call(n)}finally{if(s)throw s.error}}return r}function lt(e,t,o){if(2===arguments.length)for(var i,s=0,n=t.length;s<n;s++)!i&&s in t||(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return e.concat(i||Array.prototype.slice.call(t))}var dt=function(){return{}};function pt(e){return e}function ut(e){return"object"==typeof e&&null!==e}var mt=Object.prototype;function gt(e){return"[object Array]"===mt.toString.call(e)}function ht(e){return"number"==typeof e}function ft(e){return"string"==typeof e}function _t(e,t){if(!gt(e))return!1;if(0===e.length)return!1;for(var o=0;o<e.length;){if(e[o]===t)return!0;o++}return!1}var yt=function(e,t){if(!gt(e))return e;var o=e.indexOf(t);if(o>=0){var i=e.slice();return i.splice(o,1),i}return e};function bt(e){try{return ft(e)?e:JSON.stringify(e)}catch(e){return"[FAILED_TO_STRINGIFY]:"+String(e)}}var vt="".padStart?function(e,t){return void 0===t&&(t=8),e.padStart(t," ")}:function(e){return e},wt=0,Et=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,lt(["[SDK]",Date.now(),vt(""+wt++)],ct(e),!1))},Ct=0,It=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,lt(["[SDK]",Date.now(),vt(""+Ct++)],ct(e),!1))},At=function(e){return Math.random()<Number(e)},St=function(e,t){return e<Number(t)},kt=function(e){return function(t){for(var o=t,i=0;i<e.length&&o;i++)try{o=e[i](o)}catch(e){Et(e)}return o}};function jt(){var e=function(){for(var e=new Array(16),t=0,o=0;o<16;o++)3&o||(t=4294967296*Math.random()),e[o]=t>>>((3&o)<<3)&255;return e}();return e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){for(var t=[],o=0;o<256;++o)t[o]=(o+256).toString(16).substr(1);var i=0,s=t;return[s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]]].join("")}(e)}var Pt=["init","start","config","beforeDestroy","provide","beforeReport","report","beforeBuild","build","beforeSend","send","beforeConfig"];function zt(e){var t,o,i=e.builder,s=e.createSender,n=e.createDefaultConfig,r=e.createConfigManager,a=e.userConfigNormalizer,c=e.initConfigNormalizer,l=e.validateInitConfig,d={};Pt.forEach((function(e){return d[e]=[]}));var p=!1,u=!1,m=!1,g=[],h=[],f=function(){var e=!1,t={},o=function(e){e.length&&e.forEach((function(e){try{e()}catch(e){}})),e.length=0},i=function(e){t[e]&&t[e].forEach((function(e){o(e[1])})),t[e]=void 0};return{set:function(i,s,n){t[i]?t[i].push([s,n]):t[i]=[[s,n]],e&&o(n)},has:function(e){return!!t[e]},remove:i,removeByEvType:function(e){Object.keys(t).forEach((function(i){t[i]&&t[i].forEach((function(t){t[0]===e&&o(t[1])}))}))},clear:function(){e=!0,Object.keys(t).forEach((function(e){i(e)}))}}}(),_={getBuilder:function(){return i},getSender:function(){return t},getPreStartQueue:function(){return g},init:function(e){if(p)It("already inited");else{if(!(e&&ut(e)&&l(e)))throw new Error("invalid InitConfig, init failed");var i=n(e);if(!i)throw new Error("defaultConfig missing");var a=c(e);if((o=r(i)).setConfig(a),o.onChange((function(){y("config")})),!(t=s(o.getConfig())))throw new Error("sender missing");p=!0,y("init",!0)}},set:function(e){p&&e&&ut(e)&&(y("beforeConfig",!1,e),null==o||o.setConfig(e))},config:function(e){if(p)return e&&ut(e)&&(y("beforeConfig",!1,e),null==o||o.setConfig(a(e))),null==o?void 0:o.getConfig()},provide:function(e,t){_t(h,e)?It("cannot provide "+e+", reserved"):(_[e]=t,y("provide",!1,e))},start:function(){p&&(u||null==o||o.onReady((function(){u=!0,y("start",!0),function(e){var t=e.getPreStartQueue();t.forEach((function(t){return e.build(t)})),t.length=0}(_)})))},report:function(e){if(e){var t=kt(d.beforeReport)(e);if(t){var o=kt(d.report)(t);o&&(u?this.build(o):function(e,t,o){if(t.push(o),!(t.length<500)){var i=t.splice(0,50);e.savePreStartDataToDb&&e.savePreStartDataToDb(i)}}(_,g,o))}}},build:function(e){if(u){var t=kt(d.beforeBuild)(e);if(t){var o=i.build(t);if(o){var s=kt(d.build)(o);s&&this.send(s)}}}},send:function(e){if(u){var o=kt(d.beforeSend)(e);o&&(t.send(o),y("send",!1,o))}},destroy:function(){f.clear(),m=!0,g.length=0,y("beforeDestroy",!0)},on:function(e,t){if("init"===e&&p||"start"===e&&u||"beforeDestroy"===e&&m)try{t()}catch(e){}else d[e]&&d[e].push(t)},off:function(e,t){d[e]&&(d[e]=yt(d[e],t))},destroyAgent:f};return h=Object.keys(_),_;function y(e,t){void 0===t&&(t=!1);for(var o=[],i=2;i<arguments.length;i++)o[i-2]=arguments[i];d[e].forEach((function(e){try{e.apply(void 0,lt([],ct(o),!1))}catch(e){}})),t&&(d[e].length=0)}}var Tt=function(e){var t=function(){var e={},t={},o={set:function(i,s){return e[i]=s,t[i]=bt(s),o},merge:function(i){return e=at(at({},e),i),Object.keys(i).forEach((function(e){t[e]=bt(i[e])})),o},delete:function(i){return delete e[i],delete t[i],o},clear:function(){return e={},t={},o},get:function(e){return t[e]},toString:function(){return at({},t)}};return o}();e.provide("context",t),e.on("report",(function(e){return e.extra||(e.extra={}),e.extra.context=t.toString(),e}))};var Rt=function(){return Date.now()};var xt=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var o=function(e){if(e)return e.__SLARDAR_REGISTRY__||(e.__SLARDAR_REGISTRY__={Slardar:{plugins:[],errors:[],subject:{}}}),e.__SLARDAR_REGISTRY__.Slardar}(function(){if("object"==typeof window&&ut(window))return window}());o&&(o.errors||(o.errors=[]),o.errors.push(e))},Lt="custom",Ot=function(e){var t=function(o){var i=function(e){if(e&&ut(e)&&e.name&&ft(e.name)){var t={name:e.name,type:"event"};if("metrics"in e&&ut(e.metrics)){var o=e.metrics,i={};for(var s in o)ht(o[s])&&(i[s]=o[s]);t.metrics=i}if("categories"in e&&ut(e.categories)){var n=e.categories,r={};for(var s in n)r[s]=bt(n[s]);t.categories=r}return"attached_log"in e&&ft(e.attached_log)&&(t.attached_log=e.attached_log),t}}(o);if(i){var s=function(e){var t;if("object"==typeof window&&window.__perfsee__){var o={};return null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,o,e),o.stack}}(t);s&&(i.stacks=s),e.report({ev_type:Lt,payload:i,extra:{timestamp:Rt()}})}};e.provide("sendEvent",t),e.provide("sendLog",(function(t){var o=function(e){if(e&&ut(e)&&e.content&&ft(e.content)){var t={content:bt(e.content),type:"log",level:"info"};if("level"in e&&(t.level=e.level),"extra"in e&&ut(e.extra)){var o=e.extra,i={},s={};for(var n in o)ht(o[n])?i[n]=o[n]:s[n]=bt(o[n]);t.metrics=i,t.categories=s}return"attached_log"in e&&ft(e.attached_log)&&(t.attached_log=e.attached_log),t}}(t);o&&e.report({ev_type:Lt,payload:o,extra:{timestamp:Rt()}})}))},Dt=function(e,t){var o=e.common||{};return o.sample_rate=t,e.common=o,e},Ut=function(e,t,o,i,s){return e?(n=s(i,t),function(){return n}):function(){return o(t)};var n},qt=function(e,t,o,i){var s=function(e,t,o){for(var i,s=ct(t.split(".")),n=s[0],r=s.slice(1);e&&r.length>0;)e=e[n],n=(i=ct(r))[0],r=i.slice(1);if(e)return o(e,n)}(e,t,(function(e,t){return e[t]}));return void 0!==s&&function(e,t,o){switch(o){case"eq":return _t(t,e);case"neq":return!_t(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)}}))}(i,"boolean"==typeof s?"bool":ht(s)?"number":"string"),o)},Bt=function(e,t){try{return"rule"===t.type?qt(e,t.field,t.op,t.values):"and"===t.type?t.children.every((function(t){return Bt(e,t)})):t.children.some((function(t){return Bt(e,t)}))}catch(e){return xt(e),!1}},Mt=function(e,t,o,i,s){if(!t)return pt;var n=t.sample_rate,r=t.include_users,a=t.sample_granularity,c=t.rules,l=t.r,d=void 0===l?Math.random():l;if(_t(r,e))return function(e){return Dt(e,1)};var p="session"===a,u=Ut(p,n,o,d,i),m=function(e,t,o,i,s,n){var r={};return Object.keys(e).forEach((function(a){var c=e[a],l=c.enable,d=c.sample_rate,p=c.conditional_sample_rules;l?(r[a]={enable:l,sample_rate:d,effectiveSampleRate:d*o,hit:Ut(t,d,i,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:Ut(t,r,i,s,n),effectiveSampleRate:r*o,filter:a}})))):r[a]={enable:l,hit:function(){return!1},sample_rate:0,effectiveSampleRate:0}})),r}(c,p,n,o,d,i);return function(e){var t;if(!u())return p&&s[0](),!1;if(!(e.ev_type in m))return Dt(e,n);if(!m[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 o=m[e.ev_type],i=o.conditional_hit_rules;if(i)for(var r=0;r<i.length;r++)if(Bt(e,i[r].filter))return!!i[r].hit()&&Dt(e,i[r].effectiveSampleRate);return o.hit()?Dt(e,o.effectiveSampleRate):((!i||!i.length)&&p&&s[1](e.ev_type),!1)}},Nt={build:function(e){return{ev_type:e.ev_type,payload:e.payload,common:at(at({},e.extra||{}),e.overrides||{})}}},$t={sample_rate:1,include_users:[],sample_granularity:"session",rules:{}};function Gt(e){var t,o;try{for(var i=function(e){var t="function"==typeof Symbol&&Symbol.iterator,o=t&&e[t],i=0;if(o)return o.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(["userId","deviceId","sessionId","env"]),s=i.next();!s.done;s=i.next()){var n=s.value;e[n]||delete e[n]}}catch(e){t={error:e}}finally{try{s&&!s.done&&(o=i.return)&&o.call(i)}finally{if(t)throw t.error}}return e}function Ft(e){return Gt(at({},e))}function Vt(e){return ut(e)&&"bid"in e&&"transport"in e}function Wt(e){return Gt(at({},e))}var Ht=function(e,t){return void 0===t&&(t="/monitor_browser/collect/batch/"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Jt=function(e,t){return void 0===t&&(t="/monitor_web/settings/browser-settings"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Kt=function(e){var t,o,i=e,s={},n=dt,r=dt;return{getConfig:function(){return i},setConfig:function(e){return s=at(at({},s),e||{}),a(),t||(t=e,i.useLocalConfig||!i.bid?(o={},n()):function(e,t,o,i){if(!e.get)return i({});e.get({withCredentials:!0,url:Jt(t)+"?bid="+o+"&store=1",success:function(e){i(e.data||{})},fail:function(){i({sample:{sample_rate:.001}})}})}(i.transport,i.domain,i.bid,(function(e){o=function(e){if(!e)return{};var t=e.sample,o=e.timestamp,i=e.quota_rate,s=void 0===i?1:i;if(!t)return{};var n=t.sample_rate,r=t.sample_granularity,a=void 0===r?"session":r,c=t.include_users,l=t.rules;return{sample:{include_users:c,sample_rate:n*s,sample_granularity:a,rules:(void 0===l?[]:l).reduce((function(e,t){var o=t.name,i=t.enable,s=t.sample_rate,n=t.conditional_sample_rules;return e[o]={enable:i,sample_rate:s,conditional_sample_rules:n},e}),{})},serverTimestamp:o}}(e),a(),n()}))),i},onChange:function(e){r=e},onReady:function(e){n=e,o&&n()}};function a(){var t=at(at(at({},e),o||{}),s);t.sample=Qt(Qt(e.sample,null==o?void 0:o.sample),s.sample),i=t,r()}};function Qt(e,t){if(!e||!t)return e||t;var o=at(at({},e),t);return o.include_users=lt(lt([],ct(e.include_users||[]),!1),ct(t.include_users||[]),!1),o.rules=lt(lt([],ct(Object.keys(e.rules||{})),!1),ct(Object.keys(t.rules||{})),!1).reduce((function(o,i){var s,n;return i in o||(i in(e.rules||{})&&i in(t.rules||{})?(o[i]=at(at({},e.rules[i]),t.rules[i]),o[i].conditional_sample_rules=lt(lt([],ct(e.rules[i].conditional_sample_rules||[]),!1),ct(t.rules[i].conditional_sample_rules||[]),!1)):o[i]=(null===(s=e.rules)||void 0===s?void 0:s[i])||(null===(n=t.rules)||void 0===n?void 0:n[i])),o}),{}),o}var Yt=function(e){e.on("report",(function(t){return function(e,t){var o=t||{},i=o.version,s=o.name,n={url:"",protocol:"",domain:"",path:"",query:"",timestamp:Date.now(),sdk_version:i||"2.1.8",sdk_name:s||"SDK_BASE"};return at(at({},e),{extra:at(at({},n),e.extra||{})})}(t,e.config())}))},Zt=function(e){e.on("beforeBuild",(function(t){return function(e,t){var o={};return o.bid=t.bid,o.pid=t.pid,o.view_id=t.viewId,o.user_id=t.userId,o.device_id=t.deviceId,o.session_id=t.sessionId,o.release=t.release,o.env=t.env,at(at({},e),{extra:at(at({},o),e.extra||{})})}(t,e.config())}))};var Xt=function(e){return{bid:"",pid:"",viewId:(t="_",t+"_"+Date.now()),userId:jt(),deviceId:jt(),sessionId:jt(),domain:"mon.zijieapi.com",release:"",env:"production",sample:$t,plugins:{},transport:{get:dt,post:dt},useLocalConfig:!1};var t},eo=function(e){var t=void 0===e?{}:e,o=t.createSender,i=void 0===o?function(e){return function(e){return rt(e)}({size:20,endpoint:Ht(e.domain),transport:e.transport})}:o,s=t.builder,n=void 0===s?Nt:s,r=t.createDefaultConfig,a=zt({validateInitConfig:Vt,initConfigNormalizer:Ft,userConfigNormalizer:Wt,createSender:i,builder:n,createDefaultConfig:void 0===r?Xt:r,createConfigManager:Kt});return Tt(a),Zt(a),Yt(a),function(e){e.on("init",(function(){var t=[],o=function(o){o.forEach((function(o){var i=o.name;_t(t,i)||(t.push(i),o.setup(e),e.destroyAgent.set(i,i,[function(){t=yt(t,i),o.tearDown&&o.tearDown()}]))}))};e.provide("applyIntegrations",o);var i=e.config();i&&i.integrations&&o(i.integrations)}))}(a),function(e){try{"object"==typeof window&&ut(window)&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__.push(e)}catch(e){}}(a),a},to=function(e){void 0===e&&(e={});var t=eo(e);return function(e){e.on("start",(function(){var t=e.config(),o=t.userId,i=t.sample,s=Mt(o,i,At,St,[function(){e.destroy()},function(t){e.destroyAgent.removeByEvType(t)}]);e.on("build",s)}))}(t),Ot(t),t}();const oo=nt("slardar:transport"),io=()=>{};function so(e){const{url:t,method:o,data:i,success:s=io,fail:n=io,getResponseText:r=io}=e;if(oo("Making %s request to %s",o,t),i&&oo("Request data: %s",i.slice(0,200)),!t||"string"!=typeof t){const e=new Error(`Invalid URL: ${t}`);return oo("Invalid URL provided: %o",t),void n(e)}try{const e=new URL(t);oo("Parsed URL - protocol: %s, hostname: %s, port: %s, path: %s",e.protocol,e.hostname,e.port,e.pathname);const a="https:"===e.protocol,c=(a?d.request:l.request)({hostname:e.hostname,port:e.port,path:e.pathname+e.search,method:o,headers:{"Content-Type":"application/json",...i&&{"Content-Length":Buffer.byteLength(i)}}},(e=>{oo("Response callback triggered: status=%s",e.statusCode);let t="";e.on("data",(e=>{oo("Response data chunk received: %s bytes",e.length),t+=e.toString()})),e.on("end",(()=>{oo("Response end event fired"),oo("Response received: status=%s, body=%s",e.statusCode,t.slice(0,200)),r(t);try{if(e.statusCode&&e.statusCode>=400)oo("Request failed with status %s: %s",e.statusCode,t),n(new Error(t||e.statusMessage||"Request failed"));else if(t){const e=JSON.parse(t);oo("Request succeeded"),s(e)}else oo("Request succeeded with empty response"),s({})}catch(e){oo("Failed to parse response: %s",e.message),n(e)}}))}));c.on("error",(e=>{oo("Request error: %s",e.message),n(e)})),c.on("timeout",(()=>{oo("Request timeout"),c.destroy(),n(new Error("Request timeout"))})),i&&c.write(i),c.end()}catch(e){oo("Exception during request: %s",e.message),n(e)}}function no(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ro=nt("slardar:reporter");class ao{constructor(){ao.prototype.__init.call(this),ao.prototype.__init2.call(this)}__init(){this.initialized=!1}__init2(){this.client=to}setup(e){var t,o;if(this.initialized)ro("Already initialized, skipping setup");else try{ro("Initializing Slardar with config:",{bid:e.bid,release:e.release,env:e.env,userId:e.userId,projectId:e.projectId});const i={get(e){oo("Transport GET called: %s",e.url),so({method:"GET",...e})},post({url:e,data:t}){oo("Transport POST called: %s",e),so({method:"POST",url:e,data:t?"string"==typeof t?t:JSON.stringify(t):void 0})}};this.client.init({bid:e.bid,transport:i,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,o=()=>!1,null!=t?t:o()),domain:e.domain,sample:{sample_rate:1,include_users:[],sample_granularity:"session",rules:{}}}),this.client.on("send",(e=>{ro("send hook called for event: %s",no([e,"optionalAccess",e=>e.ev_type])||"unknown")})),this.client.start(),this.initialized=!0,ro("Slardar initialized successfully")}catch(e){ro("Failed to initialize:",e)}}ensureInitialized(){return!!this.initialized||(ro("Not initialized, call setup() first"),!1)}sendEvent(e,t,o){if(this.ensureInitialized())try{ro("Sending event:",{name:e,metrics:t,categories:o});const i=t?Object.fromEntries(Object.entries(t).filter((([,e])=>void 0!==e))):void 0,s=o?Object.fromEntries(Object.entries(o).filter((([,e])=>void 0!==e))):void 0;no([this,"access",e=>e.client,"access",e=>e.sendEvent,"optionalCall",t=>t({name:e,metrics:i,categories:s})])}catch(e){ro("Failed to send event:",e)}}sendLog(e,t,o){if(this.ensureInitialized())try{ro("Sending log:",{level:e,message:t,extra:o}),this.sendEvent("cli_log",void 0,{level:e,message:t,...o})}catch(e){ro("Failed to send log:",e)}}reportError(e,t,o){if(this.ensureInitialized())try{const i={ev_type:"js_error",payload:{error:{name:e.name,message:e.message,stack:e.stack},breadcrumbs:[],extra:t,source:o||{type:"manual"}}};ro("Reporting JS error:",{name:e.name,message:e.message.slice(0,100),stack:no([e,"access",e=>e.stack,"optionalAccess",e=>e.slice,"call",e=>e(0,200)]),extra:t,source:o}),this.client.report(i),ro("JS error reported successfully")}catch(e){ro("Failed to report error:",e)}}setContext(e,t){this.ensureInitialized()&&no([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.set,"call",o=>o(e,t)])}mergeContext(e){this.ensureInitialized()&&(ro("Merging context:",e),no([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.merge,"call",t=>t(e)]))}deleteContext(e){this.ensureInitialized()&&no([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.delete,"call",t=>t(e)])}clearContext(){this.ensureInitialized()&&no([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.clear,"call",e=>e()])}updateConfig(e){if(this.ensureInitialized())try{ro("Updating config:",e),this.client.config({userId:e.userId,release:e.release,sessionId:e.sessionId,env:e.env})}catch(e){ro("Failed to update config:",e)}}async flush(e=1500){this.ensureInitialized()&&(ro("Flushing Slardar data..."),no([this,"access",e=>e.client,"access",e=>e.getSender,"optionalCall",e=>e(),"optionalAccess",e=>e.flush,"call",e=>e()]),ro("Waiting %dms for events to be sent...",e),await new Promise((t=>setTimeout(t,e))),ro("Slardar data flushed"))}getRawClient(){return this.client}}const co=new ao;function lo(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const po="cli_start",uo="cli_command",mo="cli_command_complete",go="cli_error",ho="network_request",fo="file_operation",_o={cliStart:e=>({name:po,metrics:{duration:0,...e}}),cliCommand:(e,t)=>({name:uo,categories:{command:e,args:lo([t,"optionalAccess",e=>e.args]),status:"running",...lo([t,"optionalAccess",e=>e.categories])},metrics:lo([t,"optionalAccess",e=>e.metrics])}),cliCommandComplete:(e,t,o,i)=>({name:mo,categories:{command:e,args:lo([i,"optionalAccess",e=>e.args]),status:t?"success":"fail",...lo([i,"optionalAccess",e=>e.categories])},metrics:{duration:o,...lo([i,"optionalAccess",e=>e.errorCode])&&{errorCode:i.errorCode}}}),networkRequest:(e,t)=>({name:ho,categories:{url:e,method:lo([t,"optionalAccess",e=>e.method])||"GET",statusCode:lo([t,"optionalAccess",e=>e.statusCode,"optionalAccess",e=>e.toString,"call",e=>e()]),status:lo([t,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:lo([t,"optionalAccess",e=>e.duration])}}),fileOperation:(e,t,o)=>({name:fo,categories:{operation:e,filePath:t,status:lo([o,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:lo([o,"optionalAccess",e=>e.duration]),fileSize:lo([o,"optionalAccess",e=>e.fileSize])}}),cliError:(e,t)=>({name:go,categories:{errorName:e.name,errorMessage:e.message,stack:e.stack||"",...t},metrics:{errorCode:1}})};function yo(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function bo(e){return(...t)=>{try{const o=e(...t);return o instanceof Promise?o.catch((()=>{})):o}catch(e){}}}const vo=bo((()=>{var e,t;co.setup({bid:"coze_cli",release:Z,env:"production",userId:process.env.USER||"",useLocalConfig:!1,domain:"mon.zijieapi.com"}),co.mergeContext({platform:process.platform,callerPlatform:(e=process.env.COZE_CLI_PLATFORM,t=()=>"unknown",null!=e?e:t()),nodeVersion:process.version,cliVersion:Z})})),wo=bo((e=>{const t=_o.cliCommand(e);co.sendEvent(t.name,t.metrics,t.categories)})),Eo=bo(((e,t,o,i)=>{const s=_o.cliCommandComplete(e,t,o,{errorCode:yo([i,"optionalAccess",e=>e.errorCode])});co.sendEvent(s.name,s.metrics,s.categories)})),Co=bo(((e,t)=>{co.reportError(e,t,{type:"cli",data:t})})),Io=bo((async()=>{await co.flush()}));async function Ao(e,t){if(e.config.disableTelemetry)return void await t();vo();const o=function(e){if(e.commandName)return e.commandName;const t=[];for(const o of e.argv){if(o.startsWith("-"))break;t.push(o)}return t.join(" ")||"unknown"}(e);wo(o);const i=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()-i;try{n?Eo(o,!0,e):(s&&Co(s,{command:o}),Eo(o,!1,e)),await Io()}catch(e){}}}function So(e,t){return null!=e?e:t()}const ko=s.getGlobalLogsDir();class jo{__init(){this.fileStream=null}__init2(){this.writeError=!1}constructor(e={}){jo.prototype.__init.call(this),jo.prototype.__init2.call(this),this.format=So(e.format,(()=>"text")),this.printToStderr=So(e.printToStderr,(()=>!1)),this.tags=So(e.tags,(()=>({}))),this.startTime=Date.now();const t=So(e.logFile,(()=>this.getDefaultLogPath()));this.logFile=t;try{this.ensureLogDir(),this.rotateLogFiles(),this.fileStream=a.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 n.join(ko,`${e}-${t}.log`)}ensureLogDir(){a.existsSync(ko)||a.mkdirSync(ko,{recursive:!0})}rotateLogFiles(){try{const e=a.readdirSync(ko).filter((e=>e.endsWith(".log"))).map((e=>({name:e,path:n.join(ko,e),mtime:a.statSync(n.join(ko,e)).mtime.getTime()}))).sort(((e,t)=>t.mtime-e.mtime));e.length>=10&&e.slice(9).forEach((e=>{try{a.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,o,i=this.printToStderr){const s=this.formatEntry(e,t,o);if(this.fileStream)try{this.fileStream.write(`${s}\n`)}catch(e){!this.writeError&&i&&(process.stderr.write("Warning: Log write failed\n"),this.writeError=!0)}i&&process.stderr.write(`${s}\n`)}formatEntry(e,t,o){const i=(new Date).toISOString(),s=Date.now()-this.startTime;if("json"===this.format){const n={level:e,timestamp:i,delta:s,...this.tags,message:t};return o.length>0&&(n.args=o),JSON.stringify(n)}const n=Object.entries(this.tags).map((([e,t])=>`${e}=${t}`)).join(" "),r=o.length>0?` ${o.map(String).join(" ")}`:"";return`${e.toUpperCase().padEnd(7)} [${i}] +${s}ms ${n} ${t}${r}`}close(){if(this.fileStream)try{this.fileStream.end()}catch(e){}}}function Po(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const zo=new Set(["authorization","cookie","set-cookie"]),To=/(^|_|-)(token|secret|password|authorization|cookie)(_|-|$)/i,Ro=Symbol("request-debug-json-parse-fallback");let xo=null,Lo=!1,Oo=!1;const Do=e.customFetch.fetch.bind(e.customFetch),Uo=e=>"[object Object]"===Object.prototype.toString.call(e),qo=e=>{try{return JSON.stringify(e)}catch(t){return JSON.stringify(String(e))}},Bo=e=>{if("string"!=typeof e)return"***";const t=e.trim(),o=Po([/^bearer\s+/i,"access",e=>e.exec,"call",e=>e(t),"optionalAccess",e=>e[0]]);return o?`${o}***`:"***"},Mo=(e,t)=>t&&To.test(t)?Bo(e):Array.isArray(e)?e.map((e=>Mo(e))):Uo(e)?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,Mo(t,e)]))):e,No=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?No(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)])))},$o=(e,t)=>e[t.toLowerCase()],Go=(e,t,o="binary")=>{const i=(e=>"string"==typeof e?p.Buffer.byteLength(e):p.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=[o];return t&&s.push(t),"number"==typeof i&&s.push(`${i} bytes`),`[${s.join("; ")}]`},Fo=(t,o)=>{if(null==t||""===t)return"<empty>";const i=Po([$o,"call",e=>e(o,"content-type"),"optionalAccess",e=>e.toLowerCase,"call",e=>e()]);if(Po([i,"optionalAccess",e=>e.includes,"call",e=>e("multipart/form-data")]))return Go(t,i,"multipart");if(t instanceof URLSearchParams)return qo(Mo(Object.fromEntries(Array.from(t.entries()))));if(p.Buffer.isBuffer(t)||t instanceof Uint8Array||t instanceof ArrayBuffer||"undefined"!=typeof Blob&&t instanceof Blob)return Go(t,i);if("string"==typeof t){const o=(t=>{const o=e.safeJsonParse(t,Ro);if(o!==Ro)return o})(t);return void 0!==o?qo(Mo(o)):JSON.stringify(t)}return Array.isArray(t)||Uo(t)?qo(Mo(t)):Go(t,i,typeof t)},Vo=(e,t)=>{try{return new URL(e,t).toString()}catch(o){return t?`${t}${e}`:e}},Wo=e=>{const t=No(e);return t["x-tt-logid"]||t["x-tt-log-id"]||t.logid||""},Ho=e=>(e||"GET").toUpperCase(),Jo=e=>{Lo&&xo&&(xo instanceof jo?xo.debugFileOnly(e):xo.debug(e))},Ko=({method:e,url:t,headers:o,body:i})=>{const s=No(o);Jo(`[DBG][HTTP][REQ] ${e} ${t}\nheaders: ${qo((e=>Object.fromEntries(Object.entries(e).map((([e,t])=>[e,zo.has(e)?Bo(t):t]))))(s))}\nbody: ${Fo(i,s)}`)},Qo=({method:e,url:t,status:o,logId:i})=>{Jo(`[DBG][HTTP][RES] ${e} ${t} status=${o} logid=${i||"-"}`)},Yo=({method:e,url:t,status:o,logId:i,message:s})=>{const n=(a=()=>"ERR",null!=(r=o)?r:a());var r,a;const c=s?` error=${JSON.stringify(s)}`:"";Jo(`[DBG][HTTP][ERR] ${e} ${t} status=${n} logid=${i||"-"}${c}`)},Zo=(e,t)=>t&&"body"in t?t.body:"object"==typeof e&&e&&"body"in e&&null!==e.body?"[request body stream]":void 0,Xo=()=>{e.axiosInstance.interceptors.request.use((e=>((e=>{const t=Ho(e.method),o=Vo(e.url||"",e.baseURL),i=No(e.headers);Ko({method:t,url:o,headers:i,body:e.data})})(e),e))),e.axiosInstance.interceptors.response.use((e=>((e=>{const t=Ho(Po([e,"access",e=>e.config,"optionalAccess",e=>e.method])),o=Vo(Po([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",Po([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Qo({method:t,url:o,status:e.status,logId:Wo(e.headers)})})(e),e)),(e=>((e=>{const t=Ho(Po([e,"access",e=>e.config,"optionalAccess",e=>e.method])),o=Vo(Po([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",Po([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Yo({method:t,url:o,status:Po([e,"access",e=>e.response,"optionalAccess",e=>e.status]),logId:Wo(Po([e,"access",e=>e.response,"optionalAccess",e=>e.headers])),message:e.message})})(e),Promise.reject(e))))},ei=()=>{e.customFetch.fetch=async(t,o)=>{const i=((e,t)=>Po([t,"optionalAccess",e=>e.method])?Ho(t.method):"object"==typeof e&&e&&"method"in e&&"string"==typeof e.method?Ho(e.method):"GET")(t,o),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,o);Ko({method:i,url:s,headers:n,body:Zo(t,o)});try{const e=await Do(t,o);return Qo({method:i,url:s,status:e.status,logId:Wo(e.headers)}),e}catch(e){throw Yo({method:i,url:s,message:e instanceof Error?e.message:String(e)}),e}}};function ti(e,t){return null!=e?e:t()}function oi(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}var ii;!function(e){e.AUTHORIZATION_PENDING="authorization_pending";e.SLOW_DOWN="slow_down";e.ACCESS_DENIED="access_denied";e.EXPIRED_TOKEN="expired_token"}(ii||(ii={}));const si=e=>new Promise((t=>setTimeout(t,e))),ni=e.createRequestClient({baseURL:"https://api.coze.com",useDefaultPlugins:!0,plugins:[{name:"oauth-error-handler",onError:t=>{if(e.isHttpError(t))throw t;const o=t,i=ti(oi([o,"access",e=>e.response,"optionalAccess",e=>e.data]),(()=>({}))),s=i.error_description||i.error||o.message,n={status:oi([o,"access",e=>e.response,"optionalAccess",e=>e.status]),code:i.error,config:o.config,response:o.response,data:i};throw new e.HttpError(ti(s,(()=>"OAuth request failed")),n)}}]});async function ri(e){return(await ni.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}function ai(e,t){return null!=e?e:t()}const ci=async(t,o)=>{const i=process.env.HTTP_PROXY||process.env.http_proxy,s=process.env.HTTPS_PROXY||process.env.https_proxy;if(s||i){const o=new u.EnvHttpProxyAgent;e.customFetch.setDispatcher(o);const{ProxyAgent:n}=await import("proxy-agent"),r=new n;e.axiosInstance$1.defaults.proxy=!1,ni.defaults.proxy=!1,e.axiosInstance$1.defaults.httpAgent=r,e.axiosInstance$1.defaults.httpsAgent=r,ni.defaults.httpAgent=r,ni.defaults.httpsAgent=r,t.ui.debug(`Proxy enabled via ProxyAgent (honors NO_PROXY): http=${ai(i,(()=>"-"))}, https=${ai(s,(()=>"-"))}`)}await o()};let li=()=>{},di=null;const pi=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ui=(e,t)=>{return pi(o=e)&&"function"==typeof o.set?(Object.entries(t).forEach((([t,o])=>{e.set(t,o)})),e):{...pi(e)?e:{},...t};var o},mi=t=>{li=t,null===di&&(di=e.axiosInstance$1.interceptors.request.use((t=>{const o=s.getCozeAccountHeaders(li());return 0!==Object.keys(o).length&&s.shouldInjectCozeAccountHeader((t=>{const o=t.url;if(!o)return"";try{return new URL(o,t.baseURL||e.axiosInstance$1.defaults.baseURL).toString()}catch(e){return""}})(t))?(t.headers=ui(t.headers,o),t):t})))};async function gi(t,o){mi((()=>t.config.organizationId)),s.installScopedCozeAccountFetchHeader({getOrganizationId:()=>t.config.organizationId});const i=await t.auth.getValidAccessToken();e.axiosInstance$1.defaults.baseURL=t.config.apiBaseUrl;const n=`Bearer ${i}`;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 o()}function hi(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,o){let i=-1;return function s(n){if(n<=i)return Promise.reject(new Error("next() called multiple times"));i=n;let r=e[n];n===e.length&&(r=o);if(!r)return Promise.resolve();try{return Promise.resolve(r(t,s.bind(null,n+1)))}catch(e){return Promise.reject(e)}}(0)}}var fi,_i,yi,bi,vi,wi,Ei,Ci,Ii,Ai,Si,ki,ji,Pi,zi,Ti,Ri,xi,Li,Oi,Di,Ui,qi,Bi,Mi,Ni,$i,Gi,Fi,Vi,Wi,Hi,Ji,Ki,Qi,Yi,Zi,Xi,es,ts,os,is,ss,ns,rs,as,cs,ls,ds,ps,us,ms,gs,hs,fs,_s;function ys(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e.app="app";e.pat="pat"}(fi||(fi={})),function(e){e.can_apply2="CanApply";e.already_applied2="AlreadyApplied";e.joined4="Joined";e.deny3="Deny"}(_i||(_i={})),function(e){e.processing="Processing";e.approved="Approved";e.rejected="Rejected";e.auto_approved="AutoApproved"}(yi||(yi={})),function(e){e.normal="Normal";e.connector="Connector";e.privilege="Privilege"}(bi||(bi={})),function(e){e.auth_app="AuthApp";e.on_behalf_of_user="OnBehalfOfUser"}(vi||(vi={})),function(e){e.password="Password";e.sms="Sms";e.email="Email";e.unknown3="Unknown"}(wi||(wi={})),function(e){e.email2="Email";e.phone="Phone";e.unknown4="Unknown"}(Ei||(Ei={})),function(e){e.authorized="authorized";e.unauthorized="unauthorized";e.expired4="expired"}(Ci||(Ci={})),function(e){e.api_key="api_key";e.wechat_official="wechat_official";e.oauth_2="oauth2"}(Ii||(Ii={})),function(e){e.noncertificated="Noncertificated";e.certificated="Certificated"}(Ai||(Ai={})),function(e){e.uncertified="Uncertified";e.personal_certification="PersonalCertification";e.enterprise_certification="EnterpriseCertification"}(Si||(Si={})),function(e){e.obo="Obo";e.app_auth="AppAuth";e.personal_access_token="PersonalAccessToken"}(ki||(ki={})),function(e){e.legacy="Legacy";e.web_backend="WebBackend";e.single_page_or_native="SinglePageOrNative";e.terminal="Terminal";e.service="Service"}(ji||(ji={})),function(e){e.bot_editor="BotEditor";e.bot_developer="BotDeveloper";e.bot_operator="BotOperator"}(Pi||(Pi={})),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"}(zi||(zi={})),function(e){e.visitors_prohibited="VisitorsProhibited";e.guest_prohibited_by_invited_user_enterprise2="GuestProhibitedByInvitedUserEnterprise";e.prohibited_by_custom_people_management="ProhibitedByCustomPeopleManagement"}(Ti||(Ti={})),function(e){e.dev2="DEV";e.prod2="PROD"}(Ri||(Ri={})),function(e){e._1="1";e._30="30";e._90="90";e._180="180";e._365="365";e.customize="customize";e.permanent="permanent"}(xi||(xi={})),function(e){e._12="1";e._302="30";e._902="90";e._1802="180";e._3652="365";e.customize2="customize";e.permanent2="permanent"}(Li||(Li={})),function(e){e.aes_256_gcm="AES-256-GCM"}(Oi||(Oi={})),function(e){e.conversation="Conversation";e.unknown="Unknown"}(Di||(Di={})),function(e){e.active3="Active";e.inactive="Inactive"}(Ui||(Ui={})),function(e){e.cloud_kms="CloudKMS",e.default="Default";e.unknown2="Unknown"}(qi||(qi={})),function(e){e.user_custom2="user_custom";e.consumer3="consumer"}(Bi||(Bi={})),function(e){e.volcano="Volcano";e.coze_team="CozeTeam"}(Mi||(Mi={})),function(e){e.super_admin="SuperAdmin";e.admin="Admin";e.member="Member";e.guest="Guest"}(Ni||(Ni={})),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"}($i||($i={})),function(e){e.string="String";e.boolean="Boolean";e.integer="Integer";e.string_list="StringList"}(Gi||(Gi={})),function(e){e.must_handle="MustHandle";e.no_need_handle="NoNeedHandle"}(Fi||(Fi={})),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"}(Vi||(Vi={})),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"}(Wi||(Wi={})),function(e){e.confirming2="Confirming";e.joined3="Joined";e.rejected3="Rejected";e.revoked2="Revoked";e.expired3="Expired";e.deny2="Deny"}(Hi||(Hi={})),function(e){e.confirming="Confirming";e.joined2="Joined";e.rejected2="Rejected";e.revoked="Revoked";e.expired2="Expired"}(Ji||(Ji={})),function(e){e.can_join="CanJoin";e.guest_prohibited_by_enterprise="GuestProhibitedByEnterprise";e.guest_prohibited_by_invited_user_enterprise="GuestProhibitedByInvitedUserEnterprise"}(Ki||(Ki={})),function(e){e.can_apply="CanApply";e.already_applied="AlreadyApplied";e.joined="Joined";e.expired="Expired";e.deny="Deny"}(Qi||(Qi={})),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";e.coze_team_advanced="CozeTeamAdvanced";e.coze_team_pro="CozeTeamPro";e.coze_team_ultra="CozeTeamUltra"}(Yi||(Yi={})),function(e){e.user_custom_only="user_custom_only";e.all2="all"}(Zi||(Zi={})),function(e){e.system="system";e.custom="custom"}(Xi||(Xi={})),function(e){e.not_in_enterprise="NotInEnterprise";e.prohibited_by_custom_people_management2="ProhibitedByCustomPeopleManagement"}(es||(es={})),function(e){e.can_apply3="CanApply";e.already_applied3="AlreadyApplied";e.joined5="Joined";e.deny4="Deny"}(ts||(ts={})),function(e){e.super_admin2="SuperAdmin";e.admin2="Admin";e.member2="Member";e.guest2="Guest"}(os||(os={})),function(e){e.member_joining_auto_approved="MemberJoiningAutoApproved"}(is||(is={})),function(e){e.string2="String";e.boolean2="Boolean";e.integer2="Integer";e.string_list2="StringList"}(ss||(ss={})),function(e){e.developer="developer";e.consumer2="consumer"}(ns||(ns={})),function(e){e.all="all";e.owned="owned";e.others="others"}(rs||(rs={})),function(e){e.enterprise_member="EnterpriseMember";e.enterprise_guest="EnterpriseGuest"}(as||(as={})),function(e){e.not_created="NotCreated";e.enabled="Enabled";e.disabled="Disabled"}(cs||(cs={})),function(e){e.not_created2="NotCreated";e.not_support_not_supabase="NotSupportNotSupabase";e.enabled2="Enabled";e.disabled2="Disabled";e.not_support_project_type="NotSupportProjectType"}(ls||(ls={})),function(e){e.production="Production";e.development="Development"}(ds||(ds={})),(ps||(ps={})).skill="skill",function(e){e.dev="dev";e.prod="prod"}(us||(us={})),function(e){e.user_custom="user_custom";e.coze_default="coze_default";e.consumer="consumer"}(ms||(ms={})),function(e){e.active2="Active";e.deactive="Deactive"}(gs||(gs={})),function(e){e.active="active";e.deactivated="deactivated";e.offboarded="offboarded"}(hs||(hs={})),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";e.enterprise_member_list="enterprise_member_list";e.organization_member_list="organization_member_list"}(fs||(fs={})),function(e){e.root_user="RootUser";e.basic_user="BasicUser"}(_s||(_s={}));class bs{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){bs.prototype.__init.call(this),bs.prototype.__init2.call(this),this.request=ys([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=ys([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}CreatePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/create_personal_access_token_and_permission"),s={name:o.name,expire_at:o.expire_at,duration_day:o.duration_day,organization_id:o.organization_id,workspace_permission:o.workspace_permission,account_permission:o.account_permission,workspace_permission_v2:o.workspace_permission_v2,enterprise_permission:o.enterprise_permission},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}UpdatePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/update_personal_access_token_and_permission"),s={workspace_permission:o.workspace_permission,account_permission:o.account_permission,workspace_permission_v2:o.workspace_permission_v2,enterprise_permission:o.enterprise_permission,id:o.id,name:o.name},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}DeletePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/delete_personal_access_token_and_permission"),s={id:o.id};return this.request({url:i,method:"POST",data:s},t)}ListPersonalAccessTokens(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/pat/list_personal_access_tokens"),s={organization_id:o.organization_id,page:o.page,size:o.size,search_option:o.search_option};return this.request({url:i,method:"GET",params:s},t)}GetPersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/get_personal_access_token_and_permission"),s={id:o.id};return this.request({url:i,method:"GET",params:s},t)}ListPersonalAccessTokenSupportPermissions(e,t){const o=this.genBaseURL("/api/permission_api/pat/list_personal_access_token_support_permissions");return this.request({url:o,method:"GET"},t)}CheckPersonalAccessTokenInWorkspace(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/check_personal_access_token_in_workspace"),s={workspace_id:o.workspace_id};return this.request({url:i,method:"GET",params:s},t)}AddCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/add_collaborator"),s={collaborator_types:o.collaborator_types,principal:o.principal,resource:o.resource};return this.request({url:i,method:"POST",data:s},t)}RemoveCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/remove_collaborator"),s={principal:o.principal,resource:o.resource};return this.request({url:i,method:"POST",data:s},t)}CreateAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/create_app_meta"),s={app_type:o.app_type,client_type:o.client_type,name:o.name,description:o.description,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListAppMeta(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/list_app_meta"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}GetAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_meta"),s={appid:o.appid},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}UpdateAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/update_app_meta"),s={status:o.status,oauth2_configuration:o.oauth2_configuration,appid:o.appid,name:o.name,description:o.description,declared_permission:o.declared_permission,declared_permission_v2:o.declared_permission_v2},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}UploadPublicKey(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/upload_public_key"),s={appid:o.appid,public_key_pem:o.public_key_pem};return this.request({url:i,method:"POST",data:s},t)}DeletePublicKey(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_public_key"),s={fingerprint:o.fingerprint};return this.request({url:i,method:"POST",data:s},t)}CreateClientSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/create_client_secret"),s={appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}DeleteClientSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_client_secret"),s={appid:o.appid,client_secret_id:o.client_secret_id};return this.request({url:i,method:"POST",data:s},t)}PutOAuth2Configuration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/put_oauth2_configuration"),s={oauth2_configuration:o.oauth2_configuration,appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}AuthorizeAppWithDeclaredPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/authorize_app_with_declared_permission"),s={appid:o.appid,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListAuthorizedApps(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/list_authorized_apps"),s={page:o.page,size:o.size},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetAppAuthorizationRequestInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_authorization_request_info"),s={authorize_key:o.authorize_key},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}RevokeAppAuthorizedPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/revoke_app_authorized_permission"),s={authorization_type:o.authorization_type,appid:o.appid,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DeleteApp(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_app"),s={appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}ModifyCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/modify_collaborator"),s={principal:o.principal,resource:o.resource,collaborator_types:o.collaborator_types};return this.request({url:i,method:"POST",data:s},t)}BatchAddCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/batch_add_collaborator"),s={principal_type:o.principal_type,resource:o.resource,principal_ids:o.principal_ids,collaborator_types:o.collaborator_types};return this.request({url:i,method:"POST",data:s},t)}GetAppInstallationRequestInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_installation_request_info"),s={appid:o.appid},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}AppInstallationConsent(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/app_installation_consent"),s={appid:o.appid,installation_account_hint:o.installation_account_hint};return this.request({url:i,method:"POST",data:s},t)}ImpersonateCozeUser(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/coze_web_app/impersonate_coze_user"),s={duration_seconds:o.duration_seconds,scope:o.scope,connector_info:o.connector_info};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoConnectInfoWithInsName(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_connect_info_with_ins_name");return this.request({url:o,method:"GET"},t)}GetVolcanoMaskedMobile(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_masked_mobile");return this.request({url:o,method:"GET"},t)}BindVolcano(e,t){const o=this.genBaseURL("/api/permission_api/volcano/bind_volcano");return this.request({url:o,method:"POST"},t)}AuthorizeAppWithSpecifiedWorkspace(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/authorize_app_with_specified_permission"),s={appid:o.appid,workspace_list:o.workspace_list,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetUserProfile(e,t){const o=this.genBaseURL("/v1/users/me");return this.request({url:o,method:"GET"},t)}ListAppAuthorizations(e,t){const o=e,i=this.genBaseURL(`/v1/oauth-apps/${o.appid}/authorizations`),s={page_num:o.page_num,page_size:o.page_size},n={authorization:o.authorization};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetCertificationInfo(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/get_certification_info");return this.request({url:o,method:"GET"},t)}NeedCreateEnterprise(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/need_create_enterprise");return this.request({url:o,method:"GET"},t)}CreateEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_enterprise"),s={name:o.name,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}ListEnterprise(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/enterprise/list_enterprises"),s={contain_enterprise_of_user:o.contain_enterprise_of_user,contain_organization_of_user:o.contain_organization_of_user,contain_guest_enterprise_of_user:o.contain_guest_enterprise_of_user,contain_coze_team_of_user:o.contain_coze_team_of_user,is_space:o.is_space};return this.request({url:i,method:"GET",params:s},t)}GetEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_enterprise"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"GET",params:s},t)}UpdateEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise"),s={enterprise_id:o.enterprise_id,name:o.name,icon_uri:o.icon_uri,replace_logo:o.replace_logo};return this.request({url:i,method:"POST",data:s},t)}UpdateEnterpriseSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_settings"),s={enterprise_id:o.enterprise_id,enterprise_settings:o.enterprise_settings};return this.request({url:i,method:"POST",data:s},t)}BatchAddEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_add_enterprise_people"),s={enterprise_id:o.enterprise_id,enterprise_people:o.enterprise_people,need_check_people_valid:o.need_check_people_valid};return this.request({url:i,method:"POST",data:s},t)}RemoveEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/remove_enterprise_people"),s={enterprise_id:o.enterprise_id,user_id:o.user_id,receiver:o.receiver,sync_default_organization:o.sync_default_organization};return this.request({url:i,method:"POST",data:s},t)}UpdateEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_people"),s={enterprise_id:o.enterprise_id,user_id:o.user_id,enterprise_role_type_list:o.enterprise_role_type_list,sync_default_organization:o.sync_default_organization};return this.request({url:i,method:"POST",data:s},t)}CreateEnterpriseInviteLink(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_enterprise_invite_link"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}CreateJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_join_application"),s={key:o.key,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}GetInviteInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_invite_info"),s={invite_key:o.invite_key};return this.request({url:i,method:"GET",params:s},t)}UpdateJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_application"),s={application_status:o.application_status,enterprise_id:o.enterprise_id,join_application_id_list:o.join_application_id_list};return this.request({url:i,method:"POST",data:s},t)}ListPersonalAccessTokensByCreator(e,t){const o=e,i=this.genBaseURL("/api/permission_api/permission/list_personal_access_tokens_by_creator"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}ListAppInstallations(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/list_app_installations"),s={enterprise_id:o.enterprise_id,organization_id:o.organization_id},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetEnterpriseSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_enterprise_settings"),s={enterprise_id:o.enterprise_id,enterprise_setting_key_list:o.enterprise_setting_key_list};return this.request({url:i,method:"POST",data:s},t)}SearchCanAddEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_can_add_enterprise_people"),s={people_type:o.people_type,enterprise_id:o.enterprise_id,search_key:o.search_key};return this.request({url:i,method:"POST",data:s},t)}SearchEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_enterprise_people"),s={people_type:o.people_type,enterprise_id:o.enterprise_id,search_key:o.search_key,enterprise_role_type_list:o.enterprise_role_type_list,need_volcano_user_info:o.need_volcano_user_info,need_people_number:o.need_people_number,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}ListJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_application"),s={application_status:o.application_status,enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PostAdapterMpV1Code2Session(e,t){const o=e||{},i=this.genBaseURL("/adapter/mp/v1/code2session"),s={bot_id:o.bot_id,app_id:o.app_id,connector_id:o.connector_id,code:o.code,with_userinfo:o.with_userinfo,execute_mode:o.execute_mode,agent_type:o.agent_type,agent_version:o.agent_version};return this.request({url:i,method:"POST",data:s},t)}SubmitAppOboInstallationReview(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/submit_app_obo_installation_review"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}InstallAppObo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/install_app_obo"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}UninstallAppObo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/uninstall_app_obo"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetChecklistForWorkspaceMigration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_checklist_for_workspace_migration"),s={workspace_id_list:o.workspace_id_list};return this.request({url:i,method:"POST",data:s},t)}CheckEnterpriseExist(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/check_enterprise_exist");return this.request({url:o,method:"GET"},t)}GetSSOSetting(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_sso_setting"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}BatchMigrateAuthorization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/batch_migrate_authorization"),s={authorization_list:o.authorization_list,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_invitation"),s={invitation_status:o.invitation_status,enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}RevokeJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/revoke_join_invitation"),s={enterprise_id:o.enterprise_id,join_invitation_id:o.join_invitation_id};return this.request({url:i,method:"POST",data:s},t)}UpdateJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_invitation"),s={enterprise_id:o.enterprise_id,join_invitation_id:o.join_invitation_id,joined:o.joined};return this.request({url:i,method:"POST",data:s},t)}GetJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_join_invitation"),s={join_invitation_id:o.join_invitation_id};return this.request({url:i,method:"POST",data:s},t)}SearchPeopleInOtherEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_people_in_other_enterprise"),s={enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}CreateApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_application_for_enterprise_member"),s={enterprise_id:o.enterprise_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}GetApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_application_for_enterprise_member"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}AuthorizeAppsAndPersonalaccesstokenListWithPersonalAccountPermission(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/authorize_apps_and_patlist_with_personalaccountpermission"),s={crossaccount_authinfo_list:o.crossaccount_authinfo_list};return this.request({url:i,method:"POST",data:s},t)}RevokeAppAndPersonalaccesstokenPersonalAccountPermission(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/revoke_app_and_pat_personalaccountpermission"),s={crossaccount_authinfo:o.crossaccount_authinfo};return this.request({url:i,method:"POST",data:s},t)}GetAppsAndPersonalAccessTokenListForPersonalAccountPermissionAuthorization(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/get_apps_and_patlist_for_personalaccountpermission_authorization"),s={page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}create_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/create_service_identity"),s={name:o.name,organization_id:o.organization_id,expire_at:o.expire_at,duration_day:o.duration_day,permission:o.permission},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}get_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/get_service_identity"),s={id:o.id};return this.request({url:i,method:"GET",params:s},t)}update_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/update_service_identity"),s={permission:o.permission,id:o.id,name:o.name,expire_at:o.expire_at,duration_day:o.duration_day},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}delete_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/delete_service_identity"),s={id:o.id};return this.request({url:i,method:"POST",params:s},t)}list_service_identities(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/service/list_service_identities"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}ListEncryptionConfiguration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterpise/list_encryption_configuration"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}UpdateEncryptionConfiguration(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/enterpise/update_encryption_configuration"),s={encryption_configuration:o.encryption_configuration};return this.request({url:i,method:"POST",data:s},t)}SearchOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_organization"),s={enterprise_id:o.enterprise_id,search_key:o.search_key,joined:o.joined,need_people_number:o.need_people_number,need_workspace_number:o.need_workspace_number,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}CreateOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_organization"),s={enterprise_id:o.enterprise_id,name:o.name,icon_uri:o.icon_uri,description:o.description};return this.request({url:i,method:"POST",data:s},t)}GetOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization"),s={organization_id:o.organization_id,name:o.name,icon_uri:o.icon_uri,description:o.description};return this.request({url:i,method:"POST",data:s},t)}SearchCanAddOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_can_add_organization_people"),s={organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}SearchOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_organization_people"),s={organization_role_type:o.organization_role_type,people_type:o.people_type,organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size,organization_role_type_list:o.organization_role_type_list};return this.request({url:i,method:"POST",data:s},t)}CreateJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_join_organization_application"),s={organization_id:o.organization_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}ListJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_organization_application"),s={application_status:o.application_status,organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}UpdateJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_organization_application"),s={application_status:o.application_status,organization_id:o.organization_id,join_application_id_list:o.join_application_id_list};return this.request({url:i,method:"POST",data:s},t)}GetOrganizationApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization_application_for_enterprise_member"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}CanCustomEncryptionConfiguration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterpise/can_custom_encryption_configuration"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"GET",params:s},t)}BatchAddOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_add_organization_people"),s={organization_id:o.organization_id,organization_people:o.organization_people};return this.request({url:i,method:"POST",data:s},t)}RemoveOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/remove_organization_people"),s={organization_id:o.organization_id,user_id:o.user_id,receiver:o.receiver};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization_people"),s={organization_role_type:o.organization_role_type,organization_id:o.organization_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}DownloadRemoteAttestationEvidence(e,t){const o=e,i=this.genBaseURL("/api/permission_api/aicc/download_remote_attestation_evidence"),s={component_name:o.component_name};return this.request({url:i,method:"GET",params:s},t)}GetAgentAiccInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/aicc/get_agent_aicc_info"),s={agent_id:o.agent_id};return this.request({url:i,method:"GET",params:s},t)}CheckDeleteOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/check_delete_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DeleteOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/delete_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListProjectUsers(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/list_project_users"),s={project_id:o.project_id,page_size:o.page_size,page_number:o.page_number,environment:o.environment,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectUser(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user"),s={environment:o.environment,project_id:o.project_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}GetProjectAuthConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}UpdateProjectAuthConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config"),s={project_id:o.project_id,configuration:o.configuration};return this.request({url:i,method:"POST",data:s},t)}ListProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/list_project_secret"),s={env:o.env,project_id:o.project_id,with_providers:o.with_providers,deploy_id:o.deploy_id,option:o.option};return this.request({url:i,method:"POST",data:s},t)}UpdateProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/update_project_secret"),s={project_id:o.project_id,update_secrets:o.update_secrets,update_cred_provider:o.update_cred_provider};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/delete_project_secret"),s={project_id:o.project_id,keys:o.keys,cred_provider_ids:o.cred_provider_ids};return this.request({url:i,method:"POST",data:s},t)}EncryptProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/encrypt_project_secret"),s={project_id:o.project_id,project_type:o.project_type,encrypt_secrets:o.encrypt_secrets};return this.request({url:i,method:"POST",data:s},t)}InsertProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/insert_project_secret"),s={project_id:o.project_id,insert_secrets:o.insert_secrets};return this.request({url:i,method:"POST",data:s},t)}OutboundAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/outbound_auth/callback"),s={session_id:o.session_id,error:o.error};return this.request({url:i,method:"GET",params:s},t)}CreateAgentAccessToken(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:o.project_id,deployment_env:o.deployment_env};return this.request({url:i,method:"POST",data:s},t)}ListAgentAccessTokens(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}DeleteAgentAccessToken(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={token_id:o.token_id,project_id:o.project_id};return this.request({url:i,method:"DELETE",data:s},t)}GenerateInviteCode(e,t){const o=this.genBaseURL("/api/permission_api/coze_user/generate_invite_code");return this.request({url:o,method:"POST"},t)}GetInviteCodeInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/coze_user/get_invite_code_info"),s={invite_code:o.invite_code};return this.request({url:i,method:"GET",params:s},t)}AuthorizeCredProvider(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/authorize"),s={provider_id:o.provider_id};return this.request({url:i,method:"GET",params:s},t)}ProjectSecretAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/project_secret/callback"),s={code:o.code,state:o.state,error:o.error};return this.request({url:i,method:"GET",params:s},t)}ListAuthInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/list_auth_info"),s={credential_ids:o.credential_ids};return this.request({url:i,method:"POST",data:s},t)}RevokeAuthorization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/revoke"),s={credential_id:o.credential_id};return this.request({url:i,method:"POST",data:s},t)}UpdateProjectAuthConfigV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config_v2"),s={environment:o.environment,project_id:o.project_id,configuration:o.configuration};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectUserV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user_v2"),s={environment:o.environment,project_id:o.project_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}VisibilityConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/visibility_config"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoLoginMaskedMobile(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_login_masked_mobile");return this.request({url:o,method:"GET"},t)}ListProjectUsersV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/list_project_users_v2"),s={environment:o.environment,project_id:o.project_id,page_size:o.page_size,page_number:o.page_number,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}GetProjectAuthConfigV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config_v2"),s={environment:o.environment,project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}BatchGetPeopleJoinedOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_get_people_joined_organization"),s={enterprise_id:o.enterprise_id,user_ids:o.user_ids};return this.request({url:i,method:"POST",data:s},t)}BatchRemoveOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_remove_organization_people"),s={enterprise_id:o.enterprise_id,remove_user_list:o.remove_user_list};return this.request({url:i,method:"POST",data:s},t)}BatchRemoveEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_remove_enterprise_people"),s={enterprise_id:o.enterprise_id,remove_user_list:o.remove_user_list};return this.request({url:i,method:"POST",data:s},t)}GetOrganizationSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization_settings"),s={organization_id:o.organization_id,organization_setting_key_list:o.organization_setting_key_list};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganizationSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization_settings"),s={organization_id:o.organization_id,organization_settings:o.organization_settings};return this.request({url:i,method:"POST",data:s},t)}GithubAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/github_auth/callback"),s={code:o.code,state:o.state,error:o.error};return this.request({url:i,method:"GET",params:s},t)}BatchListOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_list_organization_people"),s={organization_ids:o.organization_ids,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}}const vs=new bs({});function ws(e,t){return null!=e?e:t()}const Es=1e3,Cs=Math.floor(new Date("2000-01-01T00:00:00.000Z").getTime()/Es),Is=e=>e instanceof Error?e.message:String(e);class As{constructor(e){this.ctx=e,this.config=e.config}getOAuthConfig(){return{baseURL:ws(this.config.openApiBaseUrl,(()=>s.DEFAULT_CONFIG.openApiBaseUrl)),clientId:ws(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",o="win32"===process.platform?["/c","start",'""',e]:[e],s="Failed to open browser automatically. Please open the URL manually.";try{const e=i.spawn(t,o,{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:i}=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 ni.post(t,{client_id:e.clientId},{baseURL:e.baseURL})).data}({baseURL:t,clientId:i}),n=`${s.verification_uri}?user_code=${s.user_code}`;this.ctx.ui.info(`Please visit ${o.underline(n)} and authorize the application.\n\nPrivacy Policy: ${o.underline("https://docs.coze.cn/guides/privacy")}\nTerms of Service: ${o.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,o){if(!t.poll)return ri(t);let i=5e3;for(o.ui.debug("Start Polling for device token..."),o.ui.debug(`Polling interval: ${i}ms`),o.ui.debug("Polling timeout: 30000ms");;)try{o.ui.debug(`Polling for device token..., ${JSON.stringify(t)}`);const e=await ri(t);return o.ui.debug(`Polling for device token success: ${JSON.stringify(e)}`),e}catch(t){if(e.isHttpError(t)){const e=t;o.ui.debug(`Polling for device token error, the error is a HttpError.\n logid: ${oi([e,"access",e=>e.response,"optionalAccess",e=>e.headers,"access",e=>e["x-tt-logid"]])}`),o.ui.debug(`Polling for device token error: ${JSON.stringify(ti(oi([e,"access",e=>e.toJSON,"optionalCall",e=>e()]),(()=>e)))}`);const s=e.data;if(oi([s,"optionalAccess",e=>e.error])===ii.AUTHORIZATION_PENDING){o.ui.debug("Polling for device token: user has not completed authorization yet."),await si(i);continue}if(oi([s,"optionalAccess",e=>e.error])===ii.SLOW_DOWN){i<3e4&&(i+=5e3),o.ui.debug(`Polling for device token: client is polling too frequently. Increasing interval to ${i}ms`),await si(i);continue}}const s=t;throw o.ui.debug(`Polling for device token error, the error is: ${s.message}\n ${s.stack}\n `),t}}({baseURL:t,clientId:i,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: ${Is(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,o=!!this.config.refreshToken,{data:i}=await vs.GetUserProfile({},{baseURL:this.config.openApiBaseUrl}),s={logged_in:!0,user:i,token_expires_at:t?new Date(t).toISOString():o?void 0:"Never (PAT)"};this.ctx.response.print(s)}async getValidAccessToken(){const{accessToken:e,refreshToken:t,tokenExpiresAt:o}=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})(o))return e;this.ctx.ui.verbose("Access token is expired or expiring soon, refreshing...");try{const{baseURL:e,clientId:o}=this.getOAuthConfig(),i=await async function(e){const t={};return e.clientSecret&&(t.Authorization=`Bearer ${e.clientSecret}`),(await ni.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:o,refreshToken:t});return await this.saveOAuthToken(i),this.ctx.ui.verbose("Token refreshed successfully."),i.access_token}catch(e){return this.ctx.ui.error(`Failed to refresh token: ${Is(e)}`),void await this.clearAuthData()}}}async saveOAuthToken(e){const t=(o=e.expires_in)>=Cs?o*Es:Date.now()+o*Es;var o;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 Ss="",ks="",js="",Ps="",zs="",Ts="",Rs="",xs="",Ls="[PROC]",Os="[INFO]",Ds="[WARN]",Us="[ERR]",qs="[DONE]",Bs="[DBG]",Ms={debug:0,verbose:1,info:2,success:3,warn:4,error:5};function Ns(e){return`${js}${ks}${e}${Ss}`}class $s{constructor(e,t,o="info"){var i,s;this.log=e,this.silent="json"===t,this.useColor=this.detectColorSupport(),this.level=o,this.levelPriority=(s=()=>2,null!=(i=Ms[o])?i:s())}detectColorSupport(){return!0===function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([process,"access",e=>e.stderr,"optionalAccess",e=>e.isTTY])&&void 0===process.env.NO_COLOR}paint(e,t){return this.useColor?`${e}${t}${Ss}`:t}shouldOutput(e){return!this.silent&&Ms[e]>=this.levelPriority}verbose(e,...t){this.log.verbose(e,...t),this.shouldOutput("verbose")&&process.stderr.write(`${Ns(Ls)} ${this.paint(Rs,e)}\n`)}info(e,...t){this.log.info(e,...t),this.shouldOutput("info")&&process.stderr.write(`${Ns(Os)} ${this.paint(Ss,e)}\n`)}warn(e,...t){this.log.warn(e,...t),this.shouldOutput("warn")&&process.stderr.write(`${Ns(Ds)} ${this.paint(Ts,e)}\n`)}error(e,...t){this.log.error(e,...t),this.shouldOutput("error")&&process.stderr.write(`${Ns(Us)} ${this.paint(Ps,e)}\n`)}success(e,...t){this.log.success(e,...t),this.shouldOutput("success")&&process.stderr.write(`${Ns(qs)} ${this.paint(zs,e)}\n`)}debug(e,...t){this.log.debug(e,...t),this.shouldOutput("debug")&&process.stderr.write(`${Ns(Bs)} ${this.paint(xs,e)}\n`)}}class Gs{constructor(e){const{format:t}=e;this.format=t,this.formatter=function(e){return"text"===e?new M:new k}(t)}setNotice(e){this.notice={...this.notice,...e}}hasPendingNotice(){return void 0!==this.notice}print(e){const t=this.formatter.format(this.withNotice(e));process.stdout.write(t)}withNotice(e){if("json"!==this.format||!this.notice||"object"!=typeof e||null===e||Array.isArray(e))return e;const t={...e,_notice:this.notice};return this.notice=void 0,t}eprint(e){const t=this.formatter.formatError(e);process.stderr.write(t)}}function Fs(e,t){return null!=e?e:t()}const Vs=["config.json","skills",".skill-lock.json","logs","tasks","completion.sh"];async function Ws(e){try{return await A.access(e),!0}catch(e){return!1}}async function Hs(e,t){const o=Date.now();e.ui.verbose(`[Logger] CLI start: ${e.argv.join(" ")}`);try{await t()}finally{const t=Date.now()-o;e.ui.verbose(`[Logger] CLI end (took ${t}ms)`)}}var Js,Ks,Qs,Ys,Zs,Xs,en,tn,on,sn,nn,rn,an,cn,ln,dn,pn,un,mn,gn,hn,fn,_n,yn,bn,vn,wn,En,Cn,In,An,Sn,kn,jn,Pn,zn,Tn,Rn,xn,Ln,On,Dn,Un,qn,Bn,Mn,Nn,$n,Gn,Fn,Vn,Wn,Hn,Jn,Kn,Qn,Yn,Zn,Xn,er,tr,or,ir,sr,nr,rr,ar,cr,lr,dr,pr,ur,mr,gr,hr,fr,_r,yr,br,vr,wr,Er,Cr,Ir,Ar,Sr,kr,jr,Pr,zr,Tr,Rr,xr,Lr,Or,Dr,Ur,qr,Br,Mr,Nr,$r,Gr,Fr,Vr,Wr,Hr,Jr,Kr,Qr,Yr,Zr,Xr,ea,ta,oa,ia,sa,na,ra,aa,ca,la,da,pa,ua,ma,ga,ha,fa,_a;function ya(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!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"}(Js||(Js={})),function(e){e[e.OldVersion=0]="OldVersion";e[e.MiddleVersion=1]="MiddleVersion";e[e.NewVersion=2]="NewVersion";e[e.MiddleVersionNotPrompt=3]="MiddleVersionNotPrompt"}(Ks||(Ks={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(Qs||(Qs={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(Ys||(Ys={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Zs||(Zs={})),function(e){e[e.Current=1]="Current";e[e.Previous=2]="Previous";e[e.Start=3]="Start";e[e.MostSuitable=4]="MostSuitable"}(Xs||(Xs={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(en||(en={})),function(e){e[e.Default=0]="Default";e[e.Function=1]="Function"}(tn||(tn={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned"}(on||(on={})),function(e){e[e.LimitedReadWrite=1]="LimitedReadWrite";e[e.ReadOnly=2]="ReadOnly";e[e.UnlimitedReadWrite=3]="UnlimitedReadWrite";e[e.RWModeMax=4]="RWModeMax"}(sn||(sn={})),function(e){e[e.Default=0]="Default";e[e.DouyinAvatar=1]="DouyinAvatar"}(nn||(nn={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(rn||(rn={})),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"}(an||(an={})),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"}(cn||(cn={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(ln||(ln={})),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"}(dn||(dn={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(pn||(pn={})),function(e){e[e.SLM=0]="SLM";e[e.LLM=1]="LLM"}(un||(un={})),function(e){e[e.Pre=1]="Pre";e[e.Post=2]="Post";e[e.PreAndPost=3]="PreAndPost"}(mn||(mn={})),function(e){e[e.Default=0]="Default";e[e.CustomizePrompt=1]="CustomizePrompt"}(gn||(gn={})),function(e){e[e.ReplyBottom=0]="ReplyBottom";e[e.CardList=1]="CardList"}(hn||(hn={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(fn||(fn={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(_n||(_n={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(yn||(yn={})),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"}(bn||(bn={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(vn||(vn={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(wn||(wn={})),function(e){e[e.Curve=0]="Curve";e[e.Straight=1]="Straight"}(En||(En={})),function(e){e[e.Flow=1]="Flow";e[e.Host=2]="Host"}(Cn||(Cn={})),function(e){e[e.NO_NEED=1]="NO_NEED";e[e.USE_MANUAL=2]="USE_MANUAL";e[e.USE_LLM=3]="USE_LLM"}(In||(In={})),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"}(An||(An={})),function(e){e[e.Input=0]="Input";e[e.Variable=1]="Variable"}(Sn||(Sn={})),function(e){e[e.Default=0]="Default";e[e.FromSaas=1]="FromSaas"}(kn||(kn={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(jn||(jn={})),function(e){e[e.FunctionCall=1]="FunctionCall";e[e.Independent=2]="Independent"}(Pn||(Pn={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(zn||(zn={})),function(e){e[e.ManualUpdate=1]="ManualUpdate";e[e.AutoUpdate=2]="AutoUpdate"}(Tn||(Tn={})),function(e){e[e.SemanticSearch=0]="SemanticSearch";e[e.HybirdSearch=1]="HybirdSearch";e[e.FullTextSearch=20]="FullTextSearch"}(Rn||(Rn={})),function(e){e[e.Public=1]="Public";e[e.Anonymous=2]="Anonymous";e[e.Custom=3]="Custom"}(xn||(xn={})),function(e){e[e.Random=0]="Random";e[e.All=1]="All"}(Ln||(Ln={})),function(e){e[e.System=0]="System";e[e.Custom=1]="Custom";e[e.Disable=2]="Disable";e[e.OriBot=3]="OriBot"}(On||(On={})),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"}(Dn||(Dn={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Un||(Un={})),function(e){e[e.CozeOldTimeCapsule=0]="CozeOldTimeCapsule";e[e.VolcanoTimeCapsule=1]="VolcanoTimeCapsule"}(qn||(qn={})),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"}(Bn||(Bn={})),function(e){e[e.BotQuery=1]="BotQuery";e[e.Plugin=2]="Plugin";e[e.Workflow=3]="Workflow"}(Mn||(Mn={})),function(e){e[e.Unknown=0]="Unknown";e[e.Webhook=1]="Webhook"}(Nn||(Nn={})),function(e){e[e.Unknown=0]="Unknown";e[e.Time=1]="Time";e[e.Event=2]="Event"}($n||($n={})),function(e){e[e.NoHistory=0]="NoHistory";e[e.NeedHistory=1]="NeedHistory"}(Gn||(Gn={})),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"}(Fn||(Fn={})),function(e){e[e.Init=0]="Init";e[e.Activated=1]="Activated";e[e.Deactivated=2]="Deactivated";e[e.Suspended=3]="Suspended"}(Vn||(Vn={})),function(e){e[e.Preset=1]="Preset";e[e.UserTask=2]="UserTask";e[e.PluginRunTask=3]="PluginRunTask"}(Wn||(Wn={})),function(e){e[e.Deploying=0]="Deploying";e[e.Successful=1]="Successful";e[e.Failed=2]="Failed"}(Hn||(Hn={})),function(e){e[e.All=0]="All";e[e.Bind=1]="Bind";e[e.UnBind=2]="UnBind"}(Jn||(Jn={})),function(e){e[e.CreateTime=0]="CreateTime";e[e.UpdateTime=1]="UpdateTime"}(Kn||(Kn={})),function(e){e[e.EventMeta=1]="EventMeta";e[e.ProfileMeta=2]="ProfileMeta"}(Qn||(Qn={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Yn||(Yn={})),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"}(Zn||(Zn={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(Xn||(Xn={})),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"}(er||(er={})),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"}(tr||(tr={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(or||(or={})),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"}(ir||(ir={})),function(e){e[e.Upgrade=1]="Upgrade";e[e.BrowseOldNoPrompt=2]="BrowseOldNoPrompt"}(sr||(sr={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(nr||(nr={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(rr||(rr={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(ar||(ar={})),function(e){e[e.Visit=1]="Visit";e[e.Edit=2]="Edit"}(cr||(cr={})),function(e){e[e.Online=1]="Online";e[e.Offline=2]="Offline"}(lr||(lr={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online"}(dr||(dr={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(pr||(pr={})),function(e){e[e.AutoGenBeforePublish=1]="AutoGenBeforePublish"}(ur||(ur={})),function(e){e[e.CozeHome=1]="CozeHome";e[e.Space=2]="Space"}(mr||(mr={})),function(e){e[e.Undefined=0]="Undefined";e[e.PersonalDraft=1]="PersonalDraft";e[e.Base=2]="Base";e[e.Publish=3]="Publish"}(gr||(gr={})),function(e){e[e.Undefined=0]="Undefined";e[e.Committed=1]="Committed";e[e.Behind=2]="Behind";e[e.NoDraftReplica=3]="NoDraftReplica"}(hr||(hr={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(fr||(fr={})),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"}(_r||(_r={})),function(e){e[e.Personal=1]="Personal";e[e.Organization=2]="Organization"}(yr||(yr={})),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"}(br||(br={})),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"}(vr||(vr={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned";e[e.MoveFail=3]="MoveFail"}(wr||(wr={})),function(e){e[e.ByteTree=1]="ByteTree";e[e.GPTAK=2]="GPTAK";e[e.MaasAK=3]="MaasAK"}(Er||(Er={})),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"}(Cr||(Cr={})),function(e){e[e.BotStore=1]="BotStore"}(Ir||(Ir={})),function(e){e[e.shorcutIcon=1]="shorcutIcon"}(Ar||(Ar={})),function(e){e[e.Onboarding=0]="Onboarding";e[e.BackgroundImage=1]="BackgroundImage"}(Sr||(Sr={})),function(e){e[e.BasicUser=1]="BasicUser";e[e.ExternalUser=2]="ExternalUser";e[e.RootUser=3]="RootUser"}(kr||(kr={})),function(e){e[e.GetInfo=1]="GetInfo"}(jr||(jr={})),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"}(Pr||(Pr={})),function(e){e[e.Apply=1]="Apply";e[e.Invite=2]="Invite";e[e.EnterpriseApply=3]="EnterpriseApply"}(zr||(zr={})),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"}(Tr||(Tr={})),function(e){e[e.Douyin=1]="Douyin"}(Rr||(Rr={})),function(e){e[e.GPTOpenAPI=1]="GPTOpenAPI";e[e.Maas=2]="Maas";e[e.LLMFlow=3]="LLMFlow";e[e.Merlin=4]="Merlin"}(xr||(xr={})),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"}(Lr||(Lr={})),function(e){e[e.All=0]="All";e[e.Unread=1]="Unread"}(Or||(Or={})),function(e){e[e.Bot=1]="Bot"}(Dr||(Dr={})),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"}(Ur||(Ur={})),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"}(qr||(qr={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ShortcutCommand=3]="ShortcutCommand";e[e.Task=4]="Task"}(Br||(Br={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Knowledge=4]="Knowledge"}(Mr||(Mr={})),function(e){e[e.NoPublish=0]="NoPublish";e[e.HadPublished=1]="HadPublished"}(Nr||(Nr={})),function(e){e[e.Success=1]="Success";e[e.Failed=2]="Failed";e[e.InReview=3]="InReview"}($r||($r={})),function(e){e[e.Unread=1]="Unread";e[e.Read=2]="Read"}(Gr||(Gr={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(Fr||(Fr={})),function(e){e[e.UnLimit=1]="UnLimit";e[e.Forbidden=2]="Forbidden"}(Vr||(Vr={})),function(e){e[e.Plugin=1]="Plugin";e[e.NewBotIDEGuide=2]="NewBotIDEGuide";e[e.NewBeginnerGuide=3]="NewBeginnerGuide"}(Wr||(Wr={})),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"}(Hr||(Hr={})),function(e){e[e.All=0]="All";e[e.Self=1]="Self"}(Jr||(Jr={})),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"}(Kr||(Kr={})),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"}(Qr||(Qr={})),function(e){e[e.EnterpriseUser=1]="EnterpriseUser";e[e.ExternalUser=2]="ExternalUser"}(Yr||(Yr={})),function(e){e[e.Normal=0]="Normal";e[e.DevMode=1]="DevMode"}(Zr||(Zr={})),function(e){e[e.DraftBot=1]="DraftBot";e[e.Project=2]="Project";e[e.Space=3]="Space";e[e.DouyinAvatarBot=4]="DouyinAvatarBot"}(Xr||(Xr={})),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"}(ea||(ea={})),function(e){e[e.Professional=1]="Professional"}(ta||(ta={})),function(e){e[e.Personal=1]="Personal";e[e.Team=2]="Team"}(oa||(oa={})),function(e){e[e.Dark=1]="Dark";e[e.Light=2]="Light"}(ia||(ia={})),function(e){e[e.AlwaysOn=0]="AlwaysOn";e[e.AlwaysOff=1]="AlwaysOff"}(sa||(sa={})),function(e){e[e.CozeAssistantGuide=1]="CozeAssistantGuide"}(na||(na={})),function(e){e[e.Normal=1]="Normal";e[e.Banned=2]="Banned";e[e.Canceled=3]="Canceled"}(ra||(ra={})),function(e){e[e.External=0]="External";e[e.Internal=1]="Internal"}(aa||(aa={})),function(e){e[e.Invisible=0]="Invisible";e[e.Visible=1]="Visible";e[e.SocietyInvisible=2]="SocietyInvisible"}(ca||(ca={})),function(e){e[e.SingleAgent=1]="SingleAgent";e[e.MultiAgent=2]="MultiAgent";e[e.WorkflowAsAgent=3]="WorkflowAsAgent"}(la||(la={})),function(e){e[e.Preset=1]="Preset";e[e.Library=2]="Library"}(da||(da={})),function(e){e[e.DatasetServiceValid=0]="DatasetServiceValid";e[e.DatasetServiceInvalid=1]="DatasetServiceInvalid"}(pa||(pa={})),function(e){e[e.DatasetValid=0]="DatasetValid";e[e.DatasetInvalid=1]="DatasetInvalid"}(ua||(ua={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(ma||(ma={})),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"}(ga||(ga={})),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"}(ha||(ha={})),function(e){e[e.SendTypeQuery=0]="SendTypeQuery";e[e.SendTypePanel=1]="SendTypePanel"}(fa||(fa={})),function(e){e[e.ToolTypeWorkFlow=1]="ToolTypeWorkFlow";e[e.ToolTypePlugin=2]="ToolTypePlugin"}(_a||(_a={}));class ba{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){ba.prototype.__init.call(this),ba.prototype.__init2.call(this),this.request=ya([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=ya([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}GetSpaceInfoV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/info"),s={space_id:o.space_id,join_space_type:o.join_space_type};return this.request({url:i,method:"POST",data:s},t)}DeleteSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/delete"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}SaveSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/save"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri,space_type:o.space_type,space_mode:o.space_mode,space_config:o.space_config,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetSpaceListV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/list"),s={search_word:o.search_word,enterprise_id:o.enterprise_id,organization_id:o.organization_id,scope_type:o.scope_type,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}UpdateAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_agent"),s={id:o.id,reference_id:o.reference_id,current_version:o.current_version,space_id:o.space_id,bot_id:o.bot_id,base_commit_version:o.base_commit_version,name:o.name,description:o.description,position:o.position,icon_uri:o.icon_uri,intents:o.intents,work_info:o.work_info,is_delete:o.is_delete};return this.request({url:i,method:"POST",data:s},t)}BatchCreateAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/batch_create_agent"),s={space_id:o.space_id,bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,agent_cnt:o.agent_cnt,base_commit_version:o.base_commit_version,version_compat:o.version_compat};return this.request({url:i,method:"POST",data:s},t)}GetPublishBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_publish_bot_list"),s={space_id:o.space_id,bot_mode:o.bot_mode,page_num:o.page_num,page_size:o.page_size,name:o.name,login_user_create:o.login_user_create,bot_id:o.bot_id};return this.request({url:i,method:"GET",params:s},t)}MGetBotByVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/mget_bot_by_version"),s={bot_versions:o.bot_versions,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}BotLastPublishInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_last_publish_info"),s={space_id:o.space_id,bot_id:o.bot_id,bot_mode:o.bot_mode};return this.request({url:i,method:"GET",params:s},t)}ProduceBot(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/produce/create_bot"),s={space_id:o.space_id,name:o.name,description:o.description,icon_url:o.icon_url,icon_uri:o.icon_uri,prompt:o.prompt,plugin_apis:o.plugin_apis,prologue:o.prologue,suggested_questions:o.suggested_questions,bot_source:o.bot_source};return this.request({url:i,method:"POST",data:s},t)}UpdateProducedBot(e,t){const o=e,i=this.genBaseURL("/api/playground_api/produce/update_bot"),s={bot_id:o.bot_id,name:o.name,description:o.description,icon_url:o.icon_url,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetPublishedBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_version/get_published_bot_list"),s={space_id_list:o.space_id_list,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}GetBotVersionInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_version/get_bot_version_info"),s={bot_id:o.bot_id,version:o.version,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}DuplicateBotVersionToSpace(e,t){const o=e,i=this.genBaseURL("/api/playground_api/dup_bot_version"),s={target_space_id:o.target_space_id,bot_id:o.bot_id,version:o.version,name:o.name,dup_society_host:o.dup_society_host};return this.request({url:i,method:"POST",data:s},t)}UpdateUserRiskAlertInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/update_user_risk_alert_info"),s={risk_alert_type:o.risk_alert_type,switch_info:o.switch_info};return this.request({url:i,method:"POST",data:s},t)}GetUserRiskAlertInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_user_risk_alert_info"),s={risk_alert_type_list:o.risk_alert_type_list,switch_type_list:o.switch_type_list},n={Cookie:o.Cookie};return this.request({url:i,method:"POST",data:s,headers:n},t)}DraftBotCollaboration(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/collaboration"),s={space_id:o.space_id,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}BotInfoAudit(e,t){const o=e,i=this.genBaseURL("/api/playground_api/audit/bot_info"),s={bot_id:o.bot_id,bot_audit_info:o.bot_audit_info,space_id:o.space_id,bot_mode:o.bot_mode};return this.request({url:i,method:"POST",data:s},t)}TimeCapsuleInvokeEvent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/timecapsule_invoke_event"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}InviteMemberLinkV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/invite"),s={space_id:o.space_id,team_invite_link_status:o.team_invite_link_status,func:o.func};return this.request({url:i,method:"POST",data:s},t)}SpaceMemberDetailV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/detail"),s={space_id:o.space_id,search_word:o.search_word,space_role_type:o.space_role_type,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}JoinSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/join"),s={space_id:o.space_id,join_space_type:o.join_space_type,is_reject:o.is_reject};return this.request({url:i,method:"POST",data:s},t)}UpdateSpaceMemberV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/update"),s={space_id:o.space_id,user_id:o.user_id,space_role_type:o.space_role_type};return this.request({url:i,method:"POST",data:s},t)}TransferSpaceV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/transfer"),s={space_id:o.space_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}RemoveSpaceMemberV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/remove"),s={space_id:o.space_id,remove_user_id:o.remove_user_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}SearchMemberV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/member/search"),s={search_list:o.search_list,space_id:o.space_id,search_volcano_account_list:o.search_volcano_account_list,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}AddBotSpaceMemberV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/member/add"),s={member_info_list:o.member_info_list,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}ExitSpaceV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/exit"),s={space_id:o.space_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}GetBotPopupInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/operate/get_bot_popup_info"),s={bot_popup_types:o.bot_popup_types,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}UpdateBotPopupInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/operate/update_bot_popup_info"),s={bot_popup_type:o.bot_popup_type,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}GenerateDescription(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/generate_description"),s={bot_name:o.bot_name,prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}DraftBotPublishHistoryDetail(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/publish_history_detail"),s={bot_id:o.bot_id,space_id:o.space_id,publish_id:o.publish_id,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GenerateStoreCategory(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/generate_store_category"),s={bot_name:o.bot_name,bot_description:o.bot_description,prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}UpdateMultiAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_multi_agent"),s={space_id:o.space_id,bot_id:o.bot_id,session_type:o.session_type,base_commit_version:o.base_commit_version,connector_type:o.connector_type};return this.request({url:i,method:"POST",data:s},t)}SwitchAgentVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/switch_agent_version"),s={bot_id:o.bot_id,space_id:o.space_id,operate_type:o.operate_type};return this.request({url:i,method:"POST",data:s},t)}LangDetect(e,t){const o=e,i=this.genBaseURL("/api/playground_api/audio/lang/detect"),s={detect_text_list:o.detect_text_list};return this.request({url:i,method:"POST",data:s},t)}GetImagexShortUrl(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_imagex_url"),s={uris:o.uris,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetPlatformCommonConfig(e,t){const o=this.genBaseURL("/api/playground_api/get_platform_common_config");return this.request({url:o,method:"GET"},t)}CreateShortcutCommand(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/create_shortcut_command"),s={object_id:o.object_id,shortcuts:o.shortcuts};return this.request({url:i,method:"POST",data:s},t)}MGetUserBasicInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/mget_user_info"),s={user_ids:o.user_ids,need_user_status:o.need_user_status,need_enterprise_identity:o.need_enterprise_identity,need_volcano_user_name:o.need_volcano_user_name};return this.request({url:i,method:"POST",data:s},t)}BindVolcanoTrn(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/bind_volcano_trn"),s={space_id:o.space_id,trn:o.trn,account_name:o.account_name};return this.request({url:i,method:"POST",data:s},t)}UnbindVolcanoTrn(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/unbind_volcano_trn"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}RetrieveFileOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/retrieve"),s={file_id:o.file_id};return this.request({url:i,method:"GET",params:s},t)}RetrieveFileContentOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/content/retrieve"),s={file_id:o.file_id};return this.request({url:i,method:"GET",params:s},t)}UploadFileOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/upload"),s={Data:o.Data},n={"Content-Type":o["Content-Type"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}BotInfoCheck(e,t){const o=e,i=this.genBaseURL("/api/playground_api/check/bot_info_check"),s={bot_id:o.bot_id,space_id:o.space_id,bot_audit_info:o.bot_audit_info};return this.request({url:i,method:"POST",data:s},t)}SupportVoiceCall(e,t){const o=e,i=this.genBaseURL("/api/playground_api/support_voice_call"),s={voice_id_list:o.voice_id_list};return this.request({url:i,method:"POST",data:s},t)}CreateUpdateShortcutCommand(e,t){const o=e,i=this.genBaseURL("/api/playground_api/create_update_shortcut_command"),s={object_id:o.object_id,space_id:o.space_id,shortcuts:o.shortcuts};return this.request({url:i,method:"POST",data:s},t)}MoveDraftBot(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/move_draft_bot"),s={bot_id:o.bot_id,target_spaceId:o.target_spaceId,from_spaceId:o.from_spaceId,move_action:o.move_action};return this.request({url:i,method:"POST",data:s},t)}GetShortcutAvailNodes(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_shortcut_avail_nodes"),s={bot_id:o.bot_id,space_id:o.space_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}MarkReadNotice(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/mark_read_notice"),s={bot_id:o.bot_id,pic_type:o.pic_type};return this.request({url:i,method:"POST",data:s},t)}CancelGenerateGif(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/cancel_generate_gif"),s={task_id:o.task_id};return this.request({url:i,method:"POST",data:s},t)}GetPicTask(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/get_pic_task"),s={bot_id:o.bot_id,pic_type:o.pic_type};return this.request({url:i,method:"POST",data:s},t)}GeneratePic(e,t){const o=e,i=this.genBaseURL("/api/playground_api/gen_img/generate_pic"),s={gen_prompt:o.gen_prompt,image_url:o.image_url,image_uri:o.image_uri,bot_id:o.bot_id,pic_type:o.pic_type,device_id:o.device_id,bot_name:o.bot_name,bot_desc:o.bot_desc};return this.request({url:i,method:"POST",data:s},t)}GetGenPicTimes(e,t){const o=this.genBaseURL("/api/playground_api/gen_img/get_gen_pic_times");return this.request({url:o,method:"POST"},t)}ListStyle(e,t){const o=this.genBaseURL("/api/playground_api/gen_img/list_style");return this.request({url:o,method:"POST"},t)}GetFileUrls(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_file_list"),s={scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetDraftBotInfoAgw(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/get_draft_bot_info"),s={bot_id:o.bot_id,version:o.version,commit_version:o.commit_version};return this.request({url:i,method:"POST",data:s},t)}CommitDraftBotInfoAgw(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/commit_draft_bot_info"),s={bot_id:o.bot_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}UpdateDraftBotInfoAgw(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/update_draft_bot_info"),s={bot_info:o.bot_info,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}GetUserQueryCollectOption(e,t){const o=this.genBaseURL("/api/playground_api/draftbot/get_user_query_collect_option");return this.request({url:o,method:"GET"},t)}GenerateUserQueryCollectPolicy(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/generate_user_query_collect_policy"),s={bot_id:o.bot_id,developer_name:o.developer_name,contact_information:o.contact_information};return this.request({url:i,method:"POST",data:s},t)}GetCozeProRights(e,t){const o=this.genBaseURL("/api/playground_api/get_coze_pro_rights");return this.request({url:o,method:"POST"},t)}GetPolicyContent(e,t){const o=e,i=this.genBaseURL(`/api/playground_api/private_policy/${o.secret}`);return this.request({url:i,method:"GET"},t)}UpdateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_agent_v2"),s={id:o.id,reference_id:o.reference_id,current_version:o.current_version,space_id:o.space_id,bot_id:o.bot_id,base_commit_version:o.base_commit_version,name:o.name,description:o.description,position:o.position,icon_uri:o.icon_uri,intents:o.intents,is_delete:o.is_delete,prompt_info:o.prompt_info,model_info:o.model_info,plugin_info_list:o.plugin_info_list,knowledge:o.knowledge,workflow_info_list:o.workflow_info_list,jump_config:o.jump_config,suggest_reply_info:o.suggest_reply_info,hook_info:o.hook_info};return this.request({url:i,method:"POST",data:s},t)}CopyAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/copy_agent_v2"),s={bot_id:o.bot_id,agent_id:o.agent_id,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}CreateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/create_agent_v2"),s={bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}BatchCreateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/batch_create_agent_v2"),s={bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,agent_cnt:o.agent_cnt,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyGetLinkMetaInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/get_link_meta_info"),s={auth_code:o.auth_code};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyTaskConfirm(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/copy_task_confirm"),s={auth_code:o.auth_code};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyGenerateAuthLink(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/generate_auth_link"),s={copy_user_id:o.copy_user_id,target_space_id:o.target_space_id};return this.request({url:i,method:"POST",data:s},t)}GetOpVoiceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_op_voice_list"),s={voice_ids:o.voice_ids,name:o.name,style_id:o.style_id,language_code:o.language_code,status:o.status,page_index:o.page_index,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetSupportLanguage(e,t){const o=this.genBaseURL("/api/playground_api/get_support_language");return this.request({url:o,method:"GET"},t)}SynchronizeVoiceList(e,t){const o=this.genBaseURL("/api/playground_api/synchronize_voice_list");return this.request({url:o,method:"GET"},t)}CheckBotAllModelPluginIds(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/check_bot_all_model_plugin_ids"),s={bot_id:o.bot_id,commit_version:o.commit_version};return this.request({url:i,method:"POST",data:s},t)}GetBotCollaborationQuota(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/collaboration_quota"),s={bot_id:o.bot_id,only_config_item:o.only_config_item,account_type:o.account_type};return this.request({url:i,method:"POST",data:s},t)}OpenCreateSpace(e,t){const o=e||{},i=this.genBaseURL("/v1/workspaces"),s={name:o.name,description:o.description,icon_file_id:o.icon_file_id,coze_account_id:o.coze_account_id,owner_uid:o.owner_uid};return this.request({url:i,method:"POST",data:s},t)}NoticeMarkRead(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/notice/mark_read"),s={notice_ids:o.notice_ids,mark_all:o.mark_all};return this.request({url:i,method:"POST",data:s},t)}GetNoticeList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/notice/get_list"),s={cursor:o.cursor,count:o.count,notice_rank_type:o.notice_rank_type};return this.request({url:i,method:"POST",data:s},t)}GetNoticeUnreadCount(e,t){const o=this.genBaseURL("/api/playground_api/notice/get_unread_count");return this.request({url:o,method:"POST"},t)}OpenSpaceList(e,t){const o=e||{},i=this.genBaseURL("/v1/workspaces"),s={page_num:o.page_num,page_size:o.page_size,enterprise_id:o.enterprise_id,user_id:o.user_id,coze_account_id:o.coze_account_id,scope:o.scope};return this.request({url:i,method:"GET",params:s},t)}ReportUserBehavior(e,t){const o=e,i=this.genBaseURL("/api/playground_api/report_user_behavior"),s={resource_id:o.resource_id,resource_type:o.resource_type,behavior_type:o.behavior_type,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_user_config"),s={risk_alert_type_list:o.risk_alert_type_list,switch_type_list:o.switch_type_list},n={Cookie:o.Cookie};return this.request({url:i,method:"POST",data:s,headers:n},t)}UpdateUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/update_user_config"),s={risk_alert_type:o.risk_alert_type,switch_info:o.switch_info};return this.request({url:i,method:"POST",data:s},t)}GetRecentDraftBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/get_recent_draft_bot"),s={behavior_type:o.behavior_type,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}GetPromptResourceInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_prompt_resource_info"),s={prompt_resource_id:o.prompt_resource_id};return this.request({url:i,method:"GET",params:s},t)}UpsertPromptResource(e,t){const o=e,i=this.genBaseURL("/api/playground_api/upsert_prompt_resource"),s={prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}DeletePromptResource(e,t){const o=e,i=this.genBaseURL("/api/playground_api/delete_prompt_resource"),s={prompt_resource_id:o.prompt_resource_id};return this.request({url:i,method:"POST",data:s},t)}GetPromptReferenceInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_prompt_reference_info"),s={space_id:o.space_id,reference_id:o.reference_id,reference_type:o.reference_type,api_id:o.api_id,project_id:o.project_id,avatar_bot_id:o.avatar_bot_id};return this.request({url:i,method:"POST",data:s},t)}GetOfficialPromptResourceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_official_prompt_list"),s={keyword:o.keyword};return this.request({url:i,method:"POST",data:s},t)}GetByteTreeByName(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/search_byte_tree"),s={name:o.name},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}CreatePrivateModel(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/create_private_model"),s={space_id:o.space_id,model_vendor:o.model_vendor,model_show_name:o.model_show_name,model_arch:o.model_arch,ak:o.ak,token_limit:o.token_limit,upper_limit_of_max_token:o.upper_limit_of_max_token,function_call:o.function_call,multimodal:o.multimodal,multimodal_types:o.multimodal_types,form_detail:o.form_detail,record_id:o.record_id,maas_model_name:o.maas_model_name,maas_model_version:o.maas_model_version,maas_model_customer_id:o.maas_model_customer_id,model_family:o.model_family,space_id_i18n:o.space_id_i18n,operator:o.operator,email:o.email,employee_id:o.employee_id,presence_penalty_config:o.presence_penalty_config,frequency_penalty_config:o.frequency_penalty_config,temperature_config:o.temperature_config,top_p_config:o.top_p_config},n={"x-inner-auth":o["x-inner-auth"],"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}CheckExemptFormInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/check_exempt_form_info"),s={exempt_form_type:o.exempt_form_type,space_id:o.space_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}SetByteTreeForSpace(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/set_byte_tree_for_space"),s={space_id:o.space_id,byte_tree_node_id:o.byte_tree_node_id,byte_tree_node_name:o.byte_tree_node_name,form_detail:o.form_detail,record_id:o.record_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetModelCapability(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bpm/get_model_capability"),s={vendor:o.vendor,model_arch:o.model_arch,maas_model_name:o.maas_model_name,maas_model_version:o.maas_model_version,maas_customer_id:o.maas_customer_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetSpaceDetail(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/detail"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}RevocateSpaceInvite(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/revocate_invite"),s={space_id:o.space_id,invite_user_id:o.invite_user_id};return this.request({url:i,method:"GET",params:s},t)}SaveVolcanoUserManageInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/save_volcano_user_manage_info"),s={volcano_basic_user_config:o.volcano_basic_user_config};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoUserManageInfo(e,t){const o=this.genBaseURL("/api/playground_api/coze_pro/get_volcano_user_manage_info");return this.request({url:o,method:"POST"},t)}GetSpaceInviteManageList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/invite_manage_list"),s={space_id:o.space_id,space_invite_status:o.space_invite_status,search_word:o.search_word,page:o.page,size:o.size};return this.request({url:i,method:"GET",params:s},t)}DebugDouYin(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/debug"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}GetDouYinAuthCode(e,t){const o=this.genBaseURL("/api/playground_api/douyin/get_auth_qr_code");return this.request({url:o,method:"GET"},t)}GetDouyinAvatarInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/douyin/v1/get_avatar_info"),s={is_draft:o.is_draft,body:o.body},n={"Open-Platform-App-ID":o["Open-Platform-App-ID"],"Byte-Signature":o["Byte-Signature"],"Byte-Timestamp":o["Byte-Timestamp"],"Byte-Nonce-Str":o["Byte-Nonce-Str"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}DouYinAuthUserList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/auth_user_list"),s={page_index:o.page_index,page_size:o.page_size,bind_status:o.bind_status,order_by:o.order_by};return this.request({url:i,method:"POST",data:s},t)}GetDebugDouYinStatus(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/get_debug_status"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}CanUserApplyClose(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/coze_pro/can_user_apply_close"),s={AccountId:o.AccountId,EventName:o.EventName,Action:o.Action,Version:o.Version},n={"X-Tt-Logid":o["X-Tt-Logid"],"X-Top-Service":o["X-Top-Service"],"X-Top-Region":o["X-Top-Region"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}CreateRoom(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/create_room"),s={bot_id:o.bot_id,conversation_id:o.conversation_id,scene:o.scene,voice_id:o.voice_id,video_config:o.video_config};return this.request({url:i,method:"POST",data:s},t)}GetVoiceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_list"),s={page_index:o.page_index,page_size:o.page_size,language_code:o.language_code};return this.request({url:i,method:"POST",data:s},t)}GetVoiceByIds(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_by_ids"),s={voice_id_map:o.voice_id_map,voice_type:o.voice_type,space_id:o.space_id,emotion_config:o.emotion_config,voice_biz_scene:o.voice_biz_scene};return this.request({url:i,method:"POST",data:s},t)}GrayVoice(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gray_voice"),s={bot_id:o.bot_id,language_to_voice_id:o.language_to_voice_id};return this.request({url:i,method:"POST",data:s},t)}GetSpaceApplyManageList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/apply_manage_list"),s={space_id:o.space_id,space_apply_status:o.space_apply_status,search_word:o.search_word,page:o.page,size:o.size};return this.request({url:i,method:"GET",params:s},t)}DraftBotCrossSpaceCopy(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/crossspace_copy"),s={bot_id:o.bot_id,to_space_id:o.to_space_id};return this.request({url:i,method:"POST",data:s},t)}RemovePublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/remove_publish_member"),s={space_id:o.space_id,member_list:o.member_list};return this.request({url:i,method:"POST",data:s},t)}AddPublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/add_publish_member"),s={space_id:o.space_id,member_list:o.member_list};return this.request({url:i,method:"POST",data:s},t)}SearchAddablePublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/search_addable_publish_member"),s={space_id:o.space_id,search_word:o.search_word,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}PublishMemberList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/publish_member_list"),s={space_id:o.space_id,search_word:o.search_word,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}OperateSpaceApply(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/operate_apply"),s={space_id:o.space_id,enterprise_id:o.enterprise_id,organization_id:o.organization_id,apply_id_list:o.apply_id_list,space_apply_status:o.space_apply_status};return this.request({url:i,method:"POST",data:s},t)}ImportSpaceConfirm(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/confirm"),s={space_id_list:o.space_id_list,enterprise_id:o.enterprise_id,organization_id:o.organization_id,personal_space_new_name:o.personal_space_new_name,user_id_list:o.user_id_list};return this.request({url:i,method:"POST",data:s},t)}ImportSpaceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/list"),s={enterprise_id:o.enterprise_id,organization_id:o.organization_id,search_word:o.search_word};return this.request({url:i,method:"GET",params:s},t)}ImportSpaceUserList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/user_list"),s={space_id_list:o.space_id_list,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetDouYinInfo(e,t){const o=this.genBaseURL("/api/playground_api/douyin/get_douyin_info");return this.request({url:o,method:"POST"},t)}LongTermMemoryList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/list"),s={bot_id:o.bot_id,connector_id:o.connector_id,offset:o.offset,limit:o.limit,time_capsule_item_type:o.time_capsule_item_type};return this.request({url:i,method:"GET",params:s},t)}LongTermMemoryUpdate(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/update"),s={bot_id:o.bot_id,connector_id:o.connector_id,biz_id:o.biz_id,new_content:o.new_content,event_ms:o.event_ms,ext:o.ext,tags:o.tags,time_capsule_item_type:o.time_capsule_item_type,iid:o.iid,meta_type:o.meta_type,memory_type:o.memory_type};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryClearAll(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/clear_all"),s={bot_id:o.bot_id,connector_id:o.connector_id,time_capsule_item_type:o.time_capsule_item_type};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryDelete(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/delete"),s={bot_id:o.bot_id,connector_id:o.connector_id,biz_ids:o.biz_ids,time_capsule_item_type:o.time_capsule_item_type,iids:o.iids,memory_meta_type_map:o.memory_meta_type_map};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/version"),s={bot_id:o.bot_id};return this.request({url:i,method:"GET",params:s},t)}GetVoiceListV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_list_v2"),s={language_code:o.language_code,space_id:o.space_id,voice_type:o.voice_type,page_size:o.page_size,next_cursor:o.next_cursor};return this.request({url:i,method:"POST",data:s},t)}GetUserUpdateProfileTag(e,t){const o=this.genBaseURL("/api/playground_api/get_user_update_profile_tag");return this.request({url:o,method:"GET"},t)}OpenRemoveSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={user_ids:o.user_ids};return this.request({url:i,method:"DELETE",data:s},t)}OpenSpaceMemberList(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}OpenAddSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={users:o.users};return this.request({url:i,method:"POST",data:s},t)}OpenGetBotInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}`),s={is_published:o.is_published,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}OpenApplyJoinSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members/apply`),s={user_ids:o.user_ids};return this.request({url:i,method:"POST",data:s},t)}OpenRemoveSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}`);return this.request({url:i,method:"DELETE"},t)}GetTypeList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_type_list"),s={model:o.model,voice:o.voice,raw_model:o.raw_model,space_id:o.space_id,cur_model_id:o.cur_model_id,cur_model_ids:o.cur_model_ids,model_scene:o.model_scene,tag_filters:o.tag_filters};return this.request({url:i,method:"POST",data:s},t)}GetCozeLaneInfo(e,t){const o=this.genBaseURL("/api/playground_api/get_coze_lane_info");return this.request({url:o,method:"POST"},t)}OpenUpdateSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members/${o.user_id}`),s={role_type:o.role_type};return this.request({url:i,method:"PUT",data:s},t)}OpenListBotVersions(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}/versions`),s={page_num:o.page_num,page_size:o.page_size,publish_status:o.publish_status,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}OpenSwitchBotDevelopMode(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}/collaboration_mode`),s={collaboration_mode:o.collaboration_mode};return this.request({url:i,method:"POST",data:s},t)}OpenUpdateSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}`),s={name:o.name,description:o.description};return this.request({url:i,method:"PUT",data:s},t)}MGetUserDefaultSpace(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/default/mget"),s={organization_ids:o.organization_ids,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}SetDefaultSpace(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/default/set"),s={space_id:o.space_id,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}}const va=new ba({});function wa(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function Ea(t,o){if(wa([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"});if(wa([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipOrgCheck]))return void await o();const i=await async function(t){const o=t.config.organizationId;if(!o)return!1;const{data:i}=await vs.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0}),s=i.enterprise_info_list||[];if(!s.some((e=>wa([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>"});return!1}(t);if(wa([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipSpaceCheck]))return i&&await Ca(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId}),void await o();const s=await async function(t){const o=t.config.organizationId,{enterpriseId:i}=t.config;let{spaceId:s}=t.config,n=!1;try{if(s){const{data:t}=await va.GetSpaceListV2({organization_id:o,enterprise_id:i}),n=wa([t,"optionalAccess",e=>e.bot_space_list])||[];if(!n.some((e=>e.id===s))){const t=o?`[Context] Space ID ${s} is invalid or not found in organization ${o}.`:`[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 va.GetSpaceListV2({organization_id:o,enterprise_id:i,page:1,size:1}),a=wa([r,"optionalAccess",e=>e.bot_space_list,"optionalAccess",e=>e[0]]);if(!a){const t=o?`[Context] No spaces found in organization ${o}. 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 o=t instanceof e.CozeError?t:new e.CozeError(e.ErrorCode.E5000,t.message,t instanceof Error?t.stack:t);throw o.fix??="Switch organization or space using `coze organization use <organization_id>` or `coze space use <space_id>`",o.example??="coze organization list",o}return n}(t);await Ia(t),(i||s)&&await Ca(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId,spaceId:t.config.spaceId,billingProjectId:t.config.billingProjectId}),await o()}async function Ca(e,t){try{await s.saveConfig(t)}catch(t){e.ui.warn(`Failed to save auto-initialized context: ${t}`)}}const Ia=async o=>{const{spaceId:i}=o.config;try{const{data:s}=await t.IdeApi.GetOrCreateBillingProject({space_id:i});if(!wa([s,"optionalAccess",e=>e.project_id]))throw new e.CozeError(e.ErrorCode.E5002,"[Context] Failed to get billing project ID from response.",s);o.config.billingProjectId=s.project_id,o.ui.success(`[Context] Billing Project: ${s.project_id} (space: ${i})`)}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 Aa(e,t){return null!=e?e:t()}function Sa(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ka=t=>{const o=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");o.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"}}}}},errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Not logged in or credentials have expired",fix:"Run `coze auth login` to authenticate first.",example:"coze auth login"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server failed to fetch the space list",fix:"Retry later; run with --debug for details if the issue persists"}],seeAlso:["coze space use","coze organization list"]}}).action((async(e,t)=>{const o=t.getContext(),i=e.orgId||Sa([o,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),s=Sa([o,"optionalAccess",e=>e.config,"access",e=>e.enterpriseId]);Sa([o,"optionalAccess",e=>e.ui,"access",e=>e.verbose,"call",e=>e(`Fetching spaces for organization '${i}'...`)]);const n=await async function(e){const{data:t}=await va.GetSpaceListV2({organization_id:e.orgId,enterprise_id:e.enterpriseId,page:1,size:100});return Aa(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([t,"optionalAccess",e=>e.bot_space_list]),(()=>[])).map((t=>({id:Aa(t.id,(()=>"")),name:Aa(t.name,(()=>"")),org_id:Aa(e.orgId,(()=>""))})))}({orgId:i,enterpriseId:s});Sa([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Spaces:")]),Sa([o,"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>"];Sa([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(r.join("\n"))])})),o.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",description:"Operation result status"},message:{type:"string",description:"Human-readable result message"}}},errors:[{code:e.ErrorCode.E1102,name:"MISSING_ARGUMENT",desc:"Required argument <space_id> is not provided",fix:"Pass the space ID as the first argument; run `coze space list` to find it.",example:"coze space use 7349123847123"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to write the local configuration file",fix:"Check file permissions of the local config directory and retry"}],seeAlso:["coze space list","coze organization use"]}}).action((async(t,o,i)=>{const n=i.getContext();Sa([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(o){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set default space to '${t}': ${o.message}`,o.stack)}}(t),Sa([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default space set to '${t}' successfully.`)]),"json"===Sa([n,"optionalAccess",e=>e.format])&&Sa([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default space set to '${t}'.`})])}))};function ja(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Pa=async e=>{ja([e,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switching to personal account...")]),await async function(){const e=!!(await s.loadConfig()).organizationId;await s.saveConfig({organizationId:void 0,enterpriseId:void 0,...e?{spaceId:void 0}:{}})}(),ja([e,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switched to personal account successfully.")]),"json"===ja([e,"optionalAccess",e=>e.format])&&ja([e,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:"Switched to personal account."})])},za=t=>{const o=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");o.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"}}}}},seeAlso:["coze organization use","coze space list"]}}).action((async(e,t)=>{const o=t.getContext();ja([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching organizations...")]);const i=await async function(){const{data:e}=await vs.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})))))}();ja([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Organizations (Teams):")]),ja([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(i)]);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>"];ja([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])})),o.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 (or pass an empty string) to switch to personal account mode.",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.E3000,name:"RESOURCE_NOT_FOUND",desc:"Organization not found",fix:"Run `coze organization list` to see available organizations."}],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)"}}},seeAlso:["coze organization list","coze space use"]}}).action((async(t,o,i)=>{const n=i.getContext();if(!t)return void await Pa(n);ja([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to organization '${t}'...`)]);const{enterpriseId:r}=await async function(t){const[o,{data:i}]=await Promise.all([s.loadConfig(),vs.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);let n="",r=!1;for(const e of i.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=o.organizationId!==t;return await s.saveConfig({organizationId:t,enterpriseId:n,...a?{spaceId:void 0}:{}}),{enterpriseId:n}}(t);ja([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Organization '${t}' found in enterprise '${r}'. Config saved.`)]),ja([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default organization set to '${t}' successfully.`)]),"json"===ja([n,"optionalAccess",e=>e.format])&&ja([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})])})),o.command("unset").alias("reset").description("Clear the organization context (switch to personal account)").config({help:{brief:"Clear organization context",description:"Clear the saved organizationId / enterpriseId (and spaceId) from the local configuration, switching back to personal account mode. Equivalent to `coze organization use` with no org_id.",examples:[{desc:"Clear organization context",cmd:"coze organization unset",tags:["[RECOMMENDED]"]},{desc:"Clear organization context (alias)",cmd:"coze org reset"}],schema:{output:{status:{type:"string",description:"Operation result status"},message:{type:"string",description:"Human-readable result message"}}},seeAlso:["coze organization use","coze organization list"]}}).action((async(e,t)=>{const o=t.getContext();await Pa(o)}))};function Ta(e,t){return null!=e?e:t()}const Ra=async(e={})=>{const t=Ta(e.stdin,(()=>process.stdin));return!0===Ta(e.isTTY,(()=>t.isTTY))?null:await(async e=>{let t="";e.setEncoding("utf-8");for await(const o of e)t+=o;return t})(t)},xa=e=>{process.stdout.write(e.endsWith("\n")?e:`${e}\n`)},La=e=>{xa(JSON.stringify(e))},Oa=async(e,t)=>{const o=n.resolve(e),i=n.dirname(o);if(await r.mkdir(i,{recursive:!0}),t instanceof Blob){const e=Buffer.from(await t.arrayBuffer());await r.writeFile(o,e)}else Buffer.isBuffer(t)?await r.writeFile(o,t):t instanceof ArrayBuffer?await r.writeFile(o,Buffer.from(t)):await r.writeFile(o,String(t));return o};const Da=e=>"object"==typeof e&&null!==e,Ua=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},qa=e=>Da(e)&&"data"in e&&void 0!==e.data?e.data:e,Ba=(e,t)=>{try{const{pathname:o}=new URL(e);return n.extname(o)||t}catch(e){return t}},Ma=()=>{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")}`},Na=e=>{const{outputPath:t,type:o,index:i,ext:s,timestamp:r}=e,a=`${o}_${r}_${i}${s}`;return n.join(t,a)},$a=async(t,o={})=>{let i=null;o.stdin&&(i=await Ra());const s=Ua(t),n=Ua(i),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},Ga="720p",Fa="16:9",Va=!0,Wa=!0,Ha=!1,Ja=!1;function Ka(e,t){return null!=e?e:t()}function Qa(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ya=(e,t)=>{if(null==e)return 5;const o=Number(e);if(!Number.isFinite(o))return Qa([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --duration '${String(e)}', falling back to 5`)]),5;const i=Math.floor(o);return i<4||i>12?(Qa([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):i},Za=(e,t)=>{if(null==e)return;const o=Number(e);if(Number.isSafeInteger(o)&&o>=0)return o;Qa([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --seed '${String(e)}', this parameter will be ignored`)])},Xa=e=>{const{content:t,options:o,ctx:i}=e,s=(e=>{if("string"!=typeof e)return null;const t=e.trim(),o=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(t);if(!o)return null;const i=Number(o[1]),s=Number(o[2]);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=0)return null;const n=((e,t)=>{let o=Math.abs(e),i=Math.abs(t);for(;0!==i;){const e=o%i;o=i,i=e}return o})(i,s)||1,r=`${Math.round(i/n)}:${Math.round(s/n)}`,a=Math.max(i,s);return{ratio:r,resolution:a<=854?"480p":a<=1280?"720p":"1080p"}})(o.size),n=((e,t)=>"480p"===e||"720p"===e||"1080p"===e?e:(void 0!==e&&Qa([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --resolution '${String(e)}', falling back to '${Ga}'`)]),Ga))(Ka(o.resolution,(()=>Qa([s,"optionalAccess",e=>e.resolution]))),i),r=((e,t)=>{if("string"==typeof e){const t=e.trim();if(t.length>0)return t}return void 0!==e&&Qa([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --ratio '${String(e)}', falling back to '${Fa}'`)]),Fa})(Ka(o.ratio,(()=>Qa([s,"optionalAccess",e=>e.ratio]))),i);return{model:"doubao-seedance-1-5-pro-251215",content:t,callback_url:Ka(Ua(o.callbackUrl),(()=>{})),return_last_frame:"boolean"==typeof o.returnLastFrame?o.returnLastFrame:Ja,resolution:n,ratio:r,duration:Ya(o.duration,i),watermark:"boolean"==typeof o.watermark?o.watermark:Va,seed:Za(o.seed,i),camerafixed:"boolean"==typeof o.camerafixed?o.camerafixed:Ha,generate_audio:"boolean"==typeof o.generateAudio?o.generateAudio:Wa}},ec={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',tags:["[RECOMMENDED]"]},{desc:"Save result into a directory",cmd:'coze generate video create "A dancing kitten" --wait --output-path ./videos'},{desc:"Animate an image as the first frame",cmd:'coze generate video create "Camera slowly zooms in" --first-frame https://example.com/cat.png --wait'},{desc:"Read prompt from a pipe",cmd:"cat prompt.txt | coze generate video create --stdin --wait",tags:["[PIPELINE]"]}],enums:{resolution:{"480p":"Standard definition output","720p":"High definition output (default)","1080p":"Full high definition output"}},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.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Configure billing project ID and retry"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid access token",fix:"Run `coze auth login` 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)"},callbackUrl:{type:"string",required:!1,description:"Callback URL for task status changes"},returnLastFrame:{type:"boolean",required:!1,default:Ja,description:"Return last frame URL"},resolution:{type:"string",required:!1,enum:["480p","720p","1080p"],default:Ga,description:"Video resolution"},ratio:{type:"string",required:!1,default:Fa,description:"Aspect ratio"},size:{type:"string",required:!1,description:"Derive ratio/resolution from WIDTHxHEIGHT (lower priority than explicit --ratio/--resolution)"},duration:{type:"number",required:!1,default:5,description:"Duration in seconds (4..12; out-of-bounds fallback -1)"},watermark:{type:"boolean",required:!1,default:Va,description:"Add watermark (disable with --no-watermark)"},seed:{type:"number",required:!1,description:"Random seed (safe integer)"},camerafixed:{type:"boolean",required:!1,default:Ha,description:"Fixed camera position"},generateAudio:{type:"boolean",required:!1,default:Wa,description:"Generate accompanying audio (disable with --no-generate-audio)"},firstFrame:{type:"string",required:!1,description:"First frame image URL"},lastFrame:{type:"string",required:!1,description:"Last frame image URL"},stdin:{type:"boolean",required:!1,description:"Read prompt from stdin (pipe input)"},wait:{type:"boolean",required:!1,description:"Wait for task completion by polling; by default the command returns taskId immediately"}},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"}}}}},caveats:["Without --wait the command only submits the task; query progress with `coze generate video status <taskId>`","--wait polls every 2 seconds and fails with E5003 after 5 minutes; the task keeps running server-side, so query it later with `coze generate video status <taskId>`","--output-path only takes effect together with --wait and must be a directory; files are saved inside it as video_<timestamp>_0.<ext> (plus last_frame_<timestamp>_0.<ext> with --return-last-frame)","--size has lower priority than explicit --ratio/--resolution; explicit values win when both are given","An out-of-bounds --duration (outside 4..12) falls back to -1 (the model decides) with a warning","Each task is billed to the configured billing project"],seeAlso:["coze generate video status","coze generate image","coze generate audio"]},tc={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",tags:["[RECOMMENDED]"]},{desc:"Output full response as JSON",cmd:"coze generate video status task_123 --format 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.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Configure billing project ID and retry"},{code:e.ErrorCode.E3000,name:"RESOURCE_NOT_FOUND",desc:"The task ID does not exist or has expired",fix:"Check the task ID returned by `coze generate video create`",example:"coze generate video status <taskId>"},{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"}],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"}}}},caveats:["Task IDs are not kept forever; an unknown or expired task ID fails with E3000"],seeAlso:["coze generate video create"]},oc=async t=>{const o=await e.customFetch.fetch(t);if(!o.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download generated resource: ${o.status} ${o.statusText}`,{url:t});return Buffer.from(await o.arrayBuffer())},ic=async e=>{const{outputPath:t,videoUrl:o,lastFrameUrl:i,shouldSaveLastFrame:s}=e,r=Ba(o,".mp4"),a=Ma(),c=Na({outputPath:t,type:"video",index:0,ext:r,timestamp:a}),l=await oc(o),d=[await Oa(c,l)];if(s&&"string"==typeof i&&i.length>0){const e=(e=>{const{outputPath:t,ext:o,timestamp:i}=e,s=`last_frame_${i}_0${o}`;return n.join(t,s)})({outputPath:t,ext:Ba(i,".png"),timestamp:a}),o=await oc(i),s=await Oa(e,o);d.push(s)}return d};var sc,nc,rc,ac,cc,lc,dc,pc,uc,mc,gc,hc,fc,_c,yc,bc,vc,wc,Ec;function Cc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInputTokens=2]="TotalInputTokens";e[e.TotalOutputTokens=3]="TotalOutputTokens"}(sc||(sc={})),function(e){e[e.ASC=1]="ASC";e[e.DESC=2]="DESC"}(nc||(nc={})),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"}(rc||(rc={})),function(e){e[e.Free=1]="Free";e[e.Trial=2]="Trial";e[e.Paid=3]="Paid"}(ac||(ac={})),function(e){e[e.Inactive=1]="Inactive";e[e.Active=2]="Active"}(cc||(cc={})),function(e){e[e.CNY=1]="CNY";e[e.ResourcePoint=2]="ResourcePoint"}(lc||(lc={})),function(e){e[e.Cancellable=0]="Cancellable";e[e.NoCancellable=1]="NoCancellable";e[e.AlwaysDefault=2]="AlwaysDefault"}(dc||(dc={})),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"}(pc||(pc={})),function(e){e[e.Internal=1]="Internal";e[e.External=2]="External";e[e.Infra=3]="Infra"}(uc||(uc={})),function(e){e[e.Text=1]="Text";e[e.Image=2]="Image";e[e.Video=3]="Video";e[e.Audio=4]="Audio"}(mc||(mc={})),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"}(gc||(gc={})),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"}(hc||(hc={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online";e[e.GradualRollout=2]="GradualRollout";e[e.ReadyToOffline=3]="ReadyToOffline"}(fc||(fc={})),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"}(_c||(_c={})),function(e){e[e.Install=1]="Install";e[e.Uninstall=2]="Uninstall"}(yc||(yc={})),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"}(bc||(bc={})),function(e){e[e.Scene=1]="Scene";e[e.Type=2]="Type"}(vc||(vc={})),function(e){e[e.Official=1]="Official";e[e.Community=2]="Community"}(wc||(wc={})),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"}(Ec||(Ec={}));class Ic{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Ic.prototype.__init.call(this),Ic.prototype.__init2.call(this),this.request=Cc([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Cc([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}ListIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/list"),s={space_id:o.space_id,project_id:o.project_id,integration_type:o.integration_type,integration_id:o.integration_id,filter_installed:o.filter_installed,org_id:o.org_id,search_words:o.search_words,page_num:o.page_num,page_size:o.page_size,project_type:o.project_type};return this.request({url:i,method:"POST",data:s},t)}SetIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/update"),s={integration_id:o.integration_id,space_id:o.space_id,auth_schema_value:o.auth_schema_value};return this.request({url:i,method:"POST",data:s},t)}DeleteIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/delete"),s={integration_id:o.integration_id,space_id:o.space_id,project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}AuthIntegrationStatus(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/auth/status"),s={integration_id:o.integration_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}ManageSpaceIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/space/manage"),s={space_ids:o.space_ids,integration_ids:o.integration_ids,op_type:o.op_type};return this.request({url:i,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}FlashASR(e,t){const o=e||{},i=this.genBaseURL("/api/v3/auc/bigmodel/recognize/flash"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}ListModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/list"),s={model_type:o.model_type,current_model_ids:o.current_model_ids,integration_ids:o.integration_ids,need_model_config_param:o.need_model_config_param,page_size:o.page_size,offset:o.offset};return this.request({url:i,method:"POST",data:s},t)}ChatCompletions(e,t){const o=e||{},i=this.genBaseURL("/api/v3/chat/completions"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CreateResponses(e,t){const o=e||{},i=this.genBaseURL("/api/v3/responses"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}GenerateImages(e,t){const o=e||{},i=this.genBaseURL("/api/v3/images/generations"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const o=e||{},i=this.genBaseURL("/api/v3/tts/unidirectional"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}GetIntegrationOauthConfig(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/auth/oauth_config"),s={integration_id:o.integration_id,space_id:o.space_id,project_id:o.project_id,session_id:o.session_id};return this.request({url:i,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks/:id"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"GET",data:s,params:n},t)}WebSearch(e,t){const o=e||{},i=this.genBaseURL("/api/search_api/web_search"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}WebSearch(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/search_api/web_search"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CreateResponses(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/responses"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks/:id"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"GET",data:s,params:n},t)}FlashASR(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/auc/bigmodel/recognize/flash"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}GenerateImages(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/images/generations"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/tts/unidirectional"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}ChatCompletions(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/chat/completions"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CancelIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/cancel"),s={integration_id:o.integration_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}Embeddings(e,t){const o=e||{},i=this.genBaseURL("/api/v3/embeddings/multimodal"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}Embeddings(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/embeddings/multimodal"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}VideoEditingUtils(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/video_editing_utils"),s={Body:o.Body},n={tool_name:o.tool_name};return this.request({url:i,method:"POST",data:s,params:n},t)}GetProjectDefaultSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/default"),s={project_type:o.project_type,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillByIDs(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/by_ids"),s={project_type:o.project_type,skill_ids:o.skill_ids,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillCategoryList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/category/list"),s={project_type:o.project_type};return this.request({url:i,method:"POST",data:s},t)}UploadSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload"),s={data:o.data},n={"Content-Type":o["Content-Type"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetUserSkillList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/user/list"),s={page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}DeleteSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/delete"),s={skill_id:o.skill_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/list"),s={project_type:o.project_type,category_type_list:o.category_type_list,space_id:o.space_id,source_list:o.source_list};return this.request({url:i,method:"POST",data:s},t)}UploadSkillConfirm(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload/confirm"),s={preview_skill_key:o.preview_skill_key};return this.request({url:i,method:"POST",data:s},t)}FetchTool(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/fetch_tool"),s={url:o.url};return this.request({url:i,method:"POST",data:s},t)}GetModelSwitchStatus(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/status"),s={model_id:o.model_id,project_ids:o.project_ids,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}StartSwitchModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/start"),s={space_id:o.space_id,project_ids:o.project_ids,current_model:o.current_model,target_model:o.target_model};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageList(e,t){const o=e||{},i=this.genBaseURL("/v1/model/usage/list"),s={space_id:o.space_id,model_id:o.model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp,order_by_field:o.order_by_field,order_by_type:o.order_by_type,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetModelDetails(e,t){const o=e||{},i=this.genBaseURL("/v1/model/details"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageDetail(e,t){const o=e||{},i=this.genBaseURL("/v1/model/usage/details"),s={space_id:o.space_id,model_id:o.model_id,project_id:o.project_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}RollbackSwitchModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/rollback"),s={space_id:o.space_id,project_ids:o.project_ids,current_model:o.current_model};return this.request({url:i,method:"POST",data:s},t)}TextEmbeddings(e,t){const o=e||{},i=this.genBaseURL("/api/v3/embeddings"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}TextEmbeddings(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/embeddings"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CheckModelReadyToOffline(e,t){const o=e||{},i=this.genBaseURL("/v1/model/ready_to_offline/check"),s={model_type:o.model_type};return this.request({url:i,method:"POST",data:s},t)}Audit(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/audit"),s={content:o.content};return this.request({url:i,method:"POST",data:s},t)}}Ic.prototype.UploadSkill=function(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload"),s=o.body;return this.request({url:i,method:"POST",data:s},t)},Ic.prototype.GenerateImages=function(e,t){const o=e||{},i=this.genBaseURL("/api/v3/images/generations"),s=o.Body;return this.request({url:i,method:"POST",data:s},t)},Ic.prototype.SubmitVideoGenerationsTasks=function(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks"),s=o;return this.request({url:i,method:"POST",data:s},t)},Ic.prototype.GetVideoGenerationsTasks=function(e,t){const o=e||{},i=this.genBaseURL(`/api/v3/contents/generations/tasks/${o.id}`);return this.request({url:i,method:"GET"},t)};const Ac=new Ic({});const Sc=async e=>await new Promise((t=>setTimeout(t,e))),kc=async e=>{const{taskId:t,baseURL:o,accessToken:i,projectId:s}=e,n=await Ac.GetVideoGenerationsTasks({id:t},{baseURL:o,headers:{Authorization:`Bearer ${i}`},params:{project_id:s}});return qa(n)};function jc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Pc=e=>`coze generate video status ${e}`,zc=e=>{const{ctx:t,response:o}=e;"json"!==jc([t,"optionalAccess",e=>e.format])?xa((e=>{const t=[e.status],o=jc([e,"access",e=>e.content,"optionalAccess",e=>e.video_url]),i=jc([e,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);return"succeeded"===e.status?("string"==typeof o&&o.length>0&&t.push(o),"string"==typeof i&&i.length>0&&t.push(i),t.join("\n")):("string"==typeof e.error_message&&e.error_message&&t.push(e.error_message),t.join("\n"))})(o)):La(o)},Tc=t=>{const o=t.getContext(),{outputPath:i}=t.optsWithGlobals(),n=(r=jc([o,"optionalAccess",e=>e.config,"optionalAccess",e=>e.integrationApiBaseUrl]),a=()=>s.DEFAULT_CONFIG.integrationApiBaseUrl,null!=r?r:a());var r,a;const c=jc([o,"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` first");return{accessToken:c,ctx:o,integrationApiBaseUrl:n,outputPath:i}},Rc=async(t,o,i)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:r,outputPath:a}=Tc(i);let c=null;o.stdin&&(c=await Ra());const{content:l}=(t=>{const{prompt:o,stdinPrompt:i,options:s}=t,n=Ka(Ua(o),(()=>Ua(i))),r=Ua(s.firstFrame),a=Ua(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 l=[];return n&&l.push({type:"text",text:n}),r&&l.push({type:"image_url",image_url:{url:r},role:"first_frame"}),a&&l.push({type:"image_url",image_url:{url:a},role:"last_frame"}),{content:l}})({prompt:t,stdinPrompt:c,options:o}),d=Xa({content:l,options:o,ctx:n}),p=n.format,u=jc([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!u)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const{createResp:m,taskId:g}=await(async t=>{const{requestBody:o,baseURL:i,accessToken:s,projectId:n}=t,r=await Ac.SubmitVideoGenerationsTasks(o,{baseURL:i,headers:{Authorization:`Bearer ${s}`},params:{project_id:n}}),a=qa(r),c=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([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:d,baseURL:r,accessToken:s,projectId:u});if(!o.wait)return"json"===p?void La({query_command:Pc(g),response:m,task_id:g}):void xa((e=>["Video generation task created successfully.",`taskId: ${e}`,`Use \`${Pc(e)}\` to query status.`].join("\n"))(g));const h=await(async t=>{const{taskId:o,baseURL:i,accessToken:s,pollIntervalMs:n,pollTimeoutMs:r,projectId:a}=t,c=Date.now();for(;;){const t=await kc({taskId:o,baseURL:i,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}): ${l=t.error_message,d=()=>"unknown",null!=l?l:d()}`,t);if(Date.now()-c>r)throw new e.CozeError(e.ErrorCode.E5003,[`Video generation timed out after ${r}ms.`,`taskId: ${o}`,`Use \`coze generate video status ${o}\` to query status.`].join("\n"),{task_id:o,last_status:t.status});await Sc(n)}var l,d})({taskId:g,baseURL:r,accessToken:s,pollIntervalMs:2e3,pollTimeoutMs:3e5,projectId:u}),f=jc([h,"access",e=>e.content,"optionalAccess",e=>e.video_url]),_=jc([h,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);if(!f||"string"!=typeof f)throw new e.CozeError(e.ErrorCode.E5002,"Video generated successfully but video_url was not returned");if(a){const e=await ic({outputPath:a,videoUrl:f,lastFrameUrl:_,shouldSaveLastFrame:!0===o.returnLastFrame});return"json"===p?void La({task_id:g,request:d,response:h,saved_paths:e}):void xa(e.join("\n"))}if("json"===p)return void La({task_id:g,request:d,response:h});const y=[f];!0===o.returnLastFrame&&"string"==typeof _&&_.length>0&&y.push(_),xa(y.join("\n"))},xc=async(t,o,i)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:r}=Tc(i),a=jc([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!a)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");let c;try{c=await kc({taskId:t,baseURL:r,accessToken:s,projectId:a})}catch(o){if((e=>404===jc([e,"optionalAccess",e=>e.response,"optionalAccess",e=>e.status]))(o))throw new e.CozeError(e.ErrorCode.E3000,`Video generation task '${t}' not found`,{taskId:t},{trigger:"The task ID does not exist or has expired",fix:"Check the task ID returned by `coze generate video create`",example:"coze generate video status <taskId>"});throw o}zc({ctx:n,response:c})},Lc=(e,t)=>{const o=t.getContext();Q(e,o)},Oc=e=>{var t;t=e.command("create [prompt]").description("Create a video generation task").config({help:ec}).action((async(e,t,o)=>{try{await Rc(e,t,o)}catch(e){Lc(e,o)}})),t.option("--callback-url <url>","Callback URL for task status changes").option("--return-last-frame","Return last frame URL (default: disabled)",Ja).option("--resolution <res>","Resolution: 480p|720p|1080p",Ga).option("--ratio <ratio>",`Aspect ratio (default: ${Fa})`,Fa).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)",Ha).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")},Dc=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);Oc(t),(e=>{e.command("status <taskId>").description("Query video generation task status by task ID").config({help:tc}).action((async(e,t,o)=>{try{await xc(e,0,o)}catch(e){Lc(e,o)}}))})(t)},Uc="2K",qc=!0,Bc="url",Mc="standard",Nc="disabled",$c={brief:"Generate images from text",description:"Generate images from a text prompt, optionally guided by reference images. Requires login and a configured billing project; each call is billed to that project. Without --output-path the command prints image URLs (or base64 data); with --output-path it downloads the images into the given directory.",examples:[{desc:"Generate image",cmd:'coze generate image "A futuristic city"',tags:["[RECOMMENDED]"]},{desc:"Save into a directory",cmd:'coze generate image "A cat" --output-path ./images'},{desc:"Specify size",cmd:'coze generate image "A dog" --size 2048x2048'},{desc:"Use a reference image",cmd:'coze generate image "Make it watercolor style" --image https://example.com/cat.png'},{desc:"Read prompt from a pipe",cmd:"cat prompt.txt | coze generate image --stdin --output-path ./images",tags:["[PIPELINE]"]}],enums:{"response-format":{url:"Return a temporary download URL for each generated image",b64_json:"Return each generated image inline as base64-encoded data"},sequential:{auto:"Let the model decide whether to generate a group of related images (up to --max-images)",disabled:"Generate a single image only (default)"}},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)"},outputPath:{type:"string",description:"Directory path to save the generated image files (inherited from `coze generate --output-path`)"},size:{type:"string",default:Uc,description:"Image size: 2K|4K or WIDTHxHEIGHT"},watermark:{type:"boolean",default:qc,description:"Add watermark (disable with --no-watermark)"},image:{type:"array",items:{type:"string"},description:"Reference image URL (can be used multiple times)"},responseFormat:{type:"string",enum:["url","b64_json"],default:Bc,description:"Response format"},optimizePromptMode:{type:"string",default:Mc,description:"Prompt optimization mode"},sequential:{type:"string",enum:["auto","disabled"],default:Nc,description:"Group image generation mode"},maxImages:{type:"number",default:15,description:"Maximum number of group images (1-15)"},stdin:{type:"boolean",description:"Read prompt from stdin (pipe input)"}},output:{type:"object",description:"Without --output-path, prints the ImageData array (url/b64_json/size per item). With --output-path, prints an object { created, image_0..image_N, saved_paths }.",properties:{created:{type:"number"},image_0:{type:"object",description:"ImageData of the Nth image (image_0..image_N)"},saved_paths:{type:"array",items:{type:"string"}}}}},caveats:["--output-path must be a directory; files are saved inside it as image_<timestamp>_<index>.<ext>","Invalid --response-format, --sequential, or --max-images values fall back to defaults with a warning; an invalid --size fails with E1000 instead of falling back","With --sequential auto the model may return multiple images in one call (capped by --max-images)","Each call is billed to the configured billing project"],seeAlso:["coze generate audio","coze generate video create","coze file upload"]};function Gc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Fc=3686400,Vc=16777216,Wc=e=>"object"==typeof e&&null!==e,Hc=(t,o)=>new e.CozeError(e.ErrorCode.E1000,`Invalid --size '${t}': ${o}`,{size:t},{trigger:"The --size value failed local validation",fix:"Use 2K/4K or WIDTHxHEIGHT with total pixels in [3686400, 16777216] and aspect ratio in [1:16, 16:1]",example:'coze generate image "A dog" --size 2048x2048'}),Jc=e=>{if("string"==typeof e){const t=e.trim();return t.length?t:Mc}return Mc},Kc=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},Qc=t=>{t.command("image [prompt]").description("Generate images from text prompts").config({help:$c}).option("--size <size>","Image size: 2K|4K or WIDTHxHEIGHT (local validation)",Uc).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",Bc).option("--optimize-prompt-mode <mode>",`Prompt optimization mode (default: ${Mc})`,Mc).option("--sequential <mode>","Group image generation mode: auto|disabled",Nc).option("--max-images <n>","Maximum number of group images (1-15)",String(15)).option("--stdin","Read prompt from stdin (pipe input)").action((async(t,o,i)=>{const n=i.getContext(),{outputPath:r}=i.optsWithGlobals(),a=await $a(t,{stdin:o.stdin}),c=Gc([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const l=(e=>{if(null==e)return{value:Uc};if("string"!=typeof e)throw Hc(String(e),"expected 2K/4K or WIDTHxHEIGHT");const t=e.trim();if("2K"===t||"4K"===t)return{value:t};const o=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(t);if(!o)throw Hc(t,"expected 2K/4K or WIDTHxHEIGHT");const i=Number(o[1]),s=Number(o[2]),n=i*s,r=i/s;if(!(Number.isFinite(i)&&Number.isFinite(s)&&i>0&&s>0&&n>=Fc&&n<=Vc&&r>=.0625&&r<=16))throw Hc(t,"total pixels must be in [3686400, 16777216], aspect ratio must be in [1:16, 16:1]");return{value:`${i}x${s}`}})(o.size),d="url"===(p=o.responseFormat)||"b64_json"===p?{value:p}:void 0!==p?{value:Bc,warning:`Invalid --response-format '${String(p)}', falling back to '${Bc}'`}:{value:Bc};var p;const u=(e=>"auto"===e||"disabled"===e?{value:e}:void 0!==e?{value:Nc,warning:`Invalid --sequential '${String(e)}', falling back to '${Nc}'`}:{value:Nc})(o.sequential),m=(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'`}})(o.maxImages);l.warning&&Gc([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(l.warning)]),d.warning&&Gc([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(d.warning)]),u.warning&&Gc([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(u.warning)]),m.warning&&Gc([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(m.warning)]);const g={model:"doubao-seedream-4-5-251128",prompt:a,size:l.value,watermark:"boolean"==typeof o.watermark?o.watermark:qc,image:Kc(o.image),response_format:d.value,optimize_prompt_options:{mode:Jc(o.optimizePromptMode)},sequential_image_generation:u.value,sequential_image_generation_options:{max_images:m.value}},h=(t=>{const o=Wc(t)&&"data"in t?t.data:t;if(Wc(i=o)&&"string"==typeof i.model&&"number"==typeof i.created&&Array.isArray(i.data))return o;var i;throw new e.CozeError(e.ErrorCode.E5002,"Image generation API returned an unexpected response format",t)})(await Ac.GenerateImages({Body:g},{baseURL:s.DEFAULT_CONFIG.integrationApiBaseUrl,params:{project_id:c}}));if(h.error)throw new e.CozeError(e.ErrorCode.E5002,"Image generation failed (top-level error)",h.error);const f=(y=()=>Bc,null!=(_=g.response_format)?_:y());var _,y;const b=h.data.filter((e=>!e.error&&("url"===f?"string"==typeof e.url&&e.url.length>0:"string"==typeof e.b64_json&&e.b64_json.length>0)));if(0===b.length)throw new e.CozeError(e.ErrorCode.E5002,"Image generation succeeded but no valid image data was returned",h);if(r){const t=[],o=Ma();for(const[i,s]of b.entries()){const n="url"===f&&s.url?Ba(s.url,".png"):".png",a=Na({outputPath:r,type:"image",index:i,ext:n,timestamp:o});let c;if("url"===f){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 l=await Oa(a,c);t.push(l)}const{model:i,usage:s,HttpHeader:a,...c}=(e=>{const{data:t,...o}=e,i=Object.fromEntries(t.map(((e,t)=>[`image_${t}`,e])));return{...o,...i}})(h);Gc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...c,saved_paths:t})])}else Gc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(h.data)])}))},Yc="cli_user",Zc="zh_female_xiaohe_uranus_bigtts",Xc="mp3",el=24e3,tl={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"',tags:["[RECOMMENDED]"]},{desc:"Save into a directory",cmd:'coze generate audio "Hello" --output-path ./out'},{desc:"Pipe SSML input from stdin",cmd:'echo "<speak>Hello</speak>" | coze generate audio --ssml --stdin',tags:["[PIPELINE]"]},{desc:"Specify audio encoding",cmd:'coze generate audio "Hello" --audio-format ogg_opus'}],enums:{"audio-format":{pcm:"Raw PCM audio frames without a container header (for further processing)",mp3:"MP3 encoded audio, playable by most players (default)",ogg_opus:"Opus audio in an OGG container, smaller at comparable quality"}},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` 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)"},outputPath:{type:"string",description:"Directory path to save the generated audio file (inherited from `coze generate --output-path`)"},uid:{type:"string",default:Yc,description:"User UID"},speaker:{type:"string",default:Zc,description:"Speaker voice"},audioFormat:{type:"string",enum:["pcm","mp3","ogg_opus"],default:Xc,description:"Audio encoding format"},sampleRate:{type:"number",default:el,description:"Sample rate"},speechRate:{type:"number",default:0,description:"Speech rate (-50..100)"},loudnessRate:{type:"number",default:0,description:"Loudness (-50..100)"},ssml:{type:"boolean",default:!1,description:"Treat input as SSML (defaults to plain text)"},stdin:{type:"boolean",description:"Read prompt from stdin (pipe input)"}},output:{type:"object",description:"Applies to `--format json` only; in text mode the command prints a plain string (saved path or audio URL)",properties:{request:{type:"object"},url:{type:"string",description:"Audio download URL"},saved_path:{type:"string",description:"Local path if saved"}}}},caveats:["--output-path must be a directory; the audio file is saved inside it as audio_<timestamp>_0.<ext>","Plain text and SSML are mutually exclusive: with --ssml the whole input is sent as SSML, otherwise it is sent as plain text","pcm output has no container header; most players require mp3 or ogg_opus","Each call is billed to the configured billing project"],seeAlso:["coze generate image","coze generate video create","coze file upload"]};function ol(e,t){return null!=e?e:t()}function il(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const sl=(e,t)=>"pcm"===e||"mp3"===e||"ogg_opus"===e?e:(void 0!==e&&il([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --audio-format '${String(e)}', falling back to '${Xc}'`)]),Xc),nl=(e,t,o,i)=>{if(null==e)return t;const s=Number(e);return Number.isFinite(s)?Math.floor(s):(il([i,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",i=>i(`Invalid --${o} '${String(e)}', falling back to ${t}`)]),t)},rl=t=>{const o=t.trim();if(0===o.length)return null;const i=o.startsWith("data:")?o.slice(5).trim():o;if(0===i.length)return null;const s=i[0];if("{"!==s&&"["!==s)return null;const n=e.safeJsonParse(i,void 0,{onError:t=>{const i=t instanceof Error?t.message:String(t);throw new e.CozeError(e.ErrorCode.E5002,`Failed to parse response: ${i}`,{line:o})}});return void 0===n?null:Da(n)&&"number"==typeof n.code?n:null},al=t=>{const o=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. All subcommands require login and a configured billing project, and the generation cost is billed to that project. Use the shared --output-path option to download generated files into a local directory; without it, commands print result URLs or data.",examples:[{desc:"Generate image",cmd:'coze generate image "A cat"',tags:["[RECOMMENDED]"]},{desc:"Generate audio",cmd:'coze generate audio "Hello world"'},{desc:"Generate video",cmd:'coze generate video create "A dancing dog"'},{desc:"Save generated files into a directory",cmd:'coze generate image "A cat" --output-path ./out'}],seeAlso:["coze file upload","coze auth login"]}}).option("--output-path <path>","Directory path to save the generated media files");Qc(o),(t=>{t.command("audio [prompt]").description("Synthesize speech from text or SSML (streaming)").config({help:tl}).option("--uid <uid>",`User UID (default: ${Yc})`,Yc).option("--speaker <speaker>",`Speaker (default: ${Zc})`,Zc).option("--audio-format <format>","Audio encoding: pcm|mp3|ogg_opus",Xc).option("--sample-rate <n>","Sample rate (default: 24000)",String(el)).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,o,i)=>{const s=i.getContext();try{const{outputPath:n}=i.optsWithGlobals(),r=il([s,"optionalAccess",e=>e.config,"access",e=>e.integrationApiBaseUrl]);if(!il([s,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]))throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login` first");const a=await $a(t,{stdin:o.stdin}),c=il([s,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const l={user:{uid:ol(Ua(o.uid),(()=>Yc))},req_params:{speaker:ol(Ua(o.speaker),(()=>Zc)),audio_params:{format:sl(o.audioFormat,s),sample_rate:nl(o.sampleRate,el,"sample-rate",s),speech_rate:nl(o.speechRate,0,"speech-rate",s),loudness_rate:nl(o.loudnessRate,0,"loudness-rate",s)}}};o.ssml?l.req_params={...l.req_params,ssml:a}:l.req_params={...l.req_params,text:a};const d=new URL("/api/v3/tts/unidirectional",r);d.searchParams.append("project_id",c);const p=await e.customFetch.fetch(d.toString(),{method:"POST",body:JSON.stringify(l)});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"),m=p.body.getReader(),g=[];let h;const f=t=>{if(0===t.code)return n&&"string"==typeof t.data&&g.push(Buffer.from(t.data,"base64")),!1;if(2e7===t.code)return"string"==typeof t.url&&t.url.length>0&&(h=t.url),!0;throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis failed (code=${t.code}): ${ol(t.message,(()=>"unknown"))}`,t)};let _="";for(;;){const{done:e,value:t}=await m.read();if(e)break;_+=u.decode(t,{stream:!0});const o=_.split(/\r?\n/);_=ol(o.pop(),(()=>""));for(const e of o){const t=rl(e);if(t&&f(t)){await m.cancel();break}}if(h)break}if(!h){_+=u.decode();const e=_.split(/\r?\n/);_="";for(const t of e){const e=rl(t);if(e&&f(e))break}}if(n){const t=ol(il([l,"access",e=>e.req_params,"optionalAccess",e=>e.audio_params,"optionalAccess",e=>e.format]),(()=>Xc)),o="pcm"===t?".pcm":"ogg_opus"===t?".ogg":".mp3",i=Ma(),r=Na({outputPath:n,type:"audio",index:0,ext:o,timestamp:i});let a=null;if(g.length>0)a=await Oa(r,Buffer.concat(g));else if(h){const t=await e.customFetch.fetch(h);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=Ba(h,o),c=Na({outputPath:n,type:"audio",index:0,ext:r,timestamp:i});a=await Oa(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:h});return"json"===il([s,"optionalAccess",e=>e.format])?void La({request:l,url:h,saved_path:a}):void xa(a)}if("json"===il([s,"optionalAccess",e=>e.format]))return void La({request:l,url:h});if(h)return void xa(h);xa("Speech synthesis completed, but no audio download URL was returned; you can use --format json to view details.")}catch(e){Q(e,s)}}))})(o),Dc(o)};function cl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ll=o=>{(o=>{o.command("upload <path>").description("Upload a local file").config({help:{brief:"Upload a local file",description:"Upload a local file to Coze and get an online URL back. The file can be used as an attachment or context in projects. In text mode the command prints only the file URL, which makes it easy to embed in other commands.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf",tags:["[RECOMMENDED]"]},{desc:"Get the full result as JSON (file_url and file_uri)",cmd:"coze file upload ./screenshot.png --format json"},{desc:"Upload and reference the URL in a project message",cmd:'coze code message send "Use this asset: $(coze file upload ./logo.png)" -p 123456',tags:["[PIPELINE]"]}],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"},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The given path points to a directory, not a file",fix:"Pass a path to a single file; uploading directories is not supported",example:"coze file upload ./document.pdf"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed during upload",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Upload API returned an error",fix:"Please retry later. Use --debug for more details"}],schema:{input:{path:{type:"string",required:!0,description:"Local file path to upload"}},output:{type:"object",description:"In `--format json` mode prints the upload result object; in text mode prints the uploaded file URL string",properties:{file_url:{type:"string",description:"Uploaded file URL"},file_uri:{type:"string",description:"Uploaded file URI"}}}},caveats:["Uploading directories is not supported; pass a single file path","Uploaded files are stored as temporary CLI attachments and the returned URL expires after a retention period (about 24 hours); re-upload when the link expires"],seeAlso:["coze code message send","coze generate image"]}}).action((async(o,i,s)=>{let n;try{let i;n=s.getContext();try{i=await g.stat(o)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${o}`,{filePath:o})}if(!i.isFile())throw new e.CozeError(e.ErrorCode.E1000,`Not a file: ${o}. Uploading directories is not supported`,{filePath:o},{trigger:"The given path points to a directory",fix:"Pass a path to a single file",example:"coze file upload ./document.pdf"});const r=m.basename(o),a=m.extname(o),c=a?r.slice(0,-a.length):r,l=a.slice(1),d=new f;d.append("file_name",c),d.append("file_extension",l),d.append("file_content",h.createReadStream(o)),d.append("biz_type","cli_attachment");const p=await t.IdeApi.UploadFile({data:d},{headers:{...d.getHeaders()}});"json"===cl([n,"optionalAccess",e=>e.format])?cl([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(p.data)]):cl([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(cl([p,"access",e=>e.data,"optionalAccess",e=>e.file_url]))])}catch(e){Q(e,n)}}))})(o.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. Uploading returns an online URL for the file.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf",tags:["[RECOMMENDED]"]},{desc:"Get the upload result as JSON",cmd:"coze file upload ./screenshot.png --format json"}],seeAlso:["coze code message send","coze generate image"]}}))};function dl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function pl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function ul(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function ml(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const gl=t=>{const o=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. Effective configuration is merged from environment variables, the local `.cozerc.json` in the current directory, and the global `~/.coze/cli/config.json` (environment variables take the highest priority). No authentication is required for any config subcommand.",examples:[{desc:"List all configurations",cmd:"coze config list",tags:["[RECOMMENDED]"]},{desc:"Get a configuration value",cmd:"coze config get spaceId"},{desc:"Set a configuration value",cmd:"coze config set spaceId 123456789"},{desc:"Delete a configuration value",cmd:"coze config delete spaceId"}],seeAlso:["coze auth status","coze space use","coze organization use"]}});(t=>{t.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 and source of the specified configuration keys. Values are resolved from environment variables, the local `.cozerc.json`, the global `~/.coze/cli/config.json`, and built-in defaults, in that priority order. If a key does not exist, a warning is printed and the command still exits with code 0.",examples:[{desc:"Get default Space ID",cmd:"coze config get spaceId",tags:["[RECOMMENDED]"]},{desc:"Get API base URL",cmd:"coze config get apiBaseUrl"},{desc:"Get multiple configurations",cmd:"coze config get spaceId organizationId"},{desc:"Read a value in a script",cmd:"coze config get spaceId --format json",tags:["[PIPELINE]"]}],schema:{input:{keys:{type:"array",items:{type:"string"},required:!0,description:"Configuration key names (e.g. spaceId, organizationId, apiBaseUrl)",example:["spaceId"]}},output:{key:{type:"string",description:"Configuration key name",example:"spaceId"},value:{type:"any",description:"Configuration value",example:"123456789"},source:{type:"string",enum:["env","env-file","local","global","default"],description:"Where the effective value comes from",example:"global"}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Unexpected failure while reading configuration files",fix:"Retry with --debug to see details; check that config files are readable",example:"coze config get spaceId --debug"}],seeAlso:["coze config list","coze config set","coze config delete"],caveats:["A missing key only prints a warning; it does not fail the command"]}}).action((async(e,t,o)=>{const i=o.getContext(),n=await s.listConfigs();for(const t of e){const e=n.find((e=>e.key===t));dl(e?[i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)]:[i,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Configuration '${t}' not found.`)])}}))})(o),(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 configuration key-value pair. Nested keys use dot paths, e.g. `upgrade.mode`. The value is persisted in the global configuration file `~/.coze/cli/config.json` (or the file pointed to by the COZE_CONFIG_FILE environment variable, if set). The key is free-form, but only known keys (see the `key` enum below) affect CLI behavior; internal state paths (e.g. `upgrade.cache.*`) cannot be set.",examples:[{desc:"Set default workspace",cmd:"coze config set spaceId 123456789",tags:["[RECOMMENDED]"]},{desc:"Set default organization",cmd:"coze config set organizationId 987654321"},{desc:"Switch upgrade strategy to notify-only",cmd:"coze config set upgrade.mode notify"},{desc:"Switch upgrade channel to beta",cmd:"coze config set upgrade.channel beta"},{desc:"Set then verify in a script",cmd:"coze config set spaceId 123456789 && coze config get spaceId --format json",tags:["[PIPELINE]"]}],enums:{key:{spaceId:"Default Space ID used when --space-id is not passed",organizationId:"Default Organization ID used when --org-id is not passed",apiBaseUrl:"Base URL of the Coze Coding API",openApiBaseUrl:"Base URL of the Coze Open API",defaultOutputFormat:"Default output format when --format is not passed","upgrade.mode":"Auto-upgrade strategy: auto (silent background upgrade, default) / notify (prompt only) / off (disabled)","upgrade.channel":"npm dist-tag used for upgrades: latest (default), beta, alpha, ...","skill.mode":"Bundled-skill consistency strategy: auto (silently run `coze self skill install` on mismatch, default) / notify (prompt only) / off (disabled)",disableTelemetry:"Whether to disable anonymous usage statistics (true/false)"}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to write the configuration file (e.g. directory not writable)",fix:"Please check the key/value and file permissions, then retry. Use --debug for more details.",example:"coze config set spaceId 123456789 --debug"}],schema:{input:{key:{type:"string",required:!0,description:"Configuration key name",example:"spaceId"},value:{type:"string",required:!0,description:"New configuration value",example:"123456789"}},output:{key:{type:"string",description:"Configuration key name",example:"spaceId"},value:{type:"string",description:"Saved configuration value",example:"123456789"},scope:{type:"string",enum:["global"],description:"Scope the value was written to (always global)",example:"global"},status:{type:"string",enum:["updated"],description:"Operation result",example:"updated"},message:{type:"string",description:"Human-readable result message",example:"Configuration 'spaceId' updated successfully in global scope."}}},seeAlso:["coze config get","coze config list","coze config delete"],caveats:["Always writes to the global scope; the local `.cozerc.json` is never modified by this command","Unknown keys are saved as-is without validation"]}}).action((async(t,o,i,n)=>{const r=n.getContext();try{if(s.isInternalConfigPath(t))throw new e.CozeError(e.ErrorCode.E5000,`'${t}' is internal state managed by the CLI and cannot be set.`);const i=s.buildPatchByPath(t,o),n="global";await s.saveConfig(i,n);const a={key:t,value:o,scope:n,status:"updated",message:`Configuration '${t}' updated successfully in ${n} scope.`};if(pl([r,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(a.message)]),"json"===pl([r,"optionalAccess",e=>e.format]))return void pl([r,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])}catch(i){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set '${t}' to '${o}': ${i.message}`,i.stack)}}))})(o),(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 keys from the configuration files. For each key, the local `.cozerc.json` in the current directory is checked first; if the key is not there, it is removed from the global `~/.coze/cli/config.json`. Deleting a key that does not exist is a no-op and still reports success.",examples:[{desc:"Delete a specific configuration key",cmd:"coze config delete spaceId",tags:["[RECOMMENDED]"]},{desc:"Delete multiple configuration keys",cmd:"coze config delete spaceId organizationId"},{desc:"Delete then verify in a script",cmd:"coze config delete spaceId && coze config get spaceId --format json",tags:["[PIPELINE]"]}],errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to write the configuration file when removing the key",fix:"Please check the configuration key and file permissions, then retry. Use --debug for more details.",example:"coze config delete spaceId --debug"}],schema:{input:{keys:{type:"array",items:{type:"string"},required:!0,description:"Configuration key names to delete",example:["spaceId"]}},output:{key:{type:"string",description:"Deleted configuration key name",example:"spaceId"},status:{type:"string",enum:["deleted"],description:"Operation result",example:"deleted"},message:{type:"string",description:"Human-readable result message",example:"Configuration 'spaceId' has been removed."}}},seeAlso:["coze config list","coze config get","coze config set"],caveats:["Built-in defaults and environment variables cannot be deleted; only values stored in config files are removed"]}}).action((async(t,o,i)=>{const n=i.getContext();for(const o of t)try{await s.deleteConfig(o);const e={key:o,status:"deleted",message:`Configuration '${o}' has been removed.`};ul([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleted ${o} from configuration file successfully.`)]),"json"===ul([n,"optionalAccess",e=>e.format])&&ul([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)])}catch(t){const i=t;throw new e.CozeError(e.ErrorCode.E5000,`Failed to delete config '${o}': ${i.message}`,i.stack)}}))})(o),(t=>{t.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 every effective configuration item with its value and source. Items are merged from environment variables, the local `.cozerc.json`, the global `~/.coze/cli/config.json`, and built-in defaults (environment variables take the highest priority). The command is read-only and requires no authentication.",examples:[{desc:"List configurations",cmd:"coze config list",tags:["[RECOMMENDED]"]},{desc:"List configurations as JSON for scripts",cmd:"coze config list --format json",tags:["[PIPELINE]"]},{desc:"Inspect merge result with debug logs",cmd:"coze config list --debug"}],schema:{output:{type:"array",description:"All effective configuration items",items:{key:{type:"string",description:"Configuration key name",example:"spaceId"},value:{type:"any",description:"Effective configuration value",example:"123456789"},source:{type:"string",enum:["env","env-file","local","global","default"],description:"Where the effective value comes from",example:"global"}}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Unexpected failure while reading configuration files",fix:"Retry with --debug to see details; check that config files are readable",example:"coze config list --debug"}],seeAlso:["coze config get","coze config set","coze config delete"]}}).action((async(e,t)=>{const o=t.getContext(),i=(await s.listConfigs()).map((({key:e,value:t,source:o})=>({key:e,value:t,source:o})));ml([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Configurations found:")]),ml([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(i)])}))})(o)},hl="__COZE_FILE_COMP__";function fl(){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 _l(e){const t=y.homedir();switch(e){case"bash":return n.join(t,"darwin"===process.platform?".bash_profile":".bashrc");case"zsh":return n.join(t,".zshrc");case"fish":return n.join(t,".config/fish/config.fish");case"powershell":return function(){const e=["pwsh","powershell"];for(const t of e)try{const e=i.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 yl(){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]}" == "${hl}" ]]; 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" == "${hl}" ]]; 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(y.EOL)}function bl(e){switch(e){case"bash":return`\n# begin coze completion\nsource ${s.getGlobalCompletionFile()}\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 '${hl}') {\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 vl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}let wl,El,Cl=!1,Il=!1;function Al(e){const t=(o=e._args,i=()=>[],null!=o?o:i());var o,i;if(0===t.length)return!1;const s=/path|file|dir|folder/i;return t.some((e=>s.test(e._name)))}function Sl(){const e=fl();if(!e)return!1;const t=_l(e);if(!t)return!1;if("bash"===e){const e=s.getGlobalConfigDir(),t=n.join(e,"completion.sh");a.existsSync(e)||a.mkdirSync(e,{recursive:!0}),a.writeFileSync(t,yl())}const o=n.dirname(t);a.existsSync(o)||a.mkdirSync(o,{recursive:!0});const i=bl(e);return!!i&&(a.appendFileSync(t,i),!0)}async function kl(e){if(!e.completionInstalled&&process.stdout.isTTY&&!process.env.CI&&!(process.argv.includes("--compzsh")||process.argv.includes("--compbash")||process.argv.includes("--compfish")||process.argv.includes("--comppwsh")||Cl||Il))if(function(){try{const e=fl();if(!e)return!1;const t=_l(e);return!(!t||!a.existsSync(t))&&a.readFileSync(t,"utf8").includes("begin coze completion")}catch(e){return!1}}())try{await s.saveConfig({completionInstalled:!0})}catch(e){}else try{Sl()&&(await s.saveConfig({completionInstalled:!0}),console.log("Shell auto-completion has been configured. Restart your terminal to activate."))}catch(e){}}function jl(t){El=t,function(){const e=process.argv.indexOf("--completion");e>-1&&(Cl=!0,process.argv.splice(e,1));const t=process.argv.indexOf("--completion-fish");t>-1&&(Il=!0,process.argv.splice(t,1))}(),wl=_("coze"),wl.on("complete",((e,o)=>{const i=o.line.trimStart().split(/\s+/);i.length>0&&(i[0].endsWith("coze")||i[0].endsWith("bin/main"))&&i.shift();let s="";o.line.endsWith(" ")?(s="",""===i[i.length-1]&&i.pop()):s=i.pop()||"";const n=function(e,t,o){let i=e;for(const e of t){const t=i.commands.find((t=>t.name()===e||t.alias()===e));if(t)i=t;else if(!e.startsWith("-"))return Al(i)?[hl]:[]}const s=[];i.commands.length>0&&i.commands.forEach((e=>{s.push(e.name())})),i.options.forEach((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))})),i!==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(o)));return 0===n.length&&Al(i)?[hl]:n}(t,i,s);o.reply(n)})),t.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). The shell type is auto-detected and the completion block is written to its startup script (.bashrc / .zshrc / fish config / $PROFILE). Running the command without options behaves the same as --setup; when --setup and --cleanup are both passed, --cleanup wins. A terminal restart (or sourcing the startup script) is required for changes to take effect.",examples:[{desc:"Install completion for the detected shell (minimal)",cmd:"coze completion",tags:["[RECOMMENDED]"]},{desc:"Install completion script explicitly",cmd:"coze completion --setup"},{desc:"Remove completion script",cmd:"coze completion --cleanup"}],schema:{input:{setup:{type:"boolean",required:!1,default:!0,description:"Install shell completion into the startup script (default behavior when no option is passed)"},cleanup:{type:"boolean",required:!1,default:!1,description:"Remove shell completion from the startup script (takes precedence over --setup)"}},output:{message:{type:"string",description:"Plain-text result message printed to stdout (no JSON output)",example:"Shell completion (zsh) setup successful! Please restart your terminal or source your config file."}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Shell type could not be detected, or writing the completion block to the startup script failed (exit code 1)",fix:"Use a supported shell (bash, zsh, fish, powershell) and ensure the startup script is writable",example:"coze completion --setup"}],seeAlso:["coze upgrade","coze config list"],caveats:["Completion is also auto-installed on the first interactive run of the CLI (skipped in CI or non-TTY environments)","Changes only take effect after restarting the terminal or sourcing the shell startup script","For bash, an extra completion script is written to the `~/.coze/cli/` directory"]}}).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=fl();if(!e)return;const t=_l(e);if(!t||!a.existsSync(t))return;const o=bl(e);if(o){const e=a.readFileSync(t,"utf8").replace(new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"");a.writeFileSync(t,e)}if("bash"===e){const e=s.getGlobalConfigDir(),t=n.join(e,"completion.sh");a.existsSync(t)&&a.unlinkSync(t),a.existsSync(e)&&0===a.readdirSync(e).length&&a.rmdirSync(e)}}(),await s.saveConfig({completionInstalled:!1}),console.log("Shell completion removed! Please restart your terminal.");else{const e=fl();if(!e)return console.error("Could not detect your shell type. Supported shells: bash, zsh, fish, powershell."),void(process.exitCode=1);Sl()?(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 Pl(){return Cl?(console.log(yl()),void process.exit()):Il?(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]" = "${hl}"`," return"," end"," for c in $completions"," echo $c"," end","end","complete -c coze -a '(_coze_completion)' -n '_coze_completion'","### coze completion - end ###"].join(y.EOL)),void process.exit()):void(process.argv.includes("--comppwsh")?function(){if(!El)return void process.exit();const e=process.argv.indexOf("--comppwsh"),t=process.argv.slice(e+1);let o=El;const i=[];for(const e of t){const t=vl([o,"access",e=>e.commands,"optionalAccess",e=>e.find,"call",t=>t((t=>t.name()===e||t.alias()===e))]);t?o=t:i.push(e)}const s=[];vl([o,"access",e=>e.commands,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{s.push(e.name())}))]),vl([o,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}))]),o!==El&&vl([El,"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=i[i.length-1]||"",r=Array.from(new Set(s)).filter((e=>e.startsWith(n)));0===r.length&&Al(o)?console.log(hl):r.length>0&&console.log(r.join("\n")),process.exit()}():wl&&wl.init())}class zl{static getInstance(){return zl.INSTANCE||(zl.INSTANCE=new zl),zl.INSTANCE}async getDefaultConversation(e){return(await t.BuildAgentApi.GetProjectDefaultConversation({project_id:e})).Data}async updateConversationSetting(e,o,i){await t.BuildAgentApi.UpdateConversationSetting({project_id:e,conversation_id:o,...void 0!==i.modelSetting?{model_setting:i.modelSetting}:{},...void 0!==i.skillSetting?{skill_setting:i.skillSetting}:{},...void 0!==i.mode?{mode:i.mode}:{},...void 0!==i.agentTools?{agent_tools:i.agentTools}:{}})}}const Tl=zl.getInstance();function Rl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function xl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Ll(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ol=o=>{const i=o.command("tools").config({help:{brief:"Manage project tools",description:"Manage tools associated with a project. Tools extend project capabilities such as web search, image generation, etc.",examples:[{desc:"List project tools",cmd:"coze code tools list -p <projectId>"},{desc:"Enable a tool",cmd:"coze code tools enable enable_image_gen -p <projectId>"},{desc:"Disable a tool",cmd:"coze code tools disable enable_image_gen -p <projectId>"}],seeAlso:["coze code project","coze code model"]}}).description("Manage project tools");!function(o){o.command("list").description("List available tools for the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List available tools for the project",description:"List all available tools for the specified project type, with enabled status indicating current configuration.",examples:[{desc:"List project tools",cmd:"coze code tools list -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:"array",items:{type:"object",properties:{tool_name:{type:"string",description:"Tool name"},description:{type:"string",description:"Tool description"},enabled:{type:"boolean",description:"Whether the tool is enabled"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Check the project ID, run `coze code project list` to view available projects"},{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"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server failed to fetch the tool list or conversation settings",fix:"Retry later; run with --debug for details if the issue persists"}],seeAlso:["coze code tools enable","coze code tools disable"]}}).action((async function(e,o){const i=o.getContext(),{projectId:s}=e,n=Rl([await t.IdeApi.GetVibeProject({project_id:s}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=Rl([await Tl.getDefaultConversation(s),"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools]),a=Rl([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===n)),"optionalAccess",e=>e.tools]);if(!a||0===a.length)return Rl([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("No tools available for this project type.")]),void Rl([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e([])]);const c=a.map((e=>({tool_name:e.name,description:e.description||e.display_name,enabled:Rl([r,"optionalAccess",t=>t[e.name]])})));Rl([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${c.length} tools.`)]),Rl([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(c)])}))}(i),function(o){o.command("enable <toolName>").description("Enable a conversation tool").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Enable a conversation tool",description:"Enable a specified tool in the default conversation settings.",examples:[{desc:"Enable image generation",cmd:"coze code tools enable enable_image_gen -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{toolName:{type:"string",required:!0,description:"Tool name to enable"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},enable_tool_name:{type:"string",description:"Enabled tool name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified tool is not available for this project type",fix:"Use 'coze code tools list -p <projectId>' to see available tools"}],seeAlso:["coze code tools list","coze code tools disable"]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=xl([await t.IdeApi.GetVibeProject({project_id:r}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=xl([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===a)),"optionalAccess",e=>e.tools]);if(!xl([c,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Tool '${o}' is not available for this project type`,{toolName:o,projectId:r});const l=await Tl.getDefaultConversation(r),d=xl([l,"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools])||{};await Tl.updateConversationSetting(r,l.id,{agentTools:{...d,[o]:!0}}),xl([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Tool '${o}' enabled.`)]),xl([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,enable_tool_name:o,message:`Tool '${o}' has been enabled successfully`})])}))}(i),function(o){o.command("disable <toolName>").description("Disable a conversation tool").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Disable a conversation tool",description:"Disable a specified tool in the default conversation settings.",examples:[{desc:"Disable image generation",cmd:"coze code tools disable enable_image_gen -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{toolName:{type:"string",required:!0,description:"Tool name to disable"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},disable_tool_name:{type:"string",description:"Disabled tool name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified tool is not available for this project type",fix:"Use 'coze code tools list -p <projectId>' to see available tools"}],seeAlso:["coze code tools list","coze code tools enable"]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=Ll([await t.IdeApi.GetVibeProject({project_id:r}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=Ll([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===a)),"optionalAccess",e=>e.tools]);if(!Ll([c,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Tool '${o}' is not available for this project type`,{toolName:o,projectId:r});const l=await Tl.getDefaultConversation(r),d=Ll([l,"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools])||{};await Tl.updateConversationSetting(r,l.id,{agentTools:{...d,[o]:!1}}),Ll([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Tool '${o}' disabled.`)]),Ll([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,disable_tool_name:o,message:`Tool '${o}' has been disabled successfully`})])}))}(i)};function Dl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Ul(e,t){return null!=e?e:t()}function ql(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Bl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Ml(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Nl(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const $l=o=>{const i=o.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");!function(o){o.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)").option("--my","List personal skills only").option("--page <page>","Page number (for personal skills)").option("--size <size>","Page size (for personal skills)").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]"]},{desc:"List personal skills",cmd:"coze code skill list -p <projectId> --my"},{desc:"List personal skills with pagination",cmd:"coze code skill list -p <projectId> --my --page 1 --size 10"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"},my:{type:"boolean",required:!1,description:"List personal skills only"},page:{type:"number",required:!1,description:"Page number (for personal skills, default: 1)"},size:{type:"number",required:!1,description:"Page size (for personal skills, default: 20)"}},output:{type:"object",properties:{items:{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"}}}},total:{type:"number",description:"Total number of records (only present for --my mode)"}}}},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"}],seeAlso:["coze code skill add","coze code skill remove"]}}).action((async function(o,i){const s=i.getContext(),{projectId:n}=o;if(o.my){const e=o.page?parseInt(o.page,10):1,t=o.size?parseInt(o.size,10):20,i=await Ac.GetUserSkillList({page:e,size:t});return ql([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${ql([i,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} personal skills.`)]),void ql([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({items:ql([i,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({skill_id:ql([e,"optionalAccess",e=>e.skill_id]),name:ql([e,"optionalAccess",e=>e.name]),description:ql([e,"optionalAccess",e=>e.description]),icon:ql([e,"optionalAccess",e=>e.icon]),is_installed:!1})))])||[],total:Ul(ql([i,"access",e=>e.data,"optionalAccess",e=>e.total]),(()=>0))})])}const r=Ul(Ul(o.spaceId,(()=>ql([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=ql([await Tl.getDefaultConversation(n),"access",e=>e.conversation_setting,"optionalAccess",e=>e.skill_setting,"optionalAccess",e=>e.skills])||[],l=new Set(c.map((e=>e.skill_id)).filter(Boolean)),d=ql([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),p=await Ac.GetSkillList({project_type:d,space_id:r,category_type_list:[d]});ql([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${ql([p,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} skills.`)]),ql([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({items:ql([p,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({description:ql([e,"optionalAccess",e=>e.description]),skill_id:ql([e,"optionalAccess",e=>e.skill_id]),name:ql([e,"optionalAccess",e=>e.name]),icon:ql([e,"optionalAccess",e=>e.icon]),is_installed:l.has(e.skill_id||"")})))])||[]})])}))}(i),function(t){t.command("add <skillId>").description("Add skills to the conversation").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add skill to conversation",description:"Add a specified skill to the default conversation. Skills can extend 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:{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 (returned by the API layer, not thrown by the CLI itself)",fix:"Please use `skill list` to confirm available skills"}],seeAlso:["coze code skill list","coze code skill remove"]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t,n=[e],r=await Tl.getDefaultConversation(s);await Tl.updateConversationSetting(s,r.id,{skillSetting:{add_skills:n.map((e=>({skill_id:String(e),is_preload:!0})))}}),Bl([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skills added successfully.")]),Bl([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,added_skill_ids:n,message:"added Skills successfully."})])}))}(i),function(t){t.command("remove <skillId>").description("Remove skills from the conversation").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Remove skill from conversation",description:"Remove a configured skill from the default conversation.",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:{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 conversation (returned by the API layer, not thrown by the CLI itself)",fix:"Please use `skill list` to confirm installed skills"}],seeAlso:["coze code skill list","coze code skill add"]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t,n=[e],r=await Tl.getDefaultConversation(s);await Tl.updateConversationSetting(s,r.id,{skillSetting:{remove_skills:n.map((e=>({skill_id:String(e),is_preload:!0})))}}),Dl([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill removed.")]),Dl([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,removed_skill_ids:n,message:"removed Skills successfully."})])}))}(i),function(t){t.command("upload <filePath>").description("Upload a personal skill").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Upload a personal skill",description:"Upload a .skill file as a personal skill. If a naming conflict exists, it will be automatically confirmed to overwrite.",examples:[{desc:"Upload a skill file",cmd:'coze code skill upload "./my-skill.skill" -p <projectId>',tags:["[RECOMMENDED]"]}],schema:{input:{filePath:{type:"string",required:!0,description:"Path to the .skill file"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"File not found at the specified path",fix:"Please provide a valid path to a .skill file"}],seeAlso:["coze code skill list","coze code skill delete"]}}).action((async function(t,o,i){const s=i.getContext(),{projectId:n}=o,r=m.resolve(t);if(!h.existsSync(r))throw new e.CozeError(e.ErrorCode.E1000,`File not found: ${r}`,{filePath:r});const a=m.basename(r),c=h.createReadStream(r);Ml([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Uploading skill ${a}...`)]);const l=await Ac.UploadSkill({body:{file_content:c,file_name:a}},{headers:{"Content-Type":"multipart/form-data"}});if(Ml([l,"access",e=>e.data,"optionalAccess",e=>e.naming_conflict])){const e=Ml([l,"access",e=>e.data,"optionalAccess",e=>e.conflict_info,"optionalAccess",e=>e.preview_skill_key]);Ml([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Naming conflict detected, auto-confirming overwrite...")]),await Ac.UploadSkillConfirm({preview_skill_key:e})}Ml([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill uploaded successfully.")]),Ml([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,message:"Skill uploaded successfully"})])}))}(i),function(t){t.command("delete <skillId>").description("Delete a personal skill").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete a personal skill",description:"Permanently delete a personal skill. This is different from skill remove which only unlinks a skill from the project.",examples:[{desc:"Delete a skill",cmd:"coze code skill delete <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{skillId:{type:"string",required:!0,description:"Skill ID to delete"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Skill not found or invalid skill ID",fix:"Use 'coze code skill list -p <projectId> --my' to see available skills"}],seeAlso:["coze code skill list","coze code skill upload"]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t;await Ac.DeleteSkill({skill_id:e}),Nl([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Skill '${e}' deleted.`)]),Nl([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({project_id:s,message:`Skill '${e}' has been permanently deleted`})])}))}(i)};var Gl,Fl,Vl,Wl,Hl,Jl,Kl,Ql,Yl,Zl,Xl,ed,td,od,id,sd,nd,rd,ad,cd,ld,dd,pd,ud,md,gd,hd,fd,_d,yd,bd,vd,wd,Ed,Cd,Id,Ad,Sd,kd,jd,Pd,zd,Td,Rd,xd,Ld,Od,Dd,Ud,qd,Bd,Md,Nd,$d,Gd,Fd,Vd,Wd,Hd,Jd,Kd,Qd,Yd,Zd,Xd,ep,tp,op,ip,sp,np,rp,ap,cp,lp,dp,pp;function up(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Gl||(Gl={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(Fl||(Fl={})),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"}(Vl||(Vl={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(Wl||(Wl={})),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"}(Hl||(Hl={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(Jl||(Jl={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(Kl||(Kl={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(Ql||(Ql={})),function(e){e[e.Official=1]="Official";e[e.Public=2]="Public";e[e.Custom=3]="Custom";e[e.Others=101]="Others"}(Yl||(Yl={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(Zl||(Zl={})),function(e){e[e.App=1]="App";e[e.Resource=2]="Resource"}(Xl||(Xl={})),function(e){e[e.CozeModel=1]="CozeModel";e[e.VolcAccount=2]="VolcAccount";e[e.SelfAccount=3]="SelfAccount";e[e.SelfModel=4]="SelfModel"}(ed||(ed={})),function(e){e[e.Asc=1]="Asc";e[e.Desc=2]="Desc"}(td||(td={})),function(e){e[e.NoDetail=1]="NoDetail";e[e.Detail=2]="Detail";e[e.Operate=3]="Operate"}(od||(od={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(id||(id={})),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"}(sd||(sd={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi";e[e.MessagesApi=2]="MessagesApi"}(nd||(nd={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(rd||(rd={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(ad||(ad={})),function(e){e[e.Provider=1]="Provider";e[e.Custom=2]="Custom"}(cd||(cd={})),function(e){e[e.CozeAccountTypeUnknown=0]="CozeAccountTypeUnknown";e[e.CozeAccountTypePersonal=1]="CozeAccountTypePersonal";e[e.CozeAccountTypeOrganization=2]="CozeAccountTypeOrganization"}(ld||(ld={})),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"}(dd||(dd={})),function(e){e[e.Mobile=1]="Mobile";e[e.Web=2]="Web"}(pd||(pd={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(ud||(ud={})),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"}(md||(md={})),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"}(gd||(gd={})),function(e){e[e.DEFAULT=0]="DEFAULT";e[e.Chux=1]="Chux"}(hd||(hd={})),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"}(fd||(fd={})),function(e){e[e.PromptDiff=1]="PromptDiff";e[e.ModelDiff=2]="ModelDiff"}(_d||(_d={})),function(e){e[e.DraftBot=1]="DraftBot"}(yd||(yd={})),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.Archive=1]="Archive";e[e.Rollback=2]="Rollback"}(vd||(vd={})),function(e){e[e.ProjectCopyCancel=1]="ProjectCopyCancel";e[e.ProjectCopyRetry=2]="ProjectCopyRetry"}(wd||(wd={})),function(e){e[e.ProjectCopy=1]="ProjectCopy";e[e.BotCopy=2]="BotCopy";e[e.VibeProjectCopy=3]="VibeProjectCopy"}(Ed||(Ed={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Cd||(Cd={})),function(e){e[e.Bot=1]="Bot";e[e.Workflow=2]="Workflow";e[e.Application=3]="Application"}(Id||(Id={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(Ad||(Ad={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(Sd||(Sd={})),function(e){e[e.BatchSize=1]="BatchSize";e[e.LearningRate=2]="LearningRate";e[e.Epochs=3]="Epochs"}(kd||(kd={})),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"}(jd||(jd={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(Pd||(Pd={})),function(e){e[e.Douyin=1]="Douyin"}(zd||(zd={})),function(e){e[e.Terminating=1]="Terminating";e[e.Terminated=2]="Terminated"}(Td||(Td={})),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"}(xd||(xd={})),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"}(Ld||(Ld={})),function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInput=2]="TotalInput";e[e.TotalOutput=3]="TotalOutput"}(Od||(Od={})),function(e){e[e.stop=1]="stop";e[e.resume=2]="resume",e[e.delete=3]="delete"}(Dd||(Dd={})),function(e){e[e.Recommend=1]="Recommend"}(Ud||(Ud={})),function(e){e[e.Default=0]="Default";e[e.Terminate=1]="Terminate"}(qd||(qd={})),function(e){e[e.All=0]="All";e[e.WithBenefit=1]="WithBenefit"}(Bd||(Bd={})),function(e){e[e.upload=1]="upload";e[e.TrainingSetSplit=2]="TrainingSetSplit"}(Md||(Md={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(Nd||(Nd={})),function(e){e[e.Using=1]="Using";e[e.Deleted=2]="Deleted"}($d||($d={})),function(e){e[e.Publish=0]="Publish";e[e.Archive=1]="Archive"}(Gd||(Gd={})),function(e){e[e.User=0]="User";e[e.NL2App=1]="NL2App"}(Fd||(Fd={})),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"}(Hd||(Hd={})),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"}(Jd||(Jd={})),function(e){e[e.Normal=0]="Normal";e[e.InReview=1]="InReview";e[e.Offline=2]="Offline"}(Kd||(Kd={})),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"}(Qd||(Qd={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Authorizing=3]="Authorizing"}(Yd||(Yd={})),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"}(Zd||(Zd={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Xd||(Xd={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.Name=2]="Name"}(ep||(ep={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime"}(tp||(tp={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.PublishTime=2]="PublishTime";e[e.OpenTime=3]="OpenTime"}(op||(op={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(ip||(ip={})),function(e){e[e.All=0]="All";e[e.CreateByMe=1]="CreateByMe";e[e.AllWithCollaborator=2]="AllWithCollaborator";e[e.CanImportToSpace=3]="CanImportToSpace"}(sp||(sp={})),function(e){e[e.Desc=0]="Desc";e[e.Asc=1]="Asc"}(np||(np={})),function(e){e[e.Copy=1]="Copy";e[e.Move=2]="Move";e[e.Publish=3]="Publish";e[e.ImportExport=4]="ImportExport"}(rp||(rp={})),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"}(ap||(ap={})),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"}(cp||(cp={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(lp||(lp={})),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"}(dp||(dp={})),function(e){e[e.Packing=0]="Packing";e[e.PackSuccess=1]="PackSuccess";e[e.PackFail=2]="PackFail"}(pp||(pp={}));class mp{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){mp.prototype.__init.call(this),mp.prototype.__init2.call(this),this.request=up([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=up([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}Ping(e,t){const o=this.genBaseURL("/api/intelligence_api/ping");return this.request({url:o,method:"POST"},t)}DraftProjectCreate(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/create"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri,monetization_conf:o.monetization_conf,create_from:o.create_from,folder_id:o.folder_id,type:o.type};return this.request({url:i,method:"POST",data:s},t)}GetDraftIntelligenceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_list"),s={space_id:o.space_id,name:o.name,has_published:o.has_published,status:o.status,types:o.types,search_scope:o.search_scope,folder_id:o.folder_id,folder_include_children:o.folder_include_children,order_type:o.order_type,project_type:o.project_type,is_fav_filter:o.is_fav_filter,is_collaborator_filter:o.is_collaborator_filter,organization_id:o.organization_id,is_fav:o.is_fav,recently_open:o.recently_open,option:o.option,order_by:o.order_by,cursor_id:o.cursor_id,size:o.size};return this.request({url:i,method:"POST",data:s},t)}DraftProjectUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/update"),s={project_id:o.project_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetDraftIntelligenceInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_info"),s={intelligence_id:o.intelligence_id,intelligence_type:o.intelligence_type,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GetUserRecentlyEditIntelligence(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/search/get_recently_edit_intelligence"),s={size:o.size,types:o.types,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DraftProjectCopy(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/copy"),s={project_id:o.project_id,to_space_id:o.to_space_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}ProcessEntityTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/entity_task/process"),s={entity_id:o.entity_id,action:o.action,task_id_list:o.task_id_list};return this.request({url:i,method:"POST",data:s},t)}DraftProjectDelete(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/delete"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}EntityTaskSearch(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/entity_task/search"),s={task_list:o.task_list};return this.request({url:i,method:"POST",data:s},t)}ListIntelligenceCollaboration(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/collaboration/list"),s={intelligence_id:o.intelligence_id,intelligence_type:o.intelligence_type};return this.request({url:i,method:"POST",data:s},t)}OceanProjectCreate(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/ocean_project/create"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}OceanProjectUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/ocean_project/update"),s={project_id:o.project_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetOceanProjectList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_list"),s={space_id:o.space_id,status:o.status,search_scope:o.search_scope,order_by:o.order_by,page_index:o.page_index,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PublishProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_project"),s={project_id:o.project_id,version_number:o.version_number,description:o.description,connectors:o.connectors,connector_publish_config:o.connector_publish_config};return this.request({url:i,method:"POST",data:s},t)}GetPublishRecordDetail(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_record_detail"),s={project_id:o.project_id,publish_record_id:o.publish_record_id};return this.request({url:i,method:"POST",data:s},t)}GetPublishRecordList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_record_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublishConnectorList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/connector_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}CheckProjectVersionNumber(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/check_version_number"),s={project_id:o.project_id,version_number:o.version_number};return this.request({url:i,method:"POST",data:s},t)}DraftProjectInnerTaskList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/inner_task_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}GetOceanProjectInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_info"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}GetModelListFilterParams(e,t){const o=this.genBaseURL("/api/intelligence_api/model/get_model_list_filter_params");return this.request({url:o,method:"POST"},t)}StartEstimatedTrainingCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/start_estimated_training_cost"),s={base_model_id:o.base_model_id,space_id:o.space_id,training_dataset_id:o.training_dataset_id,epochs:o.epochs};return this.request({url:i,method:"POST",data:s},t)}GetModelList(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_list"),s={space_id:o.space_id,name:o.name,tag_filters:o.tag_filters,context_len_min:o.context_len_min,context_len_max:o.context_len_max,model_cost_min:o.model_cost_min,model_cost_max:o.model_cost_max,model_vendor:o.model_vendor,statusList:o.statusList,model_show_family_id:o.model_show_family_id,model_source:o.model_source,order_by:o.order_by,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}GetFinetuneTemplateDataset(e,t){const o=this.genBaseURL("/api/intelligence_api/model/get_finetune_template_dataset");return this.request({url:o,method:"POST"},t)}GetModelUsageData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_usage_data"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTrainingCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_training_cost"),s={task_id:o.task_id,space_id:o.space_id,base_model_id:o.base_model_id,epochs:o.epochs};return this.request({url:i,method:"POST",data:s},t)}CreateFinetuneTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/create_finetune_task"),s={space_id:o.space_id,base_model_id:o.base_model_id,training_dataset_id:o.training_dataset_id,validating_dataset:o.validating_dataset,finetune_configuration:o.finetune_configuration,description:o.description,name:o.name};return this.request({url:i,method:"POST",data:s},t)}UploadFinetuneDataset(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/upload_finetune_dataset"),s={space_id:o.space_id,fileType:o.fileType,fileName:o.fileName,data:o.data,testing_data:o.testing_data};return this.request({url:i,method:"POST",data:s},t)}GetModelInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_info"),s={space_id:o.space_id,model_id:o.model_id,is_finetuning:o.is_finetuning};return this.request({url:i,method:"POST",data:s},t)}GetFinetuneTrainingInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_finetune_training_info"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetModelPerformanceData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_performance_data"),s={space_id:o.space_id,model_id:o.model_id,get_pct:o.get_pct};return this.request({url:i,method:"POST",data:s},t)}OperateFinetuneTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/operate_finetune_task"),s={id:o.id,action:o.action};return this.request({url:i,method:"POST",data:s},t)}DeleteFinetuneModel(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/delete_finetune_model"),s={model_id:o.model_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetUserCompleteProfileRecord(e,t){const o=this.genBaseURL("/api/intelligence_api/user_profile/get_user_complete_profile_record");return this.request({url:o,method:"POST"},t)}DownloadUserProfile(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/user_profile/download_user_profile"),s={Cookie:o.Cookie};return this.request({url:i,method:"POST",headers:s},t)}GetProjectPublishedConnector(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/get_published_connector"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublishIntelligenceUnList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_intelligence_unlist"),s={intelligence_id:o.intelligence_id,connector_ids:o.connector_ids,intelligence_type:o.intelligence_type};return this.request({url:i,method:"POST",data:s},t)}PublishIntelligenceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_publish_intelligence_list"),s={intelligence_type:o.intelligence_type,space_id:o.space_id,owner_id:o.owner_id,name:o.name,order_last_publish_time:o.order_last_publish_time,order_total_token:o.order_total_token,size:o.size,cursor_id:o.cursor_id,intelligence_ids:o.intelligence_ids};return this.request({url:i,method:"POST",data:s},t)}UpdateDiffModeInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/diff_mode/update_diff_mode_info"),s={target_type:o.target_type,target_id:o.target_id,diff_mode_info:o.diff_mode_info,exit_and_save:o.exit_and_save,exit_and_discard:o.exit_and_discard};return this.request({url:i,method:"POST",data:s},t)}GetDiffModeInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/diff_mode/get_diff_mode_info"),s={target_type:o.target_type,target_id:o.target_id};return this.request({url:i,method:"POST",data:s},t)}GetProjectPublishSummary(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_project_publish_summary"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}DraftProjectCrossSpaceCopy(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/crossspace_copy"),s={project_id:o.project_id,to_space_id:o.to_space_id};return this.request({url:i,method:"POST",data:s},t)}EntityTaskList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/entity_task/list"),s={space_id:o.space_id,task_id_list:o.task_id_list};return this.request({url:i,method:"POST",data:s},t)}ExpansionTpm(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/expansion_tpm"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,organization_id:o.organization_id,tpm_input_expansion:o.tpm_input_expansion,tpm_output_expansion:o.tpm_output_expansion,start_time:o.start_time,end_time:o.end_time};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTpmExpansionCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion_cost"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,input_tpm:o.input_tpm,output_tpm:o.output_tpm};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTpmExpansion(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,estimated_rpm:o.estimated_rpm,StartTime:o.StartTime,EndTime:o.EndTime};return this.request({url:i,method:"POST",data:s},t)}FolderUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/update"),s={folder_id:o.folder_id,name:o.name,description:o.description};return this.request({url:i,method:"POST",data:s},t)}GetFolderList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_folder_list"),s={space_id:o.space_id,type:o.type,name:o.name,search_scope:o.search_scope,parent_folder_id:o.parent_folder_id,parent_include_children:o.parent_include_children,order_by:o.order_by,order_type:o.order_type,size:o.size,page_num:o.page_num};return this.request({url:i,method:"POST",data:s},t)}FolderMove(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/move"),s={folder_id:o.folder_id,parent_folder_id:o.parent_folder_id};return this.request({url:i,method:"POST",data:s},t)}FolderDelete(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/delete"),s={folder_id:o.folder_id};return this.request({url:i,method:"POST",data:s},t)}FolderCreate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/create"),s={space_id:o.space_id,type:o.type,name:o.name,description:o.description,parent_folder_id:o.parent_folder_id};return this.request({url:i,method:"POST",data:s},t)}ArchiveProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/archive"),s={project_id:o.project_id,description:o.description,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetIntelligenceTaskInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/entity_task/task_info"),s={task_id:o.task_id};return this.request({url:i,method:"GET",params:s},t)}ProjectHistoryList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list"),s={project_id:o.project_id,history_type:o.history_type,cursor:o.cursor,size:o.size};return this.request({url:i,method:"POST",data:s},t)}RollbackProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/rollback"),s={project_id:o.project_id,rollback_version:o.rollback_version,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetModelConcurrencyPerformanceData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_concurrency_performance_data"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}UpdateModelConfigType(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/update_model_config_type"),s={space_id:o.space_id,model_id:o.model_id,config_type:o.config_type};return this.request({url:i,method:"POST",data:s},t)}GetSpaceModelUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_space_model_user_config"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}OpenGetProjectList(e,t){const o=e||{},i=this.genBaseURL("/v1/apps"),s={workspace_id:o.workspace_id,publish_status:o.publish_status,connector_id:o.connector_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}OpenGetBotList(e,t){const o=e||{},i=this.genBaseURL("/v1/bots"),s={workspace_id:o.workspace_id,publish_status:o.publish_status,connector_id:o.connector_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}GetFolderTree(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/tree"),s={space_id:o.space_id,type:o.type};return this.request({url:i,method:"POST",data:s},t)}OpenGetSpaceFolder(e,t){const o=e||{},i=this.genBaseURL("/v1/folders"),s={workspace_id:o.workspace_id,folder_type:o.folder_type,parent_folder_id:o.parent_folder_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}MoveObjectToFolder(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/move_object"),s={dest_folder_id:o.dest_folder_id,folder_space_id:o.folder_space_id,move_objects:o.move_objects};return this.request({url:i,method:"POST",data:s},t)}GetFolderInfoByIds(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/folder/get_by_ids"),s={space_id:o.space_id,folder_ids:o.folder_ids,get_path_info:o.get_path_info};return this.request({url:i,method:"POST",data:s},t)}OpenGetFolderInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/folders/${o.folder_id}`);return this.request({url:i,method:"GET"},t)}ExportPreCheck(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/export_pre_check"),s={res_type:o.res_type,id:o.id,commit_id:o.commit_id};return this.request({url:i,method:"POST",data:s},t)}ImportPreCheck(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/import_pre_check"),s={package_uri:o.package_uri};return this.request({url:i,method:"POST",data:s},t)}GetUploadAuthToken(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/upload/auth_token"),s={scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}MarkProjectHistory(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list/read"),s={project_id:o.project_id,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelDetail(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_detail"),s={model_id:o.model_id,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_list"),s={search_key:o.search_key,sort_field:o.sort_field,org_id:o.org_id,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetProjectHistoryNotice(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list/notice"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}BindCustomModelSpace(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/bind_custom_model_space"),s={model_id:o.model_id,space_id_list:o.space_id_list,status:o.status,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelSpaceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_space_list"),s={model_id:o.model_id,search_key:o.search_key,org_id:o.org_id,cursor_id:o.cursor_id,limit:o.limit,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelParameterTemplate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_parameter_template"),s={org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}OpenCopyTaskInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/entities/copy_tasks/${o.task_id}`);return this.request({url:i,method:"GET"},t)}OpenDuplicateDraftEntity(e,t){const o=e||{},i=this.genBaseURL("/v1/entities/copy_tasks"),s={entity_id:o.entity_id,entity_type:o.entity_type,to_workspace_id:o.to_workspace_id};return this.request({url:i,method:"POST",data:s},t)}ConvertCustomModelParameter(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/convert_custom_model_parameter"),s={parameters:o.parameters,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}CreateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/create_custom_model"),s={model_name:o.model_name,model_icon_uri:o.model_icon_uri,model_arch:o.model_arch,model_desc:o.model_desc,base_url:o.base_url,secret_name:o.secret_name,model_runtime_tag:o.model_runtime_tag,inputLength:o.inputLength,parameters:o.parameters,api_agreement:o.api_agreement,safety_guardrails:o.safety_guardrails,auth:o.auth,api_mode:o.api_mode,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}TerminateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/terminate_custom_model"),s={model_id:o.model_id,terminate_time:o.terminate_time,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}UpdateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/update_custom_model"),s={model_name:o.model_name,model_icon_uri:o.model_icon_uri,model_arch:o.model_arch,model_desc:o.model_desc,base_url:o.base_url,secret_name:o.secret_name,model_runtime_tag:o.model_runtime_tag,inputLength:o.inputLength,parameters:o.parameters,model_id:o.model_id,api_agreement:o.api_agreement,safety_guardrails:o.safety_guardrails,auth:o.auth,api_mode:o.api_mode,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageRecord(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_usage_record"),s={space_id:o.space_id,model_id:o.model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp,order_by_type:o.order_by_type,order_by_field:o.order_by_field,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetEntityModelUsage(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_entity_model_usage"),s={space_id:o.space_id,model_id:o.model_id,entity_id:o.entity_id,entity_type:o.entity_type,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}GetTypeList(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/get_type_list"),s={model:o.model,voice:o.voice,raw_model:o.raw_model,space_id:o.space_id,cur_model_id:o.cur_model_id,cur_model_ids:o.cur_model_ids,model_scene:o.model_scene,tag_filters:o.tag_filters,user_benefit_filter:o.user_benefit_filter};return this.request({url:i,method:"POST",data:s},t)}SaveModelReplacement(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/save_replacement"),s={space_id:o.space_id,old_model_id:o.old_model_id,new_model_id:o.new_model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}GetModelReplacement(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_replacement"),s={space_id:o.space_id,entity_type:o.entity_type,entity_id:o.entity_id};return this.request({url:i,method:"POST",data:s},t)}UpdateCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/update"),s={model_id:o.model_id,display_name:o.display_name,model_name:o.model_name,base_url:o.base_url,api_mode:o.api_mode,auth:o.auth,support_image_understanding:o.support_image_understanding,max_tokens:o.max_tokens};return this.request({url:i,method:"POST",data:s},t)}ListProviderModels(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/list_provider_models"),s={provider:o.provider,auth:o.auth,base_url:o.base_url,search_key:o.search_key};return this.request({url:i,method:"POST",data:s},t)}ListCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/list"),s={account_type:o.account_type,coze_account_id:o.coze_account_id,enterprise_id:o.enterprise_id,search_key:o.search_key,provider:o.provider,source_type:o.source_type,sort_field:o.sort_field,sort_order:o.sort_order,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}ToggleCustomModelMemberVisibility(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/toggle_member_visibility"),s={model_id:o.model_id,member_visible:o.member_visible};return this.request({url:i,method:"POST",data:s},t)}DeleteCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/delete"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}ListProviders(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/custom_model/list_providers"),s={only_enabled:o.only_enabled};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelDetailV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/detail"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}CreateCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/create"),s={source_type:o.source_type,provider:o.provider,display_name:o.display_name,model_name:o.model_name,base_url:o.base_url,api_mode:o.api_mode,auth:o.auth,support_image_understanding:o.support_image_understanding,max_tokens:o.max_tokens,account_type:o.account_type,coze_account_id:o.coze_account_id,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}}const gp=new mp({}),hp={agent:gd.VibeProjectAgent,workflow:gd.VibeProjectAutomation,webapp:gd.VibeProjectWebApp,app:gd.VibeProjectApp,skill:gd.VibeProjectSkill,web:gd.VibeProjectGeneralWeb,miniprogram:gd.VibeProjectWechatMiniProgram,assistant:gd.VibeProjectAssistantAgent},fp={[gd.VibeProjectAgent]:"agent",[gd.VibeProjectAutomation]:"workflow",[gd.VibeProjectWebApp]:"webapp",[gd.VibeProjectApp]:"app",[gd.VibeProjectSkill]:"skill",[gd.VibeProjectGeneralWeb]:"web",[gd.VibeProjectWechatMiniProgram]:"miniprogram",[gd.VibeProjectAssistantAgent]:"assistant"};function _p(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return hp[o]}const yp=e=>fp[e],bp=[gd.VibeProjectAgent,gd.VibeProjectAutomation,gd.VibeProjectWebApp,gd.VibeProjectApp,gd.VibeProjectSkill,gd.VibeProjectGeneralWeb,gd.VibeProjectWechatMiniProgram,gd.VibeProjectAssistantAgent].map(yp).filter(Boolean);function vp(e,t){return null!=e?e:t()}function wp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Ep(e,t){return null!=e?e:t()}const Cp=["ecs","vefaas"],Ip=new Set([t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.WechatMiniProgram]),Ap=(e,t)=>{const o=void 0!==e?(e=>void 0!==e&&Ip.has(e))(e):Cp.includes(Ep(process.env.COZE_CLI_PLATFORM,(()=>"")).trim().toLowerCase());return o?"https://www.coze.cn/":Ep(t,(()=>s.DEFAULT_CONFIG.apiBaseUrl))},Sp=(e,t,o)=>`${Ap(t,o)}p/${e}`;class kp{static getInstance(){return kp.INSTANCE||(kp.INSTANCE=new kp),kp.INSTANCE}sendMessageRunTask(e){const t=[m.resolve(__dirname,"./send-message.worker.js")],o=process.execPath;b.spawn(o,[...t,JSON.stringify(e)],{detached:!0,stdio:"ignore"}).unref()}async sendMessage(e){return await t.sendProjectChatMessage(e)}}const jp=kp.getInstance();function Pp(e,t){return null!=e?e:t()}function zp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Tp=["github","local"],Rp="按标准流程初始化当前项目";async function xp(t,o){if(o)try{const i=await zp([t,"access",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!i)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const s=await Tl.getDefaultConversation(o);jp.sendMessageRunTask({projectId:o,prompt:Rp,apiBaseUrl:t.config.apiBaseUrl,accessToken:i,xTTEnv:t.config.xTTEnv,conversationId:s.id,key:`coze-coding-cli:message:${o}`}),t.ui.info(` Initial query sent. Use \`coze code message status -p ${o}\` to check the result.`)}catch(e){t.ui.warn(`Failed to send initial query: ${e instanceof Error?e.message:String(e)}. You can send it manually: coze code message send "${Rp}" -p ${o}`)}}const Lp={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},Op={[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"};function Dp(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return Lp[o]}const Up=e=>Op[e],qp={ask:t.ProjectMode.Ask,agent:t.ProjectMode.Agent,dangerous_confirm:t.ProjectMode.DangerousConfirm,plan:t.ProjectMode.Plan};t.ProjectMode.Ask,t.ProjectMode.Agent,t.ProjectMode.DangerousConfirm,t.ProjectMode.Plan;const Bp={[t.ConversationMode.Ask]:"ask",[t.ConversationMode.Agent]:"agent",[t.ConversationMode.DangerousConfirm]:"dangerous_confirm",[t.ConversationMode.Plan]:"plan"};function Mp(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return qp[o]}function Np(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function $p(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Gp={project_id:"7603316828982525988",icon_uri:"gen_project_icon/2026-02-06/7603316828982525988_1770308040.png",name:"OpenClaw助手(副本)",description:"OpenClaw智能代理:提供多场景AI服务,自动化处理任务,提升工作效率。"};function Fp(e,t){return null!=e?e:t()}function Vp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Wp=new Set([t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.WechatMiniProgram]);function Hp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Jp=o=>{const i=o.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");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 | webapp | 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").option("--chat-mode <chatMode>","Chat mode: ask | agent | dangerous_confirm | plan").option("--model-name <modelName>","Model name for the project").option("--tool-name <toolName>","Tool names to enable (can specify multiple times)",((e,t)=>t.concat(e)),[]).option("--design","Enable design wizard (auto-enabled when --chat-mode is plan)").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:Object.keys(Lp),description:"Project type: agent | workflow | app | skill | web | webapp | miniprogram | assistant"},orgId:{type:"string",required:!1,description:"Organization ID (optional, reads from context)"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"},chatMode:{type:"string",enum:Object.keys(qp),required:!1,description:'Chat mode: ask (对话模式) | agent (Agent模式, default) | dangerous_confirm (危险操作需确认) | plan (计划模式). When set to "plan", --design is auto-enabled.'},modelName:{type:"string",required:!1,description:"Model name for the project"},toolName:{type:"array",required:!1,description:"Tool names to enable (can specify multiple times with --tool-name)"},design:{type:"boolean",required:!1,description:"Enable design wizard. Auto-enabled when --chat-mode is plan. Only supported for web/app/miniprogram project types."}},output:{project_id:{type:"string",description:"Created project ID"},type:{type:"string",description:"Project type"},project_url:{type:"string",description:"Web URL to open the project conversation page directly"}}},enums:{type:Object.keys(Lp).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 | webapp | 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"},{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"}],seeAlso:["coze code project list","coze code project get"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Fp(Fp(o.spaceId,(()=>Vp([s,"optionalAccess",e=>e.config,"access",e=>e.spaceId]))),(()=>"")),{message:r,type:a,wait:c,chatMode:l,modelName:d,toolName:p,design:u}=o,m=Boolean(u)||"plan"===l;Vp([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e(`Resolving project type '${a}'...`)]);const g=Dp(a);if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!g)throw new e.CozeError(e.ErrorCode.E1005,`Unknown project type: ${a}`,{type:a});Vp([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching agent tools configuration...")]);const h=Vp([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===g)),"optionalAccess",e=>e.tools]);if(!h||0===h.length)throw new e.CozeError(e.ErrorCode.E5000,`No tools config for projectType: ${String(a)}`,{type:a,projectType:g});const f={};h.forEach((e=>{Vp([e,"optionalAccess",e=>e.name])&&(f[e.name]=Fp(Vp([p,"optionalAccess",e=>e.includes,"call",t=>t(e.name)]),(()=>Boolean(e.enabled))))})),Vp([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching project default skills...")]);const _={skills:Fp(Vp([await Ac.GetProjectDefaultSkill({project_type:g,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:[g]};let y;if(g===t.VibeProjectType.AssistantAgent){Vp([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating assistant project via template copy...")]);const e=await t.IdeApi.CopyVibeProject({...Gp,target_space_id:String(n)});y=Vp([e,"access",e=>e.data,"optionalAccess",e=>e.basic_info,"optionalAccess",e=>e.project_id])}else{Vp([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating project...")]);const e=Fp((await t.IdeApi.ChatCreateVibeProject({space_id:String(n),user_query:r,project_type:g,project_settings:{...Wp.has(g)?{project_symbol:t.ProjectSymbol.ProjectSymbolVersion3}:{},model_setting:{model_name:d||""},agent_tools:f,skill_setting:_,...l?{project_mode:Mp(l)}:{},...m?{wizards:{design:!0}}:{}}})).data,(()=>({})));y=e.project_id}const b=await Vp([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!b)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const v=y?Sp(y,g,s.config.apiBaseUrl):"";s.ui.success(`Project created successfully, please use "coze code message status -p ${y}" to check the status. Open the project: ${v}`),Vp([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:y,type:a,project_url:v})]);const w=await Tl.getDefaultConversation(Fp(y,(()=>"")));if(c){const e=await jp.sendMessage({projectId:Fp(y,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:b,xTTEnv:s.config.xTTEnv,conversationId:w.id,key:`coze-coding-cli:message:${y}`});s.response.print(e.lastAnswerMessage)}else jp.sendMessageRunTask({projectId:Fp(y,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:b,xTTEnv:s.config.xTTEnv,conversationId:w.id,key:`coze-coding-cli:message:${y}`})})),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, AllWithCollaborator = 2)"},folderId:{type:"string",required:!1,description:"Folder ID"},orderType:{type:"number",required:!1,description:"Sort type (0 for descending, 1 for ascending)"},orderBy:{type:"number",required:!1,description:"Order by (0 for updated_at, 1 for created_at)"},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:bp.reduce(((e,t)=>(e[t]=`${t.toUpperCase()} project`,e)),{}),"search-scope":{0:"All",1:"CreateByMe",2:"AllWithCollaborator"},"order-type":{0:"Descending",1:"Ascending"},"order-by":{0:"updated_at",1:"created_at"}},seeAlso:["coze code project get","coze code project create"]}}).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 o=t.getContext(),i=vp(wp([e,"optionalAccess",e=>e.size]),(()=>10)),s=vp(wp([e,"optionalAccess",e=>e.cursorId]),(()=>{})),n=wp([e,"optionalAccess",e=>e.type,"optionalAccess",e=>e.map,"call",e=>e(_p),"access",e=>e.filter,"call",e=>e(Boolean)]),r=wp([e,"optionalAccess",e=>e.name]),a=wp([e,"optionalAccess",e=>e.hasPublished])?Boolean(wp([e,"optionalAccess",e=>e.hasPublished])):void 0,c=Number(vp(wp([e,"optionalAccess",e=>e.searchScope]),(()=>sp.All))),l=vp(wp([e,"optionalAccess",e=>e.folderId]),(()=>"0")),d=Number(vp(wp([e,"optionalAccess",e=>e.orderType]),(()=>np.Desc))),p=Boolean(wp([e,"optionalAccess",e=>e.isFavFilter])),u=Number(vp(wp([e,"optionalAccess",e=>e.orderBy]),(()=>op.UpdateTime)));let m=[];wp([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching project list...")]);const g=await gp.GetDraftIntelligenceList({space_id:vp(wp([o,"optionalAccess",e=>e.config,"access",e=>e.spaceId]),(()=>"")),size:i,cursor_id:s,types:n,name:r,has_published:a,search_scope:c,folder_id:l,order_type:d,order_by:u,is_fav_filter:p,status:[md.Using,md.Banned,md.MoveFailed]});m=wp([g,"access",e=>e.data,"optionalAccess",e=>e.intelligences])||[],wp([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetched ${m.length} projects.`)]),wp([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(m.map((e=>({id:wp([e,"access",e=>e.basic_info,"optionalAccess",e=>e.id]),name:wp([e,"access",e=>e.basic_info,"optionalAccess",e=>e.name]),type:yp(e.type),description:wp([e,"access",e=>e.basic_info,"optionalAccess",e=>e.description])}))))])}))}(i),function(o){o.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"},type:{type:"string",description:"Human-readable project type string"},tools:{type:"object",description:"Project tool configurations (Record<string, boolean>)"},chat_mode:{type:"string",description:"Human-readable chat mode string"},model_name:{type:"string",description:"Current model name used by the project"},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"}],seeAlso:["coze code project list","coze code project create"]}}).action((async function(o,i,s){const n=s.getContext();Np([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetching project details for '${o}'...`)]);try{const[i,s]=await Promise.all([t.IdeApi.GetVibeProject({project_id:o}),Tl.getDefaultConversation(o)]),r=Np([i,"access",e=>e.data,"optionalAccess",e=>e.project_info]);if(!r)throw new e.CozeError(e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o});const a=s.conversation_setting;Np([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Project details for '${o}':`)]),Np([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>{return e({...v.omit(r,["project_settings"]),type:Up(Np([r,"optionalAccess",e=>e.project_type])),tools:Np([a,"optionalAccess",e=>e.agent_tools]),chat_mode:(t=Np([a,"optionalAccess",e=>e.mode]),Bp[t]),model_name:Np([a,"optionalAccess",e=>e.model_setting,"optionalAccess",e=>e.model_name]),skills:v.pick(Np([a,"optionalAccess",e=>e.skill_setting]),["skills"])});var t}])}catch(t){K(t,e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o})}}))}(i),function(o){o.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"}],seeAlso:["coze code project list"]}}).action((async function(o,i,s){const n=s.getContext();$p([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleting project '${o}'...`)]);try{await t.IdeApi.DeleteVibeProject({project_id:o})}catch(t){K(t,e.ErrorCode.E3005,`Failed to delete project '${o}': project not found or no permission`,{projectId:o})}$p([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Project '${o}' deleted successfully.`)]),$p([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:o,message:`Project '${o}' deleted successfully.`})])}))}(i),function(o){o.command("db").description("Manage project databases").command("list").description("List project database tables").requiredOption("-p, --project-id <projectId>","Project ID").option("--schema <schema>","Schema name (knowledge or public)").option("--env <env>","Environment: dev | prod (default: dev)").config({help:{brief:"List project database tables",description:"List all database tables for the specified project, grouped by schema.",examples:[{desc:"List all tables",cmd:"coze code project db list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List knowledge schema tables",cmd:"coze code project db list -p <projectId> --schema knowledge"},{desc:"List prod tables",cmd:"coze code project db list -p <projectId> --env prod"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},schema:{type:"string",required:!1,description:"Schema name filter"},env:{type:"string",required:!1,description:"Environment (dev or prod)"}},output:{type:"array",items:{type:"object",properties:{schema:{type:"string",description:"Schema name"},table_name:{type:"string",description:"Table name"}}}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid or missing project ID",fix:"Provide a valid project ID with -p <projectId>"}],seeAlso:["coze code db","coze code project get"]}}).action((async function(e,o){const i=o.getContext(),{projectId:s,env:n}=e,r="prod"===n?t.MemoryEnv.product:t.MemoryEnv.develop,a=[];await Promise.all(["knowledge","public"].map((async e=>{((await t.IdeApi.GetSchemaTables({project_id:s,database_env:r,schema:e})).table_names||[]).forEach((t=>{a.push({schema:e,table_name:t})}))}))),Hp([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${a.length} tables.`)]),Hp([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])}))}(i),function(o){o.command("import").description("Import a project from a remote repo or local zip file").requiredOption("-s, --source <source>","Import source: github / local").option("-r, --repo <fullName>","Remote repo full name (e.g. user/repo), required for --source github").option("-f, --file <path>","Local zip file path, required for --source local").config({help:{brief:"Import a project from a remote repo or local zip file",description:"Create a new project by importing from a remote Git repository or uploading a local zip file. Remote import requires prior OAuth authorization via `coze code git auth login`. Imported remote projects will be automatically bound to the source repo. Local uploads must be zip format and no more than 500MB.",examples:[{desc:"Import from GitHub (minimal)",cmd:"coze code project import --source github --repo user/my-app"},{desc:"Import from GitHub",cmd:"coze code project import -s github -r user/my-app",tags:["[RECOMMENDED]"]},{desc:"Upload local zip file",cmd:"coze code project import --source local --file ./project.zip"},{desc:"[PIPELINE] Import and check status",cmd:"ID=$(coze code project import -s github -r user/app --format json | jq -r .project_id) && coze code project get $ID",tags:["[PIPELINE]"]},{desc:"[TEMPLATE] Import from any source",cmd:"coze code project import --source <github|local> [--repo <owner/name>] [--file <path>]",tags:["[TEMPLATE]"]}],schema:{input:{source:{type:"string",required:!0,enum:["github","local"],description:"Import source type",example:"github"},repo:{type:"string",required:!1,description:"Remote repo full name (owner/name)",example:"user/my-app"},file:{type:"string",required:!1,description:"Local zip file path",example:"./project.zip"}},output:{project_id:{type:"string",description:"Created project ID",example:"proj_abc123"},source:{type:"string",description:"Import source type",example:"github"},repo:{type:"string",description:"Remote repo full name (if applicable)",example:"user/my-app"},project_url:{type:"string",description:"Web URL of the created project",example:"https://code.coze.cn/p/proj_abc123"}}},enums:{source:{github:"Import from a GitHub repository",local:"Upload a local zip file"}},errors:[{code:e.ErrorCode.E1008,name:"MISSING_IMPORT_SOURCE",desc:"Missing import source",fix:"Use --source github or --source local"},{code:e.ErrorCode.E1009,name:"MISSING_REPO",desc:"Missing --repo for github import",fix:"Add --repo <owner/name>"},{code:e.ErrorCode.E1010,name:"MISSING_FILE",desc:"Missing --file for local import",fix:"Add --file <path>"},{code:e.ErrorCode.E1011,name:"INVALID_FILE_FORMAT",desc:"File is not zip format",fix:"Only .zip files are supported"},{code:e.ErrorCode.E1012,name:"FILE_TOO_LARGE",desc:"File exceeds 500MB",fix:"Reduce file size and retry"},{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Missing Space ID",fix:"Run `coze space use <spaceId>` first"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and run with --debug if the issue persists"}],seeAlso:["coze code project create","coze code repo bind","coze code git auth login"],caveats:["Remote import requires prior OAuth authorization via `coze code git auth login`","Local upload only supports .zip format, max 500MB","Remote imported projects are automatically bound to the source repo"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Pp(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or run `coze space use <spaceId>` first");const{source:r,repo:a,file:c}=o;if(!r||!Tp.includes(r))throw new e.CozeError(e.ErrorCode.E1008,`Invalid or missing import source: "${r}". Use --source github or --source local`);if("github"===r){if(!a)throw new e.CozeError(e.ErrorCode.E1009,"Missing --repo: required when --source is github");s.ui.info(`Importing from GitHub: ${a}...`);const o=Pp(zp([await t.IdeApi.ImportProject({space_id:n,import_source:2,git_url:`https://github.com/${a}.git`,git_repo_name:a}),"access",e=>e.data,"optionalAccess",e=>e.vibe_project_id]),(()=>"")),i=o?Sp(o,t.VibeProjectType.General,s.config.apiBaseUrl):"";s.ui.success("Project imported successfully."),s.ui.info(` Project ID: ${o}`),s.ui.info(` Source: github (${a})`),s.ui.info(` Project URL: ${i}`),await xp(s,o),s.response.print({project_id:o,source:"github",repo:a,project_url:i})}else if("local"===r){if(!c)throw new e.CozeError(e.ErrorCode.E1010,"Missing --file: required when --source is local");if(!c.endsWith(".zip"))throw new e.CozeError(e.ErrorCode.E1011,`Invalid file format: "${c}". Only .zip files are supported`);if(!h.existsSync(c))throw new e.CozeError(e.ErrorCode.E1011,`File not found: "${c}"`);const o=h.statSync(c);if(o.size>524288e3)throw new e.CozeError(e.ErrorCode.E1012,`File too large: ${Math.round(o.size/1024/1024)}MB. Maximum is 500MB`);s.ui.info(`Uploading local file: ${c}...`);const i=new f;i.append("space_id",n),i.append("import_source","1"),i.append("data",h.createReadStream(c),m.basename(c));const r=Pp(zp([await e.axiosInstance.post("/api/ideserver_api/project/import_project",i,{headers:{...i.getHeaders(),"agw-js-conv":"str"}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.vibe_project_id]),(()=>"")),a=r?Sp(r,t.VibeProjectType.General,s.config.apiBaseUrl):"";s.ui.success("Project imported successfully."),s.ui.info(` Project ID: ${r}`),s.ui.info(` Source: local (${c})`),s.ui.info(` Project URL: ${a}`),await xp(s,r),s.response.print({project_id:r,source:"local",project_url:a})}}))}(i)};function Kp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Qp=new Set([t.VibeProjectType.WechatMiniProgram,t.VibeProjectType.Agent,t.VibeProjectType.Automation,t.VibeProjectType.Skill,t.VibeProjectType.AssistantAgent]);function Yp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Zp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Xp=o=>{const i=o.command("model").config({help:{brief:"Manage project models",description:"Manage models for Coze Coding projects. List available models and set the active model for a project.",examples:[{desc:"List available models",cmd:"coze code model list -p <projectId>"},{desc:"Set project model",cmd:"coze code model set doubao-dev-0213 -p <projectId>"}],seeAlso:["coze code project","coze code tools"]}}).description("Manage project models");!function(o){o.command("list").description("List available models").option("-p, --project-id <projectId>","Project ID").option("--type <type>","Project type (web, app, agent, etc.)").config({help:{brief:"List available models",description:"List all available models for the specified project or project type.",examples:[{desc:"List models for a project",cmd:"coze code model list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List models by type",cmd:"coze code model list --type web"}],schema:{input:{projectId:{type:"string",required:!1,description:"Project ID"},type:{type:"string",required:!1,description:"Project type"}},output:{type:"array",items:{type:"object",properties:{model_name:{type:"string",description:"Model name"},display_name:{type:"string",description:"Display name"},enable:{type:"boolean",description:"Whether this model is currently set for the project (only available when using -p)"}}}}},enums:{type:{agent:"AGENT project",workflow:"WORKFLOW project",webapp:"WEBAPP project",app:"APP project",skill:"SKILL project",web:"WEB project",miniprogram:"MINIPROGRAM project",assistant:"ASSISTANT project"}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Project type is required when project ID is not provided",fix:"Provide --type <type> or -p <projectId> to specify the project"}],seeAlso:["coze code model set"]}}).action((async function(o,i){const s=i.getContext(),{projectId:n}=o;let r,a,c;if(n){const e=await t.IdeApi.GetVibeProject({project_id:n});r=Zp([e,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),a=Zp([e,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.space_id]);const o=await Tl.getDefaultConversation(n);c=Zp([o,"access",e=>e.conversation_setting,"optionalAccess",e=>e.model_setting,"optionalAccess",e=>e.model_name])}else{const t=o.type;if(!t)throw new e.CozeError(e.ErrorCode.E1000,"Project type is required",{projectId:n});r=Dp(t)}if(!r)throw new e.CozeError(e.ErrorCode.E1000,"Project type is required",{projectId:n});const l=Zp([await t.BuildAgentApi.GetModelList({project_id:n,project_type:r,space_id:a}),"access",e=>e.model_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({model_name:e.name,display_name:e.display_name,enable:n?c===e.name:void 0})))]);Zp([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${Zp([l,"optionalAccess",e=>e.length])||0} models.`)]),Zp([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(l)])}))}(i),function(o){o.command("set <modelName>").description("Set conversation model").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Set conversation model",description:"Set the model used by the default conversation. Use model list to see available models.",examples:[{desc:"Set conversation model",cmd:"coze code model set doubao-dev-0213 -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{modelName:{type:"string",required:!0,description:"Model name"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},model_name:{type:"string",description:"Model name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified model is not available for this project",fix:"Use 'coze code model list -p <projectId>' to see available models"}],seeAlso:["coze code model list"]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=await t.IdeApi.GetVibeProject({project_id:r}),c=Yp([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),l=Yp([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.space_id]);if(!Yp([await t.BuildAgentApi.GetModelList({project_id:r,project_type:c,space_id:l}),"access",e=>e.model_list,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Model '${o}' is not available. Use 'coze code model list' to see available models.`,{modelName:o,projectId:r});const d=await Tl.getDefaultConversation(r);await Tl.updateConversationSetting(r,d.id,{modelSetting:{model_name:o}}),Yp([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Model set to '${o}'.`)]),Yp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,model_name:o,message:`Model has been set to '${o}' successfully`})])}))}(i)};function eu(e,t){return null!=e?e:t()}function tu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function ou(e,t){return null!=e?e:t()}function iu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const su=e=>{if(null==e)return null;return 0===e.trim().length?null:e},nu=o=>{o.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"},{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",description:'Output depends on mode. Without --wait (json): { status: "sent", project_id, message } is printed immediately. With --wait (json): one NDJSON line per finished message item, each shaped as { content, role, finish, type }. With --wait (text): the final answer text is printed.',properties:{content:{type:"string",description:"The chat response content (per NDJSON line in --wait json mode)"},role:{type:"string",description:"Message role (--wait json mode)"},finish:{type:"boolean",description:"Whether the message item finished (--wait json mode)"},type:{type:"string",description:"Message item type (--wait json mode)"},status:{type:"string",description:'Send status, e.g. "sent" (non --wait json mode)'},project_id:{type:"string",description:"Project ID (non --wait json mode)"},message:{type:"string",description:"Hint message (non --wait json mode)"}}}},seeAlso:["coze code message status","coze code message history"]}}).action((async(o,i,s)=>{const n=s.getContext();try{if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const r=iu([s,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),a=ou(iu([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 iu([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:l,stdin:d}=i;let p=null;d&&(p=await Ra());const u=su(o),m=su(p);if(!u&&!m)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin");const g=u&&m?`${u}\n\n${m}`:ou(ou(u,(()=>m)),(()=>"")),h=await Tl.getDefaultConversation(a),f=new Set,_=await t.sendProjectChatMessage({projectId:a,conversationId:h.id,prompt:g,apiBaseUrl:n.config.apiBaseUrl,accessToken:c,xTTEnv:n.config.xTTEnv,key:`coze-coding-cli:message:${a}`,onWarn:e=>n.ui.warn(e),waitForResponse:!!l,onMessageItem:e=>{if(l&&"json"===n.format&&e.finish){const t=(e=>{const t=ou(e.msg_id,(()=>"")),o=ou(e.sequence_id,(()=>""));return`${e.type}:${t}:${String(o)}`})(e);f.has(t)||(f.add(t),n.response.print({content:e.content,role:e.role,finish:e.finish,type:e.type}))}}});if(l)"text"===n.format&&n.response.print(ou(iu([_,"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){Q(e,n)}}))};function ru(e,t){return null!=e?e:t()}function au(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function cu(e,t){return null!=e?e:t()}function lu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const du=async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError("E5000","CLI context is not initialized");const n=lu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=cu(lu([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 lu([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(o.after&&o.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=await Tl.getDefaultConversation(r),c=t.createChatCore({key:`coze-coding-cli:history:${r}`,apiBaseUrl:s.config.apiBaseUrl});try{const e=o.after?"loadNext":"loadPrev",t="loadNext"===e?"11":"10",i=await c.getHistoryMessage({limit:t,project_id:r,conversation_id:a.id,after:o.after,before:o.before}),n=[],l=new Map,d=new Map;i.histories.forEach((e=>{if(e.user){const t=e.user.msg_id;l.has(t)||n.push(t);const o=(e=>{const t=lu([e,"optionalAccess",e=>e.content]);return cu(cu(lu([t,"optionalAccess",e=>e.query,"optionalAccess",e=>e.prompt]),(()=>lu([t,"optionalAccess",e=>e.retry,"optionalAccess",e=>e.prompt]))),(()=>lu([t,"optionalAccess",e=>e.edit,"optionalAccess",e=>e.prompt])))})(e.user.message);l.set(t,o?(e=>e.map((e=>"text"===e.type?e.content.text:"file"===e.type?`${au([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.path])} ${ru(au([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.from,"optionalAccess",e=>e[0]]),(()=>""))} ${ru(au([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.to,"optionalAccess",e=>e[0]]),(()=>""))} `:"console"===e.type?au([e,"access",e=>e.content,"access",e=>e.console,"optionalAccess",e=>e.content]):"node"===e.type?au([e,"access",e=>e.content,"access",e=>e.node,"optionalAccess",e=>e.node_title]):"upload_file"===e.type?au([e,"access",e=>e.content,"access",e=>e.upload_file,"optionalAccess",e=>e.file_name]):"page"===e.type?au([e,"access",e=>e.content,"access",e=>e.page,"optionalAccess",e=>e.page_title]):"page_elements"===e.type?au([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?au([e,"access",e=>e.content,"access",e=>e.wf_canvas_change,"optionalAccess",e=>e.query]):"")).join(" "))(o):"")}if(e.assistant){const t=e.assistant.messages.find((e=>"answer"===e.type&&e.content.answer));if(!t)return;const o=t.query_msg_id,i=t.content.answer;"string"==typeof o&&"string"==typeof i&&d.set(o,i)}}));const p=n[0],u=n[n.length-1],m=n.reverse().filter((e=>d.has(e))).map((e=>({userMessage:cu(l.get(e),(()=>"")),answer:cu(d.get(e),(()=>""))}))),g={histories:m,cursor:{after:p,before:u,has_more:i.has_more,loadDirection:e}};if("json"===s.format)s.response.print(g);else{if(0===m.length)return void s.response.print("No conversation history found.");m.forEach(((e,t)=>{s.response.print(`--- #${t+1} ---\nQ: ${e.userMessage}\nA: ${e.answer}\n`)})),s.response.print(`\n[cursor] after=${p}, before=${u}, has_more=${i.has_more}, loadDirection=${e}`)}}finally{c.destroy()}}catch(e){Q(e,s)}};function pu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const uu=o=>{const i=o.command("message");i.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"}],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)"),nu(i),(o=>{o.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)"}}}},seeAlso:["coze code message send","coze code message cancel"]}}).action((async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const o=tu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),n=eu(tu([o,"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 r=await Tl.getDefaultConversation(n),{code:a,msg:c,reply_id:l,...d}=await t.BuildAgentApi.GetChatCLIMessageStatus({project_id:n,conversation_id:r.id});if("done"===d.status){s.ui.verbose(`Chat completed, fetching result for project ${n}...`);const e=await t.BuildAgentApi.GetChatCLIMessageResultContent({project_id:n,conversation_id:r.id}),o="data"in e?e.data:e;"json"===s.format?s.response.print({...d,answer:o.answer}):s.response.print(`status: [${d.status}]\nanswer: ${eu(o.answer,(()=>""))}`)}else"json"===s.format?s.response.print(d):s.response.print(d.status)}catch(e){Q(e,s)}}))})(i),function(o){o.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:{message:{type:"string",description:"Result message"}}}},seeAlso:["coze code message status","coze code message send"]}}).action((async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const o=pu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=null!=(n=pu([o,"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 c=await Tl.getDefaultConversation(r),{message:l}=await t.BuildAgentApi.CancelChatCLIMessage({project_id:r,conversation_id:c.id});"json"===s.format?s.response.print({message:l}):s.response.print(l)}catch(e){Q(e,s)}var n}))}(i),(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."}}}}}},seeAlso:["coze code message send","coze code message status"]}}).action(du)})(i)};function mu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function gu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function hu(o){o.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:{type:"array",items:{type:"object",properties:{secret_key:{type:"string",description:"Environment variable key"},secret_id:{type:"string",description:"Secret ID"},secret_val:{type:"string",description:"Environment variable value"},secret_type:{type:"string",description:"Secret type"}}}}},enums:{env:{dev:"Development environment variables",prod:"Production environment variables"}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}],seeAlso:["coze code env set","coze code env delete"]}}).action((async function(e,o){const i=o.getContext(),{projectId:s}=e,n=gu([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()?us.prod:us.dev);var a;const c=gu([await vs.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])||[];gu([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secrets listed successfully.")]),gu([i,"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 fu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const _u=o=>{const i=o.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");hu(i),i.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:{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"}],seeAlso:["coze code env list","coze code env delete"]}}).action((async function(o,i,s,n){const r=n.getContext(),{projectId:a}=s,c=mu([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 vs.InsertProjectSecret({project_id:a,insert_secrets:{secrets:[{secret_key:o,secret_val:i}]}}),mu([r,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secret set successfully")]),mu([r,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:a,key:o,value:i})])})),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 a specified environment variable from the project by its key name.",examples:[{desc:"Delete an environment variable",cmd:"coze code env delete <KEY> -p <projectId>",tags:["[RECOMMENDED]"]}],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"},project_id:{type:"string",description:"Project ID"},keys:{type:"array",description:"Deleted environment variable key names"},secret_ids:{type:"array",description:"Deleted secret IDs"}}},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"}],seeAlso:["coze code env list","coze code env set"]}}).action((async function(t,o,i){const s=i.getContext(),{projectId:n}=o,r=[t],a=fu([await vs.ListProjectSecret({env:us.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)))),l=a.filter((e=>c.has(String(e.secret_key||"")))).map((e=>e.secret_id)).filter(Boolean);if(0===l.length)throw new e.CozeError(e.ErrorCode.E3003,`No matched secrets by keys: ${r.join(", ")}`,{projectId:n,keys:r});await vs.DeleteProjectSecret({project_id:n,keys:l}),fu([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env has been delete successfully")]),fu([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:l})])}))}(i)};var yu,bu,vu,wu,Eu,Cu,Iu,Au,Su,ku,ju,Pu,zu,Tu,Ru,xu,Lu,Ou,Du,Uu,qu,Bu,Mu,Nu,$u,Gu,Fu,Vu,Wu,Hu,Ju;function Ku(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!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"}(yu||(yu={})),function(e){e[e.Unknown=0]="Unknown";e[e.FreeCertificate=1]="FreeCertificate"}(bu||(bu={})),function(e){e[e.Unknown=0]="Unknown";e[e.Normal=1]="Normal"}(vu||(vu={})),function(e){e[e.Unknown=0]="Unknown";e[e.Existing=1]="Existing";e[e.Free=2]="Free"}(wu||(wu={})),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"}(Eu||(Eu={})),function(e){e[e.Passed=1]="Passed";e[e.UnPassed=2]="UnPassed";e[e.Auditing=3]="Auditing"}(Cu||(Cu={})),function(e){e[e.Official=1]="Official"}(Iu||(Iu={})),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"}(Au||(Au={})),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"}(Su||(Su={})),function(e){e[e.Unknown=0]="Unknown";e[e.Success=1]="Success";e[e.Pending=2]="Pending";e[e.Failed=3]="Failed"}(ku||(ku={})),function(e){e[e.Unknown=0]="Unknown";e[e.Default=1]="Default";e[e.Custom=2]="Custom"}(ju||(ju={})),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"}(Pu||(Pu={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(zu||(zu={})),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"}(Tu||(Tu={})),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"}(Ru||(Ru={})),function(e){e[e.Unknown=0]="Unknown";e[e.VefaasFunction=1]="VefaasFunction"}(xu||(xu={})),function(e){e[e.Unknown=0]="Unknown";e[e.Dev=1]="Dev";e[e.Prod=2]="Prod";e[e.Audit=3]="Audit"}(Lu||(Lu={})),function(e){e[e.A=1]="A";e[e.CNAME=2]="CNAME"}(Ou||(Ou={})),function(e){e[e.Unknown=0]="Unknown";e[e.Single=1]="Single";e[e.Wildcard=2]="Wildcard";e[e.Multi=3]="Multi"}(Du||(Du={})),function(e){e[e.Unknown=0]="Unknown";e[e.DV=1]="DV";e[e.OV=2]="OV";e[e.EV=3]="EV"}(Uu||(Uu={})),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"}(qu||(qu={})),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"}(Bu||(Bu={})),function(e){e[e.NeedAuthorize=1]="NeedAuthorize";e[e.BindSuccess=2]="BindSuccess";e[e.BoundToOtherProject=3]="BoundToOtherProject";e[e.BoundToOtherUser=4]="BoundToOtherUser"}(Mu||(Mu={})),function(e){e[e.BoundToSelf=1]="BoundToSelf";e[e.BoundToOtherUser=2]="BoundToOtherUser";e[e.NotAuthorized=3]="NotAuthorized"}(Nu||(Nu={})),function(e){e[e.Line=1]="Line"}($u||($u={})),function(e){e[e.Default=0]="Default";e[e.WechatMini=1]="WechatMini";e[e.DouyinMini=2]="DouyinMini"}(Gu||(Gu={})),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"}(Fu||(Fu={})),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"}(Vu||(Vu={})),function(e){e[e.Recorded=1]="Recorded"}(Wu||(Wu={})),function(e){e[e.Sum=1]="Sum";e[e.Avg=2]="Avg"}(Hu||(Hu={})),function(e){e[e.Next=1]="Next";e[e.Third=3]="Third";e[e.Seventh=7]="Seventh"}(Ju||(Ju={}));class Qu{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Qu.prototype.__init.call(this),Qu.prototype.__init2.call(this),this.request=Ku([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Ku([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}PublicCreateDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/create"),s={project_id:o.project_id,is_sync_db_to_prod:o.is_sync_db_to_prod,encrypt_env_variable:o.encrypt_env_variable,table_sync_configs:o.table_sync_configs,encrypt_deploy:o.encrypt_deploy,commit_hash:o.commit_hash,connector_configs:o.connector_configs,deploy_config:o.deploy_config};return this.request({url:i,method:"POST",data:s},t)}PublicRollbackDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/rollback"),s={project_id:o.project_id,target_deploy_history_id:o.target_deploy_history_id,rollback_database:o.rollback_database};return this.request({url:i,method:"POST",data:s},t)}PublicCancelDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/cancel"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_config/get"),s={project_id:o.project_id,commit_hash:o.commit_hash};return this.request({url:i,method:"GET",params:s},t)}PublicListDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/list"),s={project_id:o.project_id,page_token:o.page_token,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}PublicSearchRuntimeLog(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/runtime_log/search"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id,start_time:o.start_time,end_time:o.end_time,limit:o.limit,cursor:o.cursor,query:o.query,level:o.level};return this.request({url:i,method:"GET",params:s},t)}PublicGetDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"GET",params:s},t)}PublicBindCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/bind"),s={project_id:o.project_id,certificate_id:o.certificate_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicApplyFreeCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/apply_free"),s={project_id:o.project_id,domain:o.domain,auto_renew_free_cert:o.auto_renew_free_cert};return this.request({url:i,method:"POST",data:s},t)}PublicListDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/list"),s={project_id:o.project_id,unit_type:o.unit_type};return this.request({url:i,method:"GET",params:s},t)}PublicDeleteDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/delete"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicCreateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/create"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/get"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetCertificateDetail(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/get"),s={project_id:o.project_id,certificate_id:o.certificate_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/get"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicListVolcanoDomain(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/volcano_domain/list"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicListVolcanoCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/list_volcano"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicListProjectTraces(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/traces/list"),s={project_id:o.project_id,start_time:o.start_time,end_time:o.end_time,filter:o.filter,page_token:o.page_token,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PublicDownloadProjectTraces(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/traces/download"),s={project_id:o.project_id,start_time:o.start_time,end_time:o.end_time,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}PublicGetProjectMetrics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/metrics/get"),s={project_id:o.project_id,time_range:o.time_range,retention_days:o.retention_days};return this.request({url:i,method:"GET",params:s},t)}PublicDeleteDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/delete"),s={project_id:o.project_id,deploy_unit_id:o.deploy_unit_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetHelpCenterLink(e,t){const o=this.genBaseURL("/api/coding/deployment/help_center/link");return this.request({url:o,method:"GET"},t)}PublicCheckRollbackDatabase(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/check_rollback_database"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetMiniProgramPreview(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/mini_program/preview"),s={project_id:o.project_id,app_id:o.app_id,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}PublicSubmitAuthCode(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/submit_code"),s={project_id:o.project_id,connector_id:o.connector_id,code:o.code,verify_state:o.verify_state,auth_params:o.auth_params};return this.request({url:i,method:"POST",data:s},t)}PublicGetAuthStatus(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/status"),s={project_id:o.project_id,connector_id:o.connector_id,redirect_url:o.redirect_url};return this.request({url:i,method:"POST",data:s},t)}PublicBindAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/bind"),s={project_id:o.project_id,connector_id:o.connector_id,redirect_url:o.redirect_url,auth_params:o.auth_params,override:o.override};return this.request({url:i,method:"POST",data:s},t)}PublicUnbindAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/unbind"),s={project_id:o.project_id,connector_id:o.connector_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetBoundProject(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/get_bound_project"),s={connector_id:o.connector_id,related_id:o.related_id};return this.request({url:i,method:"GET",params:s},t)}PublicUpdateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/update"),s={project_id:o.project_id,domain:o.domain,auto_renew_free_cert:o.auto_renew_free_cert,visit_status:o.visit_status,next_primary_domain:o.next_primary_domain};return this.request({url:i,method:"POST",data:s},t)}PublicGetCertificateQuota(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/quota"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicListDomainCertificates(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/list"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicUnpublishConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/unpublish_project"),s={project_id:o.project_id,connector_ids:o.connector_ids};return this.request({url:i,method:"POST",data:s},t)}PublicListConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/list"),s={project_id:o.project_id,project_publish_status:o.project_publish_status};return this.request({url:i,method:"GET",params:s},t)}PublicPublishConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/publish_project"),s={project_id:o.project_id,connector_configs:o.connector_configs};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployCount(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get_count"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}GetRuntimeLogCount(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/runtime_log/count"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicExchangeFeishuAuthCode(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/auth/exchange_code"),s={project_id:o.project_id,code:o.code,verify_state:o.verify_state};return this.request({url:i,method:"POST",data:s},t)}PublicRevokeFeishuAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/auth/revoke"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublicUpdateDefaultDomainPrefix(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/update_default_prefix"),s={project_id:o.project_id,prefix:o.prefix};return this.request({url:i,method:"POST",data:s},t)}PublicFeishuWebhookEvent(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/webhook/event"),s={body:o.body};return this.request({url:i,method:"POST",data:s},t)}PublicCheckCreateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/check_create"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetHostedUsageMonthly(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/hosted_usage/monthly"),s={project_id:o.project_id,bill_month:o.bill_month};return this.request({url:i,method:"GET",params:s},t)}PublicGetEstimateHostedCost(e,t){const o=this.genBaseURL("/api/coding/deployment/hosted_usage/estimate_cost");return this.request({url:o,method:"GET"},t)}PublicGetDeployHistoryLog(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/log"),s={deploy_history_id:o.deploy_history_id,key:o.key};return this.request({url:i,method:"GET",params:s},t)}PublicGetMPICPStatus(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/mini_program/icp_status"),s={project_id:o.project_id,app_id:o.app_id,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetOnlineDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get_online"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicNeedExpansion(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_config/need_expansion"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetDeployConfigRecommend(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_config/get_recommend"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetUserAnalyticsMetrics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/metrics/user_analytics/get"),s={project_id:o.project_id,time_range:o.time_range};return this.request({url:i,method:"GET",params:s},t)}PublicPauseDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/pause"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicStopDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/stop"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicResumeDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/resume"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicReportUserAnalytics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/analytics/report"),s={events:o.events},n={project_id:o.project_id,did:o.did};return this.request({url:i,method:"POST",data:s,params:n},t)}PublicCreateDefaultDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/create_default"),s={project_id:o.project_id,prefix:o.prefix};return this.request({url:i,method:"POST",data:s},t)}PublicGetProtectionConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/protection_config/get"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicUpdateProtectionConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/protection_config/update"),s={project_id:o.project_id,config:o.config};return this.request({url:i,method:"POST",data:s},t)}PublicAuthRedirect(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/redirect"),s={url:o.url};return this.request({url:i,method:"GET",params:s},t)}PublicAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/callback"),s={redirect_url:o.redirect_url};return this.request({url:i,method:"GET",params:s},t)}}const Yu=new Qu({});function Zu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Xu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function em(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const tm=t=>{const o=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 -p <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");o.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"}],seeAlso:["coze code domain add","coze code domain remove"]}}).action((async function(e,t){const o=t.getContext(),{projectId:i}=e,s=Xu([await Yu.PublicListDomainRelated({project_id:i}),"access",e=>e.data,"optionalAccess",e=>e.items])||[];Xu([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Fetched domains List successfully")]),Xu([o,"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:{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"}],seeAlso:["coze code domain list","coze code domain remove"]}}).action((async function(t,o,i){const s=i.getContext(),{projectId:n}=o;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 Yu.PublicCreateDomainRelated({project_id:n,domain:t}),em([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Domain '${t}' added.`)]),em([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,domain:t})])}))}(o),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:{message:{type:"string",description:"Result message"},domain:{type:"string",description:"Deleted domain"}}},errors:[{code:e.ErrorCode.E3000,name:"RESOURCE_NOT_FOUND",desc:"Domain is not bound to the project",fix:"Use `coze code domain list -p <projectId>` to view bound domains"},{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"}],seeAlso:["coze code domain list","coze code domain add"]}}).action((async function(t,o,i){const s=i.getContext(),{projectId:n}=o;try{await Yu.PublicDeleteDomainRelated({project_id:n,domain:t})}catch(o){K(o,e.ErrorCode.E3000,`Domain '${t}' is not bound to project '${n}'`,{domain:t,projectId:n})}Zu([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Domain '${t}' removed.`)]),Zu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({message:`Domain '${t}' removed.`,domain:t})])}))}(o)},om={[Su.Pending]:"Pending",[Su.Running]:"Running",[Su.Succeeded]:"Succeeded",[Su.Failed]:"Failed",[Su.Canceled]:"Canceled",[Su.Interrupted]:"Interrupted"},im=[Su.Succeeded,Su.Failed,Su.Canceled],sm=e=>e&&om[e]||"Unknown";function nm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class rm{static __initStatic(){this.INSTANCE=new rm}static getInstance(){return rm.INSTANCE||(rm.INSTANCE=new rm),this.INSTANCE}async pollDeployStatus(t){const{projectId:o,deployHistoryId:i,onBeforePoll:s,onStatusChange:n}=t;let r;for(;;){nm([s,"optionalCall",e=>e()]);const t=nm([await Yu.PublicGetDeployHistory({project_id:o,deploy_history_id:i}),"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,nm([n,"optionalCall",e=>e(t)])),im.includes(a))return t;await new Promise((e=>setTimeout(e,3e3)))}}async getLatestDeployHistoryId(e){const{projectId:t}=e;return nm([await Yu.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:o,deployHistoryId:i}=t,s=await Yu.PublicGetDeployHistory({project_id:o,deploy_history_id:i});if(!nm([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.WechatMiniProgram,t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.Skill,t.VibeProjectType.Agent,t.VibeProjectType.Automation].includes(e)}async getCommitList({projectId:o}){const i=await t.IdeApi.ProxySandboxMessage({ProjectID:o,Method:"repo_version.commit.list",Params:JSON.stringify({project_id:o})});return e.safeJsonParse(i.data,{commits:[]}).commits||[]}}rm.__initStatic();const am=rm.getInstance();function cm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function lm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function dm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function pm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function um(o){const i=o.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").option("--table-name <tableName...>","Database table names to sync to production",((e,t)=>t.concat(e)),[]).option("--encrypt-deploy <encrypt_deploy>","Pre-encrypted environment variable string (for Skill projects)").option("--connector-id <connectorId>","Connector IDs for mini-program deployment channels (can specify multiple times, e.g. 10000127 for WeChat, 10000126 for TikTok)",((e,t)=>t.concat(e)),[]).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"},commitId:{type:"string",required:!1,description:"Commit ID (optional, queries latest if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"},tableName:{type:"array",required:!1,description:"Database table names to sync to production (can specify multiple times)"},encryptDeploy:{type:"string",required:!1,description:"Pre-encrypted environment variable string (for Skill projects)"},connectorId:{type:"array",required:!1,description:"Connector IDs for mini-program channels (10000127=WeChat, 10000126=TikTok). If omitted, auto-detects authorized channels."}},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.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Check the project ID, run `coze code project list` to view available projects"},{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"}],seeAlso:["coze code deploy status","coze code deploy list","coze code deploy fix"]}}).description("Deploy the project to production environment").action((async function(o,i,s){const n=s.getContext(),{wait:r,commitId:a,tableName:c,encryptDeploy:l,connectorId:d}=i;let p;try{p=await t.IdeApi.GetVibeProject({project_id:o})}catch(t){K(t,e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o})}const u=pm([p.data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(!am.canDeploy(u)){const t=`Project type ${Up(u)} is not supported for deployment`;throw new e.CozeError(e.ErrorCode.E1006,t,{projectType:u})}if(u===t.VibeProjectType.AssistantAgent)return pm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying (AssistantAgent)...")]),await e.axiosInstance$1.post("api/sandbox/coze_coding/devbox/open_claw/deploy",{project_id:o}),void pm([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"ok",type:u,message:`Assistant project deployment successfully, Please access the ${Sp(o,u,pm([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))} to view the project`})]);let m,g=a;if(!g){pm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching latest commit...")]);const e=await am.getCommitList({projectId:o});g=pm([e,"optionalAccess",e=>e[0],"optionalAccess",e=>e.id])}if(!g){const t="No commits found: commit your changes first, or pass --commit-id <commitId>";throw new e.CozeError(e.ErrorCode.E3007,t,{projectId:o})}if(u===t.VibeProjectType.WechatMiniProgram)if(d&&d.length>0)m=d.map((e=>({connector_id:e})));else{pm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking Mini-program authorization...")]);const t=[{name:"WeChat",id:"10000127"},{name:"TikTok",id:"10000126"}],i=(await Promise.all(t.map((async e=>{const t=await Yu.PublicGetAuthStatus({project_id:o,connector_id:e.id});return{...e,authorized:Boolean(pm([t,"access",e=>e.data,"optionalAccess",e=>e.bound_related_id]))}})))).filter((e=>e.authorized));if(0===i.length){const t=`Deployment failed, no authorized Mini-program channels found. Please visit ${Sp(o,u,pm([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))} to complete WeChat or TikTok AppID configuration.`;throw new e.CozeError(e.ErrorCode.E2002,t)}m=i.map((e=>({connector_id:e.id})))}pm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking deploy config...")]),await Yu.PublicGetDeployConfig({project_id:o,commit_hash:g},{__disableErrorToast:!0});let h="";const f=await vs.ListProjectSecret({env:us.dev,project_id:o,with_providers:!0}),_=pm([f,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],y=pm([f,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_cred_providers])||[];pm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Encrypting secrets...")]);h=pm([await vs.EncryptProjectSecret({project_id:o,project_type:u===t.VibeProjectType.Skill?ps.skill:void 0,encrypt_secrets:{secrets:_.map((e=>({secret_key:e.secret_key||"",secret_val:e.secret_val||"",secret_id:e.secret_id||"",secret_type:e.secret_type===ms.consumer?Bi.consumer3:Bi.user_custom2}))),cred_providers:y}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.sealed_secrets])||"",pm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying...")]);const b={project_id:o,encrypt_env_variable:h,commit_hash:g,encrypt_deploy:u===t.VibeProjectType.Skill?Boolean(l):void 0,connector_configs:m};if(c&&c.length>0){const e=new Map,i=["knowledge","public"];await Promise.all(i.map((async i=>{((await t.IdeApi.GetSchemaTables({project_id:o,database_env:t.MemoryEnv.develop,schema:i})).table_names||[]).forEach((t=>{e.set(t,i)}))}))),b.table_sync_configs=c.map((t=>({table_name:t,schema:e.get(t)||"",sync_data:!0})))}const v=pm([await Yu.PublicCreateDeployHistory(b),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_id]);pm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploy started.")]),r&&v?await am.pollDeployStatus({projectId:o,deployHistoryId:v,onBeforePoll:()=>{pm([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const t=sm(e.status);pm([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",i=>i({projectId:o,status:t,domain:pm([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:v,commitHash:e.commit_hash})])}}):pm([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({projectId:o,status:sm(Su.Pending),domain:"",deployHistoryId:v,commitHash:g})])}));!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>`"}],seeAlso:["coze code deploy","coze code deploy fix"]}}).action((async function(t,o,i){const s=i.getContext(),{deployId:n}=o,{wait:r}=cm([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=n;if(!a&&(cm([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("get latest deployment record...")]),a=await am.getLatestDeployHistoryId({projectId:t}),!a))throw new e.CozeError(e.ErrorCode.E3006,"No deployment history found for this project");if(r)await am.pollDeployStatus({projectId:t,deployHistoryId:a,onBeforePoll:()=>{cm([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const o=sm(e.status);cm([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",i=>i({projectId:t,status:o,domain:cm([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:a,commitHash:e.commit_hash})])}});else{cm([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Querying deployment status...")]);const e=await am.getDeployHistory({projectId:t,deployHistoryId:a}),o=sm(e.status),i=e.domain_list||[];cm([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",s=>s({projectId:t,status:o,domain:i[0],deployHistoryId:a,commitHash:e.commit_hash})])}}))}(i),function(t){t.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:"object",properties:{items:{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"}}},next_page_token:{type:"string",description:"Token for fetching the next page, empty if no more pages"},has_more:{type:"boolean",description:"Whether there are more records"}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Check the project ID, run `coze code project list` to view available projects"},{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"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server failed to fetch the deployment history",fix:"Retry later; run with --debug for details if the issue persists"}],seeAlso:["coze code deploy","coze code deploy status"]}}).action((async function(e,t,o){const i=o.getContext(),s=Number(t.pageSize)||10,n=await Yu.PublicListDeployHistory({project_id:e,page_size:s,page_token:t.pageToken}),r=(lm([n,"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:sm(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})));lm([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>{return e({items:r,next_page_token:lm([n,"optionalAccess",e=>e.data,"optionalAccess",e=>e.next_page_token])||"",has_more:(t=lm([n,"optionalAccess",e=>e.data,"optionalAccess",e=>e.has_more]),o=()=>!1,null!=t?t:o())});var t,o}])}))}(i),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 <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",description:"Structured output is only printed with --wait. Without --wait the fix request is sent in the background and no structured output is produced.",properties:{deploy_history_id:{type:"string"},status:{type:"string"},message:{type:"object",description:"Last answer message object (ServerMessageRaw); the answer text is in message.content.answer"}}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and run with --debug if the issue persists"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"No deploy history or deploy log found",fix:"Please confirm the project has deployment records and retry"},{code:e.ErrorCode.E3009,name:"CONFLICT",desc:"Deployment is not in Failed status",fix:"Only failed deployments can be fixed. Check the deployment status first"},{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"}],seeAlso:["coze code deploy status","coze code deploy list"]}}).action((async function(t,o,i){const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const{deployId:n}=o,r=null!=(a=o.wait)?a:(()=>dm([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"optionalAccess",e=>e.wait]))();var a;let c=n;if(n||(c=await am.getLatestDeployHistoryId({projectId:t})),!c)throw new e.CozeError(e.ErrorCode.E5002,`No deploy history found for project ${t}`,{project_id:t});const l=dm([await Yu.PublicGetDeployHistory({project_id:t,deploy_history_id:c}),"optionalAccess",e=>e.data]);if(dm([l,"optionalAccess",e=>e.status])!==Su.Failed){const t=sm(dm([l,"optionalAccess",e=>e.status]));throw new e.CozeError(e.ErrorCode.E3009,`Deployment ${c} is not in Failed status (current: ${t}). Only failed deployments can be fixed.`,{deploy_history_id:c,status:dm([l,"optionalAccess",e=>e.status])})}const d=l.deploy_log_url;if(!d)throw new e.CozeError(e.ErrorCode.E5002,`No deploy log URL found for deployment ${c}`,{deploy_history_id:c});const p=await e.customFetch.fetch(d,{method:"GET"}),u=await p.text();if(!u)throw new e.CozeError(e.ErrorCode.E5002,`Deploy log is empty for deployment ${c}`,{deploy_history_id:c,deploy_log_url:d});const m=`修复以下部署错误:\n${u}`,g=await dm([s,"access",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!g)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const h=await Tl.getDefaultConversation(t);if(r){const e=await jp.sendMessage({projectId:t,prompt:m,apiBaseUrl:s.config.apiBaseUrl,accessToken:g,xTTEnv:s.config.xTTEnv,conversationId:h.id,key:`coze-coding-cli:message:${t}`});dm([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({deploy_history_id:c,status:"fix_sent",message:e.lastAnswerMessage})])}else jp.sendMessageRunTask({projectId:t,prompt:m,apiBaseUrl:s.config.apiBaseUrl,accessToken:g,xTTEnv:s.config.xTTEnv,conversationId:h.id,key:`coze-coding-cli:message:${t}`})}))}(i)}function mm(e,t){return null!=e?e:t()}function gm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class hm{static getInstance(){return hm.INSTANCE||(hm.INSTANCE=new hm),hm.INSTANCE}async createSpaceDatabase(o){const i=await t.IdeApi.CreateSpaceDatabase({space_id:o},{});if(!i.database)throw new e.CozeError(e.ErrorCode.E5000,"Failed to create database");return i.database}async listSpaceDatabases(e,o){const i=await t.IdeApi.ListSpaceDatabase({space_id:e,cursor_id:gm([o,"optionalAccess",e=>e.cursor_id]),limit:mm(gm([o,"optionalAccess",e=>e.limit]),(()=>20))},{});return{databases:mm(gm([i,"optionalAccess",e=>e.databases]),(()=>[])),next_cursor_id:i.next_cursor_id}}async getSpaceDatabase(o,i){let s;try{s=await t.IdeApi.GetSpaceDatabase({space_id:o,database_id:i},{})}catch(t){K(t,e.ErrorCode.E3010,`Database '${i}' not found or no permission`,{databaseId:i})}if(!s.database)throw new e.CozeError(e.ErrorCode.E3010,`Database '${i}' not found or no permission`,{databaseId:i});return s.database}async deleteSpaceDatabase(e,o){await t.IdeApi.DeleteSpaceDatabase({space_id:e,database_id:o},{})}async rollbackSpaceDatabase(e,o,i){return await t.IdeApi.RollbackSpaceDatabase({space_id:e,database_id:o,timestamp:i},{})}async getSpaceDatabaseStatus(e,o){return await t.IdeApi.GetSpaceDatabaseStatus({space_id:e,database_id:o},{})}}const fm=hm.getInstance(),_m={0:"active",1:"creating"},ym={0:"dev",1:"prod"},bm={0:"restoring",1:"success",2:"failed"},vm=e=>e&&"0"!==e?new Date(Number(e)).toLocaleString():"-",wm=e=>e?e.length<=4?"***":`${e.slice(0,4)}***`:"-";function Em(e,t){return null!=e?e:t()}function Cm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Im(e,t){return null!=e?e:t()}function Am(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Sm(t){t.command("rollback").description("Rollback database to a specific timestamp").requiredOption("--db-id <dbId>","Database ID").requiredOption("--timestamp <timestamp>","Target timestamp in milliseconds (Int64)").option("--confirm","Confirm rollback (required)").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Rollback database",description:"Rollback a database to a specific point in time using PITR (Point-in-Time Recovery). The --confirm flag is required. Use `coze code db status` to check the rollback progress.",examples:[{desc:"Rollback database",cmd:"coze code db rollback --db-id <id> --timestamp 1713254400000 --confirm",tags:["[RECOMMENDED]"]},{desc:"Check rollback status",cmd:"coze code db status --db-id <id>"}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},timestamp:{type:"string",required:!0,description:"Target timestamp in milliseconds (Int64 string)"},confirm:{type:"boolean",required:!0,description:"Must be set to confirm rollback"}},output:{restore_history_id:{type:"string",description:"Restore history ID"}}},errors:[{code:e.ErrorCode.E1007,name:"DB_SQL_DANGEROUS",desc:"Rollback requires --confirm flag",fix:"Add --confirm flag to proceed",example:"coze code db rollback --db-id <id> --timestamp <ts> --confirm"},{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E3012,name:"DB_RESTORE_WINDOW_EXCEEDED",desc:"Rollback time exceeds recovery window",fix:"Use `coze code db status` to check earliest_restore_time"},{code:e.ErrorCode.E3013,name:"DB_RESTORE_IN_PROGRESS",desc:"A rollback is already in progress",fix:"Wait for the current rollback to complete"}],seeAlso:["coze code db query","coze code db status"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!t.confirm)throw new e.CozeError(e.ErrorCode.E1007,"Rollback requires --confirm flag to proceed",{databaseId:t.dbId,timestamp:t.timestamp},{trigger:"Rollback is a potentially destructive operation",fix:"Add --confirm flag to confirm rollback",example:`coze code db rollback --db-id ${t.dbId} --timestamp ${t.timestamp} --confirm`});((t,o=Date.now())=>{if(!/^\d+$/.test(t)||!Number.isSafeInteger(Number(t)))throw new e.CozeError(e.ErrorCode.E1000,`Invalid --timestamp '${t}': expected an integer millisecond timestamp`,{timestamp:t},{trigger:"Timestamp must be a millisecond Unix timestamp (Int64)",fix:"Pass the target time in milliseconds, e.g. 1713254400000",example:"coze code db rollback --db-id <id> --timestamp 1713254400000 --confirm"});const i=Number(t);if(i<1e12)throw new e.CozeError(e.ErrorCode.E1000,`Invalid --timestamp '${t}': value looks like seconds, expected milliseconds`,{timestamp:t},{trigger:"Timestamp unit looks like seconds instead of milliseconds",fix:"Multiply the value by 1000, e.g. --timestamp "+1e3*i,example:"coze code db rollback --db-id <id> --timestamp 1713254400000 --confirm"});if(i>o)throw new e.CozeError(e.ErrorCode.E1000,`Invalid --timestamp '${t}': target time is in the future`,{timestamp:t},{trigger:"PITR can only restore to a past point in time",fix:"Pass a millisecond timestamp earlier than now"})})(t.timestamp);const s=Im(Im(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Rolling back database '${t.dbId}' to ${new Date(Number(t.timestamp)).toLocaleString()}...`);const n=await fm.rollbackSpaceDatabase(s,t.dbId,t.timestamp);i.ui.success(`Rollback initiated. Use 'coze code db status --db-id ${t.dbId}' to check progress.`),i.response.print({restore_history_id:Am([n,"optionalAccess",e=>e.restore_history_id])})}))}const km=[{pattern:/\bDROP\s+(TABLE|INDEX|SCHEMA|DATABASE|VIEW|FUNCTION|TRIGGER)\b/i,level:"critical",reason:"Contains DROP statement that permanently removes database objects"},{pattern:/\bTRUNCATE\s+(TABLE\s+)?\w/i,level:"critical",reason:"Contains TRUNCATE statement that removes all rows from a table"},{pattern:/\bALTER\s+TABLE\b/i,level:"warning",reason:"Contains ALTER TABLE statement that may cause data loss"},{pattern:/\bDELETE\s+FROM\s+\w+\s*(?:;?\s*$)/im,level:"critical",reason:"Contains DELETE without WHERE clause that removes all rows"},{pattern:/\bUPDATE\s+\w+\s+SET\s+(?!.*\bWHERE\b).*$/im,level:"critical",reason:"Contains UPDATE without WHERE clause that modifies all rows"}];function jm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Pm(e,t){return null!=e?e:t()}function zm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Tm=async(t,o,i,s)=>{const n=`${t}/api/platform/pg-meta/default/query`,r=Buffer.from(`${o}:${i}`).toString("base64"),a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${r}`},body:JSON.stringify({query:s})});if(!a.ok){const t=await a.text(),o=e.safeJsonParse(t,void 0),i=Pm(Pm(zm([o,"optionalAccess",e=>e.message]),(()=>zm([o,"optionalAccess",e=>e.error,"optionalAccess",e=>e.message]))),(()=>`pg-meta request failed: ${a.status}`));throw new Error(i)}const c=await a.json();return Array.isArray(c)?c:[]};function Rm(e,t){return null!=e?e:t()}function xm(t){t.command("query").description("Execute SQL query on a database").requiredOption("--db-id <dbId>","Database ID").option("--sql <sql>","Inline SQL to execute").option("--file <path>","Read SQL from file").option("--confirm","Confirm execution of dangerous SQL").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Execute SQL query",description:"Execute SQL on a database. Supports inline SQL (--sql), file input (--file), or stdin pipe. Dangerous operations (DROP, TRUNCATE, DELETE/UPDATE without WHERE) require --confirm flag. In JSON mode, dangerous SQL without --confirm returns an error.",examples:[{desc:"Execute inline SQL",cmd:'coze code db query --db-id <id> --sql "SELECT * FROM users LIMIT 10"',tags:["[RECOMMENDED]"]},{desc:"Execute SQL from file",cmd:"coze code db query --db-id <id> --file ./query.sql"},{desc:"Pipe SQL via stdin",cmd:'echo "SELECT 1" | coze code db query --db-id <id>'},{desc:"Execute with confirmation",cmd:'coze code db query --db-id <id> --sql "DROP TABLE old_data" --confirm'}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},sql:{type:"string",required:!1,description:"Inline SQL (highest priority)"},file:{type:"string",required:!1,description:"Path to SQL file"},confirm:{type:"boolean",required:!1,description:"Confirm dangerous operations"}},output:{result:{type:"array",description:"Query results (SELECT)"},rows_affected:{type:"number",description:"Rows affected (DML)"},command:{type:"string",description:"SQL command type"},warnings:{type:"array",description:"Security warnings"}}},errors:[{code:e.ErrorCode.E1007,name:"DB_SQL_DANGEROUS",desc:"SQL contains dangerous operation",fix:"Add --confirm flag or modify the SQL",example:'coze code db query --db-id <id> --sql "DROP TABLE t" --confirm'},{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E5004,name:"DB_SQL_EXECUTION_FAILED",desc:"SQL execution failed",fix:"Check SQL syntax and table structure"},{code:e.ErrorCode.E5005,name:"DB_CONNECTION_FAILED",desc:"Cannot connect to database service",fix:"Check database status and network"}],seeAlso:["coze code db rollback","coze code db dump"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Rm(Rm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const n=t.sql||t.file?void 0:await async function(e,t){return null!=e?e:await t()}(await Ra(),(async()=>{}));let r;try{r=await(async e=>{if(jm([e,"optionalAccess",e=>e.sql]))return e.sql.trim();if(jm([e,"optionalAccess",e=>e.file])){const t=m.resolve(e.file),o=(await g.readFile(t,"utf-8")).trim();if(!o)throw new Error(`SQL file is empty: ${t}`);return o}if(jm([e,"optionalAccess",e=>e.stdin])){const t=e.stdin.trim();if(!t)throw new Error("SQL input from stdin is empty");return t}throw new Error("No SQL provided. Use --sql, --file, or pipe SQL via stdin.")})({sql:t.sql,file:t.file,stdin:n})}catch(t){throw new e.CozeError(e.ErrorCode.E1000,t instanceof Error?t.message:String(t),void 0,{trigger:"No usable SQL input",fix:"Provide SQL via --sql, --file, or stdin pipe",example:'coze code db query --db-id <id> --sql "SELECT 1"'})}const a=(e=>{const t=[];let o="safe";const i=e.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const{pattern:e,level:s,reason:n}of km)e.test(i)&&(t.push(n),"critical"===s?o="critical":"safe"===o&&(o="warning"));return{isDangerous:"safe"!==o,level:o,reasons:t}})(r);if(a.isDangerous&&!t.confirm){const o="json"===i.format,s=!0===process.stdin.isTTY;if(o||!s)throw new e.CozeError(e.ErrorCode.E1007,`SQL contains dangerous operation: ${a.reasons.join(", ")}`,{sql:r.substring(0,200),analysis:a},{trigger:"Dangerous SQL detected without --confirm",fix:"Add --confirm flag to proceed, or modify the SQL to remove dangerous operations",example:`coze code db query --db-id ${t.dbId} --sql "..." --confirm`});i.ui.info(`⚠ Warning: SQL contains dangerous operation:\n ${a.reasons.join("\n ")}`);const{confirm:n}=await import("@inquirer/prompts").then((e=>({confirm:e.confirm})));if(!await n({message:"Are you sure you want to execute this SQL?",default:!1}))return void i.ui.info("Operation cancelled.")}i.ui.info("Fetching database connection info...");const c=await fm.getSpaceDatabase(s,t.dbId);if(!c.supabase_url)throw new e.CozeError(e.ErrorCode.E5005,"Database does not have supabase_url. Cannot execute SQL via pg-meta.",{databaseId:t.dbId});if(!c.super_user||!c.super_user_password)throw new e.CozeError(e.ErrorCode.E5005,"Database does not have super_user credentials. Cannot authenticate against pg-meta.",{databaseId:t.dbId});let l;i.ui.info("Executing SQL...");try{l=await Tm(c.supabase_url,c.super_user,c.super_user_password,r)}catch(t){throw new e.CozeError(e.ErrorCode.E5004,`SQL execution failed: ${t.message}`,{sql:r.substring(0,200)})}const d=Rm(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([r,"access",e=>e.trim,"call",e=>e(),"access",e=>e.split,"call",e=>e(/\s+/),"access",e=>e[0],"optionalAccess",e=>e.toUpperCase,"call",e=>e()]),(()=>"UNKNOWN")),p="SELECT"===d,u=a.isDangerous?a.reasons:[],h=l.length>0,f=p||h?l.length:null;p||h?i.response.print("json"===i.format?{result:l,rows_affected:f,command:d,warnings:u}:l):(i.ui.success("SQL executed successfully (rows_affected unavailable from pg-meta)."),i.response.print("json"===i.format?{result:[],rows_affected:null,command:d,warnings:u,note:"pg-meta does not expose rows_affected for DDL/DML without RETURNING"}:{command:d,message:"SQL executed successfully."}))}))}function Lm(e,t){return null!=e?e:t()}function Om(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Dm=e=>({database_id:e.database_id,name:e.name,status:Lm(_m[Lm(e.status,(()=>0))],(()=>String(e.status))),database_env:Lm(ym[Lm(e.database_env,(()=>0))],(()=>String(e.database_env))),created_at:vm(e.created_at)});async function Um(t,o){const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Lm(Lm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const n=Lm(t.limit,(()=>20)),r="json"!==i.format;if(r||!0===t.all){const e=Lm(t.maxPages,(()=>10)),o=[];let a,c=t.cursor,l=0;for(i.ui.info("Fetching databases...");l<e;){const e=await fm.listSpaceDatabases(s,{cursor_id:c,limit:n});if(o.push(...Lm(e.databases,(()=>[])).map(Dm)),l+=1,i.ui.verbose(`Page ${l}: ${Lm(Om([e,"access",e=>e.databases,"optionalAccess",e=>e.length]),(()=>0))} item(s)`),a=e.next_cursor_id,!a||"0"===a){a=void 0;break}c=a}return a&&i.ui.info(`Reached --max-pages=${e}. More results available (cursor: ${a}). Pass --max-pages to fetch more.`),i.ui.info(`Fetched ${o.length} database(s).`),void(r?i.response.print(o):i.response.print({databases:o,next_cursor_id:Lm(a,(()=>"0"))}))}const a=await fm.listSpaceDatabases(s,{cursor_id:t.cursor,limit:n});i.response.print({databases:Lm(a.databases,(()=>[])).map(Dm),next_cursor_id:a.next_cursor_id})}function qm(e,t){return null!=e?e:t()}function Bm(e,t){return null!=e?e:t()}async function Mm(t,o){const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Bm(Bm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const a=t.includeSchema&&t.includeSchema.length>0?t.includeSchema:["public"];i.ui.info("Fetching database connection info...");const c=await fm.getSpaceDatabase(s,t.dbId);if(!c.supabase_url)throw new e.CozeError(e.ErrorCode.E5006,"Database does not have supabase_url. Cannot generate types via PostgREST OpenAPI.",{databaseId:t.dbId},{fix:"Check database is in active status. Run `coze code db status --db-id <id>`."});if(!c.anon_key)throw new e.CozeError(e.ErrorCode.E5006,"Database does not have anon_key. Cannot authenticate with PostgREST.",{databaseId:t.dbId});i.ui.info("Fetching OpenAPI schema from PostgREST...");const l=`${c.supabase_url}/rest/v1/`;let d,p;try{const e=await fetch(l,{headers:{apikey:c.anon_key}});if(!e.ok)throw new Error(`PostgREST returned ${e.status}`);const t=await e.json();d=await async function(e){if("string"==typeof e.openapi)return e;if("string"==typeof e.swagger){const{convertObj:t}=await import("swagger2openapi");return(await t(e,{patch:!0,warnOnly:!0})).openapi}return e}(t)}catch(o){throw new e.CozeError(e.ErrorCode.E5006,`Failed to fetch OpenAPI schema: ${o.message}`,{databaseId:t.dbId})}i.ui.info("Generating TypeScript types...");try{const e=await import("openapi-typescript"),t=await e.default(d,{exportType:!0});p="string"==typeof t?t:e.astToString(t)}catch(o){throw new e.CozeError(e.ErrorCode.E5006,`Type generation failed: ${o.message}`,{databaseId:t.dbId},{fix:"The CLI auto-converts PostgREST Swagger 2.0 to OpenAPI 3.0 before generation. If it still fails, the schema may use constructs the generator cannot map — re-run with --debug for the underlying error."})}const u=n.resolve(Bm(t.output,(()=>"types/database.ts")));await r.mkdir(n.dirname(u),{recursive:!0}),await r.writeFile(u,"// Auto-generated by coze code db gen-types\n// Do not edit manually\n\n"+p,"utf-8"),i.ui.success(`Types generated: ${u}`),i.response.print({output_path:u,schemas:a})}function Nm(e,t){return null!=e?e:t()}const $m=/^[a-zA-Z_][a-zA-Z0-9_$]{0,62}$/,Gm=e=>{let t=` ${e.column_name} ${e.data_type}`;return e.character_maximum_length&&(t=` ${e.column_name} ${e.data_type}(${e.character_maximum_length})`),"NO"===e.is_nullable&&(t+=" NOT NULL"),e.column_default&&(t+=` DEFAULT ${e.column_default}`),t};async function Fm(e,t){const[o,i,s,n]=await Promise.all([Tm(e.supabaseUrl,e.username,e.password,t.tables),Tm(e.supabaseUrl,e.username,e.password,t.columns),Tm(e.supabaseUrl,e.username,e.password,t.constraints),Tm(e.supabaseUrl,e.username,e.password,t.indexes)]),r=(e=>{const t=new Map;for(const o of e){const e=`${o.table_schema}.${o.table_name}`,i=t.get(e);i?i.push(o):t.set(e,[o])}return t})(i);let a="";for(const e of o){const t=`${e.table_schema}.${e.table_name}`,o=Nm(r.get(t),(()=>[]));a+=`CREATE TABLE IF NOT EXISTS ${e.table_schema}.${e.table_name} (\n`,a+=o.map(Gm).join(",\n"),a+="\n);\n\n"}for(const e of s){const t=e.constraint_type;("p"===t||"u"===t||"f"===t||"c"===t)&&e.definition&&(a+=`ALTER TABLE ${e.schema_name}.${e.table_name} ADD CONSTRAINT ${e.constraint_name} ${e.definition};\n`)}s.length>0&&(a+="\n");const c=new Set(s.filter((e=>"p"===e.constraint_type||"u"===e.constraint_type)).map((e=>`${e.schema_name}.${e.constraint_name}`)));for(const e of n){const t=`${e.schemaname}.${e.indexname}`;!c.has(t)&&e.indexdef&&(a+=`${e.indexdef};\n`)}return n.length>0&&(a+="\n"),a}async function Vm(t,o){const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Nm(Nm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!0===t.schemaOnly&&!0===t.dataOnly)throw new e.CozeError(e.ErrorCode.E1000,"--schema-only and --data-only are mutually exclusive");const a=!t.dataOnly,c=!0===t.dataOnly,l=c?"data-only":"schema-only",d=(t=>{const o=t&&t.length>0?Array.from(new Set(t)):["public"];for(const t of o)if(!$m.test(t))throw new e.CozeError(e.ErrorCode.E1000,`Invalid schema name '${t}'. Must be a plain PostgreSQL identifier (letters, digits, underscore, $; max 63 chars; starts with letter or underscore).`);return o})(t.includeSchema),p=(e=>{const t=e.map((e=>`'${e}'`)).join(", ");return{tables:`\n SELECT table_name, table_schema\n FROM information_schema.tables\n WHERE table_schema IN (${t})\n AND table_type = 'BASE TABLE'\n ORDER BY table_schema, table_name;\n `,columns:`\n SELECT table_name, table_schema, column_name, data_type,\n is_nullable, column_default, character_maximum_length,\n numeric_precision, numeric_scale\n FROM information_schema.columns\n WHERE table_schema IN (${t})\n ORDER BY table_schema, table_name, ordinal_position;\n `,constraints:`\n SELECT n.nspname AS schema_name,\n cl.relname AS table_name,\n c.conname AS constraint_name,\n c.contype AS constraint_type,\n pg_get_constraintdef(c.oid) AS definition\n FROM pg_catalog.pg_constraint c\n JOIN pg_catalog.pg_class cl ON c.conrelid = cl.oid\n JOIN pg_catalog.pg_namespace n ON cl.relnamespace = n.oid\n WHERE n.nspname IN (${t})\n ORDER BY n.nspname, cl.relname,\n CASE c.contype WHEN 'p' THEN 1 WHEN 'u' THEN 2 WHEN 'f' THEN 3 ELSE 4 END,\n c.conname;\n `,indexes:`\n SELECT schemaname, tablename, indexname, indexdef\n FROM pg_indexes\n WHERE schemaname IN (${t})\n ORDER BY schemaname, tablename, indexname;\n `}})(d);i.ui.info("Fetching database connection info...");const u=await fm.getSpaceDatabase(s,t.dbId);if(!u.supabase_url)throw new e.CozeError(e.ErrorCode.E5007,"Database does not have supabase_url. Cannot access pg-meta.",{databaseId:t.dbId});if(!u.super_user||!u.super_user_password)throw new e.CozeError(e.ErrorCode.E5007,"Database does not have super_user credentials. Cannot authenticate against pg-meta.",{databaseId:t.dbId});const m={supabaseUrl:u.supabase_url,username:u.super_user,password:u.super_user_password};let g="";g+="-- Dump generated by coze code db dump\n",g+=`-- Database: ${t.dbId}\n`,g+=`-- Mode: ${l}\n`,g+=`-- Schemas: ${d.join(", ")}\n`,g+=`-- Date: ${(new Date).toISOString()}\n\n`;try{a&&(i.ui.info("Exporting schema..."),g+=await Fm(m,p)),c&&(i.ui.info("Exporting data..."),g+=await async function(e,t){const o=await Tm(e.supabaseUrl,e.username,e.password,t.tables);let i="";for(const t of o){const o=`SELECT * FROM ${t.table_schema}.${t.table_name};`,s=await Tm(e.supabaseUrl,e.username,e.password,o);if(0===s.length)continue;const n=Object.keys(s[0]);for(const e of s){const o=n.map((t=>{return null==(o=e[t])?"NULL":"number"==typeof o?Number.isFinite(o)?String(o):"NULL":"boolean"==typeof o?o?"TRUE":"FALSE":"bigint"==typeof o?String(o):o instanceof Date?`'${o.toISOString()}'`:"object"==typeof o?`'${JSON.stringify(o).replace(/'/g,"''")}'`:`'${String(o).replace(/'/g,"''")}'`;var o}));i+=`INSERT INTO ${t.table_schema}.${t.table_name} (${n.join(", ")}) VALUES (${o.join(", ")});\n`}i+="\n"}return i}(m,p))}catch(o){throw new e.CozeError(e.ErrorCode.E5007,`Dump failed: ${o.message}`,{databaseId:t.dbId})}const h=n.resolve(Nm(t.output,(()=>"db/schema.sql")));await r.mkdir(n.dirname(h),{recursive:!0}),await r.writeFile(h,g,"utf-8"),i.ui.success(`Dump completed: ${h}`),i.response.print({output_path:h,mode:l,schemas:d})}function Wm(e,t){return null!=e?e:t()}function Hm(e,t){return null!=e?e:t()}const Jm=t=>{const o=t.command("db").description("Manage Coze space databases").config({help:{brief:"Database management for Coze spaces",description:"Create, query, and manage Supabase-backed databases in your Coze space. Supports database lifecycle management, SQL execution, TypeScript type generation, and schema export.",examples:[{desc:"Create a new database",cmd:"coze code db create",tags:["[RECOMMENDED]"]},{desc:"List all databases",cmd:"coze code db list"},{desc:"Execute SQL query",cmd:'coze code db query --db-id <id> --sql "SELECT 1"'},{desc:"Generate TypeScript types",cmd:"coze code db gen-types --db-id <id>"},{desc:"Export database schema",cmd:"coze code db dump --db-id <id>"}],seeAlso:["coze code project","coze code env"],schema:{input:{},output:{}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found or no permission",fix:"Check --db-id is correct, run `coze code db list`"}]}});o.command("create").description("Create a new database in current space").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Create a new database",description:"Create a new Supabase database in the current space. The database name and credentials are auto-generated. Use `coze code db get` to retrieve connection info.",examples:[{desc:"Create a database",cmd:"coze code db create",tags:["[RECOMMENDED]"]}],schema:{input:{spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{database_id:{type:"string",description:"Created database ID"},status:{type:"string",description:"Database status"},database_env:{type:"string",description:"Environment"}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Use --space-id or run `coze space use <spaceId>` first"},{code:e.ErrorCode.E4002,name:"DB_QUOTA_EXCEEDED",desc:"Space database quota exceeded",fix:"Delete unused databases with `coze code db delete`"}],seeAlso:["coze code db list","coze code db get"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Hm(Hm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info("Creating database in space...");const n=await fm.createSpaceDatabase(s);i.ui.success("Database created successfully!"),i.response.print({database_id:n.database_id,database_url:n.database_url,status:Hm(_m[Hm(n.status,(()=>0))],(()=>n.status)),database_env:Hm(ym[Hm(n.database_env,(()=>0))],(()=>n.database_env)),created_at:vm(n.created_at)})})),function(t){t.command("list").description("List databases in current space").option("--space-id <spaceId>","Space ID (optional, reads from context)").option("--limit <limit>","Number of databases per page (1-100)",parseInt).option("--cursor <cursorId>","Cursor for pagination").option("--all","Fetch all databases across pages").option("--max-pages <maxPages>","Max pages to fetch in text mode (default: 10)",parseInt).config({help:{brief:"List databases",description:"List all databases in the current space. Supports cursor-based pagination. Use --all to fetch all databases at once.",examples:[{desc:"List databases",cmd:"coze code db list",tags:["[RECOMMENDED]"]},{desc:"List all databases",cmd:"coze code db list --all"},{desc:"Paginated listing",cmd:"coze code db list --limit 5 --cursor <cursorId>"}],schema:{input:{limit:{type:"number",required:!1,description:"Items per page (1-100, default: 20)"},cursor:{type:"string",required:!1,description:"Pagination cursor"},all:{type:"boolean",required:!1,description:"Fetch all databases"}},output:{type:"array",items:{type:"object",properties:{database_id:{type:"string",description:"Database ID"},name:{type:"string",description:"Database name"},status:{type:"string",description:"Status"},database_env:{type:"string",description:"Environment"},created_at:{type:"string",description:"Creation time"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Use --space-id or run `coze space use <spaceId>` first"}],seeAlso:["coze code db create","coze code db get"]}}).action(Um)}(o),function(t){t.command("get").description("Get database details").requiredOption("--db-id <dbId>","Database ID").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Get database details",description:"Get detailed information about a specific database, including connection URLs and credentials. The console URL can be constructed from supabase_url.",examples:[{desc:"Get database details",cmd:"coze code db get --db-id <databaseId>",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{database_id:{type:"string",description:"Database ID"},database_name:{type:"string",description:"Database name"},database_url:{type:"string",description:"Connection URL"},supabase_url:{type:"string",description:"Supabase URL"},super_user:{type:"string",description:"Super user name"},super_user_password:{type:"string",description:"Super user password"},service_role_key:{type:"string",description:"Supabase service role key"},anon_key:{type:"string",description:"Supabase anon key"},status:{type:"string",description:"Status"},database_env:{type:"string",description:"Database environment (e.g. develop / production)"},created_at:{type:"string",description:"Creation time (formatted timestamp)"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found or no permission",fix:"Check --db-id is correct, run `coze code db list`"}],seeAlso:["coze code db list","coze code db status"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=qm(qm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Fetching database '${t.dbId}'...`);const n=await fm.getSpaceDatabase(s,t.dbId);i.ui.success("Database details:");const r="json"===i.format;var a;r||i.ui.info("Credentials are masked in text output. Use --format json to get full values."),i.response.print({database_id:n.database_id,database_name:n.name,database_url:r?n.database_url:(a=n.database_url,a?a.replace(/^([a-z+]+:\/\/[^:/@]+):[^@]+@/i,"$1:****@"):"-"),supabase_url:n.supabase_url,super_user:n.super_user,super_user_password:r?n.super_user_password:wm(n.super_user_password),service_role_key:r?n.service_role_key:wm(n.service_role_key),anon_key:n.anon_key,status:qm(_m[qm(n.status,(()=>0))],(()=>n.status)),database_env:qm(ym[qm(n.database_env,(()=>0))],(()=>n.database_env)),created_at:vm(n.created_at)})}))}(o),function(t){t.command("delete").description("Delete a database").requiredOption("--db-id <dbId>","Database ID").option("--confirm","Confirm deletion (required)").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Delete a database",description:"Delete a database from the current space. This operation cannot be undone. The --confirm flag is required to proceed.",examples:[{desc:"Delete a database",cmd:"coze code db delete --db-id <databaseId> --confirm",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID to delete"},confirm:{type:"boolean",required:!1,description:"Confirm deletion. Required in JSON mode or non-interactive (non-TTY) terminals; in interactive terminals an interactive confirmation prompt is shown if omitted"}},output:{deleted:{type:"boolean",description:"Deletion status"},database_id:{type:"string",description:"Deleted database ID"}}},errors:[{code:e.ErrorCode.E1007,name:"DB_SQL_DANGEROUS",desc:"Deletion requires --confirm flag",fix:"Add --confirm flag to proceed with deletion",example:"coze code db delete --db-id <id> --confirm"},{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct, run `coze code db list`"}],seeAlso:["coze code db list","coze code db create"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!t.confirm){const o="json"===i.format,s=!0===process.stdin.isTTY;if(o||!s)throw new e.CozeError(e.ErrorCode.E1007,"Deletion requires --confirm flag to proceed",{databaseId:t.dbId},{trigger:"Database deletion is a destructive operation",fix:"Add --confirm flag to confirm deletion",example:`coze code db delete --db-id ${t.dbId} --confirm`});i.ui.warn(`⚠ You are about to delete database '${t.dbId}'. This operation cannot be undone.`);const{confirm:n}=await import("@inquirer/prompts").then((e=>({confirm:e.confirm})));if(!await n({message:`Are you sure you want to delete database '${t.dbId}'?`,default:!1}))return void i.ui.info("Operation cancelled.")}const s=Wm(Wm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Deleting database '${t.dbId}'...`),await fm.deleteSpaceDatabase(s,t.dbId),i.ui.success(`Database '${t.dbId}' deleted successfully.`),i.response.print({deleted:!0,database_id:t.dbId})}))}(o),xm(o),Sm(o),function(t){t.command("status").description("Get database status and restore info").requiredOption("--db-id <dbId>","Database ID").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Check database status",description:"Get the status of a database including restore/rollback information. Shows whether the database can be rolled back, current restore status, and earliest restore time.",examples:[{desc:"Check database status",cmd:"coze code db status --db-id <databaseId>",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"}},output:{can_restore:{type:"boolean",description:"Whether PITR restore is available"},is_restoring:{type:"boolean",description:"Whether a restore is in progress"},latest_restore_status:{type:"string",description:"Latest restore status"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"}],seeAlso:["coze code db get","coze code db rollback"]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Em(Em(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Fetching status for database '${t.dbId}'...`);const n=await fm.getSpaceDatabaseStatus(s,t.dbId);i.ui.success("Database status:"),i.response.print({can_restore:Cm([n,"optionalAccess",e=>e.can_restore]),is_restoring:Cm([n,"optionalAccess",e=>e.is_restoring]),earliest_restore_time:vm(Cm([n,"optionalAccess",e=>e.earliest_restore_time])),latest_restore_status:Em(bm[Em(Cm([n,"optionalAccess",e=>e.latest_restore_status]),(()=>-1))],(()=>Cm([n,"optionalAccess",e=>e.latest_restore_status]))),latest_restore_error:Cm([n,"optionalAccess",e=>e.latest_restore_error]),latest_restore_start_time:vm(Cm([n,"optionalAccess",e=>e.latest_restore_start_time])),latest_restore_end_time:vm(Cm([n,"optionalAccess",e=>e.latest_restore_end_time]))})}))}(o),function(t){t.command("gen-types").description("Generate TypeScript types from database schema").requiredOption("--db-id <dbId>","Database ID").option("--output <path>","Output file path","types/database.ts").option("--include-schema <name>","Schema name (can be specified multiple times)",((e,t=[])=>[...t,e]),[]).option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Generate TypeScript types",description:"Generate TypeScript type definitions from database schema using PostgREST OpenAPI. The generated types follow the Supabase database type format.",examples:[{desc:"Generate types for public schema",cmd:"coze code db gen-types --db-id <id>",tags:["[RECOMMENDED]"]},{desc:"Generate types for multiple schemas",cmd:"coze code db gen-types --db-id <id> --include-schema public --include-schema auth"},{desc:"Custom output path",cmd:"coze code db gen-types --db-id <id> --output src/types/db.ts"}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},output:{type:"string",required:!1,description:"Output file path (default: types/database.ts)"},includeSchema:{type:"array",required:!1,description:"Schema names (default: public)"}},output:{output_path:{type:"string",description:"Generated file path"},schemas:{type:"array",description:"Generated schemas"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E5006,name:"DB_GEN_TYPES_FAILED",desc:"Type generation failed",fix:"Ensure the database is active. PostgREST Swagger 2.0 is auto-converted to OpenAPI 3.0; re-run with --debug to see the underlying generator error."}],seeAlso:["coze code db dump","coze code db query"]}}).action(Mm)}(o),function(t){t.command("dump").description("Export database schema or data").requiredOption("--db-id <dbId>","Database ID").option("--output <path>","Output file path","db/schema.sql").option("--schema-only","Export schema only (default if neither flag set)").option("--data-only","Export data only").option("--include-schema <name>","Schema name to dump (repeatable, default: public)",((e,t=[])=>[...t,e]),[]).option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Export database schema or data",description:"Export database schema (DDL) or data as SQL. Uses pg-meta API to query information_schema. Default mode is schema-only, default schema is public. Pass --include-schema multiple times to include additional schemas (e.g. auth, storage).",examples:[{desc:"Export public schema",cmd:"coze code db dump --db-id <id>",tags:["[RECOMMENDED]"]},{desc:"Export data only",cmd:"coze code db dump --db-id <id> --data-only"},{desc:"Include multiple schemas",cmd:"coze code db dump --db-id <id> --include-schema public --include-schema auth"},{desc:"Custom output path",cmd:"coze code db dump --db-id <id> --output backups/schema.sql"}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},output:{type:"string",required:!1,description:"Output file path (default: db/schema.sql)"},schemaOnly:{type:"boolean",required:!1,description:"Export schema only (default: true)"},dataOnly:{type:"boolean",required:!1,description:"Export data only"},includeSchema:{type:"array",required:!1,description:"Schema name(s) to include (repeatable, default: public)"}},output:{output_path:{type:"string",description:"Output file path"},mode:{type:"string",description:"Export mode"},schemas:{type:"array",description:"Schemas included in the dump"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E5007,name:"DB_DUMP_FAILED",desc:"Schema export failed",fix:"Check database status and permissions"}],seeAlso:["coze code db query","coze code db gen-types"]}}).action(Vm)}(o)};function Km(e,t){return null!=e?e:t()}function Qm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ym=["github","gitlab"];function Zm(e,t){return null!=e?e:t()}function Xm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const eg=["github","gitlab"];async function tg(t){const{ctx:o,force:i,warning:s,message:n,errorMessage:r,errorData:a,errorDetail:c}=t;if(i)return!0;const l="json"===o.format,d=!0===process.stdin.isTTY;if(l||!d)throw new e.CozeError(e.ErrorCode.E1000,r,a,c);o.ui.warn(s);const{confirm:p}=await import("@inquirer/prompts");return!!await p({message:n,default:!1})||(o.ui.info("Operation cancelled."),!1)}function og(e,t){return null!=e?e:t()}function ig(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const sg=["github","gitlab"];const ng=o=>{const i=o.command("auth").description("Git platform OAuth authorization management").config({help:{brief:"Manage Git platform OAuth authorization",description:"Manage OAuth authorization for Git platforms. Supports login, status check, and logout.",examples:[{desc:"Login",cmd:"coze code git auth login"},{desc:"Check status",cmd:"coze code git auth status"},{desc:"Logout",cmd:"coze code git auth logout"}],seeAlso:["coze code git search"]}});i.command("login").description("Authorize a Git platform via OAuth").config({help:{brief:"Authorize a Git platform via OAuth",description:"Initiate OAuth authorization flow for a Git platform. Opens a browser for the user to complete authorization. The authorization is stored at the space level and can be reused across projects. Defaults to GitHub if --provider is not specified.",examples:[{desc:"Authorize GitHub (minimal)",cmd:"coze code git auth login"},{desc:"Authorize GitHub explicitly",cmd:"coze code git auth login --provider github",tags:["[RECOMMENDED]"]},{desc:"[TEMPLATE] Authorize any provider",cmd:"coze code git auth login --provider <github|gitlab>",tags:["[TEMPLATE]"]}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",description:"Authorization status",example:"authorized"},user:{type:"string",description:"Authorized user name",example:"octocat"}}},enums:{provider:{github:"GitHub OAuth authorization",gitlab:"GitLab OAuth authorization (future)"}},errors:[{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"},{code:e.ErrorCode.E2005,name:"OAUTH_TIMEOUT",desc:"OAuth authorization timed out",fix:"Re-run `coze code git auth login`"}],seeAlso:["coze code git auth status","coze code git auth logout"],caveats:["Authorization requires a browser. In headless environments, copy the URL from terminal output and open it manually","Authorization is stored at the space level, not per-project"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Km(Km(o.provider,(()=>Qm([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!Ym.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${Ym.join(", ")}`);const r=Km(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or run `coze space use <spaceId>` first");s.ui.info("Fetching integration list...");const a=Km(Qm([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>Qm([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=Km(Qm([a,"optionalAccess",e=>e.id]),(()=>""));if(!c)throw new e.CozeError(e.ErrorCode.E5000,`No integration found for provider: ${n}`);s.ui.info(`Initiating OAuth for ${n}...`);const l=Km(Qm([await t.IdeApi.GetOauthConfig({integration_id:c,space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.auth_url]),(()=>""));if(!l)throw new e.CozeError(e.ErrorCode.E5000,"Failed to get OAuth authorization URL");s.ui.info(`Opening browser for ${n} authorization...`),s.ui.info(`Authorization URL: ${l}`),s.ui.info("Waiting for authorization... (timeout: 120s)");const d=Date.now();let p=!1;for(;Date.now()-d<12e4;)if(await new Promise((e=>setTimeout(e,2e3))),Qm([await t.IdeApi.GetOauthStatus({integration_id:c,space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.success])){p=!0;break}if(!p)throw new e.CozeError(e.ErrorCode.E2005,"OAuth authorization timed out after 120 seconds");const u=await t.IdeApi.GetUser({space_id:r,integration_id:c}),m=Km(Km(Qm([u,"access",e=>e.data,"optionalAccess",e=>e.login]),(()=>Qm([u,"access",e=>e.data,"optionalAccess",e=>e.name]))),(()=>"unknown"));s.ui.success(`${n} authorized successfully.`),s.ui.info(` User: ${m}`),s.response.print({provider:n,status:"authorized",user:m})})),function(o){o.command("status").description("Check the Git platform OAuth authorization status").config({help:{brief:"Check the Git platform OAuth authorization status",description:"Display the current OAuth authorization status and user info for the specified Git platform.",examples:[{desc:"Check GitHub auth status (minimal)",cmd:"coze code git auth status",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Check if authorized",cmd:"coze code git auth status --format json | jq .status",tags:["[PIPELINE]"]}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",enum:["authorized","not-authorized"],description:"Authorization status",example:"authorized"},user:{type:"object",description:"Authorized user info"}}},errors:[{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"}],seeAlso:["coze code git auth login","coze code git auth logout"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Zm(Zm(o.provider,(()=>Xm([i,"access",e=>e.parent,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!eg.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${eg.join(", ")}`);const r=Zm(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");const a=Zm(Xm([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>Xm([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=Zm(Xm([a,"optionalAccess",e=>e.id]),(()=>""));if(2!==Xm([a,"optionalAccess",e=>e.status])||!c)return s.ui.info("Git Authorization:"),s.ui.info(` Provider: ${n}`),s.ui.info(" Status: not-authorized"),void s.response.print({provider:n,status:"not-authorized"});const l=(await t.IdeApi.GetUser({space_id:r,integration_id:c})).data;s.ui.info("Git Authorization:"),s.ui.info(` Provider: ${n}`),s.ui.info(" Status: authorized"),s.ui.info(` User: ${Zm(Zm(Xm([l,"optionalAccess",e=>e.login]),(()=>Xm([l,"optionalAccess",e=>e.name]))),(()=>"unknown"))}`),Xm([l,"optionalAccess",e=>e.avatar_url])&&s.ui.info(` Avatar: ${l.avatar_url}`),s.response.print({provider:n,status:"authorized",user:{login:Zm(Zm(Xm([l,"optionalAccess",e=>e.login]),(()=>Xm([l,"optionalAccess",e=>e.name]))),(()=>"unknown")),avatar_url:Zm(Xm([l,"optionalAccess",e=>e.avatar_url]),(()=>""))}})}))}(i),function(o){o.command("logout").description("Revoke OAuth authorization for a Git platform").option("--force","Skip confirmation and revoke directly",!1).config({help:{brief:"Revoke OAuth authorization for a Git platform",description:"Cancel the OAuth authorization for the specified Git platform in the current space. This will revoke access for all projects in the space that use this provider. Use --force to skip the confirmation prompt.",examples:[{desc:"Logout GitHub (minimal)",cmd:"coze code git auth logout"},{desc:"Force logout without confirmation",cmd:"coze code git auth logout --force",tags:["[RECOMMENDED]"]},{desc:"Logout a specific provider",cmd:"coze code git auth logout --provider gitlab"}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"},force:{type:"boolean",required:!1,description:"Skip confirmation",example:!1}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",description:"Result status",example:"deauthorized"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Revoking requires --force in JSON mode or non-interactive terminals",fix:"Add --force flag to revoke without confirmation",example:"coze code git auth logout --force"},{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"},{code:e.ErrorCode.E2007,name:"NOT_AUTHORIZED",desc:"Git service is not authorized",fix:"Use `coze code git auth status` to check status"}],seeAlso:["coze code git auth login","coze code git auth status"],caveats:["Revoking authorization affects ALL projects in the current space that use this provider","Projects bound to repos via this provider will lose sync capability until re-authorized"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=og(og(o.provider,(()=>ig([i,"access",e=>e.parent,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!sg.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${sg.join(", ")}`);if(!await tg({ctx:s,force:o.force,warning:`⚠ You are about to revoke ${n} authorization for the current space. All projects using this provider will lose sync capability until re-authorized.`,message:`Are you sure you want to revoke ${n} authorization?`,errorMessage:"Revoking authorization requires --force flag to proceed",errorData:{provider:n},errorDetail:{trigger:"Revoking Git authorization affects all projects in the current space",fix:"Add --force flag to revoke without confirmation",example:"coze code git auth logout --force"}}))return;const r=og(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");const a=og(ig([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>ig([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=og(ig([a,"optionalAccess",e=>e.id]),(()=>""));if(2!==ig([a,"optionalAccess",e=>e.status])||!c)throw new e.CozeError(e.ErrorCode.E2007,`${n} is not currently authorized`);await t.IdeApi.CancelOauth({integration_id:c,space_id:r}),s.ui.success(`${n} authorization revoked successfully.`),s.response.print({provider:n,status:"deauthorized"})}))}(i)};function rg(e,t){return null!=e?e:t()}function ag(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const cg=["github","gitlab"];const lg=o=>{const i=o.command("git").description("Git platform integration management").option("--provider <provider>","Git service provider: github / gitlab","github").config({help:{brief:"Manage Git platform integrations (OAuth authorization and repository search)",description:"Manage Git platform integrations including OAuth authorization and repository search. Use --provider to specify the Git service provider (default: github).",examples:[{desc:"Authorize GitHub",cmd:"coze code git auth login"},{desc:"Search repos",cmd:"coze code git search --keyword react"}],seeAlso:["coze code repo"]}});ng(i),i.command("search").description("Search repositories on the authorized Git platform").option("-k, --keyword <keyword>","Search keyword").option("--page <page>","Page number",parseInt).option("--page-size <size>","Results per page",parseInt).config({help:{brief:"Search repositories on the authorized Git platform",description:"Search through repositories accessible to the authorized Git user. Supports keyword filtering and pagination. Requires prior OAuth authorization.",examples:[{desc:"List all repos (minimal)",cmd:"coze code git search"},{desc:"Search by keyword",cmd:"coze code git search --keyword react",tags:["[RECOMMENDED]"]},{desc:"Paginated search",cmd:"coze code git search -k react --page 2 --page-size 10"},{desc:"[PIPELINE] Find empty repos for binding",cmd:'coze code git search -k my-repo --format json | jq ".items[] | select(.size == 0)"',tags:["[PIPELINE]"]}],schema:{input:{keyword:{type:"string",required:!1,description:"Search keyword",example:"react"},page:{type:"number",required:!1,description:"Page number",example:1},pageSize:{type:"number",required:!1,description:"Results per page",example:20},provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider (inherited from the `git` parent command --provider option, default: github)",example:"github"}},output:{items:{type:"array",description:"Matching repositories"},total_count:{type:"number",description:"Total matching count",example:15}}},errors:[{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"}],seeAlso:["coze code repo bind","coze code repo create"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=rg(rg(o.provider,(()=>ag([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!cg.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}`);const r=rg(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");s.ui.info("Searching repositories...");const a=await t.IdeApi.SearchRepo({space_id:r,name_search:rg(o.keyword,(()=>"")),per_page:rg(o.pageSize,(()=>20)),page:rg(o.page,(()=>1))}),c=rg(ag([a,"access",e=>e.data,"optionalAccess",e=>e.items]),(()=>[])),l=rg(ag([a,"access",e=>e.data,"optionalAccess",e=>e.total_count]),(()=>0));if(0===c.length)s.ui.info("No repositories found.");else{s.ui.info(`Found ${l} repositories:`);for(const e of c){const t=e.private?"private":"public";s.ui.info(` ${e.full_name} (${t})`)}}s.response.print({items:c.map((e=>({full_name:e.full_name,private:rg(e.private,(()=>!1)),size:rg(e.size,(()=>0)),updated_at:rg(e.updated_at,(()=>""))}))),total_count:l})}))};function dg(e,t){return null!=e?e:t()}function pg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function ug(e,t){return null!=e?e:t()}function mg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const gg={brief:"Bind a remote repository to a project",description:"Bind an empty remote repository to the specified project. The repository must be empty (non-empty repo binding is not supported in this version). Requires prior Git OAuth authorization.",examples:[{desc:"Bind a repo (minimal)",cmd:"coze code repo bind -p proj_abc -r user/my-repo"},{desc:"Bind after creating a new repo",cmd:"coze code repo create --name my-repo && coze code repo bind -p proj_abc -r user/my-repo",tags:["[RECOMMENDED]"]},{desc:"[ERROR RECOVERY] E3015: Repo not empty",cmd:"coze code repo create --name my-new-repo --private && coze code repo bind -p proj_abc -r user/my-new-repo",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},repo:{type:"string",required:!0,description:"Remote repo full name (must be empty)",example:"user/my-repo"}},output:{project_id:{type:"string",description:"Project ID",example:"proj_abc123"},repo_full_name:{type:"string",description:"Bound repo full name",example:"user/my-repo"},status:{type:"string",description:"Binding result",example:"bound"}}},errors:[{code:e.ErrorCode.E1013,name:"MISSING_REPO_NAME",desc:"Missing repo name",fix:"Use --repo <owner/name>"},{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"},{code:e.ErrorCode.E3015,name:"REPO_NOT_EMPTY",desc:"Repo not empty (returned by the API layer, not thrown by the CLI itself)",fix:"Use `coze code repo create` to create an empty repo"},{code:e.ErrorCode.E3016,name:"REPO_ALREADY_BOUND",desc:"Project already bound",fix:"Run `coze code repo unbind -p <id>` first"}],seeAlso:["coze code repo unbind","coze code repo create","coze code repo status"],caveats:["Only empty repositories are supported for binding in this version","A project can only be bound to one repository at a time"]};function hg(e,t){return null!=e?e:t()}function fg(e,t){return null!=e?e:t()}function _g(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const yg=o=>{const i=o.command("repo").description("Manage remote repositories for projects").option("--provider <provider>","Git service provider: github / gitlab","github").config({help:{brief:"Manage remote repository bindings for Coze Coding projects",description:"Manage remote repository bindings and sync operations for Coze Coding projects. Supports creating, binding, unbinding, pushing, pulling, and checking status of remote repositories.",examples:[{desc:"Bind repo",cmd:"coze code repo bind -p proj_abc -r user/my-repo"},{desc:"Push changes",cmd:"coze code repo push -p proj_abc"},{desc:"Check status",cmd:"coze code repo status -p proj_abc"}],seeAlso:["coze code git"]}});i.command("create").description("Create a new repository on the remote Git platform").option("-n, --name <name>","Repository name").option("--private","Create as private repository",!1).config({help:{brief:"Create a new repository on the remote Git platform",description:"Create a new empty repository under the authorized user account on the Git platform. The created repo can then be bound to a project using `coze code repo bind`.",examples:[{desc:"Create a public repo (minimal)",cmd:"coze code repo create --name my-app"},{desc:"Create a private repo",cmd:"coze code repo create -n my-app --private",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Create and bind",cmd:"coze code repo create -n my-repo --private && coze code repo bind -p proj_abc -r user/my-repo",tags:["[PIPELINE]"]}],schema:{input:{name:{type:"string",required:!0,description:"Repository name",example:"my-new-repo"},private:{type:"boolean",required:!1,description:"Create as private [RECOMMENDED]",example:!0}},output:{full_name:{type:"string",description:"Created repo full name",example:"user/my-new-repo"},html_url:{type:"string",description:"Repository URL",example:"https://github.com/user/my-new-repo"},private:{type:"boolean",description:"Visibility",example:!0}}},errors:[{code:e.ErrorCode.E1014,name:"MISSING_REPO_CREATION_NAME",desc:"Missing repo name",fix:"Use --name <name>"},{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"},{code:e.ErrorCode.E3009,name:"CONFLICT",desc:"Repository name already exists",fix:"Use a different name"}],seeAlso:["coze code repo bind","coze code git search"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=dg(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");if(!o.name)throw new e.CozeError(e.ErrorCode.E1014,"Missing repository name: use --name <name>");s.ui.info(`Creating repository "${o.name}"...`);const r=(await t.IdeApi.CreateRepo({space_id:n,name:o.name,private:dg(o.private,(()=>!1))})).data;s.ui.success("Repository created successfully."),s.ui.info(` Name: ${dg(pg([r,"optionalAccess",e=>e.full_name]),(()=>o.name))}`),s.ui.info(` URL: ${dg(pg([r,"optionalAccess",e=>e.html_url]),(()=>""))}`),s.ui.info(" Visibility: "+(o.private?"private":"public")),s.response.print({full_name:dg(pg([r,"optionalAccess",e=>e.full_name]),(()=>o.name)),html_url:dg(pg([r,"optionalAccess",e=>e.html_url]),(()=>"")),private:dg(o.private,(()=>!1))})})),function(o){o.command("bind").description("Bind a remote repository to a project").requiredOption("-p, --project-id <projectId>","Project ID").option("-r, --repo <fullName>","Remote repo full name (e.g. user/repo)").config({help:gg}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=ug(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");if(!o.repo)throw new e.CozeError(e.ErrorCode.E1013,"Missing repository full name: use --repo <owner/name>");const r=ug(mg([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]),(()=>1));if(3===r)throw new e.CozeError(e.ErrorCode.E3016,"Project is already bound to a remote repository. Run `coze code repo unbind -p <projectId>` first.");if(1===r)throw new e.CozeError(e.ErrorCode.E2004,"Git service is not authorized. Run `coze code git auth login` first.");const a=ug(mg([await t.IdeApi.ListIntegration({space_id:n}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])),c=ug(ug(o.provider,(()=>mg([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github")),l=a.find((e=>mg([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===c)),d=ug(mg([l,"optionalAccess",e=>e.id]),(()=>""));s.ui.info(`Binding repository "${o.repo}" to project "${o.projectId}"...`),await t.IdeApi.AddRemote({project_id:o.projectId,repo_full_name:o.repo,integration_id:d}),s.ui.success("Repository bound successfully."),s.ui.info(` Project: ${o.projectId}`),s.ui.info(` Repository: ${o.repo}`),s.response.print({project_id:o.projectId,repo_full_name:o.repo,status:"bound"})}))}(i),function(o){o.command("unbind").description("Unbind the remote repository from a project").requiredOption("-p, --project-id <projectId>","Project ID").option("--force","Skip confirmation and unbind directly",!1).config({help:{brief:"Unbind the remote repository from a project",description:"Remove the remote repository binding from the specified project. This operation does not delete the remote repository itself. Use --force to skip confirmation.",examples:[{desc:"Unbind repo (minimal)",cmd:"coze code repo unbind -p proj_abc"},{desc:"Force unbind",cmd:"coze code repo unbind -p proj_abc --force",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},force:{type:"boolean",required:!1,description:"Skip confirmation",example:!1}},output:{project_id:{type:"string",description:"Project ID",example:"proj_abc123"},status:{type:"string",description:"Result status",example:"unbound"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Unbinding requires --force in JSON mode or non-interactive terminals",fix:"Add --force flag to unbind without confirmation",example:"coze code repo unbind -p <projectId> --force"},{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Use `coze code repo status -p <id>` to check status"}],seeAlso:["coze code repo bind","coze code repo status"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!await tg({ctx:s,force:o.force,warning:`⚠ You are about to unbind the remote repository from project '${o.projectId}'.`,message:`Are you sure you want to unbind the remote repository from project '${o.projectId}'?`,errorMessage:"Unbinding requires --force flag to proceed",errorData:{projectId:o.projectId},errorDetail:{trigger:"Unbinding removes the remote repository binding from the project",fix:"Add --force flag to unbind without confirmation",example:`coze code repo unbind -p ${o.projectId} --force`}}))return;var n;if(3!==(null!=(n=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]))?n:(()=>1)()))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Use `coze code repo status -p <projectId>` to check status.");s.ui.info(`Unbinding remote repository from project "${o.projectId}"...`),await t.IdeApi.RemoveRemote({project_id:o.projectId}),s.ui.success("Repository unbound successfully."),s.ui.info(` Project: ${o.projectId}`),s.response.print({project_id:o.projectId,status:"unbound"})}))}(i),function(o){o.command("push").description("Push local commits to the bound remote repository").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Push local commits to the bound remote repository",description:"Push local commits to the bound remote repository. Requires the project to be bound to a remote repository. If the remote has new commits, you must pull first before pushing.",examples:[{desc:"Push changes (minimal)",cmd:"coze code repo push -p proj_abc",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Push and check status",cmd:"coze code repo push -p proj_abc && coze code repo status -p proj_abc",tags:["[PIPELINE]"]},{desc:"[ERROR RECOVERY] E3018: Pull first",cmd:"coze code repo pull -p proj_abc && coze code repo push -p proj_abc",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"}},output:{status:{type:"string",enum:["success","failed"],description:"Push result",example:"success"},pushed_commits:{type:"number",description:"Number of commits pushed",example:2}}},errors:[{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Bind a repo first"},{code:e.ErrorCode.E3017,name:"NOTHING_TO_PUSH",desc:"Nothing to push (not triggered in current placeholder implementation)",fix:"Already in sync with remote"},{code:e.ErrorCode.E3018,name:"REMOTE_HAS_UPDATES",desc:"Remote has updates (not triggered in current placeholder implementation)",fix:"Run `coze code repo pull -p <id>` first"}],seeAlso:["coze code repo pull","coze code repo status"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");var n;if(3!==(null!=(n=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]))?n:(()=>1)()))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Run `coze code repo bind` first.");s.ui.info("Pushing to remote..."),s.ui.success("Push completed successfully."),s.response.print({status:"success",pushed_commits:0})}))}(i),function(o){o.command("pull").description("Pull remote changes from the bound repository").requiredOption("-p, --project-id <projectId>","Project ID").option("--conflict-strategy <strategy>","Auto conflict resolution strategy: ours / theirs").config({help:{brief:"Pull remote changes from the bound repository",description:"Pull the latest changes from the bound remote repository. If conflicts occur and --conflict-strategy is provided, conflicts will be auto-resolved. Without --conflict-strategy, the command will fail on conflict with exit code 1.",examples:[{desc:"Pull changes (minimal)",cmd:"coze code repo pull -p proj_abc"},{desc:"Auto-resolve keeping local",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours",tags:["[RECOMMENDED]"]},{desc:"Auto-resolve using remote",cmd:"coze code repo pull -p proj_abc --conflict-strategy theirs"},{desc:"[PIPELINE] Pull then push",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours && coze code repo push -p proj_abc",tags:["[PIPELINE]"]},{desc:"[ERROR RECOVERY] E3019: Resolve conflict",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},conflictStrategy:{type:"string",required:!1,enum:["ours","theirs"],description:"Auto conflict resolution strategy",example:"ours"}},output:{status:{type:"string",enum:["success","conflict_resolved","failed"],description:"Pull result",example:"success"},conflict_resolved:{type:"boolean",description:"Whether conflicts were resolved",example:!1},conflict_strategy:{type:"string",description:"Strategy used",example:"ours"},conflict_files:{type:"array",items:{type:"string"},description:"Conflicting files",example:["src/index.ts"]}}},enums:{"conflict-strategy":{ours:"Keep local version for all conflicting files",theirs:"Use remote version for all conflicting files"}},errors:[{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Bind a repo first"},{code:e.ErrorCode.E3019,name:"MERGE_CONFLICT",desc:"Merge conflict without strategy (not triggered in current placeholder implementation)",fix:"Use --conflict-strategy ours or theirs"},{code:e.ErrorCode.E3020,name:"WOULD_OVERWRITE",desc:"Local changes would be overwritten (not triggered in current placeholder implementation)",fix:"Commit local changes first"}],seeAlso:["coze code repo push","coze code repo status"],caveats:["Without --conflict-strategy, conflicts will cause the command to fail","Conflict resolution applies to ALL conflicting files (no per-file selection in CLI)"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(3!==hg(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]),(()=>1)))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Run `coze code repo bind` first.");s.ui.info("Pulling from remote..."),s.ui.success("Pull completed successfully."),s.response.print({status:"success",conflict_resolved:!1,conflict_strategy:hg(o.conflictStrategy,(()=>null)),conflict_files:[]})}))}(i),function(o){o.command("status").description("Show remote repository binding and sync status for a project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Show remote repository binding and sync status for a project",description:"Display the current remote repository binding status of a project, including the bind status and (when bound) the repository full name and URL.",examples:[{desc:"Check repo status (minimal)",cmd:"coze code repo status -p proj_abc"},{desc:"JSON output for scripting",cmd:"coze code repo status -p proj_abc --format json",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Check binding status",cmd:"coze code repo status -p proj_abc --format json | jq .bind_status",tags:["[PIPELINE]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"}},output:{bind_status:{type:"string",enum:["unauth","not-bound","bound"],description:"Binding status",example:"bound"},repo_full_name:{type:"string",description:"Remote repo full name",example:"user/my-app"},html_url:{type:"string",description:"Repository URL",example:"https://github.com/user/my-app"}}},errors:[],seeAlso:["coze code repo bind","coze code repo push","coze code repo pull"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");s.ui.info("Fetching remote repository status...");const n=await t.IdeApi.GetRemote({project_id:o.projectId}),{data:r}=n,a=fg(_g([r,"optionalAccess",e=>e.status]),(()=>1)),c=fg({1:"unauth",2:"not-bound",3:"bound"}[a],(()=>"unauth"));if(3!==a)return s.ui.info("Remote Repository:"),s.ui.info(` Status: ${c}`),void s.response.print({bind_status:c});const l=_g([r,"optionalAccess",e=>e.basic_info]),d=fg(_g([l,"optionalAccess",e=>e.full_name]),(()=>"")),p=fg(_g([l,"optionalAccess",e=>e.html_url]),(()=>""));s.ui.info("Remote Repository:"),s.ui.info(` Status: ${c}`),s.ui.info(` Repository: ${d}`),s.ui.info(` URL: ${p}`),s.response.print({bind_status:c,repo_full_name:d,html_url:p})}))}(i)};function bg(o){const i=o.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"]}});uu(i),um(i),Jp(i),_u(i),tm(i),$l(i),function(o){o.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. Supported for general Web/App project types, returning an accessible preview URL. Sandbox initialization takes 1-3 minutes. WechatMiniProgram, Agent, Automation, Skill, and AssistantAgent projects are not previewable from the CLI.",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 (only for previewable project types)"},message:{type:"string",description:"Hint message returned instead of preview_url when the project type does not support CLI preview"}}},errors:[{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Unsupported project type for CLI preview",fix:`Preview is not available for MiniProgram, Agent, Automation, Skill, or AssistantAgent projects. Use the Web dashboard: ${Ap().replace(/\/$/,"")}`},{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"}],seeAlso:["coze code deploy","coze code project get"]}}).action((async function(o,i,s){const n=s.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E1000,"Missing projectId: pass <projectId> as argument");const r=Kp([await t.IdeApi.GetVibeProject({project_id:o}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),a={type:Up(r)};if(Qp.has(r))return void Kp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({type:a.type,message:`Project type '${a.type}' does not support CLI preview. Please visit the Web dashboard: ${Sp(o,r,Kp([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))}`})]);const c=await t.IdeApi.InitSandbox({project_id:o});a.preview_url=c.token?`https://${c.project_host}?token=${c.token}`:`https://${c.project_host}`,Kp([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: ${a.preview_url}`)]),Kp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])}))}(i),Jm(i),Ol(i),Xp(i),lg(i),yg(i)}const vg=async e=>await new Promise((t=>setTimeout(t,e)));function wg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Eg=e=>{if(!e)return;const t=e.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);if(wg([t,"optionalAccess",e=>e[1]]))return(e=>{try{return decodeURIComponent(e)}catch(t){return URIError,e}})(t[1]);const o=e.match(/filename\s*=\s*"([^"]+)"/i);if(wg([o,"optionalAccess",e=>e[1]]))return o[1];const i=e.match(/filename\s*=\s*([^;]+)/i);return wg([i,"optionalAccess",e=>e[1]])?i[1].trim():void 0},Cg=async({url:t,outputPath:o,fetchImpl:i=t=>e.customFetch.fetch(t)})=>{const{buffer:s,response:r}=await(async(t,o)=>{const i=await o(t);if(!i.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download session file: ${i.status} ${i.statusText}`);return{buffer:Buffer.from(await i.arrayBuffer()),response:i}})(t,i),a=o||(e=>{const t=Eg((o=e.contentDisposition,i=()=>null,null!=o?o:i()));var o,i;if(t)return t;for(const t of[e.responseUrl,e.requestUrl]){if(!t||!URL.canParse(t))continue;const e=new URL(t),o=n.basename(decodeURIComponent(e.pathname));if(o&&"/"!==o&&"."!==o)return o}return"session-file.bin"})({requestUrl:t,responseUrl:r.url,contentDisposition:r.headers.get("content-disposition")}),c=await Oa(a,s);return{path:c,filename:n.basename(c),size:s.byteLength,url:t,logid:r.headers.get("x-tt-logid")||void 0}},Ig="1008033";function Ag(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Sg=async({baseUrl:t,headers:o,xTTEnv:i})=>{const n=new URL("/api/coze_claw/resource/get_frontier_key",s.normalizeBaseUrl(t));s.appendSearchParams(n,{aid:Ig});const r={...o,...s.getPpeHeaders(i)},a=await e.customFetch.fetch(n.toString(),{method:"GET",headers:r}),c=await s.parseServiceResponseBody(a,{}),l=s.getServiceResponseLogId(a);if(!a.ok)throw new Error(s.formatServiceErrorWithLogId({fallback:`Failed to get frontier key: ${a.status} ${a.statusText}`,logId:l,message:c.msg}));const d=Ag([c,"access",e=>e.data,"optionalAccess",e=>e.access_key]),p=Ag([c,"access",e=>e.data,"optionalAccess",e=>e.device_id]);if(!d||!p)throw new Error(s.formatServiceErrorWithLogId({fallback:"Frontier key response is incomplete",logId:l,message:c.msg}));return{accessKey:d,deviceId:p}};function kg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const jg=async({filePaths:t,clawId:o,sessionId:i,accessFile:s=r.access,createFileReadStream:c=a.openAsBlob,uploadFile:l})=>{const d=[];for(const r of t){try{await s(r)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${r}${t instanceof Error?` (${t.message})`:""}`)}const t=n.basename(r),a=await l({fileName:t,fileContent:await c(r),clawId:o,sessionId:i}),p=kg([a,"access",e=>e.data,"optionalAccess",e=>e.file]);if(!kg([p,"optionalAccess",e=>e.file_uri])||!kg([p,"optionalAccess",e=>e.file_url]))throw new e.CozeError(e.ErrorCode.E5002,a.msg||`Failed to upload session file: ${r}`);d.push({file_name:p.file_name||t,file_uri:p.file_uri,file_url:p.file_url})}return d},Pg=async({filePaths:e,sessionId:t,apiBaseUrl:o,sessionApiBaseUrl:i,sessionSpaceWebId:n,xTTEnv:r,service:a,deps:c})=>{if(!e||0===e.length)return[];const l=kg([c,"optionalAccess",e=>e.store])||s.createSessionConfigStore(),{sessionClawId:d}=await l.get(),p=d||(await a.getStatus()).clawId;if(!p)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const u=i||o,m=await(async({sessionSpaceWebId:e,baseUrl:t,xTTEnv:o})=>{if(e)return e;try{return(await Sg({baseUrl:t,headers:{},xTTEnv:o})).deviceId}catch(e){return}})({sessionSpaceWebId:n,baseUrl:u,xTTEnv:r}),g=(kg([c,"optionalAccess",e=>e.createApi])||s.createSessionApiClient)({baseUrl:u,webOrigin:u,xSpaceWebId:m,xTTEnv:r}),h=kg([c,"optionalAccess",e=>e.uploadFiles])||jg;return await h({filePaths:e,clawId:p,sessionId:t,uploadFile:({fileName:e,fileContent:t,clawId:o,sessionId:i})=>g.uploadFile({fileName:e,fileContent:t,clawId:o,sessionId:i})})};function zg(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Tg=1048576,Rg=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,xg=({absolutePath:e,root:t})=>{const o=n.relative(t,e);return Boolean(o)&&!o.startsWith("..")&&!n.isAbsolute(o)},Lg=async({onWarn:e,shouldWarnInvalidMention:t=()=>!0,statFile:o=r.stat,userInput:i,workTree:s})=>{(e=>{if(e.length>Tg)throw new Error("Message input is too long: max 1048576 characters")})(i);const a=[...i.matchAll(Rg)];if(0===a.length)return[{type:"text",text:i}];const c=[],l=n.resolve(s);let d=0;for(const s of a){const r=s.index,a=s[0],p=s[1];r>d&&c.push({type:"text",text:i.slice(d,r)});const u=n.resolve(l,p);let m=!1;if(xg({absolutePath:u,root:l}))try{(await o(u)).isFile()?m=!0:t(p)&&zg([e,"optionalCall",e=>e(`Uploading directories is not supported: ${p}`)])}catch(o){t(p)&&zg([e,"optionalCall",e=>e(`File not found: ${p}`)])}m?c.push({type:"file",absolutePath:u,rawMention:a,relativePath:p}):c.push({type:"text",text:a}),d=r+a.length}return d<i.length&&c.push({type:"text",text:i.slice(d)}),c};const Og=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},Dg=e=>e.includes("/")||e.includes("\\")||e.includes(".")||e.startsWith("."),Ug=async(e,t={})=>{const o=await(async e=>{const t=await Ra(),o=Og(e),i=Og(t);return o||i?o&&i?`${o}\n\n${i}`:(n=()=>i,null!=(s=o)?s:n()):null;var s,n})(e);if(!o)return{content:o,filePaths:[]};const i=await Lg({onWarn:t.onWarn,shouldWarnInvalidMention:Dg,userInput:o,workTree:t.cwd||process.cwd()}),s=[];return{content:Og(i.map((e=>"text"===e.type?e.text:(s.push(e.absolutePath),""))).join("")),filePaths:s}};const qg=e=>function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([e,"optionalAccess",e=>e.trim,"call",e=>e(),"access",e=>e.toLowerCase,"call",e=>e()])||"",Bg=async({baseUrl:t,xTTEnv:o,fetchImpl:i=e.customFetch.fetch.bind(e.customFetch)})=>{const s={"content-type":"application/json"};o&&(s["x-use-ppe"]="1",s["x-tt-env"]=o);const n=await i(`${(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||{}},Mg=({config:t,mode:o,keyword:i})=>{const s=(({config:t,mode:o})=>{if(!o)return;const i=qg(o),s=(t.mode_options||[]).find((e=>qg(e.value)===i||qg(e.label)===i));if(!s)throw new e.CozeError(e.ErrorCode.E1000,`Podcast mode not found: ${o}`);return s})({config:t,mode:o}),n=qg(i);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||(qg(e.label).includes(n)||qg(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 Mg(e,t,o,i){return new(o||(o=Promise))((function(t,s){function n(e){try{a(i.next(e))}catch(e){s(e)}}function r(e){try{a(i.throw(e))}catch(e){s(e)}}function a(e){var i;e.done?t(e.value):(i=e.value,i instanceof o?i:new o((function(e){e(i)}))).then(n,r)}a((i=i.apply(e,[])).next())}))}let Ng="";function $g(e=""){const t=`${Date.now()}`,o=Ng||(Ng=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),o=/(([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})),o=[];o[0]=Fg(t[0]+t[1]),o[1]=Fg(t[2]+t[3]);const i=["0000","0000","0000","0000","0000","ffff",o[0],o[1]];return i.join("")}(e):o?function(e){let t="";const o=[];let i=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&&(i=e.length),s+=e.length;for(let t=0;t<e.length;t++)if(4!==e[t].length){const i=r.substring(0,4-e[t].length).concat(e[t]);o.push(i)}else o.push(e[t]);n=!1}else{if(4!==t.length){const e=r.substring(0,4-t.length).concat(t);o.push(e)}else o.push(t);n&&(i+=1),s+=1,n=!1}}let c="";for(let e=0;e<8-s;e++)c=c.concat(r);for(let e=0;e<o.length;e++)e===i?(t=t.concat(c),t=t.concat(o[e])):t=t.concat(o[e]);return t}{const o=e.split(":");for(let e=0;e<o.length;e++){const i=o[e];if(4!==o[e].length){const s=r.substring(0,4-o[e].length).concat(i);t=t.concat(s)}else t=t.concat(i)}return t}}(e):"00000000000000000000000000000000"}(e));return"02"+t+o+Math.random().toString(16).slice(-6)}function Gg(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function Fg(e){return(Array(4).join("0")+parseInt(e,2).toString(16)).slice(-4)}function Vg(e,t){const o=e.key;void 0!==o&&(uh(t,10),ah(t,o));const i=e.value;void 0!==i&&(uh(t,18),ah(t,i))}function Wg(e){const t={};e:for(;!oh(e);){const o=ph(e);switch(o>>>3){case 0:break e;case 1:t.key=rh(e,ph(e));break;case 2:t.value=rh(e,ph(e));break;default:Qg(e,7&o)}}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 Hg(e){const t=Xg();return function(e,t){const o=e.SeqID;void 0!==o&&(uh(t,8),gh(t,o));const i=e.LogID;void 0!==i&&(uh(t,16),gh(t,i));const s=e.service;void 0!==s&&(uh(t,24),gh(t,Yg(s)));const n=e.method;void 0!==n&&(uh(t,32),gh(t,Yg(n)));const r=e.headers;if(void 0!==r)for(const e of r){uh(t,42);const o=Xg();Vg(e,o),uh(t,o.limit),ch(t,o),eh(o)}const a=e.payloadEncoding;void 0!==a&&(uh(t,50),ah(t,a));const c=e.payloadType;void 0!==c&&(uh(t,58),ah(t,c));const l=e.payload;void 0!==l&&(uh(t,66),uh(t,l.length),function(e,t){const o=ih(e,t.length);e.bytes.set(t,o)}(t,l));const d=e.LogIDNew;void 0!==d&&(uh(t,74),ah(t,d));const p=e.serverTiming;void 0!==p&&(uh(t,82),ah(t,p));const u=e.msgID;void 0!==u&&(uh(t,90),ah(t,u));const m=e.frameType;void 0!==m&&(uh(t,96),gh(t,Yg(m)))}(e,t),function(e){const t=e.bytes,o=e.limit;return t.length===o?t:t.subarray(0,o)}(t)}function Jg(e){return function(e){const t={};e:for(;!oh(e);){const o=ph(e);switch(o>>>3){case 0:break e;case 1:t.SeqID=mh(e,!0);break;case 2:t.LogID=mh(e,!0);break;case 3:t.service=ph(e);break;case 4:t.method=ph(e);break;case 5:{const o=Kg(e);(t.headers||(t.headers=[])).push(Wg(e)),e.limit=o;break}case 6:t.payloadEncoding=rh(e,ph(e));break;case 7:t.payloadType=rh(e,ph(e));break;case 8:t.payload=nh(e,ph(e));break;case 9:t.LogIDNew=rh(e,ph(e));break;case 10:t.serverTiming=rh(e,ph(e));break;case 11:t.msgID=rh(e,ph(e));break;case 12:t.frameType=ph(e);break;default:Qg(e,7&o)}}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 Kg(e){const t=ph(e),o=e.limit;return e.limit=e.offset+t,o}function Qg(e,t){switch(t){case 0:for(;128&lh(e););break;case 2:th(e,ph(e));break;case 5:th(e,4);break;case 1:th(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function Yg(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}const Zg=[];function Xg(){const e=Zg.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function eh(e){Zg.push(e)}function th(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function oh(e){return e.offset>=e.limit}function ih(e,t){const o=e.bytes,i=e.offset,s=e.limit,n=i+t;if(n>o.length){const t=new Uint8Array(2*n);t.set(o),e.bytes=t}return e.offset=n,n>s&&(e.limit=n),i}function sh(e,t){const o=e.offset;if(o+t>e.limit)throw new Error("Read past limit");return e.offset+=t,o}function nh(e,t){const o=sh(e,t);return e.bytes.subarray(o,o+t)}function rh(e,t){const o=sh(e,t),i=String.fromCharCode,s=e.bytes,n="�";let r="";for(let e=0;e<t;e++){const a=s[e+o];let c,l,d,p;128&a?192==(224&a)?e+1>=t?r+=n:(c=s[e+o+1],128!=(192&c)?r+=n:(p=(31&a)<<6|63&c,p<128?r+=n:(r+=i(p),e++))):224==(240&a)?e+2>=t?r+=n:(c=s[e+o+1],l=s[e+o+2],32896!=(49344&(c|l<<8))?r+=n:(p=(15&a)<<12|(63&c)<<6|63&l,p<2048||p>=55296&&p<=57343?r+=n:(r+=i(p),e+=2))):240==(248&a)?e+3>=t?r+=n:(c=s[e+o+1],l=s[e+o+2],d=s[e+o+3],8421504!=(12632256&(c|l<<8|d<<16))?r+=n:(p=(7&a)<<18|(63&c)<<12|(63&l)<<6|63&d,p<65536||p>1114111?r+=n:(p-=65536,r+=i(55296+(p>>10),56320+(1023&p)),e+=3))):r+=n:r+=i(a)}return r}function ah(e,t){const o=t.length;let i=0;for(let e=0;e<o;e++){let s=t.charCodeAt(e);s>=55296&&s<=56319&&e+1<o&&(s=(s<<10)+t.charCodeAt(++e)-56613888),i+=s<128?1:s<2048?2:s<65536?3:4}uh(e,i);let s=ih(e,i);const n=e.bytes;for(let e=0;e<o;e++){let i=t.charCodeAt(e);i>=55296&&i<=56319&&e+1<o&&(i=(i<<10)+t.charCodeAt(++e)-56613888),i<128?n[s++]=i:(i<2048?n[s++]=i>>6&31|192:(i<65536?n[s++]=i>>12&15|224:(n[s++]=i>>18&7|240,n[s++]=i>>12&63|128),n[s++]=i>>6&63|128),n[s++]=63&i|128)}}function ch(e,t){const o=ih(e,t.limit),i=e.bytes,s=t.bytes;for(let e=0,n=t.limit;e<n;e++)i[e+o]=s[e]}function lh(e){return e.bytes[sh(e,1)]}function dh(e,t){const o=ih(e,1);e.bytes[o]=t}function ph(e){let t,o=0,i=0;do{t=lh(e),o<32&&(i|=(127&t)<<o),o+=7}while(128&t);return i}function uh(e,t){for(t>>>=0;t>=128;)dh(e,127&t|128),t>>>=7;dh(e,t)}function mh(e,t){let o,i=0,s=0,n=0;return o=lh(e),i=127&o,128&o&&(o=lh(e),i|=(127&o)<<7,128&o&&(o=lh(e),i|=(127&o)<<14,128&o&&(o=lh(e),i|=(127&o)<<21,128&o&&(o=lh(e),s=127&o,128&o&&(o=lh(e),s|=(127&o)<<7,128&o&&(o=lh(e),s|=(127&o)<<14,128&o&&(o=lh(e),s|=(127&o)<<21,128&o&&(o=lh(e),n=127&o,128&o&&(o=lh(e),n|=(127&o)<<7))))))))),{low:i|s<<28,high:s>>>4|n<<24,unsigned:t}}function gh(e,t){const o=t.low>>>0,i=(t.low>>>28|t.high<<4)>>>0,s=t.high>>>24,n=0===s?0===i?o<16384?o<128?1:2:o<1<<21?3:4:i<16384?i<128?5:6:i<1<<21?7:8:s<128?9:10,r=ih(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?i>>>21|128:i>>>21&127;case 7:a[r+6]=7!==n?i>>>14|128:i>>>14&127;case 6:a[r+5]=6!==n?i>>>7|128:i>>>7&127;case 5:a[r+4]=5!==n?128|i:127&i;case 4:a[r+3]=4!==n?o>>>21|128:o>>>21&127;case 3:a[r+2]=3!==n?o>>>14|128:o>>>14&127;case 2:a[r+1]=2!==n?o>>>7|128:o>>>7&127;case 1:a[r]=1!==n?128|o:127&o}}function hh(e){return Hg(e)}const fh=4294967296,_h=0x10000000000000000,yh=_h/2,bh=String.prototype.charCodeAt;class vh{constructor(e,t,o){this.isLong=!0,this.low=0|e,this.high=0|t,this.unsigned=!!o}static isLong(e){return e&&!0===e.isLong}static fromBits(e,t,o){return new vh(e,t,o)}static fromBytes(e,t,o){return o?vh.fromBytesLE(e,t):vh.fromBytesBE(e,t)}static fromBytesLE(e,t){return new vh(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 vh(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?wh:new vh((bh.call(e,0)|bh.call(e,1)<<8|bh.call(e,2)<<16|bh.call(e,3)<<24)>>>0,(bh.call(e,4)|bh.call(e,5)<<8|bh.call(e,6)<<16|bh.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?Eh:wh;if(t){if(e>=_h)return Ih}else{if(e<=-yh)return Ah;if(e+1>=yh)return Ch}return vh.fromBits(e%fh|0,e/fh|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*fh+(this.low>>>0):this.high*fh+(this.low>>>0)}isZero(){return 0===this.high&&0===this.low}add(e){vh.isLong(e)||(e=vh.fromNumber(e));const t=this.high>>>16,o=65535&this.high,i=this.low>>>16,s=65535&this.low,n=e.high>>>16,r=65535&e.high,a=e.low>>>16;let c=0,l=0,d=0,p=0;return p+=s+(65535&e.low),d+=p>>>16,p&=65535,d+=i+a,l+=d>>>16,d&=65535,l+=o+r,c+=l>>>16,l&=65535,c+=t+n,c&=65535,vh.fromBits(d<<16|p,c<<16|l,this.unsigned)}equals(e){return vh.isLong(e)||(e=vh.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?vh.fromBits(0,0,this.unsigned):-1===this.low?vh.fromBits(0,this.high+1,this.unsigned):vh.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 wh=new vh(0,0,!1),Eh=new vh(0,0,!0),Ch=vh.fromBits(-1,2147483647,!1),Ih=vh.fromBits(-1,-1,!0),Ah=vh.fromBits(0,-2147483648,!1);var Sh;!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"}(Sh||(Sh={}));class kh{constructor(e){this.type=e,this.target=null}}class jh extends kh{constructor(e,t){super(e),this.message=t&&t.message||null}}class Ph extends kh{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||Sh.NATIVE_ERROR}}class zh extends kh{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 Th extends kh{constructor(e,t){super(e),this.data=t&&t.data||null}}class Rh extends Th{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}}class xh extends kh{constructor(e,t){super(e),this.data=t&&t.data||null}}function Lh(e,{message:t,code:o,error:i}){return new Ph(e,{message:t,code:o,error:i})}function Oh(e,{code:t,reason:o,wasClean:i,willReconnect:s}){return new zh(e,{code:t,reason:o,wasClean:i,willReconnect:s})}function Dh(e,{message:t}){return new jh(e,{message:t})}class Uh{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 qh=("undefined"!=typeof globalThis&&"Window"===globalThis.constructor.name||"undefined"!=typeof window&&"Window"===window.constructor.name)&&"undefined"!=typeof document,Bh="undefined"!=typeof globalThis&&("Object"===globalThis.constructor.name||"DedicatedWorkerGlobalScope"===globalThis.constructor.name)&&"undefined"!=typeof tt,Mh=("undefined"!=typeof globalThis&&"Object"===globalThis.constructor.name||"undefined"==typeof globalThis||"undefined"!=typeof globalThis&&!!globalThis.WeixinJSBridge)&&"undefined"!=typeof wx,Nh="undefined"!=typeof globalThis&&("DedicatedWorkerGlobalScope"===globalThis.constructor.name||"SharedWorkerGlobalScope"===globalThis.constructor.name||"ServiceWorkerGlobalScope"===globalThis.constructor.name)&&"undefined"!=typeof self,$h="undefined"!=typeof globalThis&&"Object"===globalThis.constructor.name&&"undefined"!=typeof global&&"Object"===global.constructor.name&&"undefined"!=typeof process&&!!process.version;class Gh{constructor(){this._listeners={}}emit(e,...t){const o=this._listeners[e];if(o)o.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 o=this._listeners[e];if(o)for(let e=0;e<o.length;)o[e].fn===t?o.splice(e,1):++e}return this}on(e,t,o){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:o||this}),this}}class Fh extends Gh{constructor(e,t,o){super(),this._socket=null,Mh&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:o,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),Bh&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:t,header:o,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then((()=>{this._addWsListeners()}))}_createSocketFailHandler(e){Promise.resolve().then((()=>{const t=Lh("error",{message:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)});this.emit("error",t);const o=Oh("close",{reason:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)});this.emit("close",o)}))}_addWsListeners(){this._socket.onOpen((e=>{this.emit("open",function(e,{data:t}){return new xh(e,{data:t})}("open",Object.assign(Object.assign({},e),{data:e.errMsg||""})))})),this._socket.onClose((e=>{this.emit("close",Oh("close",Object.assign({},e)))})),this._socket.onMessage((e=>{this.emit("message",function(e,{data:t,message:o}){return new Rh(e,{data:t,message:o})}("message",Object.assign({},e)))})),this._socket.onError((e=>{this.emit("error",Lh("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",Lh("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",Lh("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 Vh(e,t,o){let i=-1;!function s(n){return Mg(this,0,void 0,(function*(){if(n<=i)return Promise.reject(new Error("next() called multiple times in process"));if(i=n,n===o.length)return Promise.resolve();return o[n].bind(e)(t,s.bind(null,n+1))}))}(0)}function Wh(e){let t=0,o=0;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t+=1:o<2048?t+=2:55296==(64512&o)&&56320==(64512&e.charCodeAt(i+1))?(++i,t+=4):t+=3;return t}function Hh(e,t,o){if(o-t<1)return"";let i="";for(let s=t;s<o;){const t=e[s++];if(t<=127)i+=String.fromCharCode(t);else if(t>=192&&t<224)i+=String.fromCharCode((31&t)<<6|63&e[s++]);else if(t>=224&&t<240)i+=String.fromCharCode((15&t)<<12|(63&e[s++])<<6|63&e[s++]);else if(t>=240){const o=((7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;i+=String.fromCharCode(55296+(o>>10)),i+=String.fromCharCode(56320+(1023&o))}}return i}function Jh(e,t,o){const i=o;let s,n;for(let i=0;i<e.length;++i)s=e.charCodeAt(i),s<128?t[o++]=s:s<2048?(t[o++]=s>>6|192,t[o++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(i+1)))?(s=65536+((1023&s)<<10)+(1023&n),++i,t[o++]=s>>18|240,t[o++]=s>>12&63|128,t[o++]=s>>6&63|128,t[o++]=63&s|128):(t[o++]=s>>12|224,t[o++]=s>>6&63|128,t[o++]=63&s|128);return o-i}function Kh(e){return Mg(this,0,void 0,(function*(){if("string"==typeof e){const t=new Uint8Array(Wh(e));return Jh(e,t,0),t}return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}))}class Qh{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,o){return!!(null==e?void 0:e.find((e=>e.key===t&&e.value===o)))}function Zh(e,t){var o;return null===(o=null==e?void 0:e.find((e=>e.key===t)))||void 0===o?void 0:o.value}function Xh(e,t){return Mg(this,0,void 0,(function*(){const{enableAutoAck:o}=this._options,i=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(o&&i){const{SeqID:t,LogID:o,service:i,LogIDNew:s,method:n}=e.message;this._sendAck({SeqID:t,LogID:o,LogIDNew:s,service:i,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 ef(e,t){return Mg(this,0,void 0,(function*(){this._debug("received",e.message),t()}))}function tf(e,t){return Mg(this,0,void 0,(function*(){const o=Jg(yield Kh(e.data));try{if(o.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=o.payloadEncoding?o.payloadEncoding.replace(/\s/g,"").toLowerCase():"",i=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=o.payloadType?o.payloadType.replace(/\s/g,"").toLowerCase():"",n=i.force?i.type:s||i.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))?o.textPayload=Hh(o.payload,0,o.payload.byteLength):o.textPayload=""}else o.textPayload=""}catch(e){o.textPayload="",console.log(e)}e.message=o,t()}))}let of,sf;const nf=new WeakMap,rf=new WeakMap,af=new WeakMap,cf=new WeakMap,lf=new WeakMap;let df={get(e,t,o){if(e instanceof IDBTransaction){if("done"===t)return rf.get(e);if("objectStoreNames"===t)return e.objectStoreNames||af.get(e);if("store"===t)return o.objectStoreNames[1]?void 0:o.objectStore(o.objectStoreNames[0])}return mf(e[t])},set:(e,t,o)=>(e[t]=o,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function pf(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(sf||(sf=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(gf(this),t),mf(nf.get(this))}:function(...t){return mf(e.apply(gf(this),t))}:function(t,...o){const i=e.call(gf(this),t,...o);return af.set(i,t.sort?t.sort():[t]),mf(i)}}function uf(e){return"function"==typeof e?pf(e):(e instanceof IDBTransaction&&function(e){if(rf.has(e))return;const t=new Promise(((t,o)=>{const i=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",n),e.removeEventListener("abort",n)},s=()=>{t(),i()},n=()=>{o(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",s),e.addEventListener("error",n),e.addEventListener("abort",n)}));rf.set(e,t)}(e),t=e,(of||(of=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some((e=>t instanceof e))?new Proxy(e,df):e);var t}function mf(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,o)=>{const i=()=>{e.removeEventListener("success",s),e.removeEventListener("error",n)},s=()=>{t(mf(e.result)),i()},n=()=>{o(e.error),i()};e.addEventListener("success",s),e.addEventListener("error",n)}));return t.then((t=>{t instanceof IDBCursor&&nf.set(t,e)})).catch((()=>{})),lf.set(t,e),t}(e);if(cf.has(e))return cf.get(e);const t=uf(e);return t!==e&&(cf.set(e,t),lf.set(t,e)),t}const gf=e=>lf.get(e);const hf=["get","getKey","getAll","getAllKeys","count"],ff=["put","add","delete","clear"],_f=new Map;function yf(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(_f.get(t))return _f.get(t);const o=t.replace(/FromIndex$/,""),i=t!==o,s=ff.includes(o);if(!(o in(i?IDBIndex:IDBObjectStore).prototype)||!s&&!hf.includes(o))return;const n=async function(e,...t){const n=this.transaction(e,s?"readwrite":"readonly");let r=n.store;return i&&(r=r.index(t.shift())),(await Promise.all([r[o](...t),s&&n.done]))[0]};return _f.set(t,n),n}df=(e=>({...e,get:(t,o,i)=>yf(t,o)||e.get(t,o,i),has:(t,o)=>!!yf(t,o)||e.has(t,o)}))(df);class bf extends Gh{constructor(e,t){super(),this._dbName=e,this._keyPath=t,this._qosDB=void 0,this._init()}openDB(){return Mg(this,0,void 0,(function*(){yield this._init()}))}_init(){return Mg(this,0,void 0,(function*(){try{const e=this._dbName,t=this._keyPath;return new Promise((o=>{this._qosDB?o(this):(function(e,t,{blocked:o,upgrade:i,blocking:s,terminated:n}={}){const r=indexedDB.open(e,t),a=mf(r);return i&&r.addEventListener("upgradeneeded",(e=>{i(mf(r.result),e.oldVersion,e.newVersion,mf(r.transaction))})),o&&r.addEventListener("blocked",(()=>o())),a.then((e=>{n&&e.addEventListener("close",(()=>n())),s&&e.addEventListener("versionchange",(()=>s()))})).catch((()=>{})),a}(`frontier_${e}`,1,{upgrade(o){o.createObjectStore(e,{keyPath:t})}}).then((e=>{this._qosDB=e,this.emit("ready")})),this.on("ready",(()=>{o(this),this.off()})))}))}catch(e){console.log(e)}}))}get(e){var t;return Mg(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 o;return Mg(this,0,void 0,(function*(){return null===(o=this._qosDB)||void 0===o?void 0:o.put(this._dbName,e)}))}del(e){var t;return Mg(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 Mg(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 Mg(this,0,void 0,(function*(){return null===(e=this._qosDB)||void 0===e?void 0:e.getAllKeys(this._dbName)}))}getAll(){var e;return Mg(this,0,void 0,(function*(){return null===(e=this._qosDB)||void 0===e?void 0:e.getAll(this._dbName)}))}closeDB(){var e;return Mg(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 vf{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=localStorage}openDB(){return Mg(this,0,void 0,(function*(){}))}get _prefix(){return`frontier_${this._DBName}`}get(e){return Mg(this,0,void 0,(function*(){const t=this._qosDB.getItem(this._prefix);return JSON.parse(t||"{}")[e]}))}set(e,t){return Mg(this,0,void 0,(function*(){const o=this._qosDB.getItem(this._prefix),i=JSON.parse(o||"{}");return i[t||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(i)),t||e[this._pathKey]}))}del(e){return Mg(this,0,void 0,(function*(){const t=this._qosDB.getItem(this._prefix),o=JSON.parse(t||"{}");return o[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(o))}))}clear(){return Mg(this,0,void 0,(function*(){return this._qosDB.clear()}))}keys(){return Mg(this,0,void 0,(function*(){const e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}))}getAll(){return Mg(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 wf{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=Bh?tt:Mh?wx:null}openDB(){return Mg(this,0,void 0,(function*(){}))}get _prefix(){return`frontier_${this._DBName}`}get(e){return Mg(this,0,void 0,(function*(){const t=this._qosDB.getStorageSync(this._prefix);return JSON.parse(t||"{}")[e]}))}set(e,t){return Mg(this,0,void 0,(function*(){const o=this._qosDB.getStorageSync(this._prefix),i=JSON.parse(o||"{}");return i[t||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(i)),t||e[this._pathKey]}))}del(e){return Mg(this,0,void 0,(function*(){const t=this._qosDB.getStorageSync(this._prefix),o=JSON.parse(t||"{}");return o[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(o))}))}clear(){return Mg(this,0,void 0,(function*(){return this._qosDB.clearStorageSync()}))}keys(){return Mg(this,0,void 0,(function*(){const e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}))}getAll(){return Mg(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 Ef(e,t){if(Bh||Bh)return new wf(e,t);if((qh||Nh)&&void 0!==typeof indexedDB)return new bf(e,t);if((qh||Nh)&&void 0!==typeof localStorage)return new vf(e,t);throw new Error("init QoSDB failed")}class Cf{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=Ef("qos","message_id")}_intervalFlush(){return Mg(this,0,void 0,(function*(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval((()=>{this.flushExpired()}),this._interval)}))}openDB(){return Mg(this,0,void 0,(function*(){yield this._qosDB.openDB().then((()=>{this._intervalFlush()}))}))}flushExpired(){var e;return Mg(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 Mg(this,0,void 0,(function*(){return null===(t=this._qosDB)||void 0===t?void 0:t.del(e)}))}set(e,t){var o;return Mg(this,0,void 0,(function*(){return null===(o=this._qosDB)||void 0===o?void 0:o.set({message_id:e,timestamp:t})}))}get(e){var t;return Mg(this,0,void 0,(function*(){return null===(t=this._qosDB)||void 0===t?void 0:t.get(e)}))}closeDB(){var e;return Mg(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 If(e,t){var o,i,s,n,r;return Mg(this,0,void 0,(function*(){const a=Yh(e.message.headers,"code","-1"),c=Yh(e.message.headers,"is_ack","1"),l=Zh(e.message.headers,"x_frontier_msgid"),d=Number(Zh(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"),m=Yh(e.message.headers,"x-msg-qos","2"),g=Zh(e.message.headers,"x-msg-cursor_name"),h=Number(Zh(e.message.headers,"x-msg-cursor_value"));if(p&&u)return t();if(m&&!(null===(o=this._cursorManager)||void 0===o?void 0:o.isReady))return t();if(p&&!this._QoSManager&&(this._QoSManager=new Cf),p&&this._QoSManager&&!this._QoSManager.isReady&&(yield this._QoSManager.openDB()),e.message.service>0&&c&&!a||e.message.service>0){if(l&&p){return!!(yield null===(i=this._QoSManager)||void 0===i?void 0:i.get(l))||(this._dispatchMessageEvent(e),yield null===(s=this._QoSManager)||void 0===s?void 0:s.set(l,Date.now()+d)),t()}if(m&&(null===(n=this._cursorManager)||void 0===n?void 0:n.isReady)){const o=null!==(r=yield this._cursorManager.get(g))&&void 0!==r?r:-1;if(!(o<h))throw new Error(`recevied message cursor ${h} larger than local cursor ${o}`);return this._dispatchMessageEvent(e),this._cursorManager.set(g,h,e.message.service),t()}return this._dispatchMessageEvent(e),t()}}))}function Af(e,t){var o,i;return Mg(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===(o=Zh(e.message.headers,"x_frontier_ack_msgid"))||void 0===o?void 0:o.split(",");if(!s)return t();if(this._QoSManager||(this._QoSManager=new Cf),this._QoSManager&&!this._QoSManager.isReady&&(yield this._QoSManager.openDB()),n&&r&&r.length)for(const e of r)yield null===(i=this._QoSManager)||void 0===i?void 0:i.del(e);t()}))}function Sf(e,t){let o=0,i=t;const s=t+4;for(;i<s;){const{value:t,offset:s}=jf(e,i);i=s,o=o<<8>>>0,o+=t}return{value:o,offset:s}}function kf(e,t){return{value:new vh(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 jf(e,t){return e.readUInt8?{value:e.readUInt8(t),offset:t+1}:{value:255&e[t],offset:t+1}}function Pf(e,t,o){return t.writeUint8?t.writeUint8(e,o):t[o]=255&e,o+1}const zf="undefined"!=typeof Buffer?Buffer.allocUnsafe:function(e,t){const o=8192;let i=null,s=o;return function(n){if(n<1||n>4096)return e(n);s+n>o&&(i=e(o),s=0);const r=t.call(i,s,s+=n);return 7&s&&(s=1+(7|s)),r}}((function(e){return new Uint8Array(e)}),Uint8Array.prototype.subarray);function Tf(e,t,o){const[i,s]=function(e){let t=0;const o={};for(let i=0;i<e.length;i++)o[e[i].cursor_name]=Wh(e[i].cursor_name),t+=14+o[e[i].cursor_name];return[t,o]}(e),n=zf(i);let r=0;return e.forEach((e=>{console.log("cursor.service",e,e.service),r=Pf(0,n,r),console.log("header",r),r=function(e,t,o){if(o>4294967295)throw new Error("integer too large");let i=3;for(;i>=0;)Pf(255&o,e,t+i),o>>>=8,i--;return t+4}(n,r,e.service||0),console.log("service",r),r=Pf(s[e.cursor_name],n,r),console.log("service-name",r),r=function(e,t,o){return e?e.length<40?Jh(e,t,o)+o:t.utf8Write?t.utf8Write(e,o)+o:t.write?t.write(e,o)+o:Jh(e,t,o)+o:o}(e.cursor_name,n,r),console.log("name",r),r=function(e,t,o){const i=e.low,s=e.high;return t[o]=s>>>24,t[o+1]=s>>>16&255,t[o+2]=s>>>8&255,t[o+3]=255&s,t[o+4]=i>>>24,t[o+5]=i>>>16&255,t[o+6]=i>>>8&255,t[o+7]=255&i,o+8}(vh.fromNumber(e.cursor||t),n,r),console.log("curvalue",r)})),{frameType:32,headers:[{key:"cursor_file_name",value:o}],payload:n}}class Rf{constructor(e,t,o){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=o,this._qosDB=Ef(this._cursorNameSpace,"cursor_name")}openDB(){return Mg(this,0,void 0,(function*(){yield this._qosDB.openDB()}))}getCursors(){return Mg(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?Tf(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?Tf(t,0,this._cursorFileName):{frameType:32,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}}))}set(e,t,o){return Mg(this,0,void 0,(function*(){return console.log("setdb",e,t,o),this._qosDB.set({cursor_name:e,cursor:t,service:o})}))}setCursors(e){return Mg(this,0,void 0,(function*(){const t=function(e){let t=0;const o=[];for(;t<e.byteLength;){const{offset:i}=jf(e,t);t=i;const s={cursor_name:"",cursor:0,service:0},{value:n,offset:r}=Sf(e,t);s.service=n,t=r;const{value:a,offset:c}=jf(e,t);t=c,s.cursor_name=Hh(e,t,t+a),t+=a;const{value:l,offset:d}=kf(e,t);s.cursor=l.toNumber(),t=d,o.push(s)}return o}(e);for(const e of t)console.log("setcursor",t),yield this._qosDB.set(e)}))}get(e){var t;return Mg(this,0,void 0,(function*(){return null===(t=yield this._qosDB.get(e))||void 0===t?void 0:t.cursor}))}closeDB(){return Mg(this,0,void 0,(function*(){yield this._qosDB.closeDB()}))}get isReady(){return this._qosDB.isReady}}function xf(e,t){return Mg(this,0,void 0,(function*(){const o=16===e.message.frameType,i=32===e.message.frameType;if(!o&&!i)return t();const s=Zh(e.message.headers,"cursor_file_name"),{aID:n,fpID:r,messageStrategy:a}=this._options;if(!s)return t();if(this._cursorManager||(this._cursorManager=new Rf(`${r}_${n}_${s}`,s,a)),this._cursorManager.isReady||(yield this._cursorManager.openDB()),o){const e=yield this._cursorManager.getCursors(),t=Hg({frameType:null==e?void 0:e.frameType,SeqID:vh.fromNumber(this._seqId++),LogID:vh.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(i){const t=e.message.payload;t&&this._cursorManager.setCursors(t)}}))}const Lf=function(e,t){return Mg(this,0,void 0,(function*(){this._isInit=!1,clearTimeout(this._connectionTimeoutId),t()}))},Of=function(e,t){var o;return Mg(this,0,void 0,(function*(){const e=null===(o=this._endpointManager)||void 0===o?void 0:o.getCurrentEndpoint();this._debug(`open ${e}`),t()}))},Df=function(e,t){var o,i;return Mg(this,0,void 0,(function*(){if(!this._ws||this._ws.readyState!==this.OPEN)return t();const{pingInterval:s}=this._options;null===(o=this._endpointManager)||void 0===o||o.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===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpoint();this._debug(`open ${n} success`),t()}))};class Uf extends Gh{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=qh,this._isNode=$h,this._isMiniTT=Bh,this._isMiniWX=Mh,this._isWorker=Nh,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{Vh(this,e,[Lf,Df,Of])}catch(e){const t=Lh("error",{message:e.message,code:Sh.OPEN_ERROR,error:e});this._dispatchErrorEvent(t)}},this._onMessage=e=>Mg(this,0,void 0,(function*(){const{pingInterval:t,pingFrequency:o}=this._options;if(("hi"===e.data&&"always"===o||"auto"===o)&&(this._clearPingTimer(),this.emit("ping_once_success","success"),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),t)),"hi"!==e.data)try{Vh(this,e,[tf,Xh,Af,xf,If,ef])}catch(e){const t=Lh("error",{message:e.message,code:Sh.MESSAGE_ERROR,error:e});this._dispatchErrorEvent(t)}})),this._onError=e=>{var t,o;const i=null===(t=this._endpointManager)||void 0===t?void 0:t.checkReachMaxTries(),s=null===(o=this._endpointManager)||void 0===o?void 0:o.getCurrentEndpoint();if(!i||e.message)this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(Lh("error",{message:e.message,code:Sh.NATIVE_ERROR,error:e}));else{const t=`connect ${s} fail, max retries reached`;this._dispatchErrorEvent(Lh("error",{message:t,code:Sh.MAX_RETRIES_ERROR,error:e}))}},this._onClose=e=>Mg(this,0,void 0,(function*(){var t,o,i,s,n,r,a,c,l,d,p,u;this._clearTimer(),this._clearPingTimer(),this._removeWsListeners(),this._ws=null,this._connectLock=!1;const m=null===(t=this._endpointManager)||void 0===t?void 0:t.checkReachMaxTries();if(!m&&this._navigatorOnline()&&!this._readyClosed){const t=null===(o=this._endpointManager)||void 0===o?void 0:o.getCurrentEndpoint(),i=this._options.reconnectInterceptor(e.code,e.reason);return this._dispatchCloseEvent(Oh("close",{code:1006,reason:e.reason||`connecting failed, unknown reason, hostname: ${t}`,willReconnect:i})),void(i&&this._connect())}if(1e3!==e.code&&this._readyClosed)return this._dispatchCloseEvent(Oh("close",{code:1e3,reason:"bye"})),null===(i=this._endpointManager)||void 0===i||i.resetEndpointConfig(),void(null===(s=this._pingLossCounter)||void 0===s||s.resetCounter());if(1e3!==e.code&&m){const t=null===(n=this._endpointManager)||void 0===n?void 0:n.getCurrentEndpoint();let o=e.reason;o||(o=yield function(e){return Mg(this,0,void 0,(function*(){return new Promise((t=>{if(!qh)return t("unknown reason");try{const o=document.createElement("script");window.frontierJSONP=e=>{document.body.removeChild(o),window.frontierJSONP=void 0,t(e&&e.msg||"unknown reason")},o.type="text/javascript",o.src=e.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(o)}catch(e){document.body.removeChild(o)}}catch(e){window.frontierJSONP=void 0,t("unknown reason")}}))}))}(this._url)),o=`connecting failed, ${o}, hostname: ${t}, max retries reached`,this._dispatchCloseEvent(Oh("close",{code:e.code,reason:o}));const i=`connect ${t} fail, max retries reached`;return this._dispatchErrorEvent(Lh("error",{message:i,code:Sh.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(Oh("close",{code:e.code,reason:`connecting failed, unknown reason, hostname: ${t}`})),null===(l=this._endpointManager)||void 0===l||l.resetEndpointConfig(),void(null===(d=this._pingLossCounter)||void 0===d||d.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:Gg,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:o}=e,i=Array.isArray(t)?t:"string"==typeof t?[t]:[];if(!i||0===i.length)throw new Error("please provide valid url");if(!function(e){return!!(e||Mh&&wx.connectSocket||Bh&&tt.connectSocket||(qh||Nh)&&"undefined"!=typeof WebSocket&&WebSocket)}(o))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new Uh(i,this._options.maxRetries),this._pingLossCounter=new Qh(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=Dh("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 Mg(this,0,void 0,(function*(){const{fpID:t,deviceID:o,bddID:i,ttwID:s,accessKey:n,aID:r,customParams:a={},enableAutoAck:c,enableQoS:l,QoSLevel:d,env:p}=this._options;let u,m,g;this._isBrowser||this._isMiniWX||this._isMiniTT?(u=location&&"https:"==location.protocol?"wss://":"ws://",m=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),g=/^wss(.*:\/\/)/.test(e)?e:`${u}${m}`):(u="wss://",m=e.replace(/(^http)((?:[s]*:\/\/))/,""),g=/(^ws)((?:[s]*:\/\/))/.test(m)?m:`${u}${m}`);const h=i?"bd_did":s?"ttwid":"device_id",f=i||(s||o);if(!f||!h)throw new Error("please provide bddID, deviceID or ttwID");const _="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):{},b=Object.assign(Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:n,fpid:t,aid:r,[h]:f,xsack:c?1:0,xaack:c?1:0,xsqos:l?1:0,qos_level:l?d:void 0,qos_sdk_version:2},y),_);return`${g}/ws/v2${Object.keys(b).reduce(((e,t)=>void 0!==b[t]?`${e}${e?"&":"?"}${t}=${b[t]}`:e),"")}`}))}_connect(){var e,t,o,i,s,n,r;return Mg(this,0,void 0,(function*(){if(!this._connectLock&&!this._readyClosed){this._connectLock=!0;try{const l=null===(e=this._endpointManager)||void 0===e?void 0:e.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:d}=this._options;if(l){const e=null===(t=this._endpointManager)||void 0===t?void 0:t.getCurrentEndpoint(),s=null===(o=this._endpointManager)||void 0===o?void 0:o.replaceBackupEndpointAndUpdateCount(),n=null===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpointTriesCount();if(!s){const t=`connect ${e} timeout, max retries reached`;return this._debug(t),void this._dispatchErrorEvent(Lh("error",{message:t,code:Sh.MAX_RETRIES_ERROR}))}{const t=`connect ${e} timeout, max retries reached, will use backup endpoint ${s} to retry`,o=Lh("error",{message:t,code:Sh.MAX_RETRIES_ERROR});this._debug(t),this._dispatchErrorEvent(o),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=Dh("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):Mh||Bh?new Fh(a.url,a.protocol,a.headers):(qh||Nh)&&"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),d)}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:o,reconnectIntervalGrowFactor:i}=this._options,s=t*Math.pow(i,e-1);return s>o?o: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="",o=!1){this._ws&&this._destroyWebSocket(e,t,o)}_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=hh(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="",o=!1){var i,s,n,r;if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,t),this._connectLock=!1,o&&this._navigatorOnline()&&!this._readyClosed){if(null===(i=this._endpointManager)||void 0===i?void 0:i.checkReachMaxTries()){const e=null===(s=this._endpointManager)||void 0===s?void 0:s.getCurrentEndpoint();this._dispatchCloseEvent(Oh("close",{code:1006,reason:`connect ${e} timeout, max retries reached`,wasClean:!0}))}else{const o=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(Oh("close",{code:e,reason:t,wasClean:!0,willReconnect:o})),o&&this._connect()}}else this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(Oh("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(Oh("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 o;this._readyClosed=!0,this._clearTimer(),this._clearPingTimer(),this._dropGlobalEventListener(),null===(o=this._QoSManager)||void 0===o||o.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 Mg(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 o=yield Kh(e),i=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:l=this._options.payloadType,logIDNew:d=(this._options.logIDNewConfig.enableAutoGenerateLogIDNew?$g(this._options.logIDNewConfig.userIp):"")}=t||{};if(!n)throw new Error("please provide a valid service");const p={SeqID:vh.fromNumber(this._seqId++),LogID:vh.fromNumber(r),service:n,method:s,headers:a,payloadEncoding:c instanceof Object?c.encoding?c.encoding:"":c,payloadType:l instanceof Object?l.type?l.type:i:l||i,payload:o,LogIDNew:d},u=hh(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:d}}))}reconnect(e){var t,o;return Mg(this,0,void 0,(function*(){const{url:i}=e||{},s=Array.isArray(i)?i:"string"==typeof i?[i]:[];e&&Object.assign(this._options,e),s&&s.length?this._endpointManager=new Uh(s,this._options.maxRetries):null===(t=this._endpointManager)||void 0===t||t.resetEndpointConfig(),null===(o=this._pingLossCounter)||void 0===o||o.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 Mg(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 o=()=>{e("success"),this.off("ping_once_success",o),this.off("ping_once_timeout",i)},i=()=>{t("timeout"),this.off("ping_once_success",o),this.off("ping_once_timeout",i)};this.on("ping_once_success",o),this.on("ping_once_timeout",i),this._ping()}))}}function qf(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class Bf extends E{constructor(e,t){super((e=>{const t=new URL(e);return t.searchParams.set("aid",Cg),t.toString()})(e),"pbbp2",{headers:{...t,Origin:"https://www.coze.cn"}})}}class Mf{constructor(){Mf.prototype.__init.call(this)}__init(){this.fws=null}connect(t,o,i){return new Promise(((s,n)=>{let r=!1,a=!1;const c=e=>{if(!a)return a=!0,void n(e);qf([i,"optionalCall",t=>t(e)])},l={fpID:"1289",aID:Cg,accessKey:t.accessKey,deviceID:t.deviceId,url:"wss://frontier.coze.cn",automaticOpen:!0,enableQoS:!1,enableAutoAck:!1,ws:class extends Bf{constructor(e){super(e,t.headers)}}};this.fws=new Uf(l);const d=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(d),s()},this.fws.onerror=()=>{clearTimeout(d),c(new Error(r?"Frontier connection failed after connect":"Frontier connection failed"))},this.fws.onclose=()=>{clearTimeout(d),c(new Error(r?"Frontier connection closed after connect":"Frontier connection closed"))},this.fws.onmessage=t=>{const i=qf([t,"access",e=>e.message,"optionalAccess",e=>e.payloadType]),s=qf([t,"access",e=>e.message,"optionalAccess",e=>e.service]),n=qf([t,"access",e=>e.message,"optionalAccess",e=>e.payload]);if(!i||!n)return;const r=new TextDecoder("utf-8").decode(n),a=e.safeJsonParse(r,r);o({service:s,event:i,data:a})}}))}dispose(){qf([this,"access",e=>e.fws,"optionalAccess",e=>e.close,"call",e=>e()]),this.fws=null}}function Nf(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const $f=(e,t)=>{const o=t.toLowerCase(),i=Object.entries(e).find((([e])=>e.toLowerCase()===o));return Nf([i,"optionalAccess",e=>e[1]])},Gf=e=>JSON.stringify({accessKey:e.accessKey,authorization:$f(e.headers,"authorization"),deviceId:e.deviceId,organizationId:e.organizationId,serviceId:e.serviceId,xTTEnv:$f(e.headers,"x-tt-env")}),Ff=e=>"function"==typeof e.resolveConfig&&"string"==typeof e.scopeKey;class Vf{__init(){this.entries=new Map}constructor(e){Vf.prototype.__init.call(this),this.createClient=Nf([e,"optionalAccess",e=>e.createClient])||(()=>new Mf),this.getScopeKey=Nf([e,"optionalAccess",e=>e.getScopeKey])||Gf}async subscribe(e,t){const o=((e,t)=>Ff(e)?e.scopeKey:t(e))(e,this.getScopeKey);let i=this.entries.get(o);i||(i=this.createEntry(o,e),this.entries.set(o,i)),i.subscribers.add(t);try{await i.connectPromise}catch(e){throw i.subscribers.delete(t),e}let s=!1;return{release:()=>{s||(s=!0,this.releaseSubscriber(o,i,t))}}}createEntry(e,t){const o=this.createClient(),i={client:o,connectPromise:Promise.resolve(),subscribers:new Set};return i.connectPromise=(async e=>Ff(e)?await e.resolveConfig():e)(t).then((async t=>{await o.connect(t,(t=>{this.emitEvent(e,t)}),(t=>{this.handleConnectionError(e,t)}))})).catch((t=>{throw this.entries.get(e)===i&&this.entries.delete(e),i.subscribers.clear(),o.dispose(),t})),i}emitEvent(e,t){const o=this.entries.get(e);if(o)for(const e of o.subscribers)e.onEvent(t)}handleConnectionError(e,t){const o=this.entries.get(e);if(!o)return;this.entries.delete(e);const i=[...o.subscribers];o.subscribers.clear(),o.client.dispose();for(const e of i)Nf([e,"access",e=>e.onError,"optionalCall",e=>e(t)])}releaseSubscriber(e,t,o){t.subscribers.delete(o),t.subscribers.size>0||(this.entries.get(e)===t&&this.entries.delete(e),t.client.dispose())}}const Wf=new Vf;function Hf(e,t){return null!=e?e:t()}function Jf(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Kf=e=>({...e,files:e.files?[...e.files]:void 0}),Qf=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 Yf{constructor(){Yf.prototype.__init.call(this)}__init(){this.sessionStates=new Map}applyReplyEvent(t,o){const i=o.session_id;if(!i||!(e=>2===Number(e.source))(o))return null;const s=(({data:t,event:o})=>{const i=Jf([e.safeJsonParse(t.content,null),"optionalAccess",e=>e.message_data,"optionalAccess",e=>e.reply]),s=t.id,n="message"===o?Jf([i,"optionalAccess",e=>e.content])||t.content:Jf([i,"optionalAccess",e=>e.content]);return s&&n?{answerId:s,content:n,files:t.files,requestMessageId:Jf([i,"optionalAccess",e=>e.reply_to_message_id])}:null})({data:o,event:t});if(!s)return null;const n=this.getOrCreateSessionState(i),r=n.replies.get(s.answerId),a={answerId:s.answerId,content:"stream"===t&&r?r.content+s.content:s.content,files:Hf(s.files,(()=>Jf([r,"optionalAccess",e=>e.files]))),requestMessageId:Hf(s.requestMessageId,(()=>Jf([r,"optionalAccess",e=>e.requestMessageId])))};return"message"===t&&!r&&(({nextReply:e,sessionState:t})=>{for(const o of t.replies.values())if(o.requestMessageId===e.requestMessageId&&o.content===e.content&&Qf(o.files)===Qf(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:i,source:"stream",chunk:{answerId:s.answerId,content:s.content,requestMessageId:s.requestMessageId}}:{type:"reply_update",sessionId:i,source:"message",reply:Kf(a)})}applySessionIdleEvent(e){const t=Jf([e,"optionalAccess",e=>e.session_id]);if(!t||2!==Number(e.status))return null;const o=this.sessionStates.get(t);if(!o)return null;return{type:"session_idle",sessionId:t,replies:o.replyOrder.map((e=>o.replies.get(e))).filter((e=>Boolean(e))).map((e=>Kf(e)))}}getOrCreateSessionState(e){const t=this.sessionStates.get(e);if(t)return t;const o={replies:new Map,replyOrder:[]};return this.sessionStates.set(e,o),o}}function Zf(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Xf=e=>({type:"progress_update",progress:e});class e_{constructor(){e_.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=>Xf({progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:t.progressStatus}))):[]}applyFrontierEvent(e){const t=Zf([e,"optionalAccess",e=>e.claw_id]),o=Zf([e,"optionalAccess",e=>e.id]);if(!t||!o)return null;const i=2===Number(e.status)?"finished":1===Number(e.status)?"running":null;if(!i)return null;const s={progressId:o,clawId:t,name:e.name,progressType:e.type,progressStatus:i};return this.updateKnownProgressState(s),Xf(s)}applySnapshot(e,t){const o=this.getOrCreateProgressState(e),i=new Set,s=[];t.forEach((t=>{i.add(t.progressId);const n={progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:t.progressStatus},r=o.get(t.progressId);o.set(t.progressId,n),((e,t)=>Boolean(e&&e.name===t.name&&e.progressType===t.progressType&&e.progressStatus===t.progressStatus))(r,n)||s.push(Xf({progressId:n.progressId,clawId:e,name:n.name,progressType:n.progressType,progressStatus:n.progressStatus}))}));for(const t of[...o.values()])i.has(t.progressId)||(o.delete(t.progressId),s.push(Xf({progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:"finished"})));return 0===o.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 o=new Map;return this.progressStates.set(e,o),o}}class t_{__init(){this.progressPollTimers=new Map}__init2(){this.progressRefreshes=new Map}constructor({emitProgressUpdate:e,globalStreamKey:t,hasConnectionError:o,hasSubscribers:i,listProgresses:s,progressPollIntervalMs:n=3e4,progressStateStore:r}){t_.prototype.__init.call(this),t_.prototype.__init2.call(this),this.emitProgressUpdate=e,this.globalStreamKey=t,this.hasConnectionError=o,this.hasSubscribers=i,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 o=setTimeout((()=>{t()}),this.progressPollIntervalMs);this.progressPollTimers.set(e,o)},o=setTimeout((()=>{t()}),this.progressPollIntervalMs);this.progressPollTimers.set(e,o)}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 o=(async()=>{const{listProgresses:t}=this;if(!t)return;const o=await t(e);this.progressStateStore.applySnapshot(e,o).forEach((t=>{this.emitProgressUpdate(e,t),this.emitProgressUpdate(this.globalStreamKey,t)}))})().finally((()=>{this.progressRefreshes.delete(e)}));this.progressRefreshes.set(e,o),await o}}class o_{__init(){this.closed=!1}__init2(){this.error=null}__init3(){this.queue=[]}constructor(e){this.cleanup=e,o_.prototype.__init.call(this),o_.prototype.__init2.call(this),o_.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 i_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const s_="*";class n_{__init(){this.connectionError=null}__init2(){this.disposed=!1}__init3(){this.replyStateStore=new Yf}__init4(){this.progressStateStore=new e_}__init5(){this.sessionStreams=new Map}__init6(){this.progressStreams=new Map}constructor(e){n_.prototype.__init.call(this),n_.prototype.__init2.call(this),n_.prototype.__init3.call(this),n_.prototype.__init4.call(this),n_.prototype.__init5.call(this),n_.prototype.__init6.call(this),this.connectionManager=i_([e,"optionalAccess",e=>e.connectionManager])||(i_([e,"optionalAccess",e=>e.client])?new Vf({createClient:()=>e.client}):Wf),this.progressPoller=new t_({emitProgressUpdate:(e,t)=>{this.emitToProgress(e,t)},globalStreamKey:s_,hasConnectionError:()=>Boolean(this.connectionError),hasSubscribers:e=>this.hasProgressSubscribers(e),listProgresses:i_([e,"optionalAccess",e=>e.listProgresses]),progressPollIntervalMs:i_([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 o=new o_((()=>{this.removeStream(e,o),i_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.removeEventListener,"call",e=>e("abort",i)])})),i=()=>{o.close()};if(this.disposed)return o.fail(new Error("Frontier watcher disposed")),o;if(this.connectionError)return o.fail(this.connectionError),o;if(i_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.aborted]))return o.close(),o;let s=this.sessionStreams.get(e);return s||(s=new Set,this.sessionStreams.set(e,s)),s.add(o),i_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.addEventListener,"call",e=>e("abort",i,{once:!0})]),o}watchProgress(e,t){const o=e||s_,i=new o_((()=>{this.removeProgressStream(o,i),i_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.removeEventListener,"call",e=>e("abort",s)])})),s=()=>{i.close()};if(this.disposed)return i.fail(new Error("Frontier watcher disposed")),i;if(this.connectionError)return i.fail(this.connectionError),i;if(i_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.aborted]))return i.close(),i;let n=this.progressStreams.get(o);if(n||(n=new Set,this.progressStreams.set(o,n)),n.add(i),i_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.addEventListener,"call",e=>e("abort",s,{once:!0})]),e)this.emitKnownProgresses(i,e),this.progressPoller.refresh(e),this.progressPoller.ensure(e);else for(const e of this.progressStateStore.getKnownClawIds())this.emitKnownProgresses(i,e);return i}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 o=this.sessionStreams.get(e);o&&(o.delete(t),0===o.size&&this.sessionStreams.delete(e))}removeProgressStream(e,t){const o=this.progressStreams.get(e);o&&(o.delete(t),0===o.size&&(this.progressStreams.delete(e),e!==s_&&this.progressPoller.stop(e)))}failAllStreams(e){for(const t of this.sessionStreams.values())for(const o of t)o.fail(e);this.sessionStreams.clear();for(const t of this.progressStreams.values())for(const o of t)o.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 o=this.replyStateStore.applyReplyEvent(e,t);o&&"sessionId"in o&&this.emitToSession(o.sessionId,o)}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:o}=t.progress;this.emitToProgress(o,t),this.emitToProgress(s_,t)}emitToSession(e,t){const o=this.sessionStreams.get(e);if(o&&0!==o.size)for(const e of o)e.push(t)}emitToProgress(e,t){const o=this.progressStreams.get(e);if(o&&0!==o.size)for(const e of o)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 r_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const a_=({replies:e,requestMessageId:t,source:o})=>{if(0===e.length)return null;const i=r_([e,"access",t=>t[e.length-1],"optionalAccess",e=>e.answerId]);return i?{answerId:i,content:e.map((e=>e.content)).filter(Boolean).join("\n\n"),files:r_([e,"access",t=>t[e.length-1],"optionalAccess",e=>e.files]),requestMessageId:t,source:o}:null},c_=({replies:e,replyOrder:t,reply:o})=>{e.has(o.answerId)||t.push(o.answerId),e.set(o.answerId,o)},l_=({event:e,replies:t,replyOrder:o})=>{const i=t.get(e.chunk.answerId),s={answerId:e.chunk.answerId,content:`${r_([i,"optionalAccess",e=>e.content])||""}${e.chunk.content}`,files:r_([i,"optionalAccess",e=>e.files]),requestMessageId:e.chunk.requestMessageId||r_([i,"optionalAccess",e=>e.requestMessageId])};return c_({replies:t,reply:s,replyOrder:o}),s},d_=({event:e,replies:t,replyOrder:o})=>(c_({replies:t,reply:e.reply,replyOrder:o}),e.reply);class p_{constructor(e){this.watcher=r_([e,"optionalAccess",e=>e.watcher])||new n_}async connect(e){await this.watcher.connect(e)}async waitForReply(e){const{onReplyChunk:t,onReplyUpdate:o,sessionId:i,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,l=[];let d=!1;const p=t=>{d||(d=!0,r_([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=a_({replies:l.map((e=>c.get(e))).filter((e=>Boolean(e))),requestMessageId:s,source:"timeout"});p((({reject:t,resolve:o})=>{e?o(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(i,{signal:r.signal})){if("reply_chunk"===e.type){if(e.chunk.requestMessageId!==s)continue;l_({event:e,replies:c,replyOrder:l}),r_([t,"optionalCall",t=>t(e)]);continue}if("reply_update"===e.type){if(e.reply.requestMessageId!==s)continue;d_({event:e,replies:c,replyOrder:l}),r_([o,"optionalCall",t=>t(e)]);continue}if("session_idle"!==e.type)continue;const i=a_({replies:e.replies.filter((e=>e.requestMessageId===s)),requestMessageId:s,source:"idle"});i&&p((({resolve:e})=>{e(i)}))}})();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 u_={skipOrgCheck:!0,skipSpaceCheck:!0},m_=async t=>{if(t)return t;const o=s.createSessionConfigStore(),i=await o.get();if(i.sessionId)return i.sessionId;throw new e.CozeError(e.ErrorCode.E1000,"Missing session ID: provide --session-id or run `coze session create` first")},g_=async({clawId:e,sessionId:t})=>{const o=s.createSessionConfigStore();await o.save({sessionId:t,...e?{sessionClawId:e}:{}})},h_=({timeoutMs:e})=>{const t=new AbortController,o=()=>{t.abort()},i=void 0===e?void 0:setTimeout((()=>{o()}),e);return process.once("SIGINT",o),{abort:o,signal:t.signal,dispose:()=>{i&&clearTimeout(i),process.off("SIGINT",o)}}},f_=async(t,o)=>{const i=(t=>{const o=t.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");return{ctx:o,service:s.createDefaultSessionService(o.config)}})(t);try{await o(i)}catch(t){Q((t=>{if(t instanceof e.CozeError)return t;if(t instanceof s.SessionServiceError){const o="SESSION_AUTH_INVALID"===t.code?e.ErrorCode.E2001:e.ErrorCode.E5000;return new e.CozeError(o,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),i.ctx)}},__=t=>{const o=Number.parseInt(t,10);if(!Number.isFinite(o)||o<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --limit: expected a positive integer");return o},y_=t=>{const o=Number.parseInt(t,10);if(!Number.isFinite(o)||o<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --timeout: expected a positive integer");return o},b_=e=>{if(!e||0===e.length)return null;const t=["Files:"];return e.forEach(((e,o)=>{t.push(`${o+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")},v_=(e,t)=>{const o=b_(t);return o?[e,"",o].join("\n"):e},w_=({accessToken:e,apiBaseUrl:t,organizationId:o,sessionApiBaseUrl:i,xTTEnv:n})=>{const r=i||t,a=(({accessToken:e,xTTEnv:t})=>{if(!e)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const o={Authorization:`Bearer ${e}`};return t&&(o["x-use-ppe"]="1",o["x-tt-env"]=t),o})({accessToken:e,xTTEnv:n});return{resolveConfig:async()=>({...await Ag({baseUrl:r,headers:a,xTTEnv:n}),headers:a,organizationId:o}),scopeKey:JSON.stringify({baseUrl:r,authorization:a.Authorization,organizationId:o,xTTEnv:n})}},E_=async({accessToken:e,apiBaseUrl:t,organizationId:o,sessionApiBaseUrl:i,progressPollIntervalMs:s,service:n,xTTEnv:r})=>{const a=new n_({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(w_({accessToken:e,apiBaseUrl:t,organizationId:o,sessionApiBaseUrl:i,xTTEnv:r})),a},C_=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"),I_=e=>`${JSON.stringify(e)}\n`;class A_{__init(){this.replyStates=new Map}__init2(){this.requestPrintedContent=new Map}__init3(){this.endsWithNewline=!0}__init4(){this.hasStartedReply=!1}constructor(e){A_.prototype.__init.call(this),A_.prototype.__init2.call(this),A_.prototype.__init3.call(this),A_.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(I_({type:"reply_chunk",session_id:t,answer_message_id:e.answerId,reply_to_message_id:e.requestMessageId,delta:e.content}));const o=this.getOrCreateReplyState(e.answerId);this.ensureReplyStarted({answerId:e.answerId,requestMessageId:e.requestMessageId,state:o}),this.writeRaw(e.content),o.printedContent+=e.content,this.updateRequestPrintedContent({requestMessageId:e.requestMessageId,printedContent:o.printedContent})}writeReply({files:e,reply:t,sessionId:o,source:i}){if("text"!==this.format)return void this.write(I_({type:"message"===i?"reply_update":"reply_completed",session_id:o,answer_message_id:t.answerId,reply_to_message_id:t.requestMessageId,content:t.content,files:e,event_source:i}));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"!==i)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"!==i&&this.writeFinalReplyMetadata({files:e})}writeFinalReplyMetadata({files:e}){this.endsWithNewline||this.writeRaw("\n");const t=b_(e);t&&this.writeRaw(`\n${t}\n`)}writeProgress({progress:e,sessionId:t}){"text"===this.format?(this.endsWithNewline||this.writeRaw("\n"),this.writeRaw(`\n${C_(e)}\n`)):this.write(I_({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 o={headerPrinted:!1,printedContent:""};return this.replyStates.set(e,o),o}ensureReplyStarted({answerId:e,continuesPrintedRequest:t=!1,requestMessageId:o,state:i}){if(!i.headerPrinted){if(t)return i.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}`,o?`reply_to_message_id: ${o}`:null].filter(Boolean);this.writeRaw(`${t.join("\n")}\n`)}i.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 o=this.requestPrintedContent.get(t)||"";e.length>=o.length&&this.requestPrintedContent.set(t,e)}writeRaw(e){e&&(this.write(e),this.endsWithNewline=e.endsWith("\n"))}}function S_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const k_=({ctx:e,sessionId:t,reply:o,files:i,source:s})=>{"text"!==e.format?e.response.print({session_id:t,answer_message_id:o.answerId,reply_to_message_id:o.requestMessageId,content:o.content,files:i,event_source:s}):e.response.print((({reply:e,files:t,source:o})=>`${[`answer_message_id: ${e.answerId}`,e.requestMessageId?`reply_to_message_id: ${e.requestMessageId}`:null,`event_source: ${o}`].filter(Boolean).join("\n")}\n${v_(e.content,t)}`)({files:i,reply:o,source:s}))},j_=({ctx:e,options:t,service:o,streamRenderer:i})=>{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:o}),a=async({reply:o,source:i})=>{const s=await r(o),a=(({files:e,reply:t})=>JSON.stringify({answerId:t.answerId,content:t.content,files:e,requestMessageId:t.requestMessageId}))({files:s,reply:o});S_([n,"optionalAccess",e=>e.get,"call",e=>e(o.answerId)])!==a&&(S_([n,"optionalAccess",e=>e.set,"call",e=>e(o.answerId,a)]),k_({ctx:e,files:s,reply:o,sessionId:t.sessionId,source:i}))};return{handleReplyChunk:e=>{S_([i,"optionalAccess",e=>e.writeChunk,"call",o=>o({chunk:e.chunk,sessionId:t.sessionId})])},handleReplyUpdate:async e=>{i?i.writeReply({reply:e.reply,sessionId:t.sessionId,source:"message"}):await a({reply:e.reply,source:"message"})},handleIdleReply:async e=>{i?i.writeReply({files:await r(e),reply:e,sessionId:t.sessionId,source:"idle"}):await a({reply:e,source:"idle"})}}},P_=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",y_).option("--snapshot","Print full reply snapshots instead of streaming chunks incrementally").config({...u_,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 f_(t,(async({ctx:t,service:o})=>{const i=await m_(e.sessionId),s={...e,sessionId:i},n=await E_({accessToken:t.config.accessToken,apiBaseUrl:t.config.apiBaseUrl,organizationId:t.config.organizationId,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv});await g_({sessionId:i});const r=s.snapshot?null:new A_({format:t.format,includeReplyMetadata:"text"===t.format}),a=h_({timeoutMs:s.timeout}),c=j_({ctx:t,options:s,service:o,streamRenderer:r});try{for await(const e of n.watchSession(i,{signal:a.signal}))if("reply_chunk"!==e.type)if("reply_update"!==e.type){if("progress_update"!==e.type){await o.updateSessionRuntimeStatus({sessionId:i,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 z_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const T_=async e=>await new Promise((t=>setTimeout(t,e))),R_=e=>{const t=e.contentPreview&&e.contentPreview!==e.replyContent?e.contentPreview:void 0,o=e.resultSummary&&e.resultSummary!==e.replyContent&&e.resultSummary!==e.contentPreview?e.resultSummary:void 0;return{contentPreview:t,replyContent:e.replyContent,resultSummary:o}},x_=e=>{const t=R_(e);return{answer_message_id:e.answerMessageId,artifacts:z_([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}},L_=e=>{const t=R_(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")},O_=({ctx:e,task:t})=>{"text"!==e.format?e.response.print(x_(t)):e.response.print(L_(t))},D_=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)),U_=e=>{const t=e.command("task").description("Inspect persisted session background tasks").config({...u_,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 f_(t,(async({ctx:t,service:o})=>{try{const i=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:o,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await i.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(L_).join("\n\n"):"No session tasks");t.response.print({items:n.map((e=>x_(e)))})}catch(e){throw D_(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,o)=>{await(async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{try{const i=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:o,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await i.getTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});O_({ctx:t,task:n})}catch(e){throw D_(e)}}))})({includeExpired:t.includeExpired,taskId:e},o)})),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,o)=>{await(async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{try{const i=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:o,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await i.refreshTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});O_({ctx:t,task:n})}catch(e){throw D_(e)}}))})({includeExpired:t.includeExpired,taskId:e},o)})),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",y_).action((async(e,t,o)=>{await(async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{try{const i=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:o,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv});let n=await i.getTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});if(O_({ctx:t,task:n}),s.isSessionTaskTerminal(n.status))return;const r=void 0===e.timeout?void 0:Date.now()+e.timeout;for(;;){const o=void 0===r?1e4:Math.min(1e4,r-Date.now());if(o<=0)return;if(await T_(o),n=await i.refreshTask(e.taskId,{includeExpired:Boolean(e.includeExpired)}),O_({ctx:t,task:n}),s.isSessionTaskTerminal(n.status))return}}catch(e){throw D_(e)}}))})({includeExpired:t.includeExpired,taskId:e,timeout:t.timeout},o)})),t.command("gc").description("Remove expired terminal session tasks from local storage").action((async(e,t)=>{await(async e=>{await f_(e,(async({ctx:e,service:t})=>{try{const o=s.createSessionTaskService({apiBaseUrl:e.config.apiBaseUrl,service:t,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv}),i=await o.gcTasks();if("text"===e.format)return void e.response.print(i.length>0?`Removed ${i.length} expired task(s)`:"No expired session tasks");e.response.print({count:i.length,items:i.map((e=>x_(e)))})}catch(e){throw D_(e)}}))})(t)}))},q_=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${v_(e.content,e.files)}`,B_=async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{const i=await m_(e.sessionId),n=await o.listRepliesByMessage({sessionId:i,messageId:e.messageId});await g_({sessionId:n.sessionId});const r=s.createSessionConfigStore(),a=await r.get(),c=n.items.some((e=>e.files&&e.files.length>0)),l=c?a.sessionClawId||(await o.getStatus()).clawId:void 0,d=c?await(async({items:e,store:t,service:o,clawId:i,apiBaseUrl:n,sessionApiBaseUrl:r,xTTEnv:a})=>await Promise.all(e.map((async e=>({...e,files:await s.resolveStoredSessionReplyFiles({files:e.files,clawId:i,apiBaseUrl:n,sessionApiBaseUrl:r,xTTEnv:a,service:o,deps:{store:t}})})))))({items:n.items,store:r,service:o,clawId:l,apiBaseUrl:t.config.apiBaseUrl,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}):n.items;if("text"===t.format)return n.requestMessageFound||0!==d.length?0===d.length?void t.response.print(`No replies found for message: ${e.messageId}`):void t.response.print(d.map(q_).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:d.length,items:d.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 M_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const N_=({ctx:e})=>{const t=new Map;return o=>{const i=t.get(o.progressId);i&&i.progressStatus===o.progressStatus&&i.name===o.name&&i.type===o.type&&"snapshot"!==o.eventSource||(t.set(o.progressId,{name:o.name,progressId:o.progressId,progressStatus:o.progressStatus,type:o.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(`${C_(t)}\nevent_source: ${t.eventSource}`)})({ctx:e,progress:o}))}},$_=(e,t)=>!t||e.progressId===t,G_=async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{(({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=>C_(e))).join("\n\n"):"No active progress")})({ctx:t,progresses:await o.listProgresses({size:e.size})})}))},F_=async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{const i=await o.getStatus(),{clawId:n}=i;if(!i.authValid||!n)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const r=await E_({accessToken:t.config.accessToken,apiBaseUrl:t.config.apiBaseUrl,organizationId:t.config.organizationId,progressPollIntervalMs:3e4,sessionApiBaseUrl:t.config.sessionApiBaseUrl,service:o,xTTEnv:t.config.xTTEnv}),a=h_({timeoutMs:e.timeout}),c=N_({ctx:t});try{await(async({clawId:e,emitProgress:t,options:o,service:i})=>{(await i.listProgresses({clawId:e})).filter((e=>$_(e,o.progressId))).forEach((e=>{t({...e,eventSource:"snapshot"})}))})({clawId:n,emitProgress:c,options:e,service:o}),await(async({abortScope:e,clawId:t,emitProgress:o,options:i,watcher:s})=>{for await(const n of s.watchProgress(t,{signal:e.signal}))$_(n.progress,i.progressId)&&(o({progressId:n.progress.progressId,name:n.progress.name,type:n.progress.progressType,progressStatus:n.progress.progressStatus,eventSource:"websocket"}),i.progressId&&"finished"===n.progress.progressStatus&&e.abort())})({abortScope:a,clawId:n,emitProgress:c,options:e,watcher:r})}finally{a.dispose(),r.dispose()}}))},V_=e=>{const t=e.command("progress").description("Inspect claw background progress").config({...u_,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",__,100).action(G_),t.command("show <progressId>").description("Show one background progress snapshot").action((async(e,t,o)=>{await(async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{const i=await o.getProgress({progressId:e.progressId});"text"!==t.format?t.response.print({progress_id:e.progressId,found:Boolean(i),name:M_([i,"optionalAccess",e=>e.name]),type:M_([i,"optionalAccess",e=>e.type]),progress_status:M_([i,"optionalAccess",e=>e.progressStatus]),raw:M_([i,"optionalAccess",e=>e.raw])}):t.response.print(i?C_(i):`Progress not found: ${e.progressId}`)}))})({progressId:e},o)})),t.command("poll <progressId>").description("Poll one background progress and treat missing as finished").action((async(e,t,o)=>{await(async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{const i=await o.getProgress({progressId:e.progressId}),s=M_([i,"optionalAccess",e=>e.progressStatus])||"finished";"text"!==t.format?t.response.print({progress_id:e.progressId,name:M_([i,"optionalAccess",e=>e.name]),type:M_([i,"optionalAccess",e=>e.type]),progress_status:s,raw:M_([i,"optionalAccess",e=>e.raw])}):t.response.print(C_({progressId:e.progressId,name:M_([i,"optionalAccess",e=>e.name]),type:M_([i,"optionalAccess",e=>e.type]),progressStatus:s}))}))})({progressId:e},o)})),t.command("watch [progressId]").description("Watch one or all background progress updates").option("--timeout <timeoutMs>","Stop watching after the specified timeout in milliseconds",y_).action((async(e,t,o)=>{await F_({progressId:e,timeout:t.timeout},o)}))};function W_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const H_={...u_,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"}}}}}},J_=async({ctx:t,options:o,resolvedContent:i})=>{if(!o.podcastVoice)return i;if(!i)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-voice requires MESSAGE or stdin content");const s=(({config:t,voice:o,mode:i})=>{const s=Ug(o),n=Bg({config:t,mode:i}).filter((e=>Ug(e.label)===s||Ug(e.value)===s));if(0===n.length)throw new e.CozeError(e.ErrorCode.E1000,`Podcast voice not found: ${o}`);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 "${o}" matched multiple podcast voices; specify --podcast-mode (${t})`)}return n[0]})({config:await qg({baseUrl:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,xTTEnv:t.config.xTTEnv}),voice:o.podcastVoice,mode:o.podcastMode}).label||o.podcastVoice;return(({content:t,voiceLabel:o})=>{if(t.includes('使用音色"'))throw new e.CozeError(e.ErrorCode.E1000,"Message already contains a podcast voice instruction");const i=`使用音色"${o}", `,s=t.length-t.trimStart().length,n=t.slice(0,s),r=t.trimStart();if(/^@播客(?=\s|$)/.test(r))return`${n}@播客 ${i}${r.slice(3).trimStart()}`;return`${i}${t}`})({content:i,voiceLabel:s})},K_=async({ctx:t,message:o,options:i,service:s})=>{const{content:n,filePaths:r}=await Dg(o,{cwd:t.cwd,onWarn:e=>t.ui.warn(e)});(({options:t,resolvedContent:o})=>{if(t.podcastMode&&!t.podcastVoice)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-mode requires --podcast-voice");if(t.podcastVoice&&!o)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-voice requires MESSAGE or stdin content")})({options:i,resolvedContent:n});const a=await jg({filePaths:[...i.file||[],...r],sessionId:i.sessionId,apiBaseUrl:t.config.apiBaseUrl,sessionApiBaseUrl:t.config.sessionApiBaseUrl,sessionSpaceWebId:t.config.sessionSpaceWebId,xTTEnv:t.config.xTTEnv,service:s}),c=await J_({ctx:t,options:i,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}},Q_=async({ctx:e,options:t,service:o})=>{if(!t.wait)return{streamRenderer:null,waiter:null};const i=new A_({format:e.format}),s=W_([await o.getStatus(),"optionalAccess",e=>e.clawId]);return{clawId:s,knownProgressIds:s?await o.listProgresses({clawId:s}).then((e=>new Set(e.map((e=>e.progressId))))).catch((()=>null)):void 0,streamRenderer:i,waiter:await(async({accessToken:e,apiBaseUrl:t,organizationId:o,sessionApiBaseUrl:i,xTTEnv:s})=>new p_({watcher:await E_({accessToken:e,apiBaseUrl:t,organizationId:o,sessionApiBaseUrl:i,xTTEnv:s})}))({accessToken:e.config.accessToken,apiBaseUrl:e.config.apiBaseUrl,organizationId:e.config.organizationId,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv})}},Y_=async({ctx:e,knownProgressIds:t,options:o,result:i,service:n,streamRenderer:r,waiter:a,clawId:c})=>{const l=await a.waitForReply({onReplyChunk:r?e=>{r.writeChunk({chunk:e.chunk,sessionId:o.sessionId})}:void 0,onReplyUpdate:r?e=>{r.writeReply({reply:e.reply,sessionId:o.sessionId,source:"message"})}:void 0,sessionId:o.sessionId,requestMessageId:i.messageId,timeoutMs:o.timeout}),d="idle"===l.source&&c&&t?await(async({clawId:e,knownProgressIds:t,listProgresses:o,pollIntervalMs:i=500,timeoutMs:s=3e3})=>{const n=Date.now()+s;for(;;){const s=(await o({clawId:e})).find((e=>!t.has(e.progressId)));if(s)return s;const r=n-Date.now();if(r<=0)return null;await bg(Math.min(i,r))}})({clawId:c,knownProgressIds:t,listProgresses:e=>n.listProgresses(e),timeoutMs:3e3}):null;"idle"===l.source&&await n.updateSessionRuntimeStatus({sessionId:o.sessionId,status:"idle"});const p=await s.resolveStoredSessionReplyFiles({files:l.files,apiBaseUrl:e.config.apiBaseUrl,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv,service:n});return r?(r.writeReply({files:p,reply:{answerId:l.answerId,content:l.content,requestMessageId:i.messageId},sessionId:o.sessionId,source:l.source}),d&&r.writeProgress({progress:d,sessionId:o.sessionId}),{answerMessageId:l.answerId,content:l.content,files:p,progress:d,rendered:!0}):{answerMessageId:l.answerId,content:l.content,files:p,progress:d,rendered:!1}},Z_=async(e,t,o)=>{await f_(o,(async({ctx:o,service:i})=>{const n=await m_(t.sessionId),r={...t,sessionId:n},a=await K_({ctx:o,message:e,options:r,service:i}),c=await Q_({ctx:o,options:r,service:i});try{const e=await i.sendMessage({sessionId:n,content:a.content,files:a.files});if(await g_({sessionId:e.sessionId}),c.waiter){const t=await Y_({...c,ctx:o,options:r,result:e,service:i,waiter:c.waiter});if(t.progress)try{const r=s.createSessionTaskService({apiBaseUrl:o.config.apiBaseUrl,service:i,sessionApiBaseUrl:o.config.sessionApiBaseUrl,xTTEnv:o.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:o.config.accessToken||"",apiBaseUrl:o.config.apiBaseUrl,organizationId:o.config.organizationId,sessionApiBaseUrl:o.config.sessionApiBaseUrl,taskId:a.taskId,xTTEnv:o.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"===o.format)return void o.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(o.ui.warn(`Failed to persist task: ${t instanceof Error?t.message:String(t)}`),"json"===o.format)return void o.response.print({session_id:e.sessionId,message_id:e.messageId,status:e.status})}if(t.rendered)return}o.response.print({session_id:e.sessionId,message_id:e.messageId,status:e.status})}finally{W_([c,"access",e=>e.waiter,"optionalAccess",e=>e.dispose,"call",e=>e()])}}))};const X_={...u_,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"}]}},ey=t=>{const o=Number.parseInt(t,10);if(!Number.isFinite(o)||o<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --page: expected a positive integer");return o},ty=(e,t)=>[...t,ey(e)],oy=t=>{if("ppt"===t||"editable"===t)return t;throw new e.CozeError(e.ErrorCode.E1000,'Invalid value for --export-type: expected "ppt" or "editable"')},iy=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.")},sy=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},ny=async({file:e,service:t})=>e.fileUrl?e.fileUrl:t.resolveFileUrl({fileUri:sy(e)}),ry=async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{const i=await iy({options:e}),n=await ny({file:i,service:o}),r=await s.fetchSessionPptContent({url:n}),a=s.parseSessionPptContent(r);"text"!==t.format?t.response.print({file_name:i.fileName,file_uri:i.fileUri,file_url:n,type:a.type,page_count:a.pageCount}):t.response.print((({file:e,pageCount:t,type:o,url:i})=>[`PPT: ${e.fileName}`,e.fileUri?`file_uri: ${e.fileUri}`:null,`file_url: ${i}`,`type: ${o}`,`pages: ${t}`].filter(Boolean).join("\n"))({file:i,pageCount:a.pageCount,type:a.type,url:n}))}))},ay=t=>{const o=t.command("ppt").description("Inspect, export, share, and edit session PPT artifacts").config(X_);o.command("info").description("Get PPT metadata and page count").option("--file-uri <uri>","Specific PPT file_uri").action(((e,t)=>ry(e,t))),o.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",__).action(((e,t)=>(async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{const i=await iy({options:e}),n=await ny({file:i,service:o}),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:i.fileName,file_uri:i.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}`:"",o=(i=e.previewText||(e.previewUrl?`preview_url: ${e.previewUrl}`:"")).length>500?`${i.slice(0,500)}...`:i;var i;return o?`${e.page}.${t}\n${o}`:`${e.page}.${t}`})).join("\n\n"))(c))}))})(e,t))),o.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",oy,"ppt").action(((e,t)=>(async(e,t)=>{await f_(t,(async({ctx:t,service:o})=>{const i=await iy({options:e}),s=sy(i),n=await o.exportPpt({fileUri:s,exportType:e.exportType}),r=await Eg({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))),o.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",ty,[]).option("--wait","Wait until the edit turn becomes idle").option("--timeout <timeoutMs>","Timeout for --wait",y_).action(((t,o,i)=>(async(t,o,i)=>{if(!function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([o,"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 Z_(s.formatSessionPptEditQuery({pages:o.page,query:t}),{sessionId:o.sessionId,wait:o.wait,timeout:o.timeout},i)})(t,o,i))),o.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 f_(t,(async({ctx:t,service:o})=>{const i=await iy({options:e}),n=sy(i),r=s.buildSessionPptSlideUrl({origin:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,fileUri:n,taskId:e.taskId}),a=!1===e.short?r:await o.shortenWebUrl({url:r});"text"!==t.format?t.response.print({file_name:i.fileName,file_uri:n,url:a,original_url:r,short:!1!==e.short}):t.response.print(a)}))})(e,t)))},cy=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"),ly=async(e,t)=>{await f_(t,(async({ctx:t})=>{const o=await qg({baseUrl:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,xTTEnv:t.config.xTTEnv}),i=Bg({config:o,mode:e.mode,keyword:e.keyword});"text"!==t.format?t.response.print({count:i.length,items:i}):t.response.print(i.length>0?i.map(cy).join("\n\n"):"No podcast voices matched")}))},dy=(e,t)=>[...t,e],py=async(t,o,i)=>{(t=>{if(t.mode&&!t.voice)throw new e.CozeError(e.ErrorCode.E1000,"--mode requires --voice")})(o),await Z_(t,(e=>({file:e.file||[],podcastMode:e.mode,podcastVoice:e.voice,sessionId:e.sessionId,timeout:e.timeout,wait:e.wait}))(o),i)},uy=e=>{const t=e.command("podcast").description("Inspect podcast config");t.config({...u_,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",y_).option("--file <path>","Local file to upload and attach (can be used multiple times)",dy,[]).config({...u_,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(py)})(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({...u_,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(ly)})(t)};function my(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const gy=e=>{e.command("current").description("Show the current locally selected default session").config({...u_,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(),o=s.createSessionConfigStore(),i=await o.get();if("text"===my([t,"optionalAccess",e=>e.format])){if(!i.sessionId)return void my([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e("No current session configured")]);const e=[`session_id: ${i.sessionId}`];return i.sessionClawId&&e.push(`claw_id: ${i.sessionClawId}`),void my([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e.join("\n"))])}my([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({configured:Boolean(i.sessionId),session_id:i.sessionId,claw_id:i.sessionClawId})])})(t)}))},hy=e=>{e.command("use <sessionId>").description("Set the current locally selected default session").config({...u_,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,o)=>{await(async({cmd:e,sessionId:t})=>{const o=e.getContext();await g_({sessionId:t}),my([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"updated",session_id:t})])})({cmd:o,sessionId:e})}))},fy=e=>{const t=e.command("session").description("Manage Coze session-based claw chat").config({...u_,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({...u_,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 f_(t,(async({ctx:t,service:o})=>{if(e.sessionId){const i=await o.getSessionDisplayStatus({sessionId:e.sessionId});return void t.response.print({session_id:i.sessionId,display_status:i.displayStatus,claw_busy:i.clawBusy,claw_progress_count:i.clawProgressCount,runtime_status:i.runtimeStatus,updated_at:i.updatedAt})}const i=await o.getStatus();t.response.print({auth_configured:i.authConfigured,auth_valid:i.authValid,claw_id:i.clawId,account_id:i.accountId,updated_at:i.updatedAt})}))}))})(t),(e=>{e.command("create").description("Create a new claw chat session").config({...u_,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 f_(t,(async({ctx:e,service:t})=>{const o=await t.createSession();await g_({clawId:o.clawId,sessionId:o.sessionId}),e.response.print({status:"created",claw_id:o.clawId,session_id:o.sessionId})}))}))})(t),gy(t),hy(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",__,20).config({...u_,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 f_(t,(async({ctx:t,service:o})=>{const i=await o.listSessions({offset:e.offset,limit:e.limit});t.response.print({items:i.items,next_offset:i.nextOffset,has_more:i.hasMore})}))}))})(t),(e=>{e.command("file").description("Manage files returned by claw session replies").config({...u_,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({...u_,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,o)=>{await f_(o,(async({ctx:o})=>{const i=await Eg({url:e,outputPath:t.outputPath});"text"!==o.format?o.response.print({status:"saved",path:i.path,filename:i.filename,size:i.size,url:i.url}):o.response.print(i.path)}))}))})(t),uy(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",y_).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(H_).action(Z_)})(t),ay(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({...u_,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,o)=>{await B_({messageId:e,sessionId:t.sessionId},o)}))})(t),P_(t),V_(t),U_(t)};function _y(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"},{desc:"Upgrade then sync bundled skills",cmd:"coze upgrade && coze self skill install",tags:["[PIPELINE]"]}],enums:{tag:{latest:"Stable release channel (default)",beta:"Pre-release channel for early testing"}},schema:{input:{force:{type:"boolean",required:!1,default:!1,description:"Reinstall even if already on the latest version"},tag:{type:"string",required:!1,default:"latest",description:"npm dist-tag to upgrade to",example:"latest"}},output:{previousVersion:{type:"string",description:"Version before the upgrade",example:"1.2.3"},currentVersion:{type:"string",description:"Version reported by the running binary after install",example:"1.3.0"},latestVersion:{type:"string",description:"Latest version found on the registry for the given tag",example:"1.3.0"},status:{type:"string",enum:["upgraded"],description:"Operation result",example:"upgraded"}}},errors:[{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Failed to reach the npm registry when checking the latest version",fix:"Check network connectivity and the configured npm registry, then retry",example:"coze upgrade --force"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"The global install command failed (e.g. permission denied or unknown dist-tag), exiting with code 1",fix:"Upgrade manually with the printed command, e.g. `npm install -g @coze/cli`",example:"npm install -g @coze/cli@latest"}],seeAlso:["coze --version","coze self skill install"],caveats:["Requires permission to install global packages; on some systems this needs sudo or a configured npm prefix","The running process is still the old binary after the upgrade; run `coze self skill install` afterwards to sync bundled skills"]}}).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 ge(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: ${o.gray(e.currentVersion)} → ${o.green(e.latestVersion)}`),n.ui.info("Upgrading Coze CLI...");const s=ee(),r=function(e,t){switch(e){case"pnpm":return`pnpm add -g ${X}@${t}`;case"yarn":return`yarn global add ${X}@${t}`;default:return`npm install -g ${X}@${t}`}}(s,e.latestVersion);n.ui.verbose(`Using package manager: ${s}`),n.ui.verbose(`Running: ${r}`),i.execSync(r,{stdio:"inherit"});const a=ne();n.ui.success(`Successfully upgraded Coze CLI to ${e.latestVersion}. (was ${e.currentVersion})`),n.ui.info(`Run ${o.cyan("coze self skill install")} to sync the bundled skills to your AI tools.`),"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"),n.ui.info(`If you are on an internal network, verify your npm registry with ${o.cyan("npm config get registry")}.`),process.exit(e.ExitCode.FAILURE)}}))}function yy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const by={brief:"Install bundled skills to AI agents",description:"Idempotently sync the current CLI bundled skills via the `skills` tool: copy them into the shared central pool (`~/.agents/skills/`) and symlink them into every installed agent. Records `~/.coze/cli/.skill-lock.json` with the CLI version. User-modified skills are reported instead of silently overwritten unless `--force` is passed.",examples:[{desc:"Install to all installed agents",cmd:"coze self skill install",tags:["[RECOMMENDED]"]},{desc:"Install to a specific subset",cmd:"coze self skill install --target claude,trae"},{desc:"Overwrite user-modified skills",cmd:"coze self skill install --force"},{desc:"Re-install only when versions diverge",cmd:"coze self skill status --format json | jq -e .versionMatch >/dev/null || coze self skill install",tags:["[PIPELINE]"]}],enums:{target:{claude:"Claude Code (mapped to the skills agent id claude-code)",trae:"Trae",comate:"Comate",all:"All installed agents (same as omitting --target)"}},schema:{input:{target:{type:"string",required:!1,description:'Comma-separated agent names to install to; omit or pass "all" to fan out to every installed agent. Unknown names are passed through to the skills CLI for validation.',example:"claude,trae"},force:{type:"boolean",required:!1,default:!1,description:"Overwrite user-modified skills instead of aborting the install"}},output:{blocked:{type:"boolean",description:"True when user-modified skills were detected without --force; nothing was written"},cliVersion:{type:"string",description:"CLI version the skills were released as",example:"0.1.0"},sourceRoot:{type:"string",description:"Bundled skill source directory used as input"},poolPath:{type:"string",required:!1,description:"Skill path inside the skills central pool",example:"~/.agents/skills/using-coze-cli"},linkedTargets:{type:"array",items:{type:"string"},description:"Agent display names the skills were linked to"},skillsOk:{type:"boolean",description:"Whether every `skills` subprocess invocation succeeded"},modifiedSkills:{type:"array",items:{type:"string"},description:"User-modified skill names that blocked the sync (empty unless blocked)"}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing (no packaged skills/manifest.json and no dev-mode docs/skills), which indicates a corrupted CLI installation",fix:"Reinstall or upgrade the CLI, then run the install again",example:"coze upgrade && coze self skill install"}],seeAlso:["coze self skill status","coze self skill remove","coze self skill path"],caveats:["When user-modified skills are detected without --force, the command warns and exits without writing anything (blocked=true); --force discards those local edits","A partial `skills` subprocess failure is reported as a warning (skillsOk=false) instead of a non-zero exit; re-run the install or check `coze self skill path`","Agents share the `~/.agents/skills` central pool; a listed agent can read the skill, it does not hold a per-agent copy"]};function vy(e,t){return null!=e?e:t()}function wy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ey={brief:"Show skill consistency status",description:"Compare the installed skill lock against the current CLI: version match, binary path match, and per-skill ok/drift/modified/missing state. Fully local and read-only, no network. When no lock exists yet, the command suggests running `coze self skill install` first.",examples:[{desc:"Show status (minimal)",cmd:"coze self skill status",tags:["[RECOMMENDED]"]},{desc:"Show status as JSON",cmd:"coze self skill status --format json"},{desc:"Re-sync only when versions diverge",cmd:"coze self skill status --format json | jq -e .versionMatch >/dev/null || coze self skill install",tags:["[PIPELINE]"]}],schema:{output:{lockExists:{type:"boolean",description:"Whether `~/.coze/cli/.skill-lock.json` exists (false = never synced)"},cliVersion:{type:"string",description:"Current CLI version",example:"0.1.0"},installedVersion:{type:"string",required:!1,description:"CLI version recorded at the last sync"},versionMatch:{type:"boolean",description:"Whether installedVersion equals cliVersion"},installedBin:{type:"string",required:!1,description:"CLI binary path recorded at the last sync"},currentBin:{type:"string",description:"CLI binary path of the current process"},binMatch:{type:"boolean",description:"Whether the current binary performed the last sync"},poolPath:{type:"string",required:!1,description:"Skill path inside the skills central pool; absent when not installed"},targets:{type:"array",items:{type:"string"},description:"Agents linked at the last sync"},skills:{type:"array",description:"Per-skill consistency state",items:{type:"object",properties:{name:{type:"string",description:"Skill name"},path:{type:"string",description:"Path relative to the bundled skills root"},state:{type:"string",enum:["ok","drift","modified","missing"],description:"ok = matches current CLI, drift = matches an older sync, modified = user-edited, missing = not in the pool"}}}}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing (no packaged skills/manifest.json and no dev-mode docs/skills), so there is no baseline to compare against",fix:"Reinstall or upgrade the CLI to restore the bundled skills",example:"coze upgrade"}],seeAlso:["coze self skill install","coze self skill list","coze self skill remove"]},Cy={ok:"ok",drift:"version drift",modified:"user-modified",missing:"missing"};function Iy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Ay(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Sy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ky=t=>{const o=t.command("skill").description("Install CLI-bundled skills to your AI tools and keep versions aligned").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Manage CLI-bundled skills",description:"Sync the skills bundled with the current CLI via the `skills` tool into the shared central pool (`~/.agents/skills/`) and fan out symlinks to installed AI agents (Claude Code / Trae / Comate). Skill version is strictly equal to the CLI version, eliminating drift at the source.",examples:[{desc:"Install skills to all installed agents",cmd:"coze self skill install",tags:["[RECOMMENDED]"]},{desc:"Check skill/CLI version consistency",cmd:"coze self skill status"},{desc:"Print a bundled skill",cmd:"coze self skill show using-coze-cli"},{desc:"Uninstall installed skills from all agents",cmd:"coze self skill remove"}],seeAlso:["coze upgrade","coze code skill"]}});(e=>{e.command("install").description("Sync bundled skills into the shared pool and fan out symlinks to agents").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:by}).option("--target <names>","Comma-separated agents to install to (claude,trae,comate,all)").option("--force","Overwrite user-modified skills").action((async(e,t)=>{const o=t.getContext(),i="string"==typeof e.target?e.target.split(",").map((e=>e.trim())).filter(Boolean):void 0,s=await Je({targets:i,force:Boolean(e.force)});if(s.blocked)return yy([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Detected user-modified skills: ${s.modifiedSkills.join(", ")}.\nUse \`coze self skill install --force\` to overwrite them.`)]),void("json"===yy([o,"optionalAccess",e=>e.format])&&o.response.print(s));if(s.unknownTargets.length>0&&yy([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Unknown targets ignored: ${s.unknownTargets.join(", ")}`)]),s.linkedTargets.length>0){const e=10,t=[...s.linkedTargets].sort(((e,t)=>e.localeCompare(t))),i=t.length>e?`${t.slice(0,e).join(", ")} +${t.length-e} more`:t.join(", ");yy([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Installed skill (v${s.cliVersion}) to ${t.length} agent(s): ${i}`)]),yy([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Note: agents share `~/.agents/skills`; being listed means they can read the skill, not a per-agent copy.")])}else yy([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Installed skill (v${s.cliVersion}). No installed agent detected to link.`)]);s.skillsOk||yy([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e("The `skills` tool reported a partial failure; run `coze self skill install` again or check `coze self skill path`.")]),"json"===yy([o,"optionalAccess",e=>e.format])&&o.response.print(s)}))})(o),(e=>{e.command("status").description("Show installed skill version vs current CLI version").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:Ey}).action((async(e,t)=>{const o=t.getContext(),i=await Qe();if("json"!==wy([o,"optionalAccess",e=>e.format]))if(i.lockExists){wy([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Current CLI version : ${i.cliVersion}`)]),wy([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Installed skill ver : ${vy(i.installedVersion,(()=>"unknown"))}`)]),i.versionMatch?wy([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Version match: skills are consistent with the CLI.")]):wy([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Version mismatch: skills(${i.installedVersion}) ≠ CLI(${i.cliVersion}). Run \`coze self skill install\`.`)]),i.binMatch||wy([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Installed by a different binary (${i.installedBin}); current is ${i.currentBin}.`)]),wy([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Linked agents : ${i.targets.join(", ")||"(none)"}`)]);for(const e of i.skills){const t=vy(Cy[e.state],(()=>e.state));wy([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",o=>o(` - ${e.name}: ${t}`)])}}else wy([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e("No skills installed yet. Run `coze self skill install` to install the bundled skills.")]);else o.response.print(i)}))})(o),(t=>{t.command("list").description("List the skills bundled with this CLI").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"List bundled skills",description:"List every skill bundled with the current CLI, with its name and relative path. Version equals the CLI version. Fully local and read-only: no network access and no files are written.",examples:[{desc:"List bundled skills (minimal)",cmd:"coze self skill list",tags:["[RECOMMENDED]"]},{desc:"List bundled skills as JSON",cmd:"coze self skill list --format json"},{desc:"Extract skill names for scripting",cmd:"coze self skill list --format json | jq -r '.skills[].name'",tags:["[PIPELINE]"]},{desc:"Print the first bundled skill in full",cmd:"coze self skill show $(coze self skill list --format json | jq -r '.skills[0].name')",tags:["[PIPELINE]"]}],schema:{output:{cliVersion:{type:"string",description:"Current CLI version (equals the skill version)",example:"0.1.0"},skills:{type:"array",description:"Bundled skills",items:{type:"object",properties:{name:{type:"string",description:"Skill name"},path:{type:"string",description:"Path relative to the bundled skills root"},version:{type:"string",description:"Skill version (equals cliVersion)"}}}}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing (no packaged skills/manifest.json and no dev-mode docs/skills), which indicates a corrupted CLI installation",fix:"Reinstall or upgrade the CLI to restore the bundled skills",example:"coze upgrade"}],seeAlso:["coze self skill show","coze self skill install","coze self skill status"]}}).action((async(e,t)=>{const o=t.getContext(),{manifest:i}=await Ne(),s=Object.entries(i.skills).map((([e,t])=>({name:e,path:t.path,version:i.cliVersion})));if("json"!==Sy([o,"optionalAccess",e=>e.format])){Sy([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Bundled skills (v${i.cliVersion}):`)]);for(const e of s)Sy([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",t=>t(` - ${e.name} (${e.path})`)])}else o.response.print({cliVersion:i.cliVersion,skills:s})}))})(o),(t=>{t.command("show <name>").description("Print a bundled skill in full (always matches current CLI)").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Print a bundled skill",description:"Print the full content of the named skill bundled with the current CLI. Since the skill ships with the CLI, its version always matches — a zero-drift pull-based fallback for any agent.",examples:[{desc:"Print the shared skill (minimal)",cmd:"coze self skill show using-coze-cli",tags:["[RECOMMENDED]"]},{desc:"Print a skill as JSON with metadata",cmd:"coze self skill show using-coze-cli --format json"},{desc:"Print the first bundled skill in full",cmd:"coze self skill show $(coze self skill list --format json | jq -r '.skills[0].name')",tags:["[PIPELINE]"]}],schema:{input:{name:{type:"string",required:!0,description:"Skill name from `coze self skill list`",example:"using-coze-cli"}},output:{name:{type:"string",description:"Skill name",example:"using-coze-cli"},path:{type:"string",description:"Path relative to the bundled skills root",example:"using-coze-cli/SKILL.md"},version:{type:"string",description:"Skill version (equals the CLI version)",example:"0.1.0"},content:{type:"string",description:"Full skill content; in text mode the content is printed raw to stdout instead"}}},errors:[{code:e.ErrorCode.E3002,name:"SKILL_NOT_FOUND",desc:"The given name does not match any skill bundled with this CLI",fix:"Run `coze self skill list` and use one of the listed names",example:"coze self skill show using-coze-cli"},{code:e.ErrorCode.E1102,name:"MISSING_ARGUMENT",desc:"The required <name> argument was not provided",fix:"Pass the skill name as the first positional argument",example:"coze self skill show using-coze-cli"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing or the skill content file listed in the manifest cannot be read (corrupted CLI installation)",fix:"Reinstall or upgrade the CLI to restore the bundled skills",example:"coze upgrade"}],seeAlso:["coze self skill list","coze self skill install","coze self skill path"]}}).action((async(e,t,o)=>{const i=o.getContext(),{manifest:s,files:n}=await Ne(),r=s.skills[e];if(!r){const t=Object.keys(s.skills).join(", ");return void Iy([i,"optionalAccess",e=>e.ui,"access",e=>e.error,"call",o=>o(`Skill not found: "${e}".\nAvailable skills: ${t}\nRun \`coze self skill list\` to see all.`)])}const a=n.find((e=>e.rel===r.path));a?"json"!==Iy([i,"optionalAccess",e=>e.format])?(process.stdout.write(a.content),a.content.endsWith("\n")||process.stdout.write("\n")):i.response.print({name:e,path:r.path,version:s.cliVersion,content:a.content}):Iy([i,"optionalAccess",e=>e.ui,"access",e=>e.error,"call",t=>t(`Skill content missing for "${e}" (${r.path}).`)])}))})(o),(t=>{t.command("path").description("Print the bundled skill source and the skills pool path").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Print skill paths",description:"Print the bundled skill source directory (the `skills add` input) and the skills central pool path that agents symlink to. Fully local and read-only: no network access and no files are written. The pool path is only available after `coze self skill install` has run at least once.",examples:[{desc:"Print skill paths (minimal)",cmd:"coze self skill path",tags:["[RECOMMENDED]"]},{desc:"Print skill paths as JSON",cmd:"coze self skill path --format json"},{desc:"Inspect the bundled skill source directory",cmd:"ls $(coze self skill path --format json | jq -r .sourceRoot)",tags:["[PIPELINE]"]}],schema:{output:{sourceRoot:{type:"string",description:"Absolute path of the bundled skill source directory",example:"~/.nvm/versions/node/v20/lib/node_modules/@coze/cli/skills"},source:{type:"string",enum:["bundled","docs"],description:"Where the source was resolved from: bundled = packaged artifact, docs = dev-mode docs/skills fallback",example:"bundled"},poolPath:{type:"string",required:!1,description:"Skill path inside the skills central pool; absent until `coze self skill install` has run",example:"~/.agents/skills/using-coze-cli"}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing (no packaged skills/manifest.json and no dev-mode docs/skills), which indicates a corrupted CLI installation",fix:"Reinstall or upgrade the CLI to restore the bundled skills",example:"coze upgrade"}],seeAlso:["coze self skill install","coze self skill list","coze self skill status"],caveats:['In text mode, the pool line prints "(not synced yet)" when `coze self skill install` has never run; in JSON mode, poolPath is omitted in that case']}}).action((async(e,t)=>{const o=t.getContext(),{root:i,source:s}=await Be(),n=await Qe();var r,a;"json"!==function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([o,"optionalAccess",e=>e.format])?(process.stdout.write(`source: ${i}\n`),process.stdout.write(`pool : ${r=n.poolPath,a=()=>"(not synced yet)",null!=r?r:a()}\n`)):o.response.print({sourceRoot:i,source:s,poolPath:n.poolPath})}))})(o),(t=>{t.command("remove").description("Uninstall synced skills (skills remove + lock)").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Uninstall synced skills",description:"Delegate to `skills remove` to drop the agent symlinks and the central pool entry for every CLI-bundled skill, then delete `~/.coze/cli/.skill-lock.json`. Skills that are not present in the pool are skipped. Idempotent: running it again after a full removal is a no-op. Re-install at any time with `coze self skill install`.",examples:[{desc:"Uninstall skills (minimal)",cmd:"coze self skill remove",tags:["[RECOMMENDED]"]},{desc:"Uninstall and print the result as JSON",cmd:"coze self skill remove --format json"},{desc:"Uninstall then verify nothing is installed",cmd:"coze self skill remove && coze self skill status",tags:["[PIPELINE]"]}],schema:{output:{removed:{type:"array",description:"Skill units removed via `skills remove`",items:{type:"object",properties:{name:{type:"string",description:"Removed skill unit name"},agents:{type:"array",items:{type:"string"},description:"Agents the skill had been symlinked to before removal"}}}}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing (no packaged skills/manifest.json and no dev-mode docs/skills), so the skill list to remove cannot be resolved",fix:"Reinstall or upgrade the CLI to restore the bundled skills",example:"coze upgrade"}],seeAlso:["coze self skill install","coze self skill status","coze self skill path"],caveats:["Removes the skill for every linked agent at once; there is no per-agent removal","The skill lock file is deleted even when no skill unit was found in the pool"]}}).action((async(e,t)=>{const o=t.getContext(),i=await Ye();if("json"!==Ay([o,"optionalAccess",e=>e.format])){for(const e of i.removed)Ay([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",t=>t(`Removed ${e.name} from: ${e.agents.join(", ")||"(none)"}`)]);Ay([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Uninstalled skills and removed the skill lock.")])}else o.response.print(i)}))})(o)};function jy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Py=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},zy=t=>{if(e.isHttpError(t)&&("object"==typeof(o=t.data)&&null!==o&&("code"in o||"msg"in o||"data"in o)))return t.data;var o;throw t},Ty=e=>{if(null!=e&&!1!==e)return Array.isArray(e)?e.map(String).join(","):String(e)},Ry=(e,t)=>{const o=jy([e,"optionalAccess",e=>e.get,"optionalCall",e=>e(t)]),i=Ty(o);if(i)return i;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 Ty(t)},xy=t=>{return{baseURL:t.baseUrl,transformResponse:[...(o=e.axiosInstance$1.defaults.transformResponse,o?Array.isArray(o)?o:[o]:[]),(e,o)=>{const i=(e=>Ry(e,"x-tt-logid")||Ry(e,"x-tt-log-id")||Ry(e,"logid"))(o);return i&&jy([t,"access",e=>e.onGetLogId,"optionalCall",e=>e(i)]),e}]};var o},Ly=(t,o)=>{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 ${o}`)},Oy=async(t,o)=>{const i=s.createSessionApiClient({baseUrl:t.baseUrl,webOrigin:t.baseUrl,xTTEnv:t.xTTEnv}),{accountId:r,ownerUid:a}=await(async(e,t)=>{const o=jy([Py(await s.Claw.GetProjectInfo({project_id:t},xy(e))),"access",e=>e.data,"optionalAccess",e=>e.session]);return{accountId:Ly(jy([o,"optionalAccess",e=>e.account_id]),"account_id"),ownerUid:Ly(jy([o,"optionalAccess",e=>e.owner_uid]),"owner_uid")}})(t,o.projectId),c=`${a}_${r}/project_${o.projectId}-files${o.projectFilePath}`,l=await i.getUrl({uris:[c]},{headers:s.getCozeAccountHeaders(t.organizationId),onGetLogId:t.onGetLogId}),d=jy([l,"access",e=>e.data,"optionalAccess",e=>e.urls,"optionalAccess",e=>e[0]]);if(!d)throw new e.CozeError(e.ErrorCode.E5002,l.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",d);const u=n.basename(o.projectFilePath)||"agent-file.bin",m=await Eg({url:p.toString(),outputPath:n.join(o.localDir,u)});return m.logid&&jy([t,"access",e=>e.onGetLogId,"optionalCall",e=>e(m.logid)]),{...m,fileUrl:d,projectFilePath:o.projectFilePath,resolvedUri:c}};function Dy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Uy={skipOrgCheck:!0,skipSpaceCheck:!0},qy=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},By=e=>Dy([e,"optionalAccess",e=>e.trim,"call",e=>e()])||"/",My=(t,o)=>{const i=Number.parseInt(t,10);if(!Number.isFinite(i)||i<=0||String(i)!==t)throw new e.CozeError(e.ErrorCode.E1000,`Invalid value for ${o}: expected a positive integer, got "${t}"`);return i},Ny=t=>{if(!t)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");return t.config.sessionApiBaseUrl||t.config.apiBaseUrl},$y=()=>{let e="";return{capture:t=>{const o=Dy([t,"optionalAccess",e=>e.trim,"call",e=>e()]);o&&(e=o)},get:()=>e}},Gy=(e,t)=>{const o=t.get();return"object"!=typeof(i=e)||null===i||Array.isArray(i)?{data:e,logid:o}:{...e,logid:o};var i};function Fy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Vy={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"}]},Wy={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"}}},Hy={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"}}},Jy=t=>{const o=Fy([t,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!o)throw new e.CozeError(e.ErrorCode.E1000,"The --agent-id option is required.");return o},Ky=t=>{const o=t.command("web").description("Use Coze agent web tools").config({...Uy,help:Vy});o.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({...Uy,help:Wy}).action((async(t,o)=>{const i=new $s({format:"json"}),n=$y();try{const r=Jy(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 o=e.safeJsonParse(t,void 0);if(void 0===o)throw new e.CozeError(e.ErrorCode.E1000,"Invalid --query-list: expected a JSON string array.");if(!Array.isArray(o)||o.some((e=>"string"!=typeof e)))throw new e.CozeError(e.ErrorCode.E1000,"Invalid --query-list: expected a JSON string array.");const i=o.map((e=>e.trim())).filter((e=>e.length>0)).slice(0,5);if(0===i.length)throw new e.CozeError(e.ErrorCode.E1000,"Invalid --query-list: expected at least one non-empty query.");return i})(t.queryList),c=o.getContext(),l=Ny(c),d=await(async(e,t)=>{try{return await s.Claw.AgentWebSearch({agent_id:t.agentId,query_list:t.queryList,project_id:t.projectId},xy(e))}catch(e){return zy(e)}})({baseUrl:l,onGetLogId:n.capture},{agentId:r,queryList:a,projectId:t.projectId});i.print(Gy(d,n))}catch(e){Q(e,o.getContext())}})),o.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({...Uy,help:Hy}).action((async(t,o)=>{const i=new $s({format:"json"}),n=$y();try{const r=Jy(t.agentId),a=(t=>{const o=Fy([t,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!o)throw new e.CozeError(e.ErrorCode.E1000,"The --url option is required.");let i;try{i=new URL(o)}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:"!==i.protocol&&"https:"!==i.protocol)throw new e.CozeError(e.ErrorCode.E1000,"Invalid --url: expected an http:// or https:// URL.");return o})(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),l=o.getContext(),d=Ny(l),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},xy(e))}catch(e){return zy(e)}})({baseUrl:d,onGetLogId:n.capture},{agentId:r,url:a,responseLength:c,projectId:t.projectId});i.print(Gy(p,n))}catch(e){Q(e,o.getContext())}}))},Qy={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>"}]},Yy={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"}}},Zy=e=>{e.command("message").description("Manage Coze agent messages").config({...Uy,help:Qy}).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({...Uy,help:Yy}).action((async(e,t)=>{const o=new $s({format:"json"});try{const i=qy(e.projectId),n=e.size?My(e.size,"--size"):void 0,r=t.getContext(),a=Ny(r),c=await(async(e,t)=>{const o={session_id:t.projectId};return void 0!==t.cursor&&(o.cursor=t.cursor),void 0!==t.size&&(o.size=t.size),void 0!==t.ascMode&&(o.asc_mode=t.ascMode),void 0!==t.needReference&&(o.need_reference=t.needReference),void 0!==t.conversationId&&(o.conversation_id=t.conversationId),Py(await s.Claw.ListMessage(o,xy(e)))})({baseUrl:a},{projectId:i,cursor:e.cursor,size:n,ascMode:e.ascMode,needReference:e.needReference,conversationId:e.conversationId});o.print(c)}catch(e){Q(e,t.getContext())}}))},Xy=e=>{e.command("member").description("Manage Coze agent members").config({...Uy,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({...Uy,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 o=new $s({format:"json"});try{const i=qy(e.projectId),n=t.getContext(),r=Ny(n),a=await(async(e,t)=>Py(await s.Claw.GetProjectMembers({project_id:t.projectId},xy(e))))({baseUrl:r},{projectId:i});o.print(a)}catch(e){Q(e,t.getContext())}}))},eb=e=>{e.command("info").description("Get raw Coze agent info as JSON").requiredOption("--project-id <projectId>","The agent project ID").config({...Uy,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 o=new $s({format:"json"});try{const i=qy(e.projectId),n=t.getContext(),r=Ny(n),a=await(async(e,t)=>Py(await s.Claw.GetProjectInfo({project_id:t.projectId},xy(e))))({baseUrl:r},{projectId:i});o.print(a)}catch(e){Q(e,t.getContext())}}))};function tb(e,t){return null!=e?e:t()}function ob(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ib=t=>{if(t instanceof e.CozeError)return tb(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)}},sb=(e,t,o)=>{t.print({ok:!1,err_reason:ib(e),logid:tb(ob([o,"optionalAccess",e=>e.get,"call",e=>e()]),(()=>""))}),process.exitCode=1};function nb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const rb={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"}}},ab=(e,t)=>{const o=nb([e,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!o||"/"===o)return`/${t}`;return`${(o.startsWith("/")?o:`/${o}`).replace(/\/+$/,"")}/${t}`},cb=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({...Uy,help:rb}).action((async(t,o)=>{const i=new $s({format:"json"}),c=$y();try{const p=qy(t.projectId),u=((t,o)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${o}`);return t})(t.localFilePath,"--local-file-path");await(async t=>{try{await r.access(t)}catch(o){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${t}${o instanceof Error?` (${o.message})`:""}`)}})(u);const m=o.getContext(),g=Ny(m),h=n.basename(u),f=By(t.projectDir);await(async(e,t)=>{return Py(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:(o=t.clawId,i=()=>"",null!=o?o:i())},{onGetLogId:e.onGetLogId}));var o,i})({baseUrl:g,xTTEnv:nb([m,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv]),onGetLogId:c.capture},{projectId:p,fileName:h,fileContent:await a.openAsBlob(u),projectDir:f,clawId:(l=t.clawId,d=()=>"",null!=l?l:d())}),i.print(Gy({ok:!0,project_file_path:ab(f,h)},c))}catch(e){sb(e,i,c)}var l,d}))};function lb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const db={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"}}},pb=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({...Uy,help:db}).action((async(t,o)=>{const i=new $s({format:"json"}),s=$y();try{const n=qy(t.projectId),r=((t,o)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${o}`);return t})(t.projectFilePath,"--project-file-path"),a=o.getContext(),c=lb([a,"optionalAccess",e=>e.cwd])||process.cwd(),l=await Oy({baseUrl:Ny(a),organizationId:lb([a,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),xTTEnv:lb([a,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv]),onGetLogId:s.capture},{projectId:n,projectFilePath:r,localDir:c});i.print(Gy({ok:!0,local_file_path:l.path},s))}catch(e){sb(e,i,s)}}))};function ub(e,t){return null!=e?e:t()}function mb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const gb={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"}]},hb={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"}}},fb={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"}}},_b={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"}}},yb={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"}}},bb=(t,o)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${o}`);return t},vb=e=>e.startsWith("/")?e:`/${e}`,wb=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({...Uy,help:hb}).action((async(e,t)=>{const o=new $s({format:"json"}),i=$y();try{const n=qy(e.projectId),r=e.depth?My(e.depth,"--depth"):void 0,a=t.getContext(),c=Ny(a),l=By(e.projectDir),d=await(async(e,t)=>Py(await s.Claw.ListProjectFiles({project_id:t.projectId,file_path:t.filePath,depth:t.depth},xy(e))))({baseUrl:c,onGetLogId:i.capture},{projectId:n,filePath:l,depth:r});o.print(Gy((e=>({ok:!0,files:ub(mb([e,"access",e=>e.data,"optionalAccess",e=>e.files]),(()=>[])).map((e=>({path:vb(e.file_path||e.name||""),type:e.is_dir?"dir":"file"})))}))(d),i))}catch(e){sb(e,o,i)}}))},Eb=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({...Uy,help:fb}).action((async(e,t)=>{const o=new $s({format:"json"}),i=$y();try{const n=qy(e.projectId),r=bb(e.projectFilePath,"--project-file-path"),a=bb(e.content,"--content"),c=t.getContext(),l=Ny(c),d=await(async(e,t)=>Py(await s.Claw.WriteProjectFile({project_id:t.projectId,file_path:t.filePath,content:t.content},xy(e))))({baseUrl:l,onGetLogId:i.capture},{projectId:n,filePath:r,content:a});o.print(Gy(d,i))}catch(e){sb(e,o,i)}}))},Cb=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({...Uy,help:_b}).action((async(e,t)=>{const o=new $s({format:"json"}),i=$y();try{const n=qy(e.projectId),r=bb(e.projectFilePath,"--project-file-path"),a=e.offset?My(e.offset,"--offset"):void 0,c=e.limit?My(e.limit,"--limit"):void 0,l=t.getContext(),d=Ny(l),p=await(async(e,t)=>{const o={project_id:t.projectId,file_path:t.filePath};return void 0!==t.offset&&(o.offset=t.offset),void 0!==t.limit&&(o.limit=t.limit),Py(await s.Claw.ReadProjectFile(o,xy(e)))})({baseUrl:d,onGetLogId:i.capture},{projectId:n,filePath:r,offset:a,limit:c});o.print(Gy({ok:!0,project_file_path:r,content:ub(mb([p,"access",e=>e.data,"optionalAccess",e=>e.content]),(()=>""))},i))}catch(e){sb(e,o,i)}}))},Ib=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({...Uy,help:yb}).action((async(e,t)=>{const o=new $s({format:"json"}),i=$y();try{const n=qy(e.projectId),r=bb(e.projectFilePath,"--project-file-path"),a=bb(e.mode,"--mode"),c=t.getContext(),l=Ny(c),d=await(async(e,t)=>{const o={project_id:t.projectId,file_path:t.filePath,mode:t.mode};return void 0!==t.oldString&&(o.old_string=t.oldString),void 0!==t.newString&&(o.new_string=t.newString),void 0!==t.appendContent&&(o.append_content=t.appendContent),Py(await s.Claw.EditProjectFile(o,xy(e)))})({baseUrl:l,onGetLogId:i.capture},{projectId:n,filePath:r,mode:a,oldString:e.oldString,newString:e.newString,appendContent:e.appendContent});o.print(Gy(d,i))}catch(e){sb(e,o,i)}}))},Ab=e=>{const t=e.command("agent").description("Agent-facing Coze APIs backed by Claw project endpoints").config({...Uy,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"}]}});eb(t),Xy(t),Zy(t),(e=>{const t=e.command("file").description("Manage Coze agent project files").config({...Uy,help:gb});wb(t),Eb(t),Cb(t),Ib(t),cb(t),pb(t)})(t),Ky(t)};function Sb(t){!function(t){const o=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",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"]}});o.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",tags:["[RECOMMENDED]"]}],errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Authentication failed",fix:"Please try again with `coze auth login`."}],seeAlso:["coze auth status","coze auth logout"]}}).addOption(new w.Option("--token <PAT>","Login using an access token").hideHelp()).addOption(new w.Option("--oauth","Start browser-based OAuth device authorization flow").hideHelp()).action((async function(t,o){const i=o.getContext();if(!i)return void Q(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"));await i.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,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}}([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])})),o.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",tags:["[RECOMMENDED]"]}],seeAlso:["coze auth login","coze auth status"]}}).action((async(t,o)=>{const i=o.getContext();i?await i.auth.logout():Q(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))})),o.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` to authenticate."}],seeAlso:["coze auth login","coze auth logout"]}}).action((async(t,o)=>{const i=o.getContext();i?await i.auth.status():Q(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))}))}(t),fy(t),kl(t),yg(t),cl(t),Sa(t),Pa(t),rl(t),ml(t),_y(t),(e=>{const t=e.command("self").description("Manage the Coze CLI itself").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Manage the Coze CLI itself",description:"Home for capabilities of the Coze CLI tool itself, as opposed to commands that operate on Coze platform resources. Currently hosts `skill`, which manages the CLI-bundled skills on the local machine.",examples:[{desc:"Install bundled skills to all installed AI agents",cmd:"coze self skill install",tags:["[RECOMMENDED]"]},{desc:"Check skill/CLI version consistency",cmd:"coze self skill status"}],seeAlso:["coze upgrade","coze completion","coze config"]}});ky(t)})(t),Ab(t),jl()}function kb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function jb(e,t){return null!=e?e:t()}function Pb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function zb(e){const t=Pb([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]);let o=`@HELP ${xb(e)}\n\n`;Pb([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: ${xb(e.parent)}\n\n`),o+=`SYNTAX:\n ${Rb(e)}\n\n`,Pb([t,"optionalAccess",e=>e.description])&&(o+=`DESCRIPTION:\n ${t.description.replace(/\n/g,"\n ")}\n\n`),o+=Tb(e,"AVAILABLE COMMANDS:");const i=e._args,s=Ob(e);if((i.length>0||s.length>0)&&(o+="OPTIONS:\n",o+=" Name Type Required Default Description\n",o+=" ─────────────────────────────────────────────────────────\n",i.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(8)} ${s.padEnd(10)} ${n}\n`})),s.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()||e.negate)&&(r="flag");const a=e.mandatory?"Yes":"No",c=void 0!==e.defaultValue?String(e.defaultValue):"-",l=e.description||"";o+=` ${n.padEnd(16)} ${r.padEnd(10)} ${a.padEnd(8)} ${c.padEnd(10)} ${l}\n`})),o+="\n"),e.parent){const t=function(e){const t=[];let o=e.parent;for(;o;){for(const e of o.options){const o=jb(e.long,(()=>e.flags));e.hidden||"--version"===o||!Lb.has(o)||t.includes(o)||t.push(o)}o=o.parent}return t}(e);t.length>0&&(o+="INHERITED OPTIONS:\n",o+=` ${t.join(", ")}\n`,o+=" (see: coze --help)\n\n")}return Pb([t,"optionalAccess",e=>e.enums])&&(o+="ENUMS:\n",Object.keys(t.enums).forEach((e=>{o+=` --${e}:\n`;const i=jb(Pb([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})));Object.keys(i).forEach((e=>{o+=` ${e.padEnd(12)} ${i[e]}\n`}))})),o+="\n"),Pb([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`}))),Pb([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"),Pb([t,"optionalAccess",e=>e.seeAlso])&&t.seeAlso.length>0&&(o+="SEE ALSO:\n",t.seeAlso.forEach((e=>{o+=` ${e}\n`})),o+="\n"),o.trimEnd()}function Tb(e,t){const o=e.commands.filter((e=>!e._hidden));if(0===o.length)return"";const i=Math.max(10,...o.map((e=>e.name().length)));let s=`${t}\n`;return o.forEach((e=>{const t=e,o=Pb([t,"access",e=>e.getConfig,"optionalCall",e=>e(),"optionalAccess",e=>e.help,"optionalAccess",e=>e.brief])||t.description()||"";s+=` ${t.name().padEnd(i)} ${o}\n`})),`${s}\n`}function Rb(e,t=!0){const o=[xb(e)];e.commands.length>0&&o.push("<command>");const i=function(e){return e._args.map((e=>e.required?`<${e.name()}>`:`[${e.name()}]`)).join(" ")}(e);return i&&o.push(i),t&&o.push("[options]"),o.join(" ")}function xb(e){const t=[];let o=e;for(;o;)o.name()&&t.unshift(o.name()),o=o.parent;return t.join(" ")}const Lb=new Set(["--version","--format","--no-color","--config","--org-id","--space-id","--verbose","--debug","--log-file","--man","--schema","--commands"]);function Ob(e){const t=new Map,o=[];let i=e;for(;i;)o.unshift(i),i=i.parent;for(const i of o)for(const o of i.options){const s=jb(o.long,(()=>o.flags)),n=i!==e&&Lb.has(s);!s||o.hidden||t.has(s)||n||t.set(s,o)}return Array.from(t.values())}function Db(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class Ub extends w.Command{__init(){this.middlewares=[]}constructor(e){super(e),Ub.prototype.__init.call(this),this.helpInformation=()=>{const e=process.argv.slice(2);if(e.includes("--schema"))return`${JSON.stringify(Db([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=Pb([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),o=xb(e);let i=`@MAN ${o}\n\n`;i+=`NAME\n ${o} — ${Pb([t,"optionalAccess",e=>e.brief])||e.description()}\n\n`,i+=`SYNOPSIS\n ${Rb(e,!1)}\n`,Ob(e).forEach((e=>{i+=` [${e.flags}]\n`})),i+="\n",Pb([t,"optionalAccess",e=>e.description])&&(i+=`DESCRIPTION\n ${t.description.replace(/\n/g,"\n ")}\n\n`);const s=Tb(e,"COMMANDS");s&&(i+=s);const n=Ob(e);return n.length>0&&(i+="OPTIONS\n",n.forEach((e=>{const t=e.flags.split(", "),o=t.find((e=>e.startsWith("-")&&!e.startsWith("--")))||"",s=t.find((e=>e.startsWith("--")))||"";i+=` ${o?`${s}, ${o}`:s}\n`,i+=` Type: ${e.isBoolean()?"flag":"string"}\n`,i+=` Required: ${e.mandatory?"yes":"no"}\n`,i+=` Default: ${void 0!==e.defaultValue?String(e.defaultValue):"-"}\n`,i+=` Desc: ${e.description}\n\n`}))),Pb([t,"optionalAccess",e=>e.schema])&&(i+="SCHEMA\n",t.schema.input&&(i+=` Input:\n ${JSON.stringify(t.schema.input,null,2).replace(/\n/g,"\n ")}\n`),t.schema.output&&(i+=` Output:\n ${JSON.stringify(t.schema.output,null,2).replace(/\n/g,"\n ")}\n`),i+="\n"),Pb([t,"optionalAccess",e=>e.errors])&&t.errors.length>0&&(i+="ERRORS\n",i+=" CODE NAME TRIGGER RECOVERY\n",t.errors.forEach((e=>{i+=` ${e.code.padEnd(6)} ${e.name.padEnd(17)} ${e.desc.padEnd(37)} ${e.fix}\n`})),i+="\n"),Pb([t,"optionalAccess",e=>e.caveats])&&t.caveats.length>0&&(i+="CAVEATS\n",t.caveats.forEach((e=>{i+=` - ${e}\n`})),i+="\n"),Pb([t,"optionalAccess",e=>e.seeAlso])&&t.seeAlso.length>0&&(i+="SEE ALSO\n",t.seeAlso.forEach((e=>{i+=` ${e}\n`})),i+="\n"),i.trimEnd()}(this)}\n`;return e.includes("-h")||e.includes("--help")?`${zb(this)}\n`:`${function(e){const t=Pb([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]);let o=`@USAGE ${xb(e)}\n\n`;Pb([t,"optionalAccess",e=>e.brief])?o+=`BRIEF: ${t.brief}\n\n`:o+=`BRIEF: ${e.description()||"No description provided."}\n\n`,o+=`SYNTAX:\n ${Rb(e)}\n\n`,o+=Tb(e,"AVAILABLE COMMANDS:"),Pb([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(Pb([t,"optionalAccess",e=>e.enums])){const e=Object.keys(t.enums).filter((e=>Object.keys(jb(Pb([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})))).length<=7));e.length>0&&(o+="ENUMS:\n",e.forEach((e=>{const i=Object.keys(jb(Pb([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 Ub(e);return this.context&&t.setContext(this.context),t}action(e){return super.action((async(...t)=>{const o=this.getContext();let i={},s=[];const n=t.length>0&&t[t.length-1]instanceof Ub?t[t.length-1]:this;var r,a;if(t.length>=2&&(r=t[t.length-2],a=()=>({}),i=null!=r?r:a(),s=t.slice(0,t.length-2)),o&&(i&&(o.options=i),s&&(o.args=s),n)){o.commandName=n.name();const e=Db([n,"access",e=>e.getConfig,"optionalCall",e=>e()]);e&&(o.commandConfig=e),n.setContext(o)}if(this.middlewares.length>0&&o){const i=gi(this.middlewares);await i(o,(async()=>{await e.apply(this,t)}))}else await e.apply(this,t)}))}}function qb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Bb(e){e.exitOverride(),e.outputError=()=>{},e.commands.forEach((e=>Bb(e)))}async function Mb(t){const o=new Ub;o.name("coze").description("Coze Coding CLI").version(Z,"-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"),o.config({help:{brief:"Coze Coding CLI",description:"Command-line interface for the Coze platform. Manage Coze Coding projects (create, iterate, deploy), claw chat sessions, media generation (image, audio, video), file uploads, and local CLI configuration.\nMost commands require authentication first: run `coze auth login`.",examples:[{desc:"Log in to Coze",cmd:"coze auth login"},{desc:"Create a new Coze Coding project",cmd:'coze code project create --message "Create a chatbot" --type web'},{desc:"Deploy a project to production",cmd:"coze code deploy <projectId>"},{desc:"Generate an image from a prompt",cmd:'coze generate image "A cat in space"'},{desc:"Upload a local file and get an online URL",cmd:"coze file upload ./report.pdf"}],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"}]}}),Sb(o),await Sl(t.config),function(e,t,o){const i=new Set;e.setContext(o),function e(s){i.has(s)||(i.add(s),s.setContext(o),t.forEach((e=>s.use(e))),s.commands.forEach((t=>{const o=kb([s,"access",e=>e.getConfig,"optionalCall",e=>e()]),i=kb([t,"access",e=>e.getConfig,"optionalCall",e=>e()]);t.setConfig({...o,...i}),e(t)})))}(e)}(o,[Ws,wa],t),process.on("uncaughtException",(e=>{Q(e,t)})),process.on("unhandledRejection",(e=>{Q(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")),Bb(o);try{await o.parseAsync(t.argv,{from:"user"})}catch(n){const r=n,a=function(e,t,o){let i=e;if(t.command)i=t.command;else if(o.commandName){const t=(e,o)=>{if(e.name()===o)return e;for(const i of e.commands){const e=t(i,o);if(e)return e}return null},s=t(e,o.commandName);s&&(i=s)}let s=e;for(const e of o.argv){if(e.startsWith("-"))break;const t=s.commands.find((t=>t.name()===e));t&&(s=t,i=s)}return i}(o,r,t);"commander.helpDisplayed"!==r.code&&"commander.help"!==r.code&&"commander.version"!==r.code||process.exit(e.ExitCode.SUCCESS);const c=qb([a,"access",e=>e.getConfig,"optionalCall",e=>e()]),l=qb([o,"access",e=>e.getConfig,"optionalCall",e=>e()]);if(t.commandConfig=(s=()=>l,null!=(i=c)?i:s()),"commander.unknownOption"===r.code){const o=W(new e.CozeError(e.ErrorCode.E1100,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),process.exit(e.exitCodeForError(o.code))}if("commander.unknownCommand"===r.code){const o=W(new e.CozeError(e.ErrorCode.E1101,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),process.exit(e.exitCodeForError(o.code))}if("commander.missingArgument"===r.code){const o=W(new e.CozeError(e.ErrorCode.E1102,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),"json"!==t.format&&process.stderr.write(`\n${a.helpInformation()}`),process.exit(e.exitCodeForError(o.code))}if("commander.missingMandatoryOptionValue"===r.code||"commander.optionMissingArgument"===r.code){const o=W(new e.CozeError(e.ErrorCode.E1103,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),"json"!==t.format&&process.stderr.write(`\n${a.helpInformation()}`),process.exit(e.exitCodeForError(o.code))}Q(r,t)}var i,s}(async function(){const e=process.argv.slice(2),{globalOptions:t}=Xe(e);await async function(){const e=s.getLegacyGlobalConfigDir(),t=s.getGlobalConfigDir();if(e!==t&&await Vs(e))for(const o of Fs){const i=I.join(e,o),s=I.join(t,o);try{if(!await Vs(i)||await Vs(s))continue;await A.mkdir(t,{recursive:!0}),await A.cp(i,s,{recursive:!0,errorOnExist:!1})}catch(e){}}}();const o=function(e){const t=Gs(e.cwd,(()=>process.cwd())),o=Gs(e.env,(()=>process.env)),i=e.globalOptions||{};i.noColor&&(process.env.NO_COLOR="1");let s="text";i.format&&(s=i.format);const n={...e.config};i.orgId&&(n.organizationId=i.orgId),i.spaceId&&(n.spaceId=i.spaceId);const r=new jo({format:"text",logFile:i.logFile,printToStderr:i.printLogs});let a="info";i.debug?a="debug":i.verbose&&(a="verbose");const c=new Ns(r,s,a),l=new $s({format:s}),d={cwd:t,env:o,argv:e.argv,config:n,format:s,log:r,ui:c,response:l,globalOptions:i,auth:void 0};return d.auth=new Is(d),d}({argv:e,config:await s.loadConfig(t.config),globalOptions:t});!function(e){xo=e.log,Lo=!0===Po([e,"access",e=>e.globalOptions,"optionalAccess",e=>e.debug]),Lo&&(Oo||(Xo(),ei(),Oo=!0))}(o);const i=gi([Ao,ai,mi,it]);await i(o,(async()=>{await Mb(o)}))})().catch((e=>{Q(e,void 0),process.exitCode=1}));
31
+ function Ng(e,t,o,i){return new(o||(o=Promise))((function(t,s){function n(e){try{a(i.next(e))}catch(e){s(e)}}function r(e){try{a(i.throw(e))}catch(e){s(e)}}function a(e){var i;e.done?t(e.value):(i=e.value,i instanceof o?i:new o((function(e){e(i)}))).then(n,r)}a((i=i.apply(e,[])).next())}))}let $g="";function Gg(e=""){const t=`${Date.now()}`,o=$g||($g=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),o=/(([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})),o=[];o[0]=Vg(t[0]+t[1]),o[1]=Vg(t[2]+t[3]);const i=["0000","0000","0000","0000","0000","ffff",o[0],o[1]];return i.join("")}(e):o?function(e){let t="";const o=[];let i=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&&(i=e.length),s+=e.length;for(let t=0;t<e.length;t++)if(4!==e[t].length){const i=r.substring(0,4-e[t].length).concat(e[t]);o.push(i)}else o.push(e[t]);n=!1}else{if(4!==t.length){const e=r.substring(0,4-t.length).concat(t);o.push(e)}else o.push(t);n&&(i+=1),s+=1,n=!1}}let c="";for(let e=0;e<8-s;e++)c=c.concat(r);for(let e=0;e<o.length;e++)e===i?(t=t.concat(c),t=t.concat(o[e])):t=t.concat(o[e]);return t}{const o=e.split(":");for(let e=0;e<o.length;e++){const i=o[e];if(4!==o[e].length){const s=r.substring(0,4-o[e].length).concat(i);t=t.concat(s)}else t=t.concat(i)}return t}}(e):"00000000000000000000000000000000"}(e));return"02"+t+o+Math.random().toString(16).slice(-6)}function Fg(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function Vg(e){return(Array(4).join("0")+parseInt(e,2).toString(16)).slice(-4)}function Wg(e,t){const o=e.key;void 0!==o&&(mh(t,10),ch(t,o));const i=e.value;void 0!==i&&(mh(t,18),ch(t,i))}function Hg(e){const t={};e:for(;!ih(e);){const o=uh(e);switch(o>>>3){case 0:break e;case 1:t.key=ah(e,uh(e));break;case 2:t.value=ah(e,uh(e));break;default:Yg(e,7&o)}}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 Jg(e){const t=eh();return function(e,t){const o=e.SeqID;void 0!==o&&(mh(t,8),hh(t,o));const i=e.LogID;void 0!==i&&(mh(t,16),hh(t,i));const s=e.service;void 0!==s&&(mh(t,24),hh(t,Zg(s)));const n=e.method;void 0!==n&&(mh(t,32),hh(t,Zg(n)));const r=e.headers;if(void 0!==r)for(const e of r){mh(t,42);const o=eh();Wg(e,o),mh(t,o.limit),lh(t,o),th(o)}const a=e.payloadEncoding;void 0!==a&&(mh(t,50),ch(t,a));const c=e.payloadType;void 0!==c&&(mh(t,58),ch(t,c));const l=e.payload;void 0!==l&&(mh(t,66),mh(t,l.length),function(e,t){const o=sh(e,t.length);e.bytes.set(t,o)}(t,l));const d=e.LogIDNew;void 0!==d&&(mh(t,74),ch(t,d));const p=e.serverTiming;void 0!==p&&(mh(t,82),ch(t,p));const u=e.msgID;void 0!==u&&(mh(t,90),ch(t,u));const m=e.frameType;void 0!==m&&(mh(t,96),hh(t,Zg(m)))}(e,t),function(e){const t=e.bytes,o=e.limit;return t.length===o?t:t.subarray(0,o)}(t)}function Kg(e){return function(e){const t={};e:for(;!ih(e);){const o=uh(e);switch(o>>>3){case 0:break e;case 1:t.SeqID=gh(e,!0);break;case 2:t.LogID=gh(e,!0);break;case 3:t.service=uh(e);break;case 4:t.method=uh(e);break;case 5:{const o=Qg(e);(t.headers||(t.headers=[])).push(Hg(e)),e.limit=o;break}case 6:t.payloadEncoding=ah(e,uh(e));break;case 7:t.payloadType=ah(e,uh(e));break;case 8:t.payload=rh(e,uh(e));break;case 9:t.LogIDNew=ah(e,uh(e));break;case 10:t.serverTiming=ah(e,uh(e));break;case 11:t.msgID=ah(e,uh(e));break;case 12:t.frameType=uh(e);break;default:Yg(e,7&o)}}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 Qg(e){const t=uh(e),o=e.limit;return e.limit=e.offset+t,o}function Yg(e,t){switch(t){case 0:for(;128&dh(e););break;case 2:oh(e,uh(e));break;case 5:oh(e,4);break;case 1:oh(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function Zg(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}const Xg=[];function eh(){const e=Xg.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function th(e){Xg.push(e)}function oh(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function ih(e){return e.offset>=e.limit}function sh(e,t){const o=e.bytes,i=e.offset,s=e.limit,n=i+t;if(n>o.length){const t=new Uint8Array(2*n);t.set(o),e.bytes=t}return e.offset=n,n>s&&(e.limit=n),i}function nh(e,t){const o=e.offset;if(o+t>e.limit)throw new Error("Read past limit");return e.offset+=t,o}function rh(e,t){const o=nh(e,t);return e.bytes.subarray(o,o+t)}function ah(e,t){const o=nh(e,t),i=String.fromCharCode,s=e.bytes,n="�";let r="";for(let e=0;e<t;e++){const a=s[e+o];let c,l,d,p;128&a?192==(224&a)?e+1>=t?r+=n:(c=s[e+o+1],128!=(192&c)?r+=n:(p=(31&a)<<6|63&c,p<128?r+=n:(r+=i(p),e++))):224==(240&a)?e+2>=t?r+=n:(c=s[e+o+1],l=s[e+o+2],32896!=(49344&(c|l<<8))?r+=n:(p=(15&a)<<12|(63&c)<<6|63&l,p<2048||p>=55296&&p<=57343?r+=n:(r+=i(p),e+=2))):240==(248&a)?e+3>=t?r+=n:(c=s[e+o+1],l=s[e+o+2],d=s[e+o+3],8421504!=(12632256&(c|l<<8|d<<16))?r+=n:(p=(7&a)<<18|(63&c)<<12|(63&l)<<6|63&d,p<65536||p>1114111?r+=n:(p-=65536,r+=i(55296+(p>>10),56320+(1023&p)),e+=3))):r+=n:r+=i(a)}return r}function ch(e,t){const o=t.length;let i=0;for(let e=0;e<o;e++){let s=t.charCodeAt(e);s>=55296&&s<=56319&&e+1<o&&(s=(s<<10)+t.charCodeAt(++e)-56613888),i+=s<128?1:s<2048?2:s<65536?3:4}mh(e,i);let s=sh(e,i);const n=e.bytes;for(let e=0;e<o;e++){let i=t.charCodeAt(e);i>=55296&&i<=56319&&e+1<o&&(i=(i<<10)+t.charCodeAt(++e)-56613888),i<128?n[s++]=i:(i<2048?n[s++]=i>>6&31|192:(i<65536?n[s++]=i>>12&15|224:(n[s++]=i>>18&7|240,n[s++]=i>>12&63|128),n[s++]=i>>6&63|128),n[s++]=63&i|128)}}function lh(e,t){const o=sh(e,t.limit),i=e.bytes,s=t.bytes;for(let e=0,n=t.limit;e<n;e++)i[e+o]=s[e]}function dh(e){return e.bytes[nh(e,1)]}function ph(e,t){const o=sh(e,1);e.bytes[o]=t}function uh(e){let t,o=0,i=0;do{t=dh(e),o<32&&(i|=(127&t)<<o),o+=7}while(128&t);return i}function mh(e,t){for(t>>>=0;t>=128;)ph(e,127&t|128),t>>>=7;ph(e,t)}function gh(e,t){let o,i=0,s=0,n=0;return o=dh(e),i=127&o,128&o&&(o=dh(e),i|=(127&o)<<7,128&o&&(o=dh(e),i|=(127&o)<<14,128&o&&(o=dh(e),i|=(127&o)<<21,128&o&&(o=dh(e),s=127&o,128&o&&(o=dh(e),s|=(127&o)<<7,128&o&&(o=dh(e),s|=(127&o)<<14,128&o&&(o=dh(e),s|=(127&o)<<21,128&o&&(o=dh(e),n=127&o,128&o&&(o=dh(e),n|=(127&o)<<7))))))))),{low:i|s<<28,high:s>>>4|n<<24,unsigned:t}}function hh(e,t){const o=t.low>>>0,i=(t.low>>>28|t.high<<4)>>>0,s=t.high>>>24,n=0===s?0===i?o<16384?o<128?1:2:o<1<<21?3:4:i<16384?i<128?5:6:i<1<<21?7:8:s<128?9:10,r=sh(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?i>>>21|128:i>>>21&127;case 7:a[r+6]=7!==n?i>>>14|128:i>>>14&127;case 6:a[r+5]=6!==n?i>>>7|128:i>>>7&127;case 5:a[r+4]=5!==n?128|i:127&i;case 4:a[r+3]=4!==n?o>>>21|128:o>>>21&127;case 3:a[r+2]=3!==n?o>>>14|128:o>>>14&127;case 2:a[r+1]=2!==n?o>>>7|128:o>>>7&127;case 1:a[r]=1!==n?128|o:127&o}}function fh(e){return Jg(e)}const _h=4294967296,yh=0x10000000000000000,bh=yh/2,vh=String.prototype.charCodeAt;class wh{constructor(e,t,o){this.isLong=!0,this.low=0|e,this.high=0|t,this.unsigned=!!o}static isLong(e){return e&&!0===e.isLong}static fromBits(e,t,o){return new wh(e,t,o)}static fromBytes(e,t,o){return o?wh.fromBytesLE(e,t):wh.fromBytesBE(e,t)}static fromBytesLE(e,t){return new wh(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 wh(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?Eh:new wh((vh.call(e,0)|vh.call(e,1)<<8|vh.call(e,2)<<16|vh.call(e,3)<<24)>>>0,(vh.call(e,4)|vh.call(e,5)<<8|vh.call(e,6)<<16|vh.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?Ch:Eh;if(t){if(e>=yh)return Ah}else{if(e<=-bh)return Sh;if(e+1>=bh)return Ih}return wh.fromBits(e%_h|0,e/_h|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*_h+(this.low>>>0):this.high*_h+(this.low>>>0)}isZero(){return 0===this.high&&0===this.low}add(e){wh.isLong(e)||(e=wh.fromNumber(e));const t=this.high>>>16,o=65535&this.high,i=this.low>>>16,s=65535&this.low,n=e.high>>>16,r=65535&e.high,a=e.low>>>16;let c=0,l=0,d=0,p=0;return p+=s+(65535&e.low),d+=p>>>16,p&=65535,d+=i+a,l+=d>>>16,d&=65535,l+=o+r,c+=l>>>16,l&=65535,c+=t+n,c&=65535,wh.fromBits(d<<16|p,c<<16|l,this.unsigned)}equals(e){return wh.isLong(e)||(e=wh.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?wh.fromBits(0,0,this.unsigned):-1===this.low?wh.fromBits(0,this.high+1,this.unsigned):wh.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 Eh=new wh(0,0,!1),Ch=new wh(0,0,!0),Ih=wh.fromBits(-1,2147483647,!1),Ah=wh.fromBits(-1,-1,!0),Sh=wh.fromBits(0,-2147483648,!1);var kh;!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"}(kh||(kh={}));class jh{constructor(e){this.type=e,this.target=null}}class Ph extends jh{constructor(e,t){super(e),this.message=t&&t.message||null}}class zh extends jh{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||kh.NATIVE_ERROR}}class Th extends jh{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 Rh extends jh{constructor(e,t){super(e),this.data=t&&t.data||null}}class xh extends Rh{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}}class Lh extends jh{constructor(e,t){super(e),this.data=t&&t.data||null}}function Oh(e,{message:t,code:o,error:i}){return new zh(e,{message:t,code:o,error:i})}function Dh(e,{code:t,reason:o,wasClean:i,willReconnect:s}){return new Th(e,{code:t,reason:o,wasClean:i,willReconnect:s})}function Uh(e,{message:t}){return new Ph(e,{message:t})}class qh{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 Bh=("undefined"!=typeof globalThis&&"Window"===globalThis.constructor.name||"undefined"!=typeof window&&"Window"===window.constructor.name)&&"undefined"!=typeof document,Mh="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,$h="undefined"!=typeof globalThis&&("DedicatedWorkerGlobalScope"===globalThis.constructor.name||"SharedWorkerGlobalScope"===globalThis.constructor.name||"ServiceWorkerGlobalScope"===globalThis.constructor.name)&&"undefined"!=typeof self,Gh="undefined"!=typeof globalThis&&"Object"===globalThis.constructor.name&&"undefined"!=typeof global&&"Object"===global.constructor.name&&"undefined"!=typeof process&&!!process.version;class Fh{constructor(){this._listeners={}}emit(e,...t){const o=this._listeners[e];if(o)o.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 o=this._listeners[e];if(o)for(let e=0;e<o.length;)o[e].fn===t?o.splice(e,1):++e}return this}on(e,t,o){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:o||this}),this}}class Vh extends Fh{constructor(e,t,o){super(),this._socket=null,Nh&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:o,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),Mh&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:t,header:o,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then((()=>{this._addWsListeners()}))}_createSocketFailHandler(e){Promise.resolve().then((()=>{const t=Oh("error",{message:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)});this.emit("error",t);const o=Dh("close",{reason:e.errMsg||e.errNo?`message: ${e.errMsg}`||`code: ${e.errNo}`||"":JSON.stringify(e)});this.emit("close",o)}))}_addWsListeners(){this._socket.onOpen((e=>{this.emit("open",function(e,{data:t}){return new Lh(e,{data:t})}("open",Object.assign(Object.assign({},e),{data:e.errMsg||""})))})),this._socket.onClose((e=>{this.emit("close",Dh("close",Object.assign({},e)))})),this._socket.onMessage((e=>{this.emit("message",function(e,{data:t,message:o}){return new xh(e,{data:t,message:o})}("message",Object.assign({},e)))})),this._socket.onError((e=>{this.emit("error",Oh("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",Oh("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",Oh("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 Wh(e,t,o){let i=-1;!function s(n){return Ng(this,0,void 0,(function*(){if(n<=i)return Promise.reject(new Error("next() called multiple times in process"));if(i=n,n===o.length)return Promise.resolve();return o[n].bind(e)(t,s.bind(null,n+1))}))}(0)}function Hh(e){let t=0,o=0;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t+=1:o<2048?t+=2:55296==(64512&o)&&56320==(64512&e.charCodeAt(i+1))?(++i,t+=4):t+=3;return t}function Jh(e,t,o){if(o-t<1)return"";let i="";for(let s=t;s<o;){const t=e[s++];if(t<=127)i+=String.fromCharCode(t);else if(t>=192&&t<224)i+=String.fromCharCode((31&t)<<6|63&e[s++]);else if(t>=224&&t<240)i+=String.fromCharCode((15&t)<<12|(63&e[s++])<<6|63&e[s++]);else if(t>=240){const o=((7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;i+=String.fromCharCode(55296+(o>>10)),i+=String.fromCharCode(56320+(1023&o))}}return i}function Kh(e,t,o){const i=o;let s,n;for(let i=0;i<e.length;++i)s=e.charCodeAt(i),s<128?t[o++]=s:s<2048?(t[o++]=s>>6|192,t[o++]=63&s|128):55296==(64512&s)&&56320==(64512&(n=e.charCodeAt(i+1)))?(s=65536+((1023&s)<<10)+(1023&n),++i,t[o++]=s>>18|240,t[o++]=s>>12&63|128,t[o++]=s>>6&63|128,t[o++]=63&s|128):(t[o++]=s>>12|224,t[o++]=s>>6&63|128,t[o++]=63&s|128);return o-i}function Qh(e){return Ng(this,0,void 0,(function*(){if("string"==typeof e){const t=new Uint8Array(Hh(e));return Kh(e,t,0),t}return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}))}class Yh{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 Zh(e,t,o){return!!(null==e?void 0:e.find((e=>e.key===t&&e.value===o)))}function Xh(e,t){var o;return null===(o=null==e?void 0:e.find((e=>e.key===t)))||void 0===o?void 0:o.value}function ef(e,t){return Ng(this,0,void 0,(function*(){const{enableAutoAck:o}=this._options,i=Zh(e.message.headers,"need_ack","1"),s=Zh(e.message.headers,"is_ack","1"),n=Zh(e.message.headers,"x_frontier_qos_ack","1");if(o&&i){const{SeqID:t,LogID:o,service:i,LogIDNew:s,method:n}=e.message;this._sendAck({SeqID:t,LogID:o,LogIDNew:s,service:i,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 tf(e,t){return Ng(this,0,void 0,(function*(){this._debug("received",e.message),t()}))}function of(e,t){return Ng(this,0,void 0,(function*(){const o=Kg(yield Qh(e.data));try{if(o.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=o.payloadEncoding?o.payloadEncoding.replace(/\s/g,"").toLowerCase():"",i=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=o.payloadType?o.payloadType.replace(/\s/g,"").toLowerCase():"",n=i.force?i.type:s||i.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))?o.textPayload=Jh(o.payload,0,o.payload.byteLength):o.textPayload=""}else o.textPayload=""}catch(e){o.textPayload="",console.log(e)}e.message=o,t()}))}let sf,nf;const rf=new WeakMap,af=new WeakMap,cf=new WeakMap,lf=new WeakMap,df=new WeakMap;let pf={get(e,t,o){if(e instanceof IDBTransaction){if("done"===t)return af.get(e);if("objectStoreNames"===t)return e.objectStoreNames||cf.get(e);if("store"===t)return o.objectStoreNames[1]?void 0:o.objectStore(o.objectStoreNames[0])}return gf(e[t])},set:(e,t,o)=>(e[t]=o,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function uf(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(nf||(nf=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(hf(this),t),gf(rf.get(this))}:function(...t){return gf(e.apply(hf(this),t))}:function(t,...o){const i=e.call(hf(this),t,...o);return cf.set(i,t.sort?t.sort():[t]),gf(i)}}function mf(e){return"function"==typeof e?uf(e):(e instanceof IDBTransaction&&function(e){if(af.has(e))return;const t=new Promise(((t,o)=>{const i=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",n),e.removeEventListener("abort",n)},s=()=>{t(),i()},n=()=>{o(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",s),e.addEventListener("error",n),e.addEventListener("abort",n)}));af.set(e,t)}(e),t=e,(sf||(sf=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some((e=>t instanceof e))?new Proxy(e,pf):e);var t}function gf(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,o)=>{const i=()=>{e.removeEventListener("success",s),e.removeEventListener("error",n)},s=()=>{t(gf(e.result)),i()},n=()=>{o(e.error),i()};e.addEventListener("success",s),e.addEventListener("error",n)}));return t.then((t=>{t instanceof IDBCursor&&rf.set(t,e)})).catch((()=>{})),df.set(t,e),t}(e);if(lf.has(e))return lf.get(e);const t=mf(e);return t!==e&&(lf.set(e,t),df.set(t,e)),t}const hf=e=>df.get(e);const ff=["get","getKey","getAll","getAllKeys","count"],_f=["put","add","delete","clear"],yf=new Map;function bf(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(yf.get(t))return yf.get(t);const o=t.replace(/FromIndex$/,""),i=t!==o,s=_f.includes(o);if(!(o in(i?IDBIndex:IDBObjectStore).prototype)||!s&&!ff.includes(o))return;const n=async function(e,...t){const n=this.transaction(e,s?"readwrite":"readonly");let r=n.store;return i&&(r=r.index(t.shift())),(await Promise.all([r[o](...t),s&&n.done]))[0]};return yf.set(t,n),n}pf=(e=>({...e,get:(t,o,i)=>bf(t,o)||e.get(t,o,i),has:(t,o)=>!!bf(t,o)||e.has(t,o)}))(pf);class vf extends Fh{constructor(e,t){super(),this._dbName=e,this._keyPath=t,this._qosDB=void 0,this._init()}openDB(){return Ng(this,0,void 0,(function*(){yield this._init()}))}_init(){return Ng(this,0,void 0,(function*(){try{const e=this._dbName,t=this._keyPath;return new Promise((o=>{this._qosDB?o(this):(function(e,t,{blocked:o,upgrade:i,blocking:s,terminated:n}={}){const r=indexedDB.open(e,t),a=gf(r);return i&&r.addEventListener("upgradeneeded",(e=>{i(gf(r.result),e.oldVersion,e.newVersion,gf(r.transaction))})),o&&r.addEventListener("blocked",(()=>o())),a.then((e=>{n&&e.addEventListener("close",(()=>n())),s&&e.addEventListener("versionchange",(()=>s()))})).catch((()=>{})),a}(`frontier_${e}`,1,{upgrade(o){o.createObjectStore(e,{keyPath:t})}}).then((e=>{this._qosDB=e,this.emit("ready")})),this.on("ready",(()=>{o(this),this.off()})))}))}catch(e){console.log(e)}}))}get(e){var t;return Ng(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 o;return Ng(this,0,void 0,(function*(){return null===(o=this._qosDB)||void 0===o?void 0:o.put(this._dbName,e)}))}del(e){var t;return Ng(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 Ng(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 Ng(this,0,void 0,(function*(){return null===(e=this._qosDB)||void 0===e?void 0:e.getAllKeys(this._dbName)}))}getAll(){var e;return Ng(this,0,void 0,(function*(){return null===(e=this._qosDB)||void 0===e?void 0:e.getAll(this._dbName)}))}closeDB(){var e;return Ng(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 wf{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=localStorage}openDB(){return Ng(this,0,void 0,(function*(){}))}get _prefix(){return`frontier_${this._DBName}`}get(e){return Ng(this,0,void 0,(function*(){const t=this._qosDB.getItem(this._prefix);return JSON.parse(t||"{}")[e]}))}set(e,t){return Ng(this,0,void 0,(function*(){const o=this._qosDB.getItem(this._prefix),i=JSON.parse(o||"{}");return i[t||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(i)),t||e[this._pathKey]}))}del(e){return Ng(this,0,void 0,(function*(){const t=this._qosDB.getItem(this._prefix),o=JSON.parse(t||"{}");return o[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(o))}))}clear(){return Ng(this,0,void 0,(function*(){return this._qosDB.clear()}))}keys(){return Ng(this,0,void 0,(function*(){const e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}))}getAll(){return Ng(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 Ef{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=Mh?tt:Nh?wx:null}openDB(){return Ng(this,0,void 0,(function*(){}))}get _prefix(){return`frontier_${this._DBName}`}get(e){return Ng(this,0,void 0,(function*(){const t=this._qosDB.getStorageSync(this._prefix);return JSON.parse(t||"{}")[e]}))}set(e,t){return Ng(this,0,void 0,(function*(){const o=this._qosDB.getStorageSync(this._prefix),i=JSON.parse(o||"{}");return i[t||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(i)),t||e[this._pathKey]}))}del(e){return Ng(this,0,void 0,(function*(){const t=this._qosDB.getStorageSync(this._prefix),o=JSON.parse(t||"{}");return o[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(o))}))}clear(){return Ng(this,0,void 0,(function*(){return this._qosDB.clearStorageSync()}))}keys(){return Ng(this,0,void 0,(function*(){const e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}))}getAll(){return Ng(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 Cf(e,t){if(Mh||Mh)return new Ef(e,t);if((Bh||$h)&&void 0!==typeof indexedDB)return new vf(e,t);if((Bh||$h)&&void 0!==typeof localStorage)return new wf(e,t);throw new Error("init QoSDB failed")}class If{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=Cf("qos","message_id")}_intervalFlush(){return Ng(this,0,void 0,(function*(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval((()=>{this.flushExpired()}),this._interval)}))}openDB(){return Ng(this,0,void 0,(function*(){yield this._qosDB.openDB().then((()=>{this._intervalFlush()}))}))}flushExpired(){var e;return Ng(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 Ng(this,0,void 0,(function*(){return null===(t=this._qosDB)||void 0===t?void 0:t.del(e)}))}set(e,t){var o;return Ng(this,0,void 0,(function*(){return null===(o=this._qosDB)||void 0===o?void 0:o.set({message_id:e,timestamp:t})}))}get(e){var t;return Ng(this,0,void 0,(function*(){return null===(t=this._qosDB)||void 0===t?void 0:t.get(e)}))}closeDB(){var e;return Ng(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 Af(e,t){var o,i,s,n,r;return Ng(this,0,void 0,(function*(){const a=Zh(e.message.headers,"code","-1"),c=Zh(e.message.headers,"is_ack","1"),l=Xh(e.message.headers,"x_frontier_msgid"),d=Number(Xh(e.message.headers,"x_frontier_ttl"))||0,p=Zh(e.message.headers,"x_frontier_qos","2"),u=Zh(e.message.headers,"x_frontier_qos_ack","1"),m=Zh(e.message.headers,"x-msg-qos","2"),g=Xh(e.message.headers,"x-msg-cursor_name"),h=Number(Xh(e.message.headers,"x-msg-cursor_value"));if(p&&u)return t();if(m&&!(null===(o=this._cursorManager)||void 0===o?void 0:o.isReady))return t();if(p&&!this._QoSManager&&(this._QoSManager=new If),p&&this._QoSManager&&!this._QoSManager.isReady&&(yield this._QoSManager.openDB()),e.message.service>0&&c&&!a||e.message.service>0){if(l&&p){return!!(yield null===(i=this._QoSManager)||void 0===i?void 0:i.get(l))||(this._dispatchMessageEvent(e),yield null===(s=this._QoSManager)||void 0===s?void 0:s.set(l,Date.now()+d)),t()}if(m&&(null===(n=this._cursorManager)||void 0===n?void 0:n.isReady)){const o=null!==(r=yield this._cursorManager.get(g))&&void 0!==r?r:-1;if(!(o<h))throw new Error(`recevied message cursor ${h} larger than local cursor ${o}`);return this._dispatchMessageEvent(e),this._cursorManager.set(g,h,e.message.service),t()}return this._dispatchMessageEvent(e),t()}}))}function Sf(e,t){var o,i;return Ng(this,0,void 0,(function*(){const s=Zh(e.message.headers,"x_frontier_qos","2"),n=Zh(e.message.headers,"x_frontier_is_ack","1"),r=null===(o=Xh(e.message.headers,"x_frontier_ack_msgid"))||void 0===o?void 0:o.split(",");if(!s)return t();if(this._QoSManager||(this._QoSManager=new If),this._QoSManager&&!this._QoSManager.isReady&&(yield this._QoSManager.openDB()),n&&r&&r.length)for(const e of r)yield null===(i=this._QoSManager)||void 0===i?void 0:i.del(e);t()}))}function kf(e,t){let o=0,i=t;const s=t+4;for(;i<s;){const{value:t,offset:s}=Pf(e,i);i=s,o=o<<8>>>0,o+=t}return{value:o,offset:s}}function jf(e,t){return{value:new wh(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 Pf(e,t){return e.readUInt8?{value:e.readUInt8(t),offset:t+1}:{value:255&e[t],offset:t+1}}function zf(e,t,o){return t.writeUint8?t.writeUint8(e,o):t[o]=255&e,o+1}const Tf="undefined"!=typeof Buffer?Buffer.allocUnsafe:function(e,t){const o=8192;let i=null,s=o;return function(n){if(n<1||n>4096)return e(n);s+n>o&&(i=e(o),s=0);const r=t.call(i,s,s+=n);return 7&s&&(s=1+(7|s)),r}}((function(e){return new Uint8Array(e)}),Uint8Array.prototype.subarray);function Rf(e,t,o){const[i,s]=function(e){let t=0;const o={};for(let i=0;i<e.length;i++)o[e[i].cursor_name]=Hh(e[i].cursor_name),t+=14+o[e[i].cursor_name];return[t,o]}(e),n=Tf(i);let r=0;return e.forEach((e=>{console.log("cursor.service",e,e.service),r=zf(0,n,r),console.log("header",r),r=function(e,t,o){if(o>4294967295)throw new Error("integer too large");let i=3;for(;i>=0;)zf(255&o,e,t+i),o>>>=8,i--;return t+4}(n,r,e.service||0),console.log("service",r),r=zf(s[e.cursor_name],n,r),console.log("service-name",r),r=function(e,t,o){return e?e.length<40?Kh(e,t,o)+o:t.utf8Write?t.utf8Write(e,o)+o:t.write?t.write(e,o)+o:Kh(e,t,o)+o:o}(e.cursor_name,n,r),console.log("name",r),r=function(e,t,o){const i=e.low,s=e.high;return t[o]=s>>>24,t[o+1]=s>>>16&255,t[o+2]=s>>>8&255,t[o+3]=255&s,t[o+4]=i>>>24,t[o+5]=i>>>16&255,t[o+6]=i>>>8&255,t[o+7]=255&i,o+8}(wh.fromNumber(e.cursor||t),n,r),console.log("curvalue",r)})),{frameType:32,headers:[{key:"cursor_file_name",value:o}],payload:n}}class xf{constructor(e,t,o){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=o,this._qosDB=Cf(this._cursorNameSpace,"cursor_name")}openDB(){return Ng(this,0,void 0,(function*(){yield this._qosDB.openDB()}))}getCursors(){return Ng(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?Rf(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?Rf(t,0,this._cursorFileName):{frameType:32,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}}))}set(e,t,o){return Ng(this,0,void 0,(function*(){return console.log("setdb",e,t,o),this._qosDB.set({cursor_name:e,cursor:t,service:o})}))}setCursors(e){return Ng(this,0,void 0,(function*(){const t=function(e){let t=0;const o=[];for(;t<e.byteLength;){const{offset:i}=Pf(e,t);t=i;const s={cursor_name:"",cursor:0,service:0},{value:n,offset:r}=kf(e,t);s.service=n,t=r;const{value:a,offset:c}=Pf(e,t);t=c,s.cursor_name=Jh(e,t,t+a),t+=a;const{value:l,offset:d}=jf(e,t);s.cursor=l.toNumber(),t=d,o.push(s)}return o}(e);for(const e of t)console.log("setcursor",t),yield this._qosDB.set(e)}))}get(e){var t;return Ng(this,0,void 0,(function*(){return null===(t=yield this._qosDB.get(e))||void 0===t?void 0:t.cursor}))}closeDB(){return Ng(this,0,void 0,(function*(){yield this._qosDB.closeDB()}))}get isReady(){return this._qosDB.isReady}}function Lf(e,t){return Ng(this,0,void 0,(function*(){const o=16===e.message.frameType,i=32===e.message.frameType;if(!o&&!i)return t();const s=Xh(e.message.headers,"cursor_file_name"),{aID:n,fpID:r,messageStrategy:a}=this._options;if(!s)return t();if(this._cursorManager||(this._cursorManager=new xf(`${r}_${n}_${s}`,s,a)),this._cursorManager.isReady||(yield this._cursorManager.openDB()),o){const e=yield this._cursorManager.getCursors(),t=Jg({frameType:null==e?void 0:e.frameType,SeqID:wh.fromNumber(this._seqId++),LogID:wh.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(i){const t=e.message.payload;t&&this._cursorManager.setCursors(t)}}))}const Of=function(e,t){return Ng(this,0,void 0,(function*(){this._isInit=!1,clearTimeout(this._connectionTimeoutId),t()}))},Df=function(e,t){var o;return Ng(this,0,void 0,(function*(){const e=null===(o=this._endpointManager)||void 0===o?void 0:o.getCurrentEndpoint();this._debug(`open ${e}`),t()}))},Uf=function(e,t){var o,i;return Ng(this,0,void 0,(function*(){if(!this._ws||this._ws.readyState!==this.OPEN)return t();const{pingInterval:s}=this._options;null===(o=this._endpointManager)||void 0===o||o.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===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpoint();this._debug(`open ${n} success`),t()}))};class qf extends Fh{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=Bh,this._isNode=Gh,this._isMiniTT=Mh,this._isMiniWX=Nh,this._isWorker=$h,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{Wh(this,e,[Of,Uf,Df])}catch(e){const t=Oh("error",{message:e.message,code:kh.OPEN_ERROR,error:e});this._dispatchErrorEvent(t)}},this._onMessage=e=>Ng(this,0,void 0,(function*(){const{pingInterval:t,pingFrequency:o}=this._options;if(("hi"===e.data&&"always"===o||"auto"===o)&&(this._clearPingTimer(),this.emit("ping_once_success","success"),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),t)),"hi"!==e.data)try{Wh(this,e,[of,ef,Sf,Lf,Af,tf])}catch(e){const t=Oh("error",{message:e.message,code:kh.MESSAGE_ERROR,error:e});this._dispatchErrorEvent(t)}})),this._onError=e=>{var t,o;const i=null===(t=this._endpointManager)||void 0===t?void 0:t.checkReachMaxTries(),s=null===(o=this._endpointManager)||void 0===o?void 0:o.getCurrentEndpoint();if(!i||e.message)this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(Oh("error",{message:e.message,code:kh.NATIVE_ERROR,error:e}));else{const t=`connect ${s} fail, max retries reached`;this._dispatchErrorEvent(Oh("error",{message:t,code:kh.MAX_RETRIES_ERROR,error:e}))}},this._onClose=e=>Ng(this,0,void 0,(function*(){var t,o,i,s,n,r,a,c,l,d,p,u;this._clearTimer(),this._clearPingTimer(),this._removeWsListeners(),this._ws=null,this._connectLock=!1;const m=null===(t=this._endpointManager)||void 0===t?void 0:t.checkReachMaxTries();if(!m&&this._navigatorOnline()&&!this._readyClosed){const t=null===(o=this._endpointManager)||void 0===o?void 0:o.getCurrentEndpoint(),i=this._options.reconnectInterceptor(e.code,e.reason);return this._dispatchCloseEvent(Dh("close",{code:1006,reason:e.reason||`connecting failed, unknown reason, hostname: ${t}`,willReconnect:i})),void(i&&this._connect())}if(1e3!==e.code&&this._readyClosed)return this._dispatchCloseEvent(Dh("close",{code:1e3,reason:"bye"})),null===(i=this._endpointManager)||void 0===i||i.resetEndpointConfig(),void(null===(s=this._pingLossCounter)||void 0===s||s.resetCounter());if(1e3!==e.code&&m){const t=null===(n=this._endpointManager)||void 0===n?void 0:n.getCurrentEndpoint();let o=e.reason;o||(o=yield function(e){return Ng(this,0,void 0,(function*(){return new Promise((t=>{if(!Bh)return t("unknown reason");try{const o=document.createElement("script");window.frontierJSONP=e=>{document.body.removeChild(o),window.frontierJSONP=void 0,t(e&&e.msg||"unknown reason")},o.type="text/javascript",o.src=e.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(o)}catch(e){document.body.removeChild(o)}}catch(e){window.frontierJSONP=void 0,t("unknown reason")}}))}))}(this._url)),o=`connecting failed, ${o}, hostname: ${t}, max retries reached`,this._dispatchCloseEvent(Dh("close",{code:e.code,reason:o}));const i=`connect ${t} fail, max retries reached`;return this._dispatchErrorEvent(Oh("error",{message:i,code:kh.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(Dh("close",{code:e.code,reason:`connecting failed, unknown reason, hostname: ${t}`})),null===(l=this._endpointManager)||void 0===l||l.resetEndpointConfig(),void(null===(d=this._pingLossCounter)||void 0===d||d.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:Fg,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:o}=e,i=Array.isArray(t)?t:"string"==typeof t?[t]:[];if(!i||0===i.length)throw new Error("please provide valid url");if(!function(e){return!!(e||Nh&&wx.connectSocket||Mh&&tt.connectSocket||(Bh||$h)&&"undefined"!=typeof WebSocket&&WebSocket)}(o))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new qh(i,this._options.maxRetries),this._pingLossCounter=new Yh(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=Uh("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 Ng(this,0,void 0,(function*(){const{fpID:t,deviceID:o,bddID:i,ttwID:s,accessKey:n,aID:r,customParams:a={},enableAutoAck:c,enableQoS:l,QoSLevel:d,env:p}=this._options;let u,m,g;this._isBrowser||this._isMiniWX||this._isMiniTT?(u=location&&"https:"==location.protocol?"wss://":"ws://",m=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),g=/^wss(.*:\/\/)/.test(e)?e:`${u}${m}`):(u="wss://",m=e.replace(/(^http)((?:[s]*:\/\/))/,""),g=/(^ws)((?:[s]*:\/\/))/.test(m)?m:`${u}${m}`);const h=i?"bd_did":s?"ttwid":"device_id",f=i||(s||o);if(!f||!h)throw new Error("please provide bddID, deviceID or ttwID");const _="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):{},b=Object.assign(Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:n,fpid:t,aid:r,[h]:f,xsack:c?1:0,xaack:c?1:0,xsqos:l?1:0,qos_level:l?d:void 0,qos_sdk_version:2},y),_);return`${g}/ws/v2${Object.keys(b).reduce(((e,t)=>void 0!==b[t]?`${e}${e?"&":"?"}${t}=${b[t]}`:e),"")}`}))}_connect(){var e,t,o,i,s,n,r;return Ng(this,0,void 0,(function*(){if(!this._connectLock&&!this._readyClosed){this._connectLock=!0;try{const l=null===(e=this._endpointManager)||void 0===e?void 0:e.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:d}=this._options;if(l){const e=null===(t=this._endpointManager)||void 0===t?void 0:t.getCurrentEndpoint(),s=null===(o=this._endpointManager)||void 0===o?void 0:o.replaceBackupEndpointAndUpdateCount(),n=null===(i=this._endpointManager)||void 0===i?void 0:i.getCurrentEndpointTriesCount();if(!s){const t=`connect ${e} timeout, max retries reached`;return this._debug(t),void this._dispatchErrorEvent(Oh("error",{message:t,code:kh.MAX_RETRIES_ERROR}))}{const t=`connect ${e} timeout, max retries reached, will use backup endpoint ${s} to retry`,o=Oh("error",{message:t,code:kh.MAX_RETRIES_ERROR});this._debug(t),this._dispatchErrorEvent(o),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=Uh("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||Mh?new Vh(a.url,a.protocol,a.headers):(Bh||$h)&&"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),d)}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:o,reconnectIntervalGrowFactor:i}=this._options,s=t*Math.pow(i,e-1);return s>o?o: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="",o=!1){this._ws&&this._destroyWebSocket(e,t,o)}_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=fh(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="",o=!1){var i,s,n,r;if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,t),this._connectLock=!1,o&&this._navigatorOnline()&&!this._readyClosed){if(null===(i=this._endpointManager)||void 0===i?void 0:i.checkReachMaxTries()){const e=null===(s=this._endpointManager)||void 0===s?void 0:s.getCurrentEndpoint();this._dispatchCloseEvent(Dh("close",{code:1006,reason:`connect ${e} timeout, max retries reached`,wasClean:!0}))}else{const o=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(Dh("close",{code:e,reason:t,wasClean:!0,willReconnect:o})),o&&this._connect()}}else this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(Dh("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(Dh("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 o;this._readyClosed=!0,this._clearTimer(),this._clearPingTimer(),this._dropGlobalEventListener(),null===(o=this._QoSManager)||void 0===o||o.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 Ng(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 o=yield Qh(e),i=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:l=this._options.payloadType,logIDNew:d=(this._options.logIDNewConfig.enableAutoGenerateLogIDNew?Gg(this._options.logIDNewConfig.userIp):"")}=t||{};if(!n)throw new Error("please provide a valid service");const p={SeqID:wh.fromNumber(this._seqId++),LogID:wh.fromNumber(r),service:n,method:s,headers:a,payloadEncoding:c instanceof Object?c.encoding?c.encoding:"":c,payloadType:l instanceof Object?l.type?l.type:i:l||i,payload:o,LogIDNew:d},u=fh(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:d}}))}reconnect(e){var t,o;return Ng(this,0,void 0,(function*(){const{url:i}=e||{},s=Array.isArray(i)?i:"string"==typeof i?[i]:[];e&&Object.assign(this._options,e),s&&s.length?this._endpointManager=new qh(s,this._options.maxRetries):null===(t=this._endpointManager)||void 0===t||t.resetEndpointConfig(),null===(o=this._pingLossCounter)||void 0===o||o.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 Ng(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 o=()=>{e("success"),this.off("ping_once_success",o),this.off("ping_once_timeout",i)},i=()=>{t("timeout"),this.off("ping_once_success",o),this.off("ping_once_timeout",i)};this.on("ping_once_success",o),this.on("ping_once_timeout",i),this._ping()}))}}function Bf(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class Mf extends E{constructor(e,t){super((e=>{const t=new URL(e);return t.searchParams.set("aid",Ig),t.toString()})(e),"pbbp2",{headers:{...t,Origin:"https://www.coze.cn"}})}}class Nf{constructor(){Nf.prototype.__init.call(this)}__init(){this.fws=null}connect(t,o,i){return new Promise(((s,n)=>{let r=!1,a=!1;const c=e=>{if(!a)return a=!0,void n(e);Bf([i,"optionalCall",t=>t(e)])},l={fpID:"1289",aID:Ig,accessKey:t.accessKey,deviceID:t.deviceId,url:"wss://frontier.coze.cn",automaticOpen:!0,enableQoS:!1,enableAutoAck:!1,ws:class extends Mf{constructor(e){super(e,t.headers)}}};this.fws=new qf(l);const d=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(d),s()},this.fws.onerror=()=>{clearTimeout(d),c(new Error(r?"Frontier connection failed after connect":"Frontier connection failed"))},this.fws.onclose=()=>{clearTimeout(d),c(new Error(r?"Frontier connection closed after connect":"Frontier connection closed"))},this.fws.onmessage=t=>{const i=Bf([t,"access",e=>e.message,"optionalAccess",e=>e.payloadType]),s=Bf([t,"access",e=>e.message,"optionalAccess",e=>e.service]),n=Bf([t,"access",e=>e.message,"optionalAccess",e=>e.payload]);if(!i||!n)return;const r=new TextDecoder("utf-8").decode(n),a=e.safeJsonParse(r,r);o({service:s,event:i,data:a})}}))}dispose(){Bf([this,"access",e=>e.fws,"optionalAccess",e=>e.close,"call",e=>e()]),this.fws=null}}function $f(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Gf=(e,t)=>{const o=t.toLowerCase(),i=Object.entries(e).find((([e])=>e.toLowerCase()===o));return $f([i,"optionalAccess",e=>e[1]])},Ff=e=>JSON.stringify({accessKey:e.accessKey,authorization:Gf(e.headers,"authorization"),deviceId:e.deviceId,organizationId:e.organizationId,serviceId:e.serviceId,xTTEnv:Gf(e.headers,"x-tt-env")}),Vf=e=>"function"==typeof e.resolveConfig&&"string"==typeof e.scopeKey;class Wf{__init(){this.entries=new Map}constructor(e){Wf.prototype.__init.call(this),this.createClient=$f([e,"optionalAccess",e=>e.createClient])||(()=>new Nf),this.getScopeKey=$f([e,"optionalAccess",e=>e.getScopeKey])||Ff}async subscribe(e,t){const o=((e,t)=>Vf(e)?e.scopeKey:t(e))(e,this.getScopeKey);let i=this.entries.get(o);i||(i=this.createEntry(o,e),this.entries.set(o,i)),i.subscribers.add(t);try{await i.connectPromise}catch(e){throw i.subscribers.delete(t),e}let s=!1;return{release:()=>{s||(s=!0,this.releaseSubscriber(o,i,t))}}}createEntry(e,t){const o=this.createClient(),i={client:o,connectPromise:Promise.resolve(),subscribers:new Set};return i.connectPromise=(async e=>Vf(e)?await e.resolveConfig():e)(t).then((async t=>{await o.connect(t,(t=>{this.emitEvent(e,t)}),(t=>{this.handleConnectionError(e,t)}))})).catch((t=>{throw this.entries.get(e)===i&&this.entries.delete(e),i.subscribers.clear(),o.dispose(),t})),i}emitEvent(e,t){const o=this.entries.get(e);if(o)for(const e of o.subscribers)e.onEvent(t)}handleConnectionError(e,t){const o=this.entries.get(e);if(!o)return;this.entries.delete(e);const i=[...o.subscribers];o.subscribers.clear(),o.client.dispose();for(const e of i)$f([e,"access",e=>e.onError,"optionalCall",e=>e(t)])}releaseSubscriber(e,t,o){t.subscribers.delete(o),t.subscribers.size>0||(this.entries.get(e)===t&&this.entries.delete(e),t.client.dispose())}}const Hf=new Wf;function Jf(e,t){return null!=e?e:t()}function Kf(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Qf=e=>({...e,files:e.files?[...e.files]:void 0}),Yf=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 Zf{constructor(){Zf.prototype.__init.call(this)}__init(){this.sessionStates=new Map}applyReplyEvent(t,o){const i=o.session_id;if(!i||!(e=>2===Number(e.source))(o))return null;const s=(({data:t,event:o})=>{const i=Kf([e.safeJsonParse(t.content,null),"optionalAccess",e=>e.message_data,"optionalAccess",e=>e.reply]),s=t.id,n="message"===o?Kf([i,"optionalAccess",e=>e.content])||t.content:Kf([i,"optionalAccess",e=>e.content]);return s&&n?{answerId:s,content:n,files:t.files,requestMessageId:Kf([i,"optionalAccess",e=>e.reply_to_message_id])}:null})({data:o,event:t});if(!s)return null;const n=this.getOrCreateSessionState(i),r=n.replies.get(s.answerId),a={answerId:s.answerId,content:"stream"===t&&r?r.content+s.content:s.content,files:Jf(s.files,(()=>Kf([r,"optionalAccess",e=>e.files]))),requestMessageId:Jf(s.requestMessageId,(()=>Kf([r,"optionalAccess",e=>e.requestMessageId])))};return"message"===t&&!r&&(({nextReply:e,sessionState:t})=>{for(const o of t.replies.values())if(o.requestMessageId===e.requestMessageId&&o.content===e.content&&Yf(o.files)===Yf(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:i,source:"stream",chunk:{answerId:s.answerId,content:s.content,requestMessageId:s.requestMessageId}}:{type:"reply_update",sessionId:i,source:"message",reply:Qf(a)})}applySessionIdleEvent(e){const t=Kf([e,"optionalAccess",e=>e.session_id]);if(!t||2!==Number(e.status))return null;const o=this.sessionStates.get(t);if(!o)return null;return{type:"session_idle",sessionId:t,replies:o.replyOrder.map((e=>o.replies.get(e))).filter((e=>Boolean(e))).map((e=>Qf(e)))}}getOrCreateSessionState(e){const t=this.sessionStates.get(e);if(t)return t;const o={replies:new Map,replyOrder:[]};return this.sessionStates.set(e,o),o}}function Xf(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const e_=e=>({type:"progress_update",progress:e});class t_{constructor(){t_.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=>e_({progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:t.progressStatus}))):[]}applyFrontierEvent(e){const t=Xf([e,"optionalAccess",e=>e.claw_id]),o=Xf([e,"optionalAccess",e=>e.id]);if(!t||!o)return null;const i=2===Number(e.status)?"finished":1===Number(e.status)?"running":null;if(!i)return null;const s={progressId:o,clawId:t,name:e.name,progressType:e.type,progressStatus:i};return this.updateKnownProgressState(s),e_(s)}applySnapshot(e,t){const o=this.getOrCreateProgressState(e),i=new Set,s=[];t.forEach((t=>{i.add(t.progressId);const n={progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:t.progressStatus},r=o.get(t.progressId);o.set(t.progressId,n),((e,t)=>Boolean(e&&e.name===t.name&&e.progressType===t.progressType&&e.progressStatus===t.progressStatus))(r,n)||s.push(e_({progressId:n.progressId,clawId:e,name:n.name,progressType:n.progressType,progressStatus:n.progressStatus}))}));for(const t of[...o.values()])i.has(t.progressId)||(o.delete(t.progressId),s.push(e_({progressId:t.progressId,clawId:e,name:t.name,progressType:t.progressType,progressStatus:"finished"})));return 0===o.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 o=new Map;return this.progressStates.set(e,o),o}}class o_{__init(){this.progressPollTimers=new Map}__init2(){this.progressRefreshes=new Map}constructor({emitProgressUpdate:e,globalStreamKey:t,hasConnectionError:o,hasSubscribers:i,listProgresses:s,progressPollIntervalMs:n=3e4,progressStateStore:r}){o_.prototype.__init.call(this),o_.prototype.__init2.call(this),this.emitProgressUpdate=e,this.globalStreamKey=t,this.hasConnectionError=o,this.hasSubscribers=i,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 o=setTimeout((()=>{t()}),this.progressPollIntervalMs);this.progressPollTimers.set(e,o)},o=setTimeout((()=>{t()}),this.progressPollIntervalMs);this.progressPollTimers.set(e,o)}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 o=(async()=>{const{listProgresses:t}=this;if(!t)return;const o=await t(e);this.progressStateStore.applySnapshot(e,o).forEach((t=>{this.emitProgressUpdate(e,t),this.emitProgressUpdate(this.globalStreamKey,t)}))})().finally((()=>{this.progressRefreshes.delete(e)}));this.progressRefreshes.set(e,o),await o}}class i_{__init(){this.closed=!1}__init2(){this.error=null}__init3(){this.queue=[]}constructor(e){this.cleanup=e,i_.prototype.__init.call(this),i_.prototype.__init2.call(this),i_.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 s_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const n_="*";class r_{__init(){this.connectionError=null}__init2(){this.disposed=!1}__init3(){this.replyStateStore=new Zf}__init4(){this.progressStateStore=new t_}__init5(){this.sessionStreams=new Map}__init6(){this.progressStreams=new Map}constructor(e){r_.prototype.__init.call(this),r_.prototype.__init2.call(this),r_.prototype.__init3.call(this),r_.prototype.__init4.call(this),r_.prototype.__init5.call(this),r_.prototype.__init6.call(this),this.connectionManager=s_([e,"optionalAccess",e=>e.connectionManager])||(s_([e,"optionalAccess",e=>e.client])?new Wf({createClient:()=>e.client}):Hf),this.progressPoller=new o_({emitProgressUpdate:(e,t)=>{this.emitToProgress(e,t)},globalStreamKey:n_,hasConnectionError:()=>Boolean(this.connectionError),hasSubscribers:e=>this.hasProgressSubscribers(e),listProgresses:s_([e,"optionalAccess",e=>e.listProgresses]),progressPollIntervalMs:s_([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 o=new i_((()=>{this.removeStream(e,o),s_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.removeEventListener,"call",e=>e("abort",i)])})),i=()=>{o.close()};if(this.disposed)return o.fail(new Error("Frontier watcher disposed")),o;if(this.connectionError)return o.fail(this.connectionError),o;if(s_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.aborted]))return o.close(),o;let s=this.sessionStreams.get(e);return s||(s=new Set,this.sessionStreams.set(e,s)),s.add(o),s_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.addEventListener,"call",e=>e("abort",i,{once:!0})]),o}watchProgress(e,t){const o=e||n_,i=new i_((()=>{this.removeProgressStream(o,i),s_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.removeEventListener,"call",e=>e("abort",s)])})),s=()=>{i.close()};if(this.disposed)return i.fail(new Error("Frontier watcher disposed")),i;if(this.connectionError)return i.fail(this.connectionError),i;if(s_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.aborted]))return i.close(),i;let n=this.progressStreams.get(o);if(n||(n=new Set,this.progressStreams.set(o,n)),n.add(i),s_([t,"optionalAccess",e=>e.signal,"optionalAccess",e=>e.addEventListener,"call",e=>e("abort",s,{once:!0})]),e)this.emitKnownProgresses(i,e),this.progressPoller.refresh(e),this.progressPoller.ensure(e);else for(const e of this.progressStateStore.getKnownClawIds())this.emitKnownProgresses(i,e);return i}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 o=this.sessionStreams.get(e);o&&(o.delete(t),0===o.size&&this.sessionStreams.delete(e))}removeProgressStream(e,t){const o=this.progressStreams.get(e);o&&(o.delete(t),0===o.size&&(this.progressStreams.delete(e),e!==n_&&this.progressPoller.stop(e)))}failAllStreams(e){for(const t of this.sessionStreams.values())for(const o of t)o.fail(e);this.sessionStreams.clear();for(const t of this.progressStreams.values())for(const o of t)o.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 o=this.replyStateStore.applyReplyEvent(e,t);o&&"sessionId"in o&&this.emitToSession(o.sessionId,o)}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:o}=t.progress;this.emitToProgress(o,t),this.emitToProgress(n_,t)}emitToSession(e,t){const o=this.sessionStreams.get(e);if(o&&0!==o.size)for(const e of o)e.push(t)}emitToProgress(e,t){const o=this.progressStreams.get(e);if(o&&0!==o.size)for(const e of o)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 a_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const c_=({replies:e,requestMessageId:t,source:o})=>{if(0===e.length)return null;const i=a_([e,"access",t=>t[e.length-1],"optionalAccess",e=>e.answerId]);return i?{answerId:i,content:e.map((e=>e.content)).filter(Boolean).join("\n\n"),files:a_([e,"access",t=>t[e.length-1],"optionalAccess",e=>e.files]),requestMessageId:t,source:o}:null},l_=({replies:e,replyOrder:t,reply:o})=>{e.has(o.answerId)||t.push(o.answerId),e.set(o.answerId,o)},d_=({event:e,replies:t,replyOrder:o})=>{const i=t.get(e.chunk.answerId),s={answerId:e.chunk.answerId,content:`${a_([i,"optionalAccess",e=>e.content])||""}${e.chunk.content}`,files:a_([i,"optionalAccess",e=>e.files]),requestMessageId:e.chunk.requestMessageId||a_([i,"optionalAccess",e=>e.requestMessageId])};return l_({replies:t,reply:s,replyOrder:o}),s},p_=({event:e,replies:t,replyOrder:o})=>(l_({replies:t,reply:e.reply,replyOrder:o}),e.reply);class u_{constructor(e){this.watcher=a_([e,"optionalAccess",e=>e.watcher])||new r_}async connect(e){await this.watcher.connect(e)}async waitForReply(e){const{onReplyChunk:t,onReplyUpdate:o,sessionId:i,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,l=[];let d=!1;const p=t=>{d||(d=!0,a_([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=c_({replies:l.map((e=>c.get(e))).filter((e=>Boolean(e))),requestMessageId:s,source:"timeout"});p((({reject:t,resolve:o})=>{e?o(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(i,{signal:r.signal})){if("reply_chunk"===e.type){if(e.chunk.requestMessageId!==s)continue;d_({event:e,replies:c,replyOrder:l}),a_([t,"optionalCall",t=>t(e)]);continue}if("reply_update"===e.type){if(e.reply.requestMessageId!==s)continue;p_({event:e,replies:c,replyOrder:l}),a_([o,"optionalCall",t=>t(e)]);continue}if("session_idle"!==e.type)continue;const i=c_({replies:e.replies.filter((e=>e.requestMessageId===s)),requestMessageId:s,source:"idle"});i&&p((({resolve:e})=>{e(i)}))}})();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 m_={skipOrgCheck:!0,skipSpaceCheck:!0},g_=async t=>{if(t)return t;const o=s.createSessionConfigStore(),i=await o.get();if(i.sessionId)return i.sessionId;throw new e.CozeError(e.ErrorCode.E1000,"Missing session ID: provide --session-id or run `coze session create` first")},h_=async({clawId:e,sessionId:t})=>{const o=s.createSessionConfigStore();await o.save({sessionId:t,...e?{sessionClawId:e}:{}})},f_=({timeoutMs:e})=>{const t=new AbortController,o=()=>{t.abort()},i=void 0===e?void 0:setTimeout((()=>{o()}),e);return process.once("SIGINT",o),{abort:o,signal:t.signal,dispose:()=>{i&&clearTimeout(i),process.off("SIGINT",o)}}},__=async(t,o)=>{const i=(t=>{const o=t.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");return{ctx:o,service:s.createDefaultSessionService(o.config)}})(t);try{await o(i)}catch(t){Q((t=>{if(t instanceof e.CozeError)return t;if(t instanceof s.SessionServiceError){const o="SESSION_AUTH_INVALID"===t.code?e.ErrorCode.E2001:e.ErrorCode.E5000;return new e.CozeError(o,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),i.ctx)}},y_=t=>{const o=Number.parseInt(t,10);if(!Number.isFinite(o)||o<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --limit: expected a positive integer");return o},b_=t=>{const o=Number.parseInt(t,10);if(!Number.isFinite(o)||o<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --timeout: expected a positive integer");return o},v_=e=>{if(!e||0===e.length)return null;const t=["Files:"];return e.forEach(((e,o)=>{t.push(`${o+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")},w_=(e,t)=>{const o=v_(t);return o?[e,"",o].join("\n"):e},E_=({accessToken:e,apiBaseUrl:t,organizationId:o,sessionApiBaseUrl:i,xTTEnv:n})=>{const r=i||t,a=(({accessToken:e,xTTEnv:t})=>{if(!e)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const o={Authorization:`Bearer ${e}`};return t&&(o["x-use-ppe"]="1",o["x-tt-env"]=t),o})({accessToken:e,xTTEnv:n});return{resolveConfig:async()=>({...await Sg({baseUrl:r,headers:a,xTTEnv:n}),headers:a,organizationId:o}),scopeKey:JSON.stringify({baseUrl:r,authorization:a.Authorization,organizationId:o,xTTEnv:n})}},C_=async({accessToken:e,apiBaseUrl:t,organizationId:o,sessionApiBaseUrl:i,progressPollIntervalMs:s,service:n,xTTEnv:r})=>{const a=new r_({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(E_({accessToken:e,apiBaseUrl:t,organizationId:o,sessionApiBaseUrl:i,xTTEnv:r})),a},I_=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"),A_=e=>`${JSON.stringify(e)}\n`;class S_{__init(){this.replyStates=new Map}__init2(){this.requestPrintedContent=new Map}__init3(){this.endsWithNewline=!0}__init4(){this.hasStartedReply=!1}constructor(e){S_.prototype.__init.call(this),S_.prototype.__init2.call(this),S_.prototype.__init3.call(this),S_.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(A_({type:"reply_chunk",session_id:t,answer_message_id:e.answerId,reply_to_message_id:e.requestMessageId,delta:e.content}));const o=this.getOrCreateReplyState(e.answerId);this.ensureReplyStarted({answerId:e.answerId,requestMessageId:e.requestMessageId,state:o}),this.writeRaw(e.content),o.printedContent+=e.content,this.updateRequestPrintedContent({requestMessageId:e.requestMessageId,printedContent:o.printedContent})}writeReply({files:e,reply:t,sessionId:o,source:i}){if("text"!==this.format)return void this.write(A_({type:"message"===i?"reply_update":"reply_completed",session_id:o,answer_message_id:t.answerId,reply_to_message_id:t.requestMessageId,content:t.content,files:e,event_source:i}));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"!==i)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"!==i&&this.writeFinalReplyMetadata({files:e})}writeFinalReplyMetadata({files:e}){this.endsWithNewline||this.writeRaw("\n");const t=v_(e);t&&this.writeRaw(`\n${t}\n`)}writeProgress({progress:e,sessionId:t}){"text"===this.format?(this.endsWithNewline||this.writeRaw("\n"),this.writeRaw(`\n${I_(e)}\n`)):this.write(A_({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 o={headerPrinted:!1,printedContent:""};return this.replyStates.set(e,o),o}ensureReplyStarted({answerId:e,continuesPrintedRequest:t=!1,requestMessageId:o,state:i}){if(!i.headerPrinted){if(t)return i.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}`,o?`reply_to_message_id: ${o}`:null].filter(Boolean);this.writeRaw(`${t.join("\n")}\n`)}i.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 o=this.requestPrintedContent.get(t)||"";e.length>=o.length&&this.requestPrintedContent.set(t,e)}writeRaw(e){e&&(this.write(e),this.endsWithNewline=e.endsWith("\n"))}}function k_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const j_=({ctx:e,sessionId:t,reply:o,files:i,source:s})=>{"text"!==e.format?e.response.print({session_id:t,answer_message_id:o.answerId,reply_to_message_id:o.requestMessageId,content:o.content,files:i,event_source:s}):e.response.print((({reply:e,files:t,source:o})=>`${[`answer_message_id: ${e.answerId}`,e.requestMessageId?`reply_to_message_id: ${e.requestMessageId}`:null,`event_source: ${o}`].filter(Boolean).join("\n")}\n${w_(e.content,t)}`)({files:i,reply:o,source:s}))},P_=({ctx:e,options:t,service:o,streamRenderer:i})=>{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:o}),a=async({reply:o,source:i})=>{const s=await r(o),a=(({files:e,reply:t})=>JSON.stringify({answerId:t.answerId,content:t.content,files:e,requestMessageId:t.requestMessageId}))({files:s,reply:o});k_([n,"optionalAccess",e=>e.get,"call",e=>e(o.answerId)])!==a&&(k_([n,"optionalAccess",e=>e.set,"call",e=>e(o.answerId,a)]),j_({ctx:e,files:s,reply:o,sessionId:t.sessionId,source:i}))};return{handleReplyChunk:e=>{k_([i,"optionalAccess",e=>e.writeChunk,"call",o=>o({chunk:e.chunk,sessionId:t.sessionId})])},handleReplyUpdate:async e=>{i?i.writeReply({reply:e.reply,sessionId:t.sessionId,source:"message"}):await a({reply:e.reply,source:"message"})},handleIdleReply:async e=>{i?i.writeReply({files:await r(e),reply:e,sessionId:t.sessionId,source:"idle"}):await a({reply:e,source:"idle"})}}},z_=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",b_).option("--snapshot","Print full reply snapshots instead of streaming chunks incrementally").config({...m_,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 __(t,(async({ctx:t,service:o})=>{const i=await g_(e.sessionId),s={...e,sessionId:i},n=await C_({accessToken:t.config.accessToken,apiBaseUrl:t.config.apiBaseUrl,organizationId:t.config.organizationId,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv});await h_({sessionId:i});const r=s.snapshot?null:new S_({format:t.format,includeReplyMetadata:"text"===t.format}),a=f_({timeoutMs:s.timeout}),c=P_({ctx:t,options:s,service:o,streamRenderer:r});try{for await(const e of n.watchSession(i,{signal:a.signal}))if("reply_chunk"!==e.type)if("reply_update"!==e.type){if("progress_update"!==e.type){await o.updateSessionRuntimeStatus({sessionId:i,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 T_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const R_=async e=>await new Promise((t=>setTimeout(t,e))),x_=e=>{const t=e.contentPreview&&e.contentPreview!==e.replyContent?e.contentPreview:void 0,o=e.resultSummary&&e.resultSummary!==e.replyContent&&e.resultSummary!==e.contentPreview?e.resultSummary:void 0;return{contentPreview:t,replyContent:e.replyContent,resultSummary:o}},L_=e=>{const t=x_(e);return{answer_message_id:e.answerMessageId,artifacts:T_([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}},O_=e=>{const t=x_(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")},D_=({ctx:e,task:t})=>{"text"!==e.format?e.response.print(L_(t)):e.response.print(O_(t))},U_=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)),q_=e=>{const t=e.command("task").description("Inspect persisted session background tasks").config({...m_,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 __(t,(async({ctx:t,service:o})=>{try{const i=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:o,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await i.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(O_).join("\n\n"):"No session tasks");t.response.print({items:n.map((e=>L_(e)))})}catch(e){throw U_(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,o)=>{await(async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{try{const i=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:o,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await i.getTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});D_({ctx:t,task:n})}catch(e){throw U_(e)}}))})({includeExpired:t.includeExpired,taskId:e},o)})),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,o)=>{await(async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{try{const i=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:o,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}),n=await i.refreshTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});D_({ctx:t,task:n})}catch(e){throw U_(e)}}))})({includeExpired:t.includeExpired,taskId:e},o)})),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",b_).action((async(e,t,o)=>{await(async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{try{const i=s.createSessionTaskService({apiBaseUrl:t.config.apiBaseUrl,service:o,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv});let n=await i.getTask(e.taskId,{includeExpired:Boolean(e.includeExpired)});if(D_({ctx:t,task:n}),s.isSessionTaskTerminal(n.status))return;const r=void 0===e.timeout?void 0:Date.now()+e.timeout;for(;;){const o=void 0===r?1e4:Math.min(1e4,r-Date.now());if(o<=0)return;if(await R_(o),n=await i.refreshTask(e.taskId,{includeExpired:Boolean(e.includeExpired)}),D_({ctx:t,task:n}),s.isSessionTaskTerminal(n.status))return}}catch(e){throw U_(e)}}))})({includeExpired:t.includeExpired,taskId:e,timeout:t.timeout},o)})),t.command("gc").description("Remove expired terminal session tasks from local storage").action((async(e,t)=>{await(async e=>{await __(e,(async({ctx:e,service:t})=>{try{const o=s.createSessionTaskService({apiBaseUrl:e.config.apiBaseUrl,service:t,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv}),i=await o.gcTasks();if("text"===e.format)return void e.response.print(i.length>0?`Removed ${i.length} expired task(s)`:"No expired session tasks");e.response.print({count:i.length,items:i.map((e=>L_(e)))})}catch(e){throw U_(e)}}))})(t)}))},B_=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${w_(e.content,e.files)}`,M_=async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{const i=await g_(e.sessionId),n=await o.listRepliesByMessage({sessionId:i,messageId:e.messageId});await h_({sessionId:n.sessionId});const r=s.createSessionConfigStore(),a=await r.get(),c=n.items.some((e=>e.files&&e.files.length>0)),l=c?a.sessionClawId||(await o.getStatus()).clawId:void 0,d=c?await(async({items:e,store:t,service:o,clawId:i,apiBaseUrl:n,sessionApiBaseUrl:r,xTTEnv:a})=>await Promise.all(e.map((async e=>({...e,files:await s.resolveStoredSessionReplyFiles({files:e.files,clawId:i,apiBaseUrl:n,sessionApiBaseUrl:r,xTTEnv:a,service:o,deps:{store:t}})})))))({items:n.items,store:r,service:o,clawId:l,apiBaseUrl:t.config.apiBaseUrl,sessionApiBaseUrl:t.config.sessionApiBaseUrl,xTTEnv:t.config.xTTEnv}):n.items;if("text"===t.format)return n.requestMessageFound||0!==d.length?0===d.length?void t.response.print(`No replies found for message: ${e.messageId}`):void t.response.print(d.map(B_).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:d.length,items:d.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 N_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const $_=({ctx:e})=>{const t=new Map;return o=>{const i=t.get(o.progressId);i&&i.progressStatus===o.progressStatus&&i.name===o.name&&i.type===o.type&&"snapshot"!==o.eventSource||(t.set(o.progressId,{name:o.name,progressId:o.progressId,progressStatus:o.progressStatus,type:o.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(`${I_(t)}\nevent_source: ${t.eventSource}`)})({ctx:e,progress:o}))}},G_=(e,t)=>!t||e.progressId===t,F_=async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{(({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=>I_(e))).join("\n\n"):"No active progress")})({ctx:t,progresses:await o.listProgresses({size:e.size})})}))},V_=async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{const i=await o.getStatus(),{clawId:n}=i;if(!i.authValid||!n)throw new s.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const r=await C_({accessToken:t.config.accessToken,apiBaseUrl:t.config.apiBaseUrl,organizationId:t.config.organizationId,progressPollIntervalMs:3e4,sessionApiBaseUrl:t.config.sessionApiBaseUrl,service:o,xTTEnv:t.config.xTTEnv}),a=f_({timeoutMs:e.timeout}),c=$_({ctx:t});try{await(async({clawId:e,emitProgress:t,options:o,service:i})=>{(await i.listProgresses({clawId:e})).filter((e=>G_(e,o.progressId))).forEach((e=>{t({...e,eventSource:"snapshot"})}))})({clawId:n,emitProgress:c,options:e,service:o}),await(async({abortScope:e,clawId:t,emitProgress:o,options:i,watcher:s})=>{for await(const n of s.watchProgress(t,{signal:e.signal}))G_(n.progress,i.progressId)&&(o({progressId:n.progress.progressId,name:n.progress.name,type:n.progress.progressType,progressStatus:n.progress.progressStatus,eventSource:"websocket"}),i.progressId&&"finished"===n.progress.progressStatus&&e.abort())})({abortScope:a,clawId:n,emitProgress:c,options:e,watcher:r})}finally{a.dispose(),r.dispose()}}))},W_=e=>{const t=e.command("progress").description("Inspect claw background progress").config({...m_,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",y_,100).action(F_),t.command("show <progressId>").description("Show one background progress snapshot").action((async(e,t,o)=>{await(async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{const i=await o.getProgress({progressId:e.progressId});"text"!==t.format?t.response.print({progress_id:e.progressId,found:Boolean(i),name:N_([i,"optionalAccess",e=>e.name]),type:N_([i,"optionalAccess",e=>e.type]),progress_status:N_([i,"optionalAccess",e=>e.progressStatus]),raw:N_([i,"optionalAccess",e=>e.raw])}):t.response.print(i?I_(i):`Progress not found: ${e.progressId}`)}))})({progressId:e},o)})),t.command("poll <progressId>").description("Poll one background progress and treat missing as finished").action((async(e,t,o)=>{await(async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{const i=await o.getProgress({progressId:e.progressId}),s=N_([i,"optionalAccess",e=>e.progressStatus])||"finished";"text"!==t.format?t.response.print({progress_id:e.progressId,name:N_([i,"optionalAccess",e=>e.name]),type:N_([i,"optionalAccess",e=>e.type]),progress_status:s,raw:N_([i,"optionalAccess",e=>e.raw])}):t.response.print(I_({progressId:e.progressId,name:N_([i,"optionalAccess",e=>e.name]),type:N_([i,"optionalAccess",e=>e.type]),progressStatus:s}))}))})({progressId:e},o)})),t.command("watch [progressId]").description("Watch one or all background progress updates").option("--timeout <timeoutMs>","Stop watching after the specified timeout in milliseconds",b_).action((async(e,t,o)=>{await V_({progressId:e,timeout:t.timeout},o)}))};function H_(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const J_={...m_,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"}}}}}},K_=async({ctx:t,options:o,resolvedContent:i})=>{if(!o.podcastVoice)return i;if(!i)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-voice requires MESSAGE or stdin content");const s=(({config:t,voice:o,mode:i})=>{const s=qg(o),n=Mg({config:t,mode:i}).filter((e=>qg(e.label)===s||qg(e.value)===s));if(0===n.length)throw new e.CozeError(e.ErrorCode.E1000,`Podcast voice not found: ${o}`);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 "${o}" matched multiple podcast voices; specify --podcast-mode (${t})`)}return n[0]})({config:await Bg({baseUrl:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,xTTEnv:t.config.xTTEnv}),voice:o.podcastVoice,mode:o.podcastMode}).label||o.podcastVoice;return(({content:t,voiceLabel:o})=>{if(t.includes('使用音色"'))throw new e.CozeError(e.ErrorCode.E1000,"Message already contains a podcast voice instruction");const i=`使用音色"${o}", `,s=t.length-t.trimStart().length,n=t.slice(0,s),r=t.trimStart();if(/^@播客(?=\s|$)/.test(r))return`${n}@播客 ${i}${r.slice(3).trimStart()}`;return`${i}${t}`})({content:i,voiceLabel:s})},Q_=async({ctx:t,message:o,options:i,service:s})=>{const{content:n,filePaths:r}=await Ug(o,{cwd:t.cwd,onWarn:e=>t.ui.warn(e)});(({options:t,resolvedContent:o})=>{if(t.podcastMode&&!t.podcastVoice)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-mode requires --podcast-voice");if(t.podcastVoice&&!o)throw new e.CozeError(e.ErrorCode.E1000,"--podcast-voice requires MESSAGE or stdin content")})({options:i,resolvedContent:n});const a=await Pg({filePaths:[...i.file||[],...r],sessionId:i.sessionId,apiBaseUrl:t.config.apiBaseUrl,sessionApiBaseUrl:t.config.sessionApiBaseUrl,sessionSpaceWebId:t.config.sessionSpaceWebId,xTTEnv:t.config.xTTEnv,service:s}),c=await K_({ctx:t,options:i,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}},Y_=async({ctx:e,options:t,service:o})=>{if(!t.wait)return{streamRenderer:null,waiter:null};const i=new S_({format:e.format}),s=H_([await o.getStatus(),"optionalAccess",e=>e.clawId]);return{clawId:s,knownProgressIds:s?await o.listProgresses({clawId:s}).then((e=>new Set(e.map((e=>e.progressId))))).catch((()=>null)):void 0,streamRenderer:i,waiter:await(async({accessToken:e,apiBaseUrl:t,organizationId:o,sessionApiBaseUrl:i,xTTEnv:s})=>new u_({watcher:await C_({accessToken:e,apiBaseUrl:t,organizationId:o,sessionApiBaseUrl:i,xTTEnv:s})}))({accessToken:e.config.accessToken,apiBaseUrl:e.config.apiBaseUrl,organizationId:e.config.organizationId,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv})}},Z_=async({ctx:e,knownProgressIds:t,options:o,result:i,service:n,streamRenderer:r,waiter:a,clawId:c})=>{const l=await a.waitForReply({onReplyChunk:r?e=>{r.writeChunk({chunk:e.chunk,sessionId:o.sessionId})}:void 0,onReplyUpdate:r?e=>{r.writeReply({reply:e.reply,sessionId:o.sessionId,source:"message"})}:void 0,sessionId:o.sessionId,requestMessageId:i.messageId,timeoutMs:o.timeout}),d="idle"===l.source&&c&&t?await(async({clawId:e,knownProgressIds:t,listProgresses:o,pollIntervalMs:i=500,timeoutMs:s=3e3})=>{const n=Date.now()+s;for(;;){const s=(await o({clawId:e})).find((e=>!t.has(e.progressId)));if(s)return s;const r=n-Date.now();if(r<=0)return null;await vg(Math.min(i,r))}})({clawId:c,knownProgressIds:t,listProgresses:e=>n.listProgresses(e),timeoutMs:3e3}):null;"idle"===l.source&&await n.updateSessionRuntimeStatus({sessionId:o.sessionId,status:"idle"});const p=await s.resolveStoredSessionReplyFiles({files:l.files,apiBaseUrl:e.config.apiBaseUrl,sessionApiBaseUrl:e.config.sessionApiBaseUrl,xTTEnv:e.config.xTTEnv,service:n});return r?(r.writeReply({files:p,reply:{answerId:l.answerId,content:l.content,requestMessageId:i.messageId},sessionId:o.sessionId,source:l.source}),d&&r.writeProgress({progress:d,sessionId:o.sessionId}),{answerMessageId:l.answerId,content:l.content,files:p,progress:d,rendered:!0}):{answerMessageId:l.answerId,content:l.content,files:p,progress:d,rendered:!1}},X_=async(e,t,o)=>{await __(o,(async({ctx:o,service:i})=>{const n=await g_(t.sessionId),r={...t,sessionId:n},a=await Q_({ctx:o,message:e,options:r,service:i}),c=await Y_({ctx:o,options:r,service:i});try{const e=await i.sendMessage({sessionId:n,content:a.content,files:a.files});if(await h_({sessionId:e.sessionId}),c.waiter){const t=await Z_({...c,ctx:o,options:r,result:e,service:i,waiter:c.waiter});if(t.progress)try{const r=s.createSessionTaskService({apiBaseUrl:o.config.apiBaseUrl,service:i,sessionApiBaseUrl:o.config.sessionApiBaseUrl,xTTEnv:o.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:o.config.accessToken||"",apiBaseUrl:o.config.apiBaseUrl,organizationId:o.config.organizationId,sessionApiBaseUrl:o.config.sessionApiBaseUrl,taskId:a.taskId,xTTEnv:o.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"===o.format)return void o.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(o.ui.warn(`Failed to persist task: ${t instanceof Error?t.message:String(t)}`),"json"===o.format)return void o.response.print({session_id:e.sessionId,message_id:e.messageId,status:e.status})}if(t.rendered)return}o.response.print({session_id:e.sessionId,message_id:e.messageId,status:e.status})}finally{H_([c,"access",e=>e.waiter,"optionalAccess",e=>e.dispose,"call",e=>e()])}}))};const ey={...m_,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"}]}},ty=t=>{const o=Number.parseInt(t,10);if(!Number.isFinite(o)||o<=0)throw new e.CozeError(e.ErrorCode.E1000,"Invalid value for --page: expected a positive integer");return o},oy=(e,t)=>[...t,ty(e)],iy=t=>{if("ppt"===t||"editable"===t)return t;throw new e.CozeError(e.ErrorCode.E1000,'Invalid value for --export-type: expected "ppt" or "editable"')},sy=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.")},ny=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},ry=async({file:e,service:t})=>e.fileUrl?e.fileUrl:t.resolveFileUrl({fileUri:ny(e)}),ay=async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{const i=await sy({options:e}),n=await ry({file:i,service:o}),r=await s.fetchSessionPptContent({url:n}),a=s.parseSessionPptContent(r);"text"!==t.format?t.response.print({file_name:i.fileName,file_uri:i.fileUri,file_url:n,type:a.type,page_count:a.pageCount}):t.response.print((({file:e,pageCount:t,type:o,url:i})=>[`PPT: ${e.fileName}`,e.fileUri?`file_uri: ${e.fileUri}`:null,`file_url: ${i}`,`type: ${o}`,`pages: ${t}`].filter(Boolean).join("\n"))({file:i,pageCount:a.pageCount,type:a.type,url:n}))}))},cy=t=>{const o=t.command("ppt").description("Inspect, export, share, and edit session PPT artifacts").config(ey);o.command("info").description("Get PPT metadata and page count").option("--file-uri <uri>","Specific PPT file_uri").action(((e,t)=>ay(e,t))),o.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",y_).action(((e,t)=>(async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{const i=await sy({options:e}),n=await ry({file:i,service:o}),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:i.fileName,file_uri:i.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}`:"",o=(i=e.previewText||(e.previewUrl?`preview_url: ${e.previewUrl}`:"")).length>500?`${i.slice(0,500)}...`:i;var i;return o?`${e.page}.${t}\n${o}`:`${e.page}.${t}`})).join("\n\n"))(c))}))})(e,t))),o.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",iy,"ppt").action(((e,t)=>(async(e,t)=>{await __(t,(async({ctx:t,service:o})=>{const i=await sy({options:e}),s=ny(i),n=await o.exportPpt({fileUri:s,exportType:e.exportType}),r=await Cg({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))),o.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",oy,[]).option("--wait","Wait until the edit turn becomes idle").option("--timeout <timeoutMs>","Timeout for --wait",b_).action(((t,o,i)=>(async(t,o,i)=>{if(!function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([o,"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 X_(s.formatSessionPptEditQuery({pages:o.page,query:t}),{sessionId:o.sessionId,wait:o.wait,timeout:o.timeout},i)})(t,o,i))),o.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 __(t,(async({ctx:t,service:o})=>{const i=await sy({options:e}),n=ny(i),r=s.buildSessionPptSlideUrl({origin:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,fileUri:n,taskId:e.taskId}),a=!1===e.short?r:await o.shortenWebUrl({url:r});"text"!==t.format?t.response.print({file_name:i.fileName,file_uri:n,url:a,original_url:r,short:!1!==e.short}):t.response.print(a)}))})(e,t)))},ly=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"),dy=async(e,t)=>{await __(t,(async({ctx:t})=>{const o=await Bg({baseUrl:t.config.sessionApiBaseUrl||t.config.apiBaseUrl,xTTEnv:t.config.xTTEnv}),i=Mg({config:o,mode:e.mode,keyword:e.keyword});"text"!==t.format?t.response.print({count:i.length,items:i}):t.response.print(i.length>0?i.map(ly).join("\n\n"):"No podcast voices matched")}))},py=(e,t)=>[...t,e],uy=async(t,o,i)=>{(t=>{if(t.mode&&!t.voice)throw new e.CozeError(e.ErrorCode.E1000,"--mode requires --voice")})(o),await X_(t,(e=>({file:e.file||[],podcastMode:e.mode,podcastVoice:e.voice,sessionId:e.sessionId,timeout:e.timeout,wait:e.wait}))(o),i)},my=e=>{const t=e.command("podcast").description("Inspect podcast config");t.config({...m_,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",b_).option("--file <path>","Local file to upload and attach (can be used multiple times)",py,[]).config({...m_,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(uy)})(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({...m_,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(dy)})(t)};function gy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const hy=e=>{e.command("current").description("Show the current locally selected default session").config({...m_,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(),o=s.createSessionConfigStore(),i=await o.get();if("text"===gy([t,"optionalAccess",e=>e.format])){if(!i.sessionId)return void gy([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e("No current session configured")]);const e=[`session_id: ${i.sessionId}`];return i.sessionClawId&&e.push(`claw_id: ${i.sessionClawId}`),void gy([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e.join("\n"))])}gy([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({configured:Boolean(i.sessionId),session_id:i.sessionId,claw_id:i.sessionClawId})])})(t)}))},fy=e=>{e.command("use <sessionId>").description("Set the current locally selected default session").config({...m_,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,o)=>{await(async({cmd:e,sessionId:t})=>{const o=e.getContext();await h_({sessionId:t}),gy([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"updated",session_id:t})])})({cmd:o,sessionId:e})}))},_y=e=>{const t=e.command("session").description("Manage Coze session-based claw chat").config({...m_,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({...m_,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 __(t,(async({ctx:t,service:o})=>{if(e.sessionId){const i=await o.getSessionDisplayStatus({sessionId:e.sessionId});return void t.response.print({session_id:i.sessionId,display_status:i.displayStatus,claw_busy:i.clawBusy,claw_progress_count:i.clawProgressCount,runtime_status:i.runtimeStatus,updated_at:i.updatedAt})}const i=await o.getStatus();t.response.print({auth_configured:i.authConfigured,auth_valid:i.authValid,claw_id:i.clawId,account_id:i.accountId,updated_at:i.updatedAt})}))}))})(t),(e=>{e.command("create").description("Create a new claw chat session").config({...m_,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 __(t,(async({ctx:e,service:t})=>{const o=await t.createSession();await h_({clawId:o.clawId,sessionId:o.sessionId}),e.response.print({status:"created",claw_id:o.clawId,session_id:o.sessionId})}))}))})(t),hy(t),fy(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",y_,20).config({...m_,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 __(t,(async({ctx:t,service:o})=>{const i=await o.listSessions({offset:e.offset,limit:e.limit});t.response.print({items:i.items,next_offset:i.nextOffset,has_more:i.hasMore})}))}))})(t),(e=>{e.command("file").description("Manage files returned by claw session replies").config({...m_,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({...m_,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,o)=>{await __(o,(async({ctx:o})=>{const i=await Cg({url:e,outputPath:t.outputPath});"text"!==o.format?o.response.print({status:"saved",path:i.path,filename:i.filename,size:i.size,url:i.url}):o.response.print(i.path)}))}))})(t),my(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",b_).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(J_).action(X_)})(t),cy(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({...m_,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,o)=>{await M_({messageId:e,sessionId:t.sessionId},o)}))})(t),z_(t),W_(t),q_(t)};function yy(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"},{desc:"Upgrade then sync bundled skills",cmd:"coze upgrade && coze self skill install",tags:["[PIPELINE]"]}],enums:{tag:{latest:"Stable release channel (default)",beta:"Pre-release channel for early testing"}},schema:{input:{force:{type:"boolean",required:!1,default:!1,description:"Reinstall even if already on the latest version"},tag:{type:"string",required:!1,default:"latest",description:"npm dist-tag to upgrade to",example:"latest"}},output:{previousVersion:{type:"string",description:"Version before the upgrade",example:"1.2.3"},currentVersion:{type:"string",description:"Version reported by the running binary after install",example:"1.3.0"},latestVersion:{type:"string",description:"Latest version found on the registry for the given tag",example:"1.3.0"},status:{type:"string",enum:["upgraded"],description:"Operation result",example:"upgraded"}}},errors:[{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Failed to reach the npm registry when checking the latest version",fix:"Check network connectivity and the configured npm registry, then retry",example:"coze upgrade --force"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"The global install command failed (e.g. permission denied or unknown dist-tag), exiting with code 1",fix:"Upgrade manually with the printed command, e.g. `npm install -g @coze/cli`",example:"npm install -g @coze/cli@latest"}],seeAlso:["coze --version","coze self skill install"],caveats:["Requires permission to install global packages; on some systems this needs sudo or a configured npm prefix","The running process is still the old binary after the upgrade; run `coze self skill install` afterwards to sync bundled skills"]}}).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 ge(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: ${o.gray(e.currentVersion)} → ${o.green(e.latestVersion)}`),n.ui.info("Upgrading Coze CLI...");const s=ee(),r=function(e,t){switch(e){case"pnpm":return`pnpm add -g ${X}@${t}`;case"yarn":return`yarn global add ${X}@${t}`;default:return`npm install -g ${X}@${t}`}}(s,e.latestVersion);n.ui.verbose(`Using package manager: ${s}`),n.ui.verbose(`Running: ${r}`),i.execSync(r,{stdio:"inherit"});const a=ne();n.ui.success(`Successfully upgraded Coze CLI to ${e.latestVersion}. (was ${e.currentVersion})`),n.ui.info(`Run ${o.cyan("coze self skill install")} to sync the bundled skills to your AI tools.`),"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"),n.ui.info(`If you are on an internal network, verify your npm registry with ${o.cyan("npm config get registry")}.`),process.exit(e.ExitCode.FAILURE)}}))}function by(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const vy={brief:"Install bundled skills to AI agents",description:"Idempotently sync the current CLI bundled skills via the `skills` tool: copy them into the shared central pool (`~/.agents/skills/`) and symlink them into every installed agent. Records `~/.coze/cli/.skill-lock.json` with the CLI version. User-modified skills are reported instead of silently overwritten unless `--force` is passed.",examples:[{desc:"Install to all installed agents",cmd:"coze self skill install",tags:["[RECOMMENDED]"]},{desc:"Install to a specific subset",cmd:"coze self skill install --target claude,trae"},{desc:"Overwrite user-modified skills",cmd:"coze self skill install --force"},{desc:"Re-install only when versions diverge",cmd:"coze self skill status --format json | jq -e .versionMatch >/dev/null || coze self skill install",tags:["[PIPELINE]"]}],enums:{target:{claude:"Claude Code (mapped to the skills agent id claude-code)",trae:"Trae",comate:"Comate",all:"All installed agents (same as omitting --target)"}},schema:{input:{target:{type:"string",required:!1,description:'Comma-separated agent names to install to; omit or pass "all" to fan out to every installed agent. Unknown names are passed through to the skills CLI for validation.',example:"claude,trae"},force:{type:"boolean",required:!1,default:!1,description:"Overwrite user-modified skills instead of aborting the install"}},output:{blocked:{type:"boolean",description:"True when user-modified skills were detected without --force; nothing was written"},cliVersion:{type:"string",description:"CLI version the skills were released as",example:"0.1.0"},sourceRoot:{type:"string",description:"Bundled skill source directory used as input"},poolPath:{type:"string",required:!1,description:"Skill path inside the skills central pool",example:"~/.agents/skills/using-coze-cli"},linkedTargets:{type:"array",items:{type:"string"},description:"Agent display names the skills were linked to"},skillsOk:{type:"boolean",description:"Whether every `skills` subprocess invocation succeeded"},modifiedSkills:{type:"array",items:{type:"string"},description:"User-modified skill names that blocked the sync (empty unless blocked)"}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing (no packaged skills/manifest.json and no dev-mode docs/skills), which indicates a corrupted CLI installation",fix:"Reinstall or upgrade the CLI, then run the install again",example:"coze upgrade && coze self skill install"}],seeAlso:["coze self skill status","coze self skill remove","coze self skill path"],caveats:["When user-modified skills are detected without --force, the command warns and exits without writing anything (blocked=true); --force discards those local edits","A partial `skills` subprocess failure is reported as a warning (skillsOk=false) instead of a non-zero exit; re-run the install or check `coze self skill path`","Agents share the `~/.agents/skills` central pool; a listed agent can read the skill, it does not hold a per-agent copy"]};function wy(e,t){return null!=e?e:t()}function Ey(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Cy={brief:"Show skill consistency status",description:"Compare the installed skill lock against the current CLI: version match, binary path match, and per-skill ok/drift/modified/missing state. Fully local and read-only, no network. When no lock exists yet, the command suggests running `coze self skill install` first.",examples:[{desc:"Show status (minimal)",cmd:"coze self skill status",tags:["[RECOMMENDED]"]},{desc:"Show status as JSON",cmd:"coze self skill status --format json"},{desc:"Re-sync only when versions diverge",cmd:"coze self skill status --format json | jq -e .versionMatch >/dev/null || coze self skill install",tags:["[PIPELINE]"]}],schema:{output:{lockExists:{type:"boolean",description:"Whether `~/.coze/cli/.skill-lock.json` exists (false = never synced)"},cliVersion:{type:"string",description:"Current CLI version",example:"0.1.0"},installedVersion:{type:"string",required:!1,description:"CLI version recorded at the last sync"},versionMatch:{type:"boolean",description:"Whether installedVersion equals cliVersion"},installedBin:{type:"string",required:!1,description:"CLI binary path recorded at the last sync"},currentBin:{type:"string",description:"CLI binary path of the current process"},binMatch:{type:"boolean",description:"Whether the current binary performed the last sync"},poolPath:{type:"string",required:!1,description:"Skill path inside the skills central pool; absent when not installed"},targets:{type:"array",items:{type:"string"},description:"Agents linked at the last sync"},skills:{type:"array",description:"Per-skill consistency state",items:{type:"object",properties:{name:{type:"string",description:"Skill name"},path:{type:"string",description:"Path relative to the bundled skills root"},state:{type:"string",enum:["ok","drift","modified","missing"],description:"ok = matches current CLI, drift = matches an older sync, modified = user-edited, missing = not in the pool"}}}}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing (no packaged skills/manifest.json and no dev-mode docs/skills), so there is no baseline to compare against",fix:"Reinstall or upgrade the CLI to restore the bundled skills",example:"coze upgrade"}],seeAlso:["coze self skill install","coze self skill list","coze self skill remove"]},Iy={ok:"ok",drift:"version drift",modified:"user-modified",missing:"missing"};function Ay(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Sy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function ky(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const jy=t=>{const o=t.command("skill").description("Install CLI-bundled skills to your AI tools and keep versions aligned").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Manage CLI-bundled skills",description:"Sync the skills bundled with the current CLI via the `skills` tool into the shared central pool (`~/.agents/skills/`) and fan out symlinks to installed AI agents (Claude Code / Trae / Comate). Skill version is strictly equal to the CLI version, eliminating drift at the source.",examples:[{desc:"Install skills to all installed agents",cmd:"coze self skill install",tags:["[RECOMMENDED]"]},{desc:"Check skill/CLI version consistency",cmd:"coze self skill status"},{desc:"Print a bundled skill",cmd:"coze self skill show using-coze-cli"},{desc:"Uninstall installed skills from all agents",cmd:"coze self skill remove"}],seeAlso:["coze upgrade","coze code skill"]}});(e=>{e.command("install").description("Sync bundled skills into the shared pool and fan out symlinks to agents").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:vy}).option("--target <names>","Comma-separated agents to install to (claude,trae,comate,all)").option("--force","Overwrite user-modified skills").action((async(e,t)=>{const o=t.getContext(),i="string"==typeof e.target?e.target.split(",").map((e=>e.trim())).filter(Boolean):void 0,s=await Je({targets:i,force:Boolean(e.force)});if(s.blocked)return by([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Detected user-modified skills: ${s.modifiedSkills.join(", ")}.\nUse \`coze self skill install --force\` to overwrite them.`)]),void("json"===by([o,"optionalAccess",e=>e.format])&&o.response.print(s));if(s.unknownTargets.length>0&&by([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Unknown targets ignored: ${s.unknownTargets.join(", ")}`)]),s.linkedTargets.length>0){const e=10,t=[...s.linkedTargets].sort(((e,t)=>e.localeCompare(t))),i=t.length>e?`${t.slice(0,e).join(", ")} +${t.length-e} more`:t.join(", ");by([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Installed skill (v${s.cliVersion}) to ${t.length} agent(s): ${i}`)]),by([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Note: agents share `~/.agents/skills`; being listed means they can read the skill, not a per-agent copy.")])}else by([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Installed skill (v${s.cliVersion}). No installed agent detected to link.`)]);s.skillsOk||by([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e("The `skills` tool reported a partial failure; run `coze self skill install` again or check `coze self skill path`.")]),"json"===by([o,"optionalAccess",e=>e.format])&&o.response.print(s)}))})(o),(e=>{e.command("status").description("Show installed skill version vs current CLI version").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:Cy}).action((async(e,t)=>{const o=t.getContext(),i=await Qe();if("json"!==Ey([o,"optionalAccess",e=>e.format]))if(i.lockExists){Ey([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Current CLI version : ${i.cliVersion}`)]),Ey([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Installed skill ver : ${wy(i.installedVersion,(()=>"unknown"))}`)]),i.versionMatch?Ey([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Version match: skills are consistent with the CLI.")]):Ey([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Version mismatch: skills(${i.installedVersion}) ≠ CLI(${i.cliVersion}). Run \`coze self skill install\`.`)]),i.binMatch||Ey([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Installed by a different binary (${i.installedBin}); current is ${i.currentBin}.`)]),Ey([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Linked agents : ${i.targets.join(", ")||"(none)"}`)]);for(const e of i.skills){const t=wy(Iy[e.state],(()=>e.state));Ey([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",o=>o(` - ${e.name}: ${t}`)])}}else Ey([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e("No skills installed yet. Run `coze self skill install` to install the bundled skills.")]);else o.response.print(i)}))})(o),(t=>{t.command("list").description("List the skills bundled with this CLI").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"List bundled skills",description:"List every skill bundled with the current CLI, with its name and relative path. Version equals the CLI version. Fully local and read-only: no network access and no files are written.",examples:[{desc:"List bundled skills (minimal)",cmd:"coze self skill list",tags:["[RECOMMENDED]"]},{desc:"List bundled skills as JSON",cmd:"coze self skill list --format json"},{desc:"Extract skill names for scripting",cmd:"coze self skill list --format json | jq -r '.skills[].name'",tags:["[PIPELINE]"]},{desc:"Print the first bundled skill in full",cmd:"coze self skill show $(coze self skill list --format json | jq -r '.skills[0].name')",tags:["[PIPELINE]"]}],schema:{output:{cliVersion:{type:"string",description:"Current CLI version (equals the skill version)",example:"0.1.0"},skills:{type:"array",description:"Bundled skills",items:{type:"object",properties:{name:{type:"string",description:"Skill name"},path:{type:"string",description:"Path relative to the bundled skills root"},version:{type:"string",description:"Skill version (equals cliVersion)"}}}}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing (no packaged skills/manifest.json and no dev-mode docs/skills), which indicates a corrupted CLI installation",fix:"Reinstall or upgrade the CLI to restore the bundled skills",example:"coze upgrade"}],seeAlso:["coze self skill show","coze self skill install","coze self skill status"]}}).action((async(e,t)=>{const o=t.getContext(),{manifest:i}=await Ne(),s=Object.entries(i.skills).map((([e,t])=>({name:e,path:t.path,version:i.cliVersion})));if("json"!==ky([o,"optionalAccess",e=>e.format])){ky([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Bundled skills (v${i.cliVersion}):`)]);for(const e of s)ky([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",t=>t(` - ${e.name} (${e.path})`)])}else o.response.print({cliVersion:i.cliVersion,skills:s})}))})(o),(t=>{t.command("show <name>").description("Print a bundled skill in full (always matches current CLI)").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Print a bundled skill",description:"Print the full content of the named skill bundled with the current CLI. Since the skill ships with the CLI, its version always matches — a zero-drift pull-based fallback for any agent.",examples:[{desc:"Print the shared skill (minimal)",cmd:"coze self skill show using-coze-cli",tags:["[RECOMMENDED]"]},{desc:"Print a skill as JSON with metadata",cmd:"coze self skill show using-coze-cli --format json"},{desc:"Print the first bundled skill in full",cmd:"coze self skill show $(coze self skill list --format json | jq -r '.skills[0].name')",tags:["[PIPELINE]"]}],schema:{input:{name:{type:"string",required:!0,description:"Skill name from `coze self skill list`",example:"using-coze-cli"}},output:{name:{type:"string",description:"Skill name",example:"using-coze-cli"},path:{type:"string",description:"Path relative to the bundled skills root",example:"using-coze-cli/SKILL.md"},version:{type:"string",description:"Skill version (equals the CLI version)",example:"0.1.0"},content:{type:"string",description:"Full skill content; in text mode the content is printed raw to stdout instead"}}},errors:[{code:e.ErrorCode.E3002,name:"SKILL_NOT_FOUND",desc:"The given name does not match any skill bundled with this CLI",fix:"Run `coze self skill list` and use one of the listed names",example:"coze self skill show using-coze-cli"},{code:e.ErrorCode.E1102,name:"MISSING_ARGUMENT",desc:"The required <name> argument was not provided",fix:"Pass the skill name as the first positional argument",example:"coze self skill show using-coze-cli"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing or the skill content file listed in the manifest cannot be read (corrupted CLI installation)",fix:"Reinstall or upgrade the CLI to restore the bundled skills",example:"coze upgrade"}],seeAlso:["coze self skill list","coze self skill install","coze self skill path"]}}).action((async(e,t,o)=>{const i=o.getContext(),{manifest:s,files:n}=await Ne(),r=s.skills[e];if(!r){const t=Object.keys(s.skills).join(", ");return void Ay([i,"optionalAccess",e=>e.ui,"access",e=>e.error,"call",o=>o(`Skill not found: "${e}".\nAvailable skills: ${t}\nRun \`coze self skill list\` to see all.`)])}const a=n.find((e=>e.rel===r.path));a?"json"!==Ay([i,"optionalAccess",e=>e.format])?(process.stdout.write(a.content),a.content.endsWith("\n")||process.stdout.write("\n")):i.response.print({name:e,path:r.path,version:s.cliVersion,content:a.content}):Ay([i,"optionalAccess",e=>e.ui,"access",e=>e.error,"call",t=>t(`Skill content missing for "${e}" (${r.path}).`)])}))})(o),(t=>{t.command("path").description("Print the bundled skill source and the skills pool path").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Print skill paths",description:"Print the bundled skill source directory (the `skills add` input) and the skills central pool path that agents symlink to. Fully local and read-only: no network access and no files are written. The pool path is only available after `coze self skill install` has run at least once.",examples:[{desc:"Print skill paths (minimal)",cmd:"coze self skill path",tags:["[RECOMMENDED]"]},{desc:"Print skill paths as JSON",cmd:"coze self skill path --format json"},{desc:"Inspect the bundled skill source directory",cmd:"ls $(coze self skill path --format json | jq -r .sourceRoot)",tags:["[PIPELINE]"]}],schema:{output:{sourceRoot:{type:"string",description:"Absolute path of the bundled skill source directory",example:"~/.nvm/versions/node/v20/lib/node_modules/@coze/cli/skills"},source:{type:"string",enum:["bundled","docs"],description:"Where the source was resolved from: bundled = packaged artifact, docs = dev-mode docs/skills fallback",example:"bundled"},poolPath:{type:"string",required:!1,description:"Skill path inside the skills central pool; absent until `coze self skill install` has run",example:"~/.agents/skills/using-coze-cli"}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing (no packaged skills/manifest.json and no dev-mode docs/skills), which indicates a corrupted CLI installation",fix:"Reinstall or upgrade the CLI to restore the bundled skills",example:"coze upgrade"}],seeAlso:["coze self skill install","coze self skill list","coze self skill status"],caveats:['In text mode, the pool line prints "(not synced yet)" when `coze self skill install` has never run; in JSON mode, poolPath is omitted in that case']}}).action((async(e,t)=>{const o=t.getContext(),{root:i,source:s}=await Be(),n=await Qe();var r,a;"json"!==function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([o,"optionalAccess",e=>e.format])?(process.stdout.write(`source: ${i}\n`),process.stdout.write(`pool : ${r=n.poolPath,a=()=>"(not synced yet)",null!=r?r:a()}\n`)):o.response.print({sourceRoot:i,source:s,poolPath:n.poolPath})}))})(o),(t=>{t.command("remove").description("Uninstall synced skills (skills remove + lock)").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Uninstall synced skills",description:"Delegate to `skills remove` to drop the agent symlinks and the central pool entry for every CLI-bundled skill, then delete `~/.coze/cli/.skill-lock.json`. Skills that are not present in the pool are skipped. Idempotent: running it again after a full removal is a no-op. Re-install at any time with `coze self skill install`.",examples:[{desc:"Uninstall skills (minimal)",cmd:"coze self skill remove",tags:["[RECOMMENDED]"]},{desc:"Uninstall and print the result as JSON",cmd:"coze self skill remove --format json"},{desc:"Uninstall then verify nothing is installed",cmd:"coze self skill remove && coze self skill status",tags:["[PIPELINE]"]}],schema:{output:{removed:{type:"array",description:"Skill units removed via `skills remove`",items:{type:"object",properties:{name:{type:"string",description:"Removed skill unit name"},agents:{type:"array",items:{type:"string"},description:"Agents the skill had been symlinked to before removal"}}}}}},errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Bundled skill source is missing (no packaged skills/manifest.json and no dev-mode docs/skills), so the skill list to remove cannot be resolved",fix:"Reinstall or upgrade the CLI to restore the bundled skills",example:"coze upgrade"}],seeAlso:["coze self skill install","coze self skill status","coze self skill path"],caveats:["Removes the skill for every linked agent at once; there is no per-agent removal","The skill lock file is deleted even when no skill unit was found in the pool"]}}).action((async(e,t)=>{const o=t.getContext(),i=await Ye();if("json"!==Sy([o,"optionalAccess",e=>e.format])){for(const e of i.removed)Sy([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",t=>t(`Removed ${e.name} from: ${e.agents.join(", ")||"(none)"}`)]);Sy([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Uninstalled skills and removed the skill lock.")])}else o.response.print(i)}))})(o)};function Py(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const zy=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},Ty=t=>{if(e.isHttpError(t)&&("object"==typeof(o=t.data)&&null!==o&&("code"in o||"msg"in o||"data"in o)))return t.data;var o;throw t},Ry=e=>{if(null!=e&&!1!==e)return Array.isArray(e)?e.map(String).join(","):String(e)},xy=(e,t)=>{const o=Py([e,"optionalAccess",e=>e.get,"optionalCall",e=>e(t)]),i=Ry(o);if(i)return i;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 Ry(t)},Ly=t=>{return{baseURL:t.baseUrl,transformResponse:[...(o=e.axiosInstance$1.defaults.transformResponse,o?Array.isArray(o)?o:[o]:[]),(e,o)=>{const i=(e=>xy(e,"x-tt-logid")||xy(e,"x-tt-log-id")||xy(e,"logid"))(o);return i&&Py([t,"access",e=>e.onGetLogId,"optionalCall",e=>e(i)]),e}]};var o},Oy=(t,o)=>{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 ${o}`)},Dy=async(t,o)=>{const i=s.createSessionApiClient({baseUrl:t.baseUrl,webOrigin:t.baseUrl,xTTEnv:t.xTTEnv}),{accountId:r,ownerUid:a}=await(async(e,t)=>{const o=Py([zy(await s.Claw.GetProjectInfo({project_id:t},Ly(e))),"access",e=>e.data,"optionalAccess",e=>e.session]);return{accountId:Oy(Py([o,"optionalAccess",e=>e.account_id]),"account_id"),ownerUid:Oy(Py([o,"optionalAccess",e=>e.owner_uid]),"owner_uid")}})(t,o.projectId),c=`${a}_${r}/project_${o.projectId}-files${o.projectFilePath}`,l=await i.getUrl({uris:[c]},{headers:s.getCozeAccountHeaders(t.organizationId),onGetLogId:t.onGetLogId}),d=Py([l,"access",e=>e.data,"optionalAccess",e=>e.urls,"optionalAccess",e=>e[0]]);if(!d)throw new e.CozeError(e.ErrorCode.E5002,l.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",d);const u=n.basename(o.projectFilePath)||"agent-file.bin",m=await Cg({url:p.toString(),outputPath:n.join(o.localDir,u)});return m.logid&&Py([t,"access",e=>e.onGetLogId,"optionalCall",e=>e(m.logid)]),{...m,fileUrl:d,projectFilePath:o.projectFilePath,resolvedUri:c}};function Uy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const qy={skipOrgCheck:!0,skipSpaceCheck:!0},By=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},My=e=>Uy([e,"optionalAccess",e=>e.trim,"call",e=>e()])||"/",Ny=(t,o)=>{const i=Number.parseInt(t,10);if(!Number.isFinite(i)||i<=0||String(i)!==t)throw new e.CozeError(e.ErrorCode.E1000,`Invalid value for ${o}: expected a positive integer, got "${t}"`);return i},$y=t=>{if(!t)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");return t.config.sessionApiBaseUrl||t.config.apiBaseUrl},Gy=()=>{let e="";return{capture:t=>{const o=Uy([t,"optionalAccess",e=>e.trim,"call",e=>e()]);o&&(e=o)},get:()=>e}},Fy=(e,t)=>{const o=t.get();return"object"!=typeof(i=e)||null===i||Array.isArray(i)?{data:e,logid:o}:{...e,logid:o};var i};function Vy(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Wy={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"}]},Hy={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"}}},Jy={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"}}},Ky=t=>{const o=Vy([t,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!o)throw new e.CozeError(e.ErrorCode.E1000,"The --agent-id option is required.");return o},Qy=t=>{const o=t.command("web").description("Use Coze agent web tools").config({...qy,help:Wy});o.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({...qy,help:Hy}).action((async(t,o)=>{const i=new Gs({format:"json"}),n=Gy();try{const r=Ky(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 o=e.safeJsonParse(t,void 0);if(void 0===o)throw new e.CozeError(e.ErrorCode.E1000,"Invalid --query-list: expected a JSON string array.");if(!Array.isArray(o)||o.some((e=>"string"!=typeof e)))throw new e.CozeError(e.ErrorCode.E1000,"Invalid --query-list: expected a JSON string array.");const i=o.map((e=>e.trim())).filter((e=>e.length>0)).slice(0,5);if(0===i.length)throw new e.CozeError(e.ErrorCode.E1000,"Invalid --query-list: expected at least one non-empty query.");return i})(t.queryList),c=o.getContext(),l=$y(c),d=await(async(e,t)=>{try{return await s.Claw.AgentWebSearch({agent_id:t.agentId,query_list:t.queryList,project_id:t.projectId},Ly(e))}catch(e){return Ty(e)}})({baseUrl:l,onGetLogId:n.capture},{agentId:r,queryList:a,projectId:t.projectId});i.print(Fy(d,n))}catch(e){Q(e,o.getContext())}})),o.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({...qy,help:Jy}).action((async(t,o)=>{const i=new Gs({format:"json"}),n=Gy();try{const r=Ky(t.agentId),a=(t=>{const o=Vy([t,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!o)throw new e.CozeError(e.ErrorCode.E1000,"The --url option is required.");let i;try{i=new URL(o)}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:"!==i.protocol&&"https:"!==i.protocol)throw new e.CozeError(e.ErrorCode.E1000,"Invalid --url: expected an http:// or https:// URL.");return o})(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),l=o.getContext(),d=$y(l),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},Ly(e))}catch(e){return Ty(e)}})({baseUrl:d,onGetLogId:n.capture},{agentId:r,url:a,responseLength:c,projectId:t.projectId});i.print(Fy(p,n))}catch(e){Q(e,o.getContext())}}))},Yy={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>"}]},Zy={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"}}},Xy=e=>{e.command("message").description("Manage Coze agent messages").config({...qy,help:Yy}).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({...qy,help:Zy}).action((async(e,t)=>{const o=new Gs({format:"json"});try{const i=By(e.projectId),n=e.size?Ny(e.size,"--size"):void 0,r=t.getContext(),a=$y(r),c=await(async(e,t)=>{const o={session_id:t.projectId};return void 0!==t.cursor&&(o.cursor=t.cursor),void 0!==t.size&&(o.size=t.size),void 0!==t.ascMode&&(o.asc_mode=t.ascMode),void 0!==t.needReference&&(o.need_reference=t.needReference),void 0!==t.conversationId&&(o.conversation_id=t.conversationId),zy(await s.Claw.ListMessage(o,Ly(e)))})({baseUrl:a},{projectId:i,cursor:e.cursor,size:n,ascMode:e.ascMode,needReference:e.needReference,conversationId:e.conversationId});o.print(c)}catch(e){Q(e,t.getContext())}}))},eb=e=>{e.command("member").description("Manage Coze agent members").config({...qy,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({...qy,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 o=new Gs({format:"json"});try{const i=By(e.projectId),n=t.getContext(),r=$y(n),a=await(async(e,t)=>zy(await s.Claw.GetProjectMembers({project_id:t.projectId},Ly(e))))({baseUrl:r},{projectId:i});o.print(a)}catch(e){Q(e,t.getContext())}}))},tb=e=>{e.command("info").description("Get raw Coze agent info as JSON").requiredOption("--project-id <projectId>","The agent project ID").config({...qy,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 o=new Gs({format:"json"});try{const i=By(e.projectId),n=t.getContext(),r=$y(n),a=await(async(e,t)=>zy(await s.Claw.GetProjectInfo({project_id:t.projectId},Ly(e))))({baseUrl:r},{projectId:i});o.print(a)}catch(e){Q(e,t.getContext())}}))};function ob(e,t){return null!=e?e:t()}function ib(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const sb=t=>{if(t instanceof e.CozeError)return ob(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)}},nb=(e,t,o)=>{t.print({ok:!1,err_reason:sb(e),logid:ob(ib([o,"optionalAccess",e=>e.get,"call",e=>e()]),(()=>""))}),process.exitCode=1};function rb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ab={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"}}},cb=(e,t)=>{const o=rb([e,"optionalAccess",e=>e.trim,"call",e=>e()]);if(!o||"/"===o)return`/${t}`;return`${(o.startsWith("/")?o:`/${o}`).replace(/\/+$/,"")}/${t}`},lb=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({...qy,help:ab}).action((async(t,o)=>{const i=new Gs({format:"json"}),c=Gy();try{const p=By(t.projectId),u=((t,o)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${o}`);return t})(t.localFilePath,"--local-file-path");await(async t=>{try{await r.access(t)}catch(o){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${t}${o instanceof Error?` (${o.message})`:""}`)}})(u);const m=o.getContext(),g=$y(m),h=n.basename(u),f=My(t.projectDir);await(async(e,t)=>{return zy(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:(o=t.clawId,i=()=>"",null!=o?o:i())},{onGetLogId:e.onGetLogId}));var o,i})({baseUrl:g,xTTEnv:rb([m,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv]),onGetLogId:c.capture},{projectId:p,fileName:h,fileContent:await a.openAsBlob(u),projectDir:f,clawId:(l=t.clawId,d=()=>"",null!=l?l:d())}),i.print(Fy({ok:!0,project_file_path:cb(f,h)},c))}catch(e){nb(e,i,c)}var l,d}))};function db(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const pb={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"}}},ub=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({...qy,help:pb}).action((async(t,o)=>{const i=new Gs({format:"json"}),s=Gy();try{const n=By(t.projectId),r=((t,o)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${o}`);return t})(t.projectFilePath,"--project-file-path"),a=o.getContext(),c=db([a,"optionalAccess",e=>e.cwd])||process.cwd(),l=await Dy({baseUrl:$y(a),organizationId:db([a,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),xTTEnv:db([a,"optionalAccess",e=>e.config,"access",e=>e.xTTEnv]),onGetLogId:s.capture},{projectId:n,projectFilePath:r,localDir:c});i.print(Fy({ok:!0,local_file_path:l.path},s))}catch(e){nb(e,i,s)}}))};function mb(e,t){return null!=e?e:t()}function gb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const hb={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"}]},fb={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"}}},_b={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"}}},yb={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"}}},bb={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"}}},vb=(t,o)=>{if(!t)throw new e.CozeError(e.ErrorCode.E1000,`Missing required option: ${o}`);return t},wb=e=>e.startsWith("/")?e:`/${e}`,Eb=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({...qy,help:fb}).action((async(e,t)=>{const o=new Gs({format:"json"}),i=Gy();try{const n=By(e.projectId),r=e.depth?Ny(e.depth,"--depth"):void 0,a=t.getContext(),c=$y(a),l=My(e.projectDir),d=await(async(e,t)=>zy(await s.Claw.ListProjectFiles({project_id:t.projectId,file_path:t.filePath,depth:t.depth},Ly(e))))({baseUrl:c,onGetLogId:i.capture},{projectId:n,filePath:l,depth:r});o.print(Fy((e=>({ok:!0,files:mb(gb([e,"access",e=>e.data,"optionalAccess",e=>e.files]),(()=>[])).map((e=>({path:wb(e.file_path||e.name||""),type:e.is_dir?"dir":"file"})))}))(d),i))}catch(e){nb(e,o,i)}}))},Cb=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({...qy,help:_b}).action((async(e,t)=>{const o=new Gs({format:"json"}),i=Gy();try{const n=By(e.projectId),r=vb(e.projectFilePath,"--project-file-path"),a=vb(e.content,"--content"),c=t.getContext(),l=$y(c),d=await(async(e,t)=>zy(await s.Claw.WriteProjectFile({project_id:t.projectId,file_path:t.filePath,content:t.content},Ly(e))))({baseUrl:l,onGetLogId:i.capture},{projectId:n,filePath:r,content:a});o.print(Fy(d,i))}catch(e){nb(e,o,i)}}))},Ib=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({...qy,help:yb}).action((async(e,t)=>{const o=new Gs({format:"json"}),i=Gy();try{const n=By(e.projectId),r=vb(e.projectFilePath,"--project-file-path"),a=e.offset?Ny(e.offset,"--offset"):void 0,c=e.limit?Ny(e.limit,"--limit"):void 0,l=t.getContext(),d=$y(l),p=await(async(e,t)=>{const o={project_id:t.projectId,file_path:t.filePath};return void 0!==t.offset&&(o.offset=t.offset),void 0!==t.limit&&(o.limit=t.limit),zy(await s.Claw.ReadProjectFile(o,Ly(e)))})({baseUrl:d,onGetLogId:i.capture},{projectId:n,filePath:r,offset:a,limit:c});o.print(Fy({ok:!0,project_file_path:r,content:mb(gb([p,"access",e=>e.data,"optionalAccess",e=>e.content]),(()=>""))},i))}catch(e){nb(e,o,i)}}))},Ab=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({...qy,help:bb}).action((async(e,t)=>{const o=new Gs({format:"json"}),i=Gy();try{const n=By(e.projectId),r=vb(e.projectFilePath,"--project-file-path"),a=vb(e.mode,"--mode"),c=t.getContext(),l=$y(c),d=await(async(e,t)=>{const o={project_id:t.projectId,file_path:t.filePath,mode:t.mode};return void 0!==t.oldString&&(o.old_string=t.oldString),void 0!==t.newString&&(o.new_string=t.newString),void 0!==t.appendContent&&(o.append_content=t.appendContent),zy(await s.Claw.EditProjectFile(o,Ly(e)))})({baseUrl:l,onGetLogId:i.capture},{projectId:n,filePath:r,mode:a,oldString:e.oldString,newString:e.newString,appendContent:e.appendContent});o.print(Fy(d,i))}catch(e){nb(e,o,i)}}))},Sb=e=>{const t=e.command("agent").description("Agent-facing Coze APIs backed by Claw project endpoints").config({...qy,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"}]}});tb(t),eb(t),Xy(t),(e=>{const t=e.command("file").description("Manage Coze agent project files").config({...qy,help:hb});Eb(t),Cb(t),Ib(t),Ab(t),lb(t),ub(t)})(t),Qy(t)};function kb(t){!function(t){const o=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",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"]}});o.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",tags:["[RECOMMENDED]"]}],errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Authentication failed",fix:"Please try again with `coze auth login`."}],seeAlso:["coze auth status","coze auth logout"]}}).addOption(new w.Option("--token <PAT>","Login using an access token").hideHelp()).addOption(new w.Option("--oauth","Start browser-based OAuth device authorization flow").hideHelp()).action((async function(t,o){const i=o.getContext();if(!i)return void Q(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"));await i.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,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}}([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])})),o.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",tags:["[RECOMMENDED]"]}],seeAlso:["coze auth login","coze auth status"]}}).action((async(t,o)=>{const i=o.getContext();i?await i.auth.logout():Q(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))})),o.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` to authenticate."}],seeAlso:["coze auth login","coze auth logout"]}}).action((async(t,o)=>{const i=o.getContext();i?await i.auth.status():Q(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))}))}(t),_y(t),jl(t),bg(t),ll(t),ka(t),za(t),al(t),gl(t),yy(t),(e=>{const t=e.command("self").description("Manage the Coze CLI itself").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Manage the Coze CLI itself",description:"Home for capabilities of the Coze CLI tool itself, as opposed to commands that operate on Coze platform resources. Currently hosts `skill`, which manages the CLI-bundled skills on the local machine.",examples:[{desc:"Install bundled skills to all installed AI agents",cmd:"coze self skill install",tags:["[RECOMMENDED]"]},{desc:"Check skill/CLI version consistency",cmd:"coze self skill status"}],seeAlso:["coze upgrade","coze completion","coze config"]}});jy(t)})(t),Sb(t),Pl()}function jb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Pb(e,t){return null!=e?e:t()}function zb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Tb(e){const t=zb([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]);let o=`@HELP ${Lb(e)}\n\n`;zb([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: ${Lb(e.parent)}\n\n`),o+=`SYNTAX:\n ${xb(e)}\n\n`,zb([t,"optionalAccess",e=>e.description])&&(o+=`DESCRIPTION:\n ${t.description.replace(/\n/g,"\n ")}\n\n`),o+=Rb(e,"AVAILABLE COMMANDS:");const i=e._args,s=Db(e);if((i.length>0||s.length>0)&&(o+="OPTIONS:\n",o+=" Name Type Required Default Description\n",o+=" ─────────────────────────────────────────────────────────\n",i.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(8)} ${s.padEnd(10)} ${n}\n`})),s.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()||e.negate)&&(r="flag");const a=e.mandatory?"Yes":"No",c=void 0!==e.defaultValue?String(e.defaultValue):"-",l=e.description||"";o+=` ${n.padEnd(16)} ${r.padEnd(10)} ${a.padEnd(8)} ${c.padEnd(10)} ${l}\n`})),o+="\n"),e.parent){const t=function(e){const t=[];let o=e.parent;for(;o;){for(const e of o.options){const o=Pb(e.long,(()=>e.flags));e.hidden||"--version"===o||!Ob.has(o)||t.includes(o)||t.push(o)}o=o.parent}return t}(e);t.length>0&&(o+="INHERITED OPTIONS:\n",o+=` ${t.join(", ")}\n`,o+=" (see: coze --help)\n\n")}return zb([t,"optionalAccess",e=>e.enums])&&(o+="ENUMS:\n",Object.keys(t.enums).forEach((e=>{o+=` --${e}:\n`;const i=Pb(zb([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})));Object.keys(i).forEach((e=>{o+=` ${e.padEnd(12)} ${i[e]}\n`}))})),o+="\n"),zb([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`}))),zb([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"),zb([t,"optionalAccess",e=>e.seeAlso])&&t.seeAlso.length>0&&(o+="SEE ALSO:\n",t.seeAlso.forEach((e=>{o+=` ${e}\n`})),o+="\n"),o.trimEnd()}function Rb(e,t){const o=e.commands.filter((e=>!e._hidden));if(0===o.length)return"";const i=Math.max(10,...o.map((e=>e.name().length)));let s=`${t}\n`;return o.forEach((e=>{const t=e,o=zb([t,"access",e=>e.getConfig,"optionalCall",e=>e(),"optionalAccess",e=>e.help,"optionalAccess",e=>e.brief])||t.description()||"";s+=` ${t.name().padEnd(i)} ${o}\n`})),`${s}\n`}function xb(e,t=!0){const o=[Lb(e)];e.commands.length>0&&o.push("<command>");const i=function(e){return e._args.map((e=>e.required?`<${e.name()}>`:`[${e.name()}]`)).join(" ")}(e);return i&&o.push(i),t&&o.push("[options]"),o.join(" ")}function Lb(e){const t=[];let o=e;for(;o;)o.name()&&t.unshift(o.name()),o=o.parent;return t.join(" ")}const Ob=new Set(["--version","--format","--no-color","--config","--org-id","--space-id","--verbose","--debug","--log-file","--man","--schema","--commands"]);function Db(e){const t=new Map,o=[];let i=e;for(;i;)o.unshift(i),i=i.parent;for(const i of o)for(const o of i.options){const s=Pb(o.long,(()=>o.flags)),n=i!==e&&Ob.has(s);!s||o.hidden||t.has(s)||n||t.set(s,o)}return Array.from(t.values())}function Ub(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class qb extends w.Command{__init(){this.middlewares=[]}constructor(e){super(e),qb.prototype.__init.call(this),this.helpInformation=()=>{const e=process.argv.slice(2);if(e.includes("--schema"))return`${JSON.stringify(Ub([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=zb([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),o=Lb(e);let i=`@MAN ${o}\n\n`;i+=`NAME\n ${o} — ${zb([t,"optionalAccess",e=>e.brief])||e.description()}\n\n`,i+=`SYNOPSIS\n ${xb(e,!1)}\n`,Db(e).forEach((e=>{i+=` [${e.flags}]\n`})),i+="\n",zb([t,"optionalAccess",e=>e.description])&&(i+=`DESCRIPTION\n ${t.description.replace(/\n/g,"\n ")}\n\n`);const s=Rb(e,"COMMANDS");s&&(i+=s);const n=Db(e);return n.length>0&&(i+="OPTIONS\n",n.forEach((e=>{const t=e.flags.split(", "),o=t.find((e=>e.startsWith("-")&&!e.startsWith("--")))||"",s=t.find((e=>e.startsWith("--")))||"";i+=` ${o?`${s}, ${o}`:s}\n`,i+=` Type: ${e.isBoolean()?"flag":"string"}\n`,i+=` Required: ${e.mandatory?"yes":"no"}\n`,i+=` Default: ${void 0!==e.defaultValue?String(e.defaultValue):"-"}\n`,i+=` Desc: ${e.description}\n\n`}))),zb([t,"optionalAccess",e=>e.schema])&&(i+="SCHEMA\n",t.schema.input&&(i+=` Input:\n ${JSON.stringify(t.schema.input,null,2).replace(/\n/g,"\n ")}\n`),t.schema.output&&(i+=` Output:\n ${JSON.stringify(t.schema.output,null,2).replace(/\n/g,"\n ")}\n`),i+="\n"),zb([t,"optionalAccess",e=>e.errors])&&t.errors.length>0&&(i+="ERRORS\n",i+=" CODE NAME TRIGGER RECOVERY\n",t.errors.forEach((e=>{i+=` ${e.code.padEnd(6)} ${e.name.padEnd(17)} ${e.desc.padEnd(37)} ${e.fix}\n`})),i+="\n"),zb([t,"optionalAccess",e=>e.caveats])&&t.caveats.length>0&&(i+="CAVEATS\n",t.caveats.forEach((e=>{i+=` - ${e}\n`})),i+="\n"),zb([t,"optionalAccess",e=>e.seeAlso])&&t.seeAlso.length>0&&(i+="SEE ALSO\n",t.seeAlso.forEach((e=>{i+=` ${e}\n`})),i+="\n"),i.trimEnd()}(this)}\n`;return e.includes("-h")||e.includes("--help")?`${Tb(this)}\n`:`${function(e){const t=zb([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]);let o=`@USAGE ${Lb(e)}\n\n`;zb([t,"optionalAccess",e=>e.brief])?o+=`BRIEF: ${t.brief}\n\n`:o+=`BRIEF: ${e.description()||"No description provided."}\n\n`,o+=`SYNTAX:\n ${xb(e)}\n\n`,o+=Rb(e,"AVAILABLE COMMANDS:"),zb([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(zb([t,"optionalAccess",e=>e.enums])){const e=Object.keys(t.enums).filter((e=>Object.keys(Pb(zb([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),(()=>({})))).length<=7));e.length>0&&(o+="ENUMS:\n",e.forEach((e=>{const i=Object.keys(Pb(zb([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 qb(e);return this.context&&t.setContext(this.context),t}action(e){return super.action((async(...t)=>{const o=this.getContext();let i={},s=[];const n=t.length>0&&t[t.length-1]instanceof qb?t[t.length-1]:this;var r,a;if(t.length>=2&&(r=t[t.length-2],a=()=>({}),i=null!=r?r:a(),s=t.slice(0,t.length-2)),o&&(i&&(o.options=i),s&&(o.args=s),n)){o.commandName=n.name();const e=Ub([n,"access",e=>e.getConfig,"optionalCall",e=>e()]);e&&(o.commandConfig=e),n.setContext(o)}if(this.middlewares.length>0&&o){const i=hi(this.middlewares);await i(o,(async()=>{await e.apply(this,t)}))}else await e.apply(this,t)}))}}function Bb(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Mb(e){e.exitOverride(),e.outputError=()=>{},e.commands.forEach((e=>Mb(e)))}async function Nb(t){const o=new qb;o.name("coze").description("Coze Coding CLI").version(Z,"-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"),o.config({help:{brief:"Coze Coding CLI",description:"Command-line interface for the Coze platform. Manage Coze Coding projects (create, iterate, deploy), claw chat sessions, media generation (image, audio, video), file uploads, and local CLI configuration.\nMost commands require authentication first: run `coze auth login`.",examples:[{desc:"Log in to Coze",cmd:"coze auth login"},{desc:"Create a new Coze Coding project",cmd:'coze code project create --message "Create a chatbot" --type web'},{desc:"Deploy a project to production",cmd:"coze code deploy <projectId>"},{desc:"Generate an image from a prompt",cmd:'coze generate image "A cat in space"'},{desc:"Upload a local file and get an online URL",cmd:"coze file upload ./report.pdf"}],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"}]}}),kb(o),await kl(t.config),function(e,t,o){const i=new Set;e.setContext(o),function e(s){i.has(s)||(i.add(s),s.setContext(o),t.forEach((e=>s.use(e))),s.commands.forEach((t=>{const o=jb([s,"access",e=>e.getConfig,"optionalCall",e=>e()]),i=jb([t,"access",e=>e.getConfig,"optionalCall",e=>e()]);t.setConfig({...o,...i}),e(t)})))}(e)}(o,[Hs,Ea],t),process.on("uncaughtException",(e=>{Q(e,t)})),process.on("unhandledRejection",(e=>{Q(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")),Mb(o);try{await o.parseAsync(t.argv,{from:"user"})}catch(n){const r=n,a=function(e,t,o){let i=e;if(t.command)i=t.command;else if(o.commandName){const t=(e,o)=>{if(e.name()===o)return e;for(const i of e.commands){const e=t(i,o);if(e)return e}return null},s=t(e,o.commandName);s&&(i=s)}let s=e;for(const e of o.argv){if(e.startsWith("-"))break;const t=s.commands.find((t=>t.name()===e));t&&(s=t,i=s)}return i}(o,r,t);"commander.helpDisplayed"!==r.code&&"commander.help"!==r.code&&"commander.version"!==r.code||process.exit(e.ExitCode.SUCCESS);const c=Bb([a,"access",e=>e.getConfig,"optionalCall",e=>e()]),l=Bb([o,"access",e=>e.getConfig,"optionalCall",e=>e()]);if(t.commandConfig=(s=()=>l,null!=(i=c)?i:s()),"commander.unknownOption"===r.code){const o=W(new e.CozeError(e.ErrorCode.E1100,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),process.exit(e.exitCodeForError(o.code))}if("commander.unknownCommand"===r.code){const o=W(new e.CozeError(e.ErrorCode.E1101,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),process.exit(e.exitCodeForError(o.code))}if("commander.missingArgument"===r.code){const o=W(new e.CozeError(e.ErrorCode.E1102,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),"json"!==t.format&&process.stderr.write(`\n${a.helpInformation()}`),process.exit(e.exitCodeForError(o.code))}if("commander.missingMandatoryOptionValue"===r.code||"commander.optionMissingArgument"===r.code){const o=W(new e.CozeError(e.ErrorCode.E1103,r.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),"json"!==t.format&&process.stderr.write(`\n${a.helpInformation()}`),process.exit(e.exitCodeForError(o.code))}Q(r,t)}var i,s}(async function(){const e=process.argv.slice(2),{globalOptions:t}=Xe(e);await async function(){const e=s.getLegacyGlobalConfigDir(),t=s.getGlobalConfigDir();if(e!==t&&await Ws(e))for(const o of Vs){const i=I.join(e,o),s=I.join(t,o);try{if(!await Ws(i)||await Ws(s))continue;await A.mkdir(t,{recursive:!0}),await A.cp(i,s,{recursive:!0,errorOnExist:!1})}catch(e){}}}();const o=function(e){const t=Fs(e.cwd,(()=>process.cwd())),o=Fs(e.env,(()=>process.env)),i=e.globalOptions||{};i.noColor&&(process.env.NO_COLOR="1");let s="text";i.format&&(s=i.format);const n={...e.config};i.orgId&&(n.organizationId=i.orgId),i.spaceId&&(n.spaceId=i.spaceId);const r=new jo({format:"text",logFile:i.logFile,printToStderr:i.printLogs});let a="info";i.debug?a="debug":i.verbose&&(a="verbose");const c=new $s(r,s,a),l=new Gs({format:s}),d={cwd:t,env:o,argv:e.argv,config:n,format:s,log:r,ui:c,response:l,globalOptions:i,auth:void 0};return d.auth=new As(d),d}({argv:e,config:await s.loadConfig(t.config),globalOptions:t});!function(e){xo=e.log,Lo=!0===Po([e,"access",e=>e.globalOptions,"optionalAccess",e=>e.debug]),Lo&&(Oo||(Xo(),ei(),Oo=!0))}(o);const i=hi([Ao,ci,gi,it]);await i(o,(async()=>{await Nb(o)}))})().catch((e=>{Q(e,void 0),process.exitCode=1}));