@coze/cli 0.1.3-alpha.10a42e → 0.1.3-alpha.3cc78c

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("./index-BoboLEyP.js"),t=require("chalk"),o=require("node:child_process"),i=require("node:fs/promises"),n=require("node:os"),s=require("node:path"),r=require("tty"),a=require("util"),c=require("os"),l=require("node:http"),p=require("node:https"),d=require("undici"),u=require("node:fs"),_=require("path"),m=require("fs/promises"),g=require("fs"),h=require("form-data"),f=require("omelette"),y=require("lodash"),b=require("child_process"),v=require("commander");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("mitt"),require("crypto"),require("url"),require("http"),require("https"),require("http2"),require("stream"),require("assert"),require("zlib"),require("events");const A=C(i),P=C(n),j=C(s);function E(e,t){return null!=e?e:t()}class S{format(e){const t=JSON.stringify(e,null,2);return t.endsWith("\n")?t:`${t}\n`}formatError(e){const t={code:e.code,errorName:E(e.errorName,()=>"UNKNOWN_ERROR"),desc:E(e.desc,()=>e.message),trigger:E(e.trigger,()=>null),fix:E(e.fix,()=>null),example:E(e.example,()=>null)},o=JSON.stringify(t,null,2);return o.endsWith("\n")?o:`${o}\n`}}function w(e,t){return null!=e?e:t()}function k(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function T(e){return e.replace(/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"")}function I(e){return e>=4352&&e<=4447||(9001===e||9002===e||(e>=11904&&e<=12350||(e>=12352&&e<=42191||(e>=44032&&e<=55203||(e>=63744&&e<=64255||(e>=65040&&e<=65049||(e>=65072&&e<=65135||(e>=65280&&e<=65376||(e>=65504&&e<=65510||(e>=127744&&e<=129695||e>=131072&&e<=262141))))))))))}function R(e){const t=T(e);if(!t)return 0;const o=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/u;let i=0;const n=Array.from(t);for(let e=0;e<n.length;e+=1){const t=w(n[e],()=>"");if(o.test(t))continue;const s=t.codePointAt(0);void 0!==s&&(i+=I(s)?2:1)}return i}function O(e,t){const o=R(e);return o>=t?e:`${e}${" ".repeat(t-o)}`}function z(e,t){if(t<=0)return"";if(R(e)<=t)return e;if(1===t)return"…";const o=T(e),i=Array.from(o),n=Math.max(0,t-R("…"));let s="",r=0;for(let e=0;e<i.length;e+=1){const t=w(i[e],()=>""),o=R(t);if(r+o>n)break;s+=t,r+=o}return`${s}…`}function L(e,t={}){if(0===e.length)return"";const o=function(e,t){if(0===e.length)return[];const o=new Set,i=[],n=w(e[0],()=>({}));for(const e of Object.keys(n))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 s=[];for(const t of i){let o=R(t);for(const i of e){const e=i[t],n=void 0===e?"":String(e);o=Math.max(o,R(n))}s.push({key:t,width:o})}const r=w(t.columnGap,()=>2),a=w(w(t.maxWidth,()=>process.stdout.columns),()=>120),c=Math.max(1,Math.floor((a+r)/(6+r))),l=Math.min(w(t.maxColumns,()=>c),c);s.length>l&&s.splice(l);const p=Math.max(0,a-r*Math.max(0,s.length-1)),d=()=>s.reduce((e,t)=>e+t.width,0);for(;d()>p;){let e=-1,t=-1;for(let o=0;o<s.length;o+=1){const i=w(k([s,"access",e=>e[o],"optionalAccess",e=>e.width]),()=>0);i>t&&(t=i,e=o)}if(-1===e)break;const o=w(k([s,"access",t=>t[e],"optionalAccess",e=>e.width]),()=>0);if(o<=6)break;s[e]={...s[e],width:o-1}}for(let e=0;e<s.length;e+=1){const t=s[e];t&&(s[e]={...t,width:Math.max(6,t.width)})}return s}(e,t);if(0===o.length)return"";const i=w(t.columnGap,()=>2),n=" ".repeat(i),s=o.map(e=>O(z(e.key,e.width),e.width)).join(n),r=o.map(e=>"-".repeat(e.width)).join(n),a=[];for(const t of e){const e=o.map(e=>{const o=t[e.key];return O(z(void 0===o?"":String(o),e.width),e.width)});a.push(e.join(n))}return`${[s,r,...a].join("\n")}\n`}function U(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 n=w(w(t.maxWidth,()=>process.stdout.columns),()=>120),s=w(t.columnGap,()=>2),r=w(t.minValueWidth,()=>12);let a=Math.min(i,w(t.keyMaxWidth,()=>32));const c=Math.max(6,n-s-r);a=Math.min(a,c);const l=Math.max(0,n-a-s),p=" ".repeat(s);return`${o.map(([e,t])=>{const o=O(z(e,a),a),i=(void 0===t?"undefined":null===t?"null":String(t)).replace(/\s*\n\s*/g," "),n=l>0?z(i,l):"";return`${o}${p}${n}`}).join("\n")}\n`}function x(e,t="",o=0){const i={};if(null==e)return i;if("object"!=typeof(n=e)||null===n||Array.isArray(n))return i;var n;for(const[n,s]of Object.entries(e)){const e=t?`${t}.${n}`:n;if(null!=s)if(Array.isArray(s))o>=5?i[e]="[Array]":0===s.length?i[e]="[]":s.every(e=>"object"!=typeof e||null===e)?i[e]=s.map(e=>{return String((o=()=>"null",null!=(t=e)?t:o()));var t,o}).join(", "):i[e]="[Array]";else if("object"!=typeof s)i[e]=s;else if(o>=5)i[e]="[Object]";else{const t=x(s,e,o+1);Object.assign(i,t)}else i[e]=s}return i}function D(e,t){return null!=e?e:t()}function B(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class q{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 L(e.map(e=>x(e)))}return function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>null==e||"object"!=typeof e)}(e)?`${e.map(e=>String(D(e,()=>"null"))).join("\n")}\n`:"[Array]\n"}var t;if(B(e)){const t=x(e);return 0===Object.keys(t).length?"{}\n":U(t)}return`${String(e)}\n`}formatError(e){const t=[],o=D(e.errorName,()=>"UNKNOWN_ERROR"),i=D(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?U(x(e)):String(e)).map(e=>`${t}- ${e.trim()}`).join("\n")}\n`;if(B(e)){const o=x(e);return 0===Object.keys(o).length?"":`${U(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 M(e,t){return null!=e?e:t()}function N(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...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=N([e,"optionalAccess",e=>e.help,"optionalAccess",e=>e.errors]);if(t&&t.length>0)return t;const o=N([e,"optionalAccess",e=>e.errors]);return Array.isArray(o)?o:void 0}function $(t,o){const i=M(t.trigger,()=>function(e){if(!e||0===e.length)return;return G(("coze"===e[0]?e:["coze",...e]).join(" "),150)}(N([o,"optionalAccess",e=>e.argv]))),n=N([F,"call",e=>e(N([o,"optionalAccess",e=>e.commandConfig])),"optionalAccess",e=>e.find,"call",e=>e(e=>e.code===t.code)]),s=M(N([n,"optionalAccess",e=>e.name]),()=>e.ErrorNameByCode[t.code]),r=M(G(s,80),()=>"UNKNOWN_ERROR");let a=s;t.isMessageExplicit&&t.message.trim()?a=t.message:N([n,"optionalAccess",e=>e.desc])&&(a=n.desc);const c=M(G(a,200),()=>"An unexpected error occurred"),l=M(G(t.fix,150),()=>G(N([n,"optionalAccess",e=>e.fix]),150)),p=M(G(t.example,150),()=>G(N([n,"optionalAccess",e=>e.example]),150));return{code:t.code,errorName:r,desc:c,trigger:i,fix:l,example:p}}function V(e,t){const o=$(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 W(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}var H;!function(e){e[e.NOT_LOGIN=700012006]="NOT_LOGIN"}(H||(H={}));const K=(t,o)=>{const i=V(function(t){if(t instanceof e.CozeError)return t;if(t instanceof e.ChatCoreError){const{ext:o}=t;let i=e.ErrorCode.E5000;"number"==typeof o.code&&(o.code===H.NOT_LOGIN?i=e.ErrorCode.E2001:o.code>=500&&(i=e.ErrorCode.E5002));const{message:n}=t;return new e.CozeError(i,n,o)}if(e.isHttpError(t)){const o=t.toJSON();let i=e.ErrorCode.E5000;const n=W([t,"access",e=>e.response,"optionalAccess",e=>e.status]);t.code===H.NOT_LOGIN||401===n?i=e.ErrorCode.E2001:"ECONNREFUSED"===t.code||"ETIMEDOUT"===t.code?i=e.ErrorCode.E5001:403===n?i=e.ErrorCode.E2003:404===n?i=e.ErrorCode.E3000:429===n?i=e.ErrorCode.E4001:n&&n>=500&&(i=e.ErrorCode.E5002);const s=W([t,"access",e=>e.response,"optionalAccess",e=>e.headers,"optionalAccess",e=>e["x-tt-logid"]]),{message:r}=t;return new e.CozeError(i,r,{logId:s,...o})}return t instanceof Error?new e.CozeError(e.ErrorCode.E5000,t.message,t.stack):"string"==typeof t?new e.CozeError(e.ErrorCode.E5000,t):new e.CozeError(e.ErrorCode.E5000,"An unexpected error occurred")}(t),o?{argv:o.argv,commandConfig:o.commandConfig}:void 0);var n,s;if(i.code===e.ErrorCode.E2001&&process.stdout.write(`${n=i.desc,s=()=>i.message,null!=n?n:s()}\n`),o)o.response.eprint(i);else{const e=new q;process.stderr.write(e.formatError(i))}process.exit(e.exitCodeForError(i.code))};const J=j.join(P.homedir(),".coze"),Z=j.join(J,"config.json"),Q=j.join(process.cwd(),".cozerc.json"),Y={apiBaseUrl:"https://code.coze.cn/",openApiBaseUrl:"https://api.coze.cn",integrationApiBaseUrl:"https://integration.coze.cn",clientId:"95438868623436343239609434490626.app.coze",defaultOutputFormat:"json"};async function X(e){try{const t=await A.readFile(e,"utf8");return JSON.parse(t)}catch(e){return}}function ee(){const e={};return process.env.COZE_API_TOKEN&&(e.accessToken=process.env.COZE_API_TOKEN),process.env.COZE_ORG_ID&&(e.organizationId=process.env.COZE_ORG_ID),process.env.COZE_ENTERPRISE_ID&&(e.enterpriseId=process.env.COZE_ENTERPRISE_ID),process.env.COZE_SPACE_ID&&(e.spaceId=process.env.COZE_SPACE_ID),"global"!==process.env.COZE_CONFIG_SCOPE&&"local"!==process.env.COZE_CONFIG_SCOPE||(e.configScope=process.env.COZE_CONFIG_SCOPE),process.env.COZE_AUTO_CHECK_UPDATE&&(e.autoCheckUpdate="true"===process.env.COZE_AUTO_CHECK_UPDATE),process.env.COZE_DISABLE_TELEMETRY&&(e.disableTelemetry="true"===process.env.COZE_DISABLE_TELEMETRY),e}async function te(e){const t=process.env.COZE_CONFIG_FILE,[o,i,n,s]=await Promise.all([X(Z),X(Q),t?X(t):void 0,e?X(e):void 0]),r=ee();return{...Y,...o,...i,...n,...s,...r}}async function oe(e,t=function(e,t){return null!=e?e:t()}(ee().configScope,()=>"global")){const o=process.env.COZE_CONFIG_FILE,i=o||("global"===t?Z:Q),n=j.dirname(i);try{await A.mkdir(n,{recursive:!0});const t={...await X(i)||{},...e};await A.writeFile(i,JSON.stringify(t,null,2),"utf8")}catch(e){throw new Error(`Failed to save config to ${i}: ${e}`)}}async function ie(e){const t=process.env.COZE_CONFIG_FILE;if(t){const o=await X(t);if(o&&e in o){try{delete o[e],await A.writeFile(t,JSON.stringify(o,null,2),"utf8")}catch(e){throw new Error(`Failed to delete config from ${t}: ${e}`)}return}}let o=Q,i=await X(o);if(i&&e in i||(o=Z,i=await X(o)),i&&e in i)try{delete i[e],await A.writeFile(o,JSON.stringify(i,null,2),"utf8")}catch(e){throw new Error(`Failed to delete config from ${o}: ${e}`)}}async function ne(){const e=process.env.COZE_CONFIG_FILE,[t,o,i]=await Promise.all([X(Z),X(Q),e?X(e):void 0]),n=ee(),s=new Set([...Object.keys(Y),...Object.keys(t||{}),...Object.keys(o||{}),...Object.keys(i||{}),...Object.keys(n)]),r=[];for(const e of Array.from(s)){const s=e;let a,c="default";s in n&&void 0!==n[s]?(a=n[s],c="env"):i&&s in i&&void 0!==i[s]?(a=String(i[s]),c="env-file"):o&&s in o&&void 0!==o[s]?(a=String(o[s]),c="local"):t&&s in t&&void 0!==t[s]?(a=String(t[s]),c="global"):s in Y&&(a=String(Y[s]),c="default"),r.push({key:e,value:a,source:c})}return r}const se="0.1.3-alpha.10a42e",re="@coze/cli";function ae(){return se}function ce(e,t){const o=e=>{const t=e.replace(/^v/,"").split(".");return{major:parseInt(t[0]||"0",10),minor:parseInt(t[1]||"0",10),patch:parseInt(t[2]||"0",10)}},i=o(e),n=o(t);return n.major!==i.major?n.major>i.major:n.minor!==i.minor?n.minor>i.minor:n.patch>i.patch}async function le(t,i=!1,n="latest"){const s=ae(),{config:r}=t;if(!i&&r.latestVersion&&r.lastCheckTime&&Date.now()-r.lastCheckTime<864e5)return{currentVersion:s,latestVersion:r.latestVersion,hasUpdate:ce(s,r.latestVersion)};const a=function(){try{return o.execSync("npm config get registry",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim().replace(/\/+$/,"")}catch(e){return"https://registry.npmjs.org"}}(),c=await async function(t,o="latest"){const i=`${t}/${re}/${o}`,n=await e.customFetch.fetch(i,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`Failed to fetch latest version: ${n.status} ${n.statusText}`);return(await n.json()).version}(a,n);return await oe({latestVersion:c,lastCheckTime:Date.now()},r.configScope),{currentVersion:s,latestVersion:c,hasUpdate:ce(s,c)}}async function pe(e,o){if(await o(),!0===e.config.autoCheckUpdate)try{const o=await le(e);if(o.hasUpdate){const i=`\nUpdate available: ${t.gray(o.currentVersion)} → ${t.green(o.latestVersion)}\nRun ${t.cyan("coze upgrade")} to update\n`;e.ui.info(i)}}catch(e){}}var de,ue,_e,me,ge,he={exports:{}},fe={exports:{}};function ye(){if(ue)return de;ue=1;var e=1e3,t=60*e,o=60*t,i=24*o,n=7*i,s=365.25*i;function r(e,t,o,i){var n=t>=1.5*o;return Math.round(e/o)+" "+i+(n?"s":"")}return de=function(a,c){c=c||{};var l=typeof a;if("string"===l&&a.length>0)return function(r){if((r=String(r)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*n;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*o;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===l&&isFinite(a))return c.long?function(n){var s=Math.abs(n);if(s>=i)return r(n,s,i,"day");if(s>=o)return r(n,s,o,"hour");if(s>=t)return r(n,s,t,"minute");if(s>=e)return r(n,s,e,"second");return n+" ms"}(a):function(n){var s=Math.abs(n);if(s>=i)return Math.round(n/i)+"d";if(s>=o)return Math.round(n/o)+"h";if(s>=t)return Math.round(n/t)+"m";if(s>=e)return Math.round(n/e)+"s";return n+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}function be(){if(me)return _e;return me=1,_e=function(e){function t(e){let i,n,s,r=null;function a(...e){if(!a.enabled)return;const o=a,n=Number(new Date),s=n-(i||n);o.diff=s,o.prev=i,o.curr=n,i=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let r=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,n)=>{if("%%"===i)return"%";r++;const s=t.formatters[n];if("function"==typeof s){const t=e[r];i=s.call(o,t),e.splice(r,1),r--}return i}),t.formatArgs.call(o,e);(o.log||t.log).apply(o,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=o,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==r?r:(n!==t.namespaces&&(n=t.namespaces,s=t.enabled(e)),s),set:e=>{r=e}}),"function"==typeof t.init&&t.init(a),a}function o(e,o){const i=t(this.namespace+(void 0===o?":":o)+e);return i.log=this.log,i}function i(e,t){let o=0,i=0,n=-1,s=0;for(;o<e.length;)if(i<t.length&&(t[i]===e[o]||"*"===t[i]))"*"===t[i]?(n=i,s=o,i++):(o++,i++);else{if(-1===n)return!1;i=n+1,s++,o=s}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const o=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of o)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const o of t.skips)if(i(e,o))return!1;for(const o of t.names)if(i(e,o))return!0;return!1},t.humanize=ye(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(o=>{t[o]=e[o]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let o=0;for(let t=0;t<e.length;t++)o=(o<<5)-o+e.charCodeAt(t),o|=0;return t.colors[Math.abs(o)%t.colors.length]},t.enable(t.load()),t},_e}var ve,Ce,Ae,Pe,je,Ee,Se={exports:{}};function we(){return Ce?ve:(Ce=1,ve=(e,t)=>{t=t||process.argv;const o=e.startsWith("-")?"":1===e.length?"-":"--",i=t.indexOf(o+e),n=t.indexOf("--");return-1!==i&&(-1===n||i<n)})}function ke(){if(Pe)return Ae;Pe=1;const e=c,t=we(),o=process.env;let i;function n(n){const s=function(n){if(!1===i)return 0;if(t("color=16m")||t("color=full")||t("color=truecolor"))return 3;if(t("color=256"))return 2;if(n&&!n.isTTY&&!0!==i)return 0;const s=i?1:0;if("win32"===process.platform){const t=e.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("true"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(e=>e in o)||"codeship"===o.CI_NAME?1:s;if("TEAMCITY_VERSION"in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if("truecolor"===o.COLORTERM)return 3;if("TERM_PROGRAM"in o){const e=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||"COLORTERM"in o?1:(o.TERM,s)}(n);return function(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}(s)}return t("no-color")||t("no-colors")||t("color=false")?i=!1:(t("color")||t("colors")||t("color=true")||t("color=always"))&&(i=!0),"FORCE_COLOR"in o&&(i=0===o.FORCE_COLOR.length||0!==parseInt(o.FORCE_COLOR,10)),Ae={supportsColor:n,stdout:n(process.stdout),stderr:n(process.stderr)}}function Te(){return je||(je=1,function(e,t){const o=r,i=a;t.init=function(e){e.inspectOpts={};const o=Object.keys(t.inspectOpts);for(let i=0;i<o.length;i++)e.inspectOpts[o[i]]=t.inspectOpts[o[i]]},t.log=function(...e){return process.stderr.write(i.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(o){const{namespace:i,useColors:n}=this;if(n){const t=this.color,n="[3"+(t<8?t:"8;5;"+t),s=` ${n};1m${i} `;o[0]=s+o[0].split("\n").join("\n"+s),o.push(n+"m+"+e.exports.humanize(this.diff)+"")}else o[0]=function(){if(t.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+i+" "+o[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):o.isatty(process.stderr.fd)},t.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=ke();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{const o=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase());let i=process.env[t];return i=!!/^(yes|on|true|enabled)$/i.test(i)||!/^(no|off|false|disabled)$/i.test(i)&&("null"===i?null:Number(i)),e[o]=i,e},{}),e.exports=be()(t);const{formatters:n}=e.exports;n.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split("\n").map(e=>e.trim()).join(" ")},n.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}}(Se,Se.exports)),Se.exports}var Ie=(Ee||(Ee=1,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?he.exports=(ge||(ge=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const o="color: "+this.color;t.splice(1,0,o,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))}),t.splice(n,0,o)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=be()(t);const{formatters:o}=e.exports;o.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(fe,fe.exports)),fe.exports):he.exports=Te()),he.exports);const Re=e.getDefaultExportFromCjs(Ie);function Oe(e){var t,o,i=e.transport,n=e.endpoint,s=e.size,r=void 0===s?10:s,a=e.wait,c=void 0===a?1e3:a,l=[],p=0;function d(){if(l.length){var e=this.getBatchData();i.post({url:n,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 n},setEndpoint:function(e){n=e},send:function(e){l.push(e),l.length>=r&&d.call(this),clearTimeout(p),p=setTimeout(d.bind(this),c)},flush:function(){clearTimeout(p),d.call(this)},getBatchData:function(){return l.length?(e=l,JSON.stringify({ev_type:"batch",list:e})):"";var e},clear:function(){clearTimeout(p),l=[]},fail:function(e){t=e},success:function(e){o=e}}}
2
+ "use strict";const e=require("./index-DFbI9pjb.js"),t=require("chalk"),i=require("node:child_process"),o=require("node:fs/promises"),s=require("node:os"),n=require("node:path"),a=require("tty"),r=require("util"),c=require("os"),d=require("node:http"),p=require("node:https"),l=require("undici"),u=require("node:fs"),_=require("path"),m=require("fs/promises"),g=require("fs"),h=require("form-data"),f=require("omelette"),y=require("lodash"),b=require("child_process"),v=require("commander");function C(e){const t=Object.create(null);if(e)for(const i in e)if("default"!==i){const o=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,o.get?o:{enumerable:!0,get:function(){return e[i]}})}return t.default=e,Object.freeze(t)}require("mitt"),require("crypto"),require("url"),require("http"),require("https"),require("http2"),require("stream"),require("assert"),require("zlib"),require("events");const S=C(o),P=C(s),E=C(n);function T(e,t){return null!=e?e:t()}class A{format(e){const t=JSON.stringify(e,null,2);return t.endsWith("\n")?t:`${t}\n`}formatError(e){const t={code:e.code,errorName:T(e.errorName,()=>"UNKNOWN_ERROR"),desc:T(e.desc,()=>e.message),trigger:T(e.trigger,()=>null),fix:T(e.fix,()=>null),example:T(e.example,()=>null)},i=JSON.stringify(t,null,2);return i.endsWith("\n")?i:`${i}\n`}}function k(e,t){return null!=e?e:t()}function w(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function R(e){return e.replace(/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"")}function z(e){return e>=4352&&e<=4447||(9001===e||9002===e||(e>=11904&&e<=12350||(e>=12352&&e<=42191||(e>=44032&&e<=55203||(e>=63744&&e<=64255||(e>=65040&&e<=65049||(e>=65072&&e<=65135||(e>=65280&&e<=65376||(e>=65504&&e<=65510||(e>=127744&&e<=129695||e>=131072&&e<=262141))))))))))}function I(e){const t=R(e);if(!t)return 0;const i=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/u;let o=0;const s=Array.from(t);for(let e=0;e<s.length;e+=1){const t=k(s[e],()=>"");if(i.test(t))continue;const n=t.codePointAt(0);void 0!==n&&(o+=z(n)?2:1)}return o}function O(e,t){const i=I(e);return i>=t?e:`${e}${" ".repeat(t-i)}`}function L(e,t){if(t<=0)return"";if(I(e)<=t)return e;if(1===t)return"…";const i=R(e),o=Array.from(i),s=Math.max(0,t-I("…"));let n="",a=0;for(let e=0;e<o.length;e+=1){const t=k(o[e],()=>""),i=I(t);if(a+i>s)break;n+=t,a+=i}return`${n}…`}function j(e,t={}){if(0===e.length)return"";const i=function(e,t){if(0===e.length)return[];const i=new Set,o=[],s=k(e[0],()=>({}));for(const e of Object.keys(s))i.has(e)||(i.add(e),o.push(e));for(const t of e)for(const e of Object.keys(t))i.has(e)||(i.add(e),o.push(e));const n=[];for(const t of o){let i=I(t);for(const o of e){const e=o[t],s=void 0===e?"":String(e);i=Math.max(i,I(s))}n.push({key:t,width:i})}const a=k(t.columnGap,()=>2),r=k(k(t.maxWidth,()=>process.stdout.columns),()=>120),c=Math.max(1,Math.floor((r+a)/(6+a))),d=Math.min(k(t.maxColumns,()=>c),c);n.length>d&&n.splice(d);const p=Math.max(0,r-a*Math.max(0,n.length-1)),l=()=>n.reduce((e,t)=>e+t.width,0);for(;l()>p;){let e=-1,t=-1;for(let i=0;i<n.length;i+=1){const o=k(w([n,"access",e=>e[i],"optionalAccess",e=>e.width]),()=>0);o>t&&(t=o,e=i)}if(-1===e)break;const i=k(w([n,"access",t=>t[e],"optionalAccess",e=>e.width]),()=>0);if(i<=6)break;n[e]={...n[e],width:i-1}}for(let e=0;e<n.length;e+=1){const t=n[e];t&&(n[e]={...t,width:Math.max(6,t.width)})}return n}(e,t);if(0===i.length)return"";const o=k(t.columnGap,()=>2),s=" ".repeat(o),n=i.map(e=>O(L(e.key,e.width),e.width)).join(s),a=i.map(e=>"-".repeat(e.width)).join(s),r=[];for(const t of e){const e=i.map(e=>{const i=t[e.key];return O(L(void 0===i?"":String(i),e.width),e.width)});r.push(e.join(s))}return`${[n,a,...r].join("\n")}\n`}function U(e,t={}){const i=Object.entries(e);if(0===i.length)return"";let o=0;for(const[e]of i)o=Math.max(o,I(e));const s=k(k(t.maxWidth,()=>process.stdout.columns),()=>120),n=k(t.columnGap,()=>2),a=k(t.minValueWidth,()=>12);let r=Math.min(o,k(t.keyMaxWidth,()=>32));const c=Math.max(6,s-n-a);r=Math.min(r,c);const d=Math.max(0,s-r-n),p=" ".repeat(n);return`${i.map(([e,t])=>{const i=O(L(e,r),r),o=(void 0===t?"undefined":null===t?"null":String(t)).replace(/\s*\n\s*/g," "),s=d>0?L(o,d):"";return`${i}${p}${s}`}).join("\n")}\n`}function B(e,t="",i=0){const o={};if(null==e)return o;if("object"!=typeof(s=e)||null===s||Array.isArray(s))return o;var s;for(const[s,n]of Object.entries(e)){const e=t?`${t}.${s}`:s;if(null!=n)if(Array.isArray(n))i>=5?o[e]="[Array]":0===n.length?o[e]="[]":n.every(e=>"object"!=typeof e||null===e)?o[e]=n.map(e=>{return String((i=()=>"null",null!=(t=e)?t:i()));var t,i}).join(", "):o[e]="[Array]";else if("object"!=typeof n)o[e]=n;else if(i>=5)o[e]="[Object]";else{const t=B(n,e,i+1);Object.assign(o,t)}else o[e]=n}return o}function x(e,t){return null!=e?e:t()}function q(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class D{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(q)){return j(e.map(e=>B(e)))}return function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>null==e||"object"!=typeof e)}(e)?`${e.map(e=>String(x(e,()=>"null"))).join("\n")}\n`:"[Array]\n"}var t;if(q(e)){const t=B(e);return 0===Object.keys(t).length?"{}\n":U(t)}return`${String(e)}\n`}formatError(e){const t=[],i=x(e.errorName,()=>"UNKNOWN_ERROR"),o=x(e.desc,()=>e.message);return t.push(`ERROR [${e.code}] ${i}: ${o}`),e.trigger&&t.push(` Trigger: ${e.trigger}`),e.fix&&t.push(` Fix: ${e.fix}`),e.example&&t.push(` Example: ${e.example}`),e.details&&(t.push(" Error Details:"),t.push(`${function(e,t){if(null==e)return"";if("string"==typeof e)return`${t}${e}\n`;if(Array.isArray(e))return 0===e.length?"":`${e.map(e=>"object"==typeof e&&null!==e?U(B(e)):String(e)).map(e=>`${t}- ${e.trim()}`).join("\n")}\n`;if(q(e)){const i=B(e);return 0===Object.keys(i).length?"":`${U(i).split("\n").filter(e=>e.trim()).map(e=>`${t}${e}`).join("\n")}\n`}return`${t}${String(e)}\n`}(e.details," ")}`)),`${t.join("\n")}\n`}}function M(e,t){return null!=e?e:t()}function G(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function N(e,t){if(null==e)return;const i=String(e).replace(/\s*\n\s*/g," ").replace(/\s+/g," ").trim();return i?i.length<=t?i:`${i.slice(0,Math.max(0,t-3))}...`:void 0}function F(e){const t=G([e,"optionalAccess",e=>e.help,"optionalAccess",e=>e.errors]);if(t&&t.length>0)return t;const i=G([e,"optionalAccess",e=>e.errors]);return Array.isArray(i)?i:void 0}function $(t,i){const o=M(t.trigger,()=>function(e){if(!e||0===e.length)return;return N(("coze"===e[0]?e:["coze",...e]).join(" "),150)}(G([i,"optionalAccess",e=>e.argv]))),s=G([F,"call",e=>e(G([i,"optionalAccess",e=>e.commandConfig])),"optionalAccess",e=>e.find,"call",e=>e(e=>e.code===t.code)]),n=M(G([s,"optionalAccess",e=>e.name]),()=>e.ErrorNameByCode[t.code]),a=M(N(n,80),()=>"UNKNOWN_ERROR");let r=n;t.isMessageExplicit&&t.message.trim()?r=t.message:G([s,"optionalAccess",e=>e.desc])&&(r=s.desc);const c=M(N(r,200),()=>"An unexpected error occurred"),d=M(N(t.fix,150),()=>N(G([s,"optionalAccess",e=>e.fix]),150)),p=M(N(t.example,150),()=>N(G([s,"optionalAccess",e=>e.example]),150));return{code:t.code,errorName:a,desc:c,trigger:o,fix:d,example:p}}function V(e,t){const i=$(e,t);return e.errorName=i.errorName,e.desc=i.desc,e.message=i.desc,e.trigger=i.trigger,e.fix=i.fix,e.example=i.example,e}function W(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}var H;!function(e){e[e.NOT_LOGIN=700012006]="NOT_LOGIN"}(H||(H={}));const K=(t,i)=>{const o=V(function(t){if(t instanceof e.CozeError)return t;if(t instanceof e.ChatCoreError){const{ext:i}=t;let o=e.ErrorCode.E5000;"number"==typeof i.code&&(i.code===H.NOT_LOGIN?o=e.ErrorCode.E2001:i.code>=500&&(o=e.ErrorCode.E5002));const{message:s}=t;return new e.CozeError(o,s,i)}if(e.isHttpError(t)){const i=t.toJSON();let o=e.ErrorCode.E5000;const s=W([t,"access",e=>e.response,"optionalAccess",e=>e.status]);t.code===H.NOT_LOGIN||401===s?o=e.ErrorCode.E2001:"ECONNREFUSED"===t.code||"ETIMEDOUT"===t.code?o=e.ErrorCode.E5001:403===s?o=e.ErrorCode.E2003:404===s?o=e.ErrorCode.E3000:429===s?o=e.ErrorCode.E4001:s&&s>=500&&(o=e.ErrorCode.E5002);const n=W([t,"access",e=>e.response,"optionalAccess",e=>e.headers,"optionalAccess",e=>e["x-tt-logid"]]),{message:a}=t;return new e.CozeError(o,a,{logId:n,...i})}return t instanceof Error?new e.CozeError(e.ErrorCode.E5000,t.message,t.stack):"string"==typeof t?new e.CozeError(e.ErrorCode.E5000,t):new e.CozeError(e.ErrorCode.E5000,"An unexpected error occurred")}(t),i?{argv:i.argv,commandConfig:i.commandConfig}:void 0);var s,n;if(o.code===e.ErrorCode.E2001&&process.stdout.write(`${s=o.desc,n=()=>o.message,null!=s?s:n()}\n`),i)i.response.eprint(o);else{const e=new D;process.stderr.write(e.formatError(o))}process.exit(e.exitCodeForError(o.code))};const J=E.join(P.homedir(),".coze"),Q=E.join(J,"config.json"),Z=E.join(process.cwd(),".cozerc.json"),Y={apiBaseUrl:"https://code.coze.cn/",openApiBaseUrl:"https://api.coze.cn",integrationApiBaseUrl:"https://integration.coze.cn",clientId:"95438868623436343239609434490626.app.coze",defaultOutputFormat:"json"};async function X(e){try{const t=await S.readFile(e,"utf8");return JSON.parse(t)}catch(e){return}}function ee(){const e={};return process.env.COZE_API_TOKEN&&(e.accessToken=process.env.COZE_API_TOKEN),process.env.COZE_ORG_ID&&(e.organizationId=process.env.COZE_ORG_ID),process.env.COZE_ENTERPRISE_ID&&(e.enterpriseId=process.env.COZE_ENTERPRISE_ID),process.env.COZE_SPACE_ID&&(e.spaceId=process.env.COZE_SPACE_ID),"global"!==process.env.COZE_CONFIG_SCOPE&&"local"!==process.env.COZE_CONFIG_SCOPE||(e.configScope=process.env.COZE_CONFIG_SCOPE),process.env.COZE_AUTO_CHECK_UPDATE&&(e.autoCheckUpdate="true"===process.env.COZE_AUTO_CHECK_UPDATE),process.env.COZE_DISABLE_TELEMETRY&&(e.disableTelemetry="true"===process.env.COZE_DISABLE_TELEMETRY),e}async function te(e){const t=process.env.COZE_CONFIG_FILE,[i,o,s,n]=await Promise.all([X(Q),X(Z),t?X(t):void 0,e?X(e):void 0]),a=ee();return{...Y,...i,...o,...s,...n,...a}}async function ie(e,t=function(e,t){return null!=e?e:t()}(ee().configScope,()=>"global")){const i=process.env.COZE_CONFIG_FILE,o=i||("global"===t?Q:Z),s=E.dirname(o);try{await S.mkdir(s,{recursive:!0});const t={...await X(o)||{},...e};await S.writeFile(o,JSON.stringify(t,null,2),"utf8")}catch(e){throw new Error(`Failed to save config to ${o}: ${e}`)}}async function oe(e){const t=process.env.COZE_CONFIG_FILE;if(t){const i=await X(t);if(i&&e in i){try{delete i[e],await S.writeFile(t,JSON.stringify(i,null,2),"utf8")}catch(e){throw new Error(`Failed to delete config from ${t}: ${e}`)}return}}let i=Z,o=await X(i);if(o&&e in o||(i=Q,o=await X(i)),o&&e in o)try{delete o[e],await S.writeFile(i,JSON.stringify(o,null,2),"utf8")}catch(e){throw new Error(`Failed to delete config from ${i}: ${e}`)}}async function se(){const e=process.env.COZE_CONFIG_FILE,[t,i,o]=await Promise.all([X(Q),X(Z),e?X(e):void 0]),s=ee(),n=new Set([...Object.keys(Y),...Object.keys(t||{}),...Object.keys(i||{}),...Object.keys(o||{}),...Object.keys(s)]),a=[];for(const e of Array.from(n)){const n=e;let r,c="default";n in s&&void 0!==s[n]?(r=s[n],c="env"):o&&n in o&&void 0!==o[n]?(r=String(o[n]),c="env-file"):i&&n in i&&void 0!==i[n]?(r=String(i[n]),c="local"):t&&n in t&&void 0!==t[n]?(r=String(t[n]),c="global"):n in Y&&(r=String(Y[n]),c="default"),a.push({key:e,value:r,source:c})}return a}const ne="0.1.3-alpha.3cc78c",ae="@coze/cli";function re(){return ne}function ce(e,t){const i=e=>{const t=e.replace(/^v/,"").split(".");return{major:parseInt(t[0]||"0",10),minor:parseInt(t[1]||"0",10),patch:parseInt(t[2]||"0",10)}},o=i(e),s=i(t);return s.major!==o.major?s.major>o.major:s.minor!==o.minor?s.minor>o.minor:s.patch>o.patch}async function de(t,o=!1,s="latest"){const n=re(),{config:a}=t;if(!o&&a.latestVersion&&a.lastCheckTime&&Date.now()-a.lastCheckTime<864e5)return{currentVersion:n,latestVersion:a.latestVersion,hasUpdate:ce(n,a.latestVersion)};const r=function(){try{return i.execSync("npm config get registry",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim().replace(/\/+$/,"")}catch(e){return"https://registry.npmjs.org"}}(),c=await async function(t,i="latest"){const o=`${t}/${ae}/${i}`,s=await e.customFetch.fetch(o,{headers:{accept:"application/json"}});if(!s.ok)throw new Error(`Failed to fetch latest version: ${s.status} ${s.statusText}`);return(await s.json()).version}(r,s);return await ie({latestVersion:c,lastCheckTime:Date.now()},a.configScope),{currentVersion:n,latestVersion:c,hasUpdate:ce(n,c)}}async function pe(e,i){if(await i(),!0===e.config.autoCheckUpdate)try{const i=await de(e);if(i.hasUpdate){const o=`\nUpdate available: ${t.gray(i.currentVersion)} → ${t.green(i.latestVersion)}\nRun ${t.cyan("coze upgrade")} to update\n`;e.ui.info(o)}}catch(e){}}var le,ue,_e,me,ge,he={exports:{}},fe={exports:{}};function ye(){if(ue)return le;ue=1;var e=1e3,t=60*e,i=60*t,o=24*i,s=7*o,n=365.25*o;function a(e,t,i,o){var s=t>=1.5*i;return Math.round(e/i)+" "+o+(s?"s":"")}return le=function(r,c){c=c||{};var d=typeof r;if("string"===d&&r.length>0)return function(a){if((a=String(a)).length>100)return;var r=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!r)return;var c=parseFloat(r[1]);switch((r[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*n;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*o;case"hours":case"hour":case"hrs":case"hr":case"h":return c*i;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(r);if("number"===d&&isFinite(r))return c.long?function(s){var n=Math.abs(s);if(n>=o)return a(s,n,o,"day");if(n>=i)return a(s,n,i,"hour");if(n>=t)return a(s,n,t,"minute");if(n>=e)return a(s,n,e,"second");return s+" ms"}(r):function(s){var n=Math.abs(s);if(n>=o)return Math.round(s/o)+"d";if(n>=i)return Math.round(s/i)+"h";if(n>=t)return Math.round(s/t)+"m";if(n>=e)return Math.round(s/e)+"s";return s+"ms"}(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))}}function be(){if(me)return _e;return me=1,_e=function(e){function t(e){let o,s,n,a=null;function r(...e){if(!r.enabled)return;const i=r,s=Number(new Date),n=s-(o||s);i.diff=n,i.prev=o,i.curr=s,o=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(o,s)=>{if("%%"===o)return"%";a++;const n=t.formatters[s];if("function"==typeof n){const t=e[a];o=n.call(i,t),e.splice(a,1),a--}return o}),t.formatArgs.call(i,e);(i.log||t.log).apply(i,e)}return r.namespace=e,r.useColors=t.useColors(),r.color=t.selectColor(e),r.extend=i,r.destroy=t.destroy,Object.defineProperty(r,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(s!==t.namespaces&&(s=t.namespaces,n=t.enabled(e)),n),set:e=>{a=e}}),"function"==typeof t.init&&t.init(r),r}function i(e,i){const o=t(this.namespace+(void 0===i?":":i)+e);return o.log=this.log,o}function o(e,t){let i=0,o=0,s=-1,n=0;for(;i<e.length;)if(o<t.length&&(t[o]===e[i]||"*"===t[o]))"*"===t[o]?(s=o,n=i,o++):(i++,o++);else{if(-1===s)return!1;o=s+1,n++,i=n}for(;o<t.length&&"*"===t[o];)o++;return o===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const i=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of i)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const i of t.skips)if(o(e,i))return!1;for(const i of t.names)if(o(e,i))return!0;return!1},t.humanize=ye(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(i=>{t[i]=e[i]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let i=0;for(let t=0;t<e.length;t++)i=(i<<5)-i+e.charCodeAt(t),i|=0;return t.colors[Math.abs(i)%t.colors.length]},t.enable(t.load()),t},_e}var ve,Ce,Se,Pe,Ee,Te,Ae={exports:{}};function ke(){return Ce?ve:(Ce=1,ve=(e,t)=>{t=t||process.argv;const i=e.startsWith("-")?"":1===e.length?"-":"--",o=t.indexOf(i+e),s=t.indexOf("--");return-1!==o&&(-1===s||o<s)})}function we(){if(Pe)return Se;Pe=1;const e=c,t=ke(),i=process.env;let o;function s(s){const n=function(s){if(!1===o)return 0;if(t("color=16m")||t("color=full")||t("color=truecolor"))return 3;if(t("color=256"))return 2;if(s&&!s.isTTY&&!0!==o)return 0;const n=o?1:0;if("win32"===process.platform){const t=e.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("true"in i)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(e=>e in i)||"codeship"===i.CI_NAME?1:n;if("TEAMCITY_VERSION"in i)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(i.TEAMCITY_VERSION)?1:0;if("truecolor"===i.COLORTERM)return 3;if("TERM_PROGRAM"in i){const e=parseInt((i.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(i.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(i.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(i.TERM)||"COLORTERM"in i?1:(i.TERM,n)}(s);return function(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}(n)}return t("no-color")||t("no-colors")||t("color=false")?o=!1:(t("color")||t("colors")||t("color=true")||t("color=always"))&&(o=!0),"FORCE_COLOR"in i&&(o=0===i.FORCE_COLOR.length||0!==parseInt(i.FORCE_COLOR,10)),Se={supportsColor:s,stdout:s(process.stdout),stderr:s(process.stderr)}}function Re(){return Ee||(Ee=1,function(e,t){const i=a,o=r;t.init=function(e){e.inspectOpts={};const i=Object.keys(t.inspectOpts);for(let o=0;o<i.length;o++)e.inspectOpts[i[o]]=t.inspectOpts[i[o]]},t.log=function(...e){return process.stderr.write(o.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(i){const{namespace:o,useColors:s}=this;if(s){const t=this.color,s="[3"+(t<8?t:"8;5;"+t),n=` ${s};1m${o} `;i[0]=n+i[0].split("\n").join("\n"+n),i.push(s+"m+"+e.exports.humanize(this.diff)+"")}else i[0]=function(){if(t.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+o+" "+i[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):i.isatty(process.stderr.fd)},t.destroy=o.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=we();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{const i=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase());let o=process.env[t];return o=!!/^(yes|on|true|enabled)$/i.test(o)||!/^(no|off|false|disabled)$/i.test(o)&&("null"===o?null:Number(o)),e[i]=o,e},{}),e.exports=be()(t);const{formatters:s}=e.exports;s.o=function(e){return this.inspectOpts.colors=this.useColors,o.inspect(e,this.inspectOpts).split("\n").map(e=>e.trim()).join(" ")},s.O=function(e){return this.inspectOpts.colors=this.useColors,o.inspect(e,this.inspectOpts)}}(Ae,Ae.exports)),Ae.exports}var ze=(Te||(Te=1,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?he.exports=(ge||(ge=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const i="color: "+this.color;t.splice(1,0,i,"color: inherit");let o=0,s=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(o++,"%c"===e&&(s=o))}),t.splice(s,0,i)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=be()(t);const{formatters:i}=e.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(fe,fe.exports)),fe.exports):he.exports=Re()),he.exports);const Ie=e.getDefaultExportFromCjs(ze);function Oe(e){var t,i,o=e.transport,s=e.endpoint,n=e.size,a=void 0===n?10:n,r=e.wait,c=void 0===r?1e3:r,d=[],p=0;function l(){if(d.length){var e=this.getBatchData();o.post({url:s,data:e,fail:function(i){t&&t(i,e)},success:function(){i&&i(e)}}),d=[]}}return{getSize:function(){return a},getWait:function(){return c},setSize:function(e){a=e},setWait:function(e){c=e},getEndpoint:function(){return s},setEndpoint:function(e){s=e},send:function(e){d.push(e),d.length>=a&&l.call(this),clearTimeout(p),p=setTimeout(l.bind(this),c)},flush:function(){clearTimeout(p),l.call(this)},getBatchData:function(){return d.length?(e=d,JSON.stringify({ev_type:"batch",list:e})):"";var e},clear:function(){clearTimeout(p),d=[]},fail:function(e){t=e},success:function(e){i=e}}}
3
3
  /*! *****************************************************************************
4
4
  Copyright (c) Microsoft Corporation.
5
5
 
@@ -13,4 +13,4 @@ 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 ze=function(){return ze=Object.assign||function(e){for(var t,o=1,i=arguments.length;o<i;o++)for(var n in t=arguments[o])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},ze.apply(this,arguments)};function Le(e,t){var o="function"==typeof Symbol&&e[Symbol.iterator];if(!o)return e;var i,n,s=o.call(e),r=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)r.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(o=s.return)&&o.call(s)}finally{if(n)throw n.error}}return r}function Ue(e,t,o){if(2===arguments.length)for(var i,n=0,s=t.length;n<s;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}var xe=function(){return{}};function De(e){return e}function Be(e){return"object"==typeof e&&null!==e}var qe=Object.prototype;function Me(e){return"[object Array]"===qe.toString.call(e)}function Ne(e){return"number"==typeof e}function Ge(e){return"string"==typeof e}function Fe(e,t){if(!Me(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 $e=function(e,t){if(!Me(e))return e;var o=e.indexOf(t);if(o>=0){var i=e.slice();return i.splice(o,1),i}return e};function Ve(e){try{return Ge(e)?e:JSON.stringify(e)}catch(e){return"[FAILED_TO_STRINGIFY]:"+String(e)}}var We="".padStart?function(e,t){return void 0===t&&(t=8),e.padStart(t," ")}:function(e){return e},He=0,Ke=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,Ue(["[SDK]",Date.now(),We(""+He++)],Le(e),!1))},Je=0,Ze=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,Ue(["[SDK]",Date.now(),We(""+Je++)],Le(e),!1))},Qe=function(e){return Math.random()<Number(e)},Ye=function(e,t){return e<Number(t)},Xe=function(e){return function(t){for(var o=t,i=0;i<e.length&&o;i++)try{o=e[i](o)}catch(e){Ke(e)}return o}};function et(){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,n=t;return[n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]]].join("")}(e)}var tt=["init","start","config","beforeDestroy","provide","beforeReport","report","beforeBuild","build","beforeSend","send","beforeConfig"];function ot(e){var t,o,i=e.builder,n=e.createSender,s=e.createDefaultConfig,r=e.createConfigManager,a=e.userConfigNormalizer,c=e.initConfigNormalizer,l=e.validateInitConfig,p={};tt.forEach(function(e){return p[e]=[]});var d=!1,u=!1,_=!1,m=[],g=[],h=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,n,s){t[i]?t[i].push([n,s]):t[i]=[[n,s]],e&&o(s)},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)})}}}(),f={getBuilder:function(){return i},getSender:function(){return t},getPreStartQueue:function(){return m},init:function(e){if(d)Ze("already inited");else{if(!(e&&Be(e)&&l(e)))throw new Error("invalid InitConfig, init failed");var i=s(e);if(!i)throw new Error("defaultConfig missing");var a=c(e);if((o=r(i)).setConfig(a),o.onChange(function(){y("config")}),!(t=n(o.getConfig())))throw new Error("sender missing");d=!0,y("init",!0)}},set:function(e){d&&e&&Be(e)&&(y("beforeConfig",!1,e),null==o||o.setConfig(e))},config:function(e){if(d)return e&&Be(e)&&(y("beforeConfig",!1,e),null==o||o.setConfig(a(e))),null==o?void 0:o.getConfig()},provide:function(e,t){Fe(g,e)?Ze("cannot provide "+e+", reserved"):(f[e]=t,y("provide",!1,e))},start:function(){d&&(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}(f)}))},report:function(e){if(e){var t=Xe(p.beforeReport)(e);if(t){var o=Xe(p.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)}}(f,m,o))}}},build:function(e){if(u){var t=Xe(p.beforeBuild)(e);if(t){var o=i.build(t);if(o){var n=Xe(p.build)(o);n&&this.send(n)}}}},send:function(e){if(u){var o=Xe(p.beforeSend)(e);o&&(t.send(o),y("send",!1,o))}},destroy:function(){h.clear(),_=!0,m.length=0,y("beforeDestroy",!0)},on:function(e,t){if("init"===e&&d||"start"===e&&u||"beforeDestroy"===e&&_)try{t()}catch(e){}else p[e]&&p[e].push(t)},off:function(e,t){p[e]&&(p[e]=$e(p[e],t))},destroyAgent:h};return g=Object.keys(f),f;function y(e,t){void 0===t&&(t=!1);for(var o=[],i=2;i<arguments.length;i++)o[i-2]=arguments[i];p[e].forEach(function(e){try{e.apply(void 0,Ue([],Le(o),!1))}catch(e){}}),t&&(p[e].length=0)}}var it=function(e){var t=function(){var e={},t={},o={set:function(i,n){return e[i]=n,t[i]=Ve(n),o},merge:function(i){return e=ze(ze({},e),i),Object.keys(i).forEach(function(e){t[e]=Ve(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 ze({},t)}};return o}();e.provide("context",t),e.on("report",function(e){return e.extra||(e.extra={}),e.extra.context=t.toString(),e})};var nt=function(){return Date.now()};var st=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&&Be(window))return window}());o&&(o.errors||(o.errors=[]),o.errors.push(e))},rt="custom",at=function(e){var t=function(o){var i=function(e){if(e&&Be(e)&&e.name&&Ge(e.name)){var t={name:e.name,type:"event"};if("metrics"in e&&Be(e.metrics)){var o=e.metrics,i={};for(var n in o)Ne(o[n])&&(i[n]=o[n]);t.metrics=i}if("categories"in e&&Be(e.categories)){var s=e.categories,r={};for(var n in s)r[n]=Ve(s[n]);t.categories=r}return"attached_log"in e&&Ge(e.attached_log)&&(t.attached_log=e.attached_log),t}}(o);if(i){var n=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);n&&(i.stacks=n),e.report({ev_type:rt,payload:i,extra:{timestamp:nt()}})}};e.provide("sendEvent",t),e.provide("sendLog",function(t){var o=function(e){if(e&&Be(e)&&e.content&&Ge(e.content)){var t={content:Ve(e.content),type:"log",level:"info"};if("level"in e&&(t.level=e.level),"extra"in e&&Be(e.extra)){var o=e.extra,i={},n={};for(var s in o)Ne(o[s])?i[s]=o[s]:n[s]=Ve(o[s]);t.metrics=i,t.categories=n}return"attached_log"in e&&Ge(e.attached_log)&&(t.attached_log=e.attached_log),t}}(t);o&&e.report({ev_type:rt,payload:o,extra:{timestamp:nt()}})})},ct=function(e,t){var o=e.common||{};return o.sample_rate=t,e.common=o,e},lt=function(e,t,o,i,n){return e?(s=n(i,t),function(){return s}):function(){return o(t)};var s},pt=function(e,t,o,i){var n=function(e,t,o){for(var i,n=Le(t.split(".")),s=n[0],r=n.slice(1);e&&r.length>0;)e=e[s],s=(i=Le(r))[0],r=i.slice(1);if(e)return o(e,s)}(e,t,function(e,t){return e[t]});return void 0!==n&&function(e,t,o){switch(o){case"eq":return Fe(t,e);case"neq":return!Fe(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}}(n,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 n?"bool":Ne(n)?"number":"string"),o)},dt=function(e,t){try{return"rule"===t.type?pt(e,t.field,t.op,t.values):"and"===t.type?t.children.every(function(t){return dt(e,t)}):t.children.some(function(t){return dt(e,t)})}catch(e){return st(e),!1}},ut=function(e,t,o,i,n){if(!t)return De;var s=t.sample_rate,r=t.include_users,a=t.sample_granularity,c=t.rules,l=t.r,p=void 0===l?Math.random():l;if(Fe(r,e))return function(e){return ct(e,1)};var d="session"===a,u=lt(d,s,o,p,i),_=function(e,t,o,i,n,s){var r={};return Object.keys(e).forEach(function(a){var c=e[a],l=c.enable,p=c.sample_rate,d=c.conditional_sample_rules;l?(r[a]={enable:l,sample_rate:p,effectiveSampleRate:p*o,hit:lt(t,p,i,n,s)},d&&(r[a].conditional_hit_rules=d.map(function(e){var r=e.sample_rate,a=e.filter;return{sample_rate:r,hit:lt(t,r,i,n,s),effectiveSampleRate:r*o,filter:a}}))):r[a]={enable:l,hit:function(){return!1},sample_rate:0,effectiveSampleRate:0}}),r}(c,d,s,o,p,i);return function(e){var t;if(!u())return d&&n[0](),!1;if(!(e.ev_type in _))return ct(e,s);if(!_[e.ev_type].enable)return d&&n[1](e.ev_type),!1;if(null===(t=e.common)||void 0===t?void 0:t.sample_rate)return e;var o=_[e.ev_type],i=o.conditional_hit_rules;if(i)for(var r=0;r<i.length;r++)if(dt(e,i[r].filter))return!!i[r].hit()&&ct(e,i[r].effectiveSampleRate);return o.hit()?ct(e,o.effectiveSampleRate):((!i||!i.length)&&d&&n[1](e.ev_type),!1)}},_t={build:function(e){return{ev_type:e.ev_type,payload:e.payload,common:ze(ze({},e.extra||{}),e.overrides||{})}}},mt={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"]),n=i.next();!n.done;n=i.next()){var s=n.value;e[s]||delete e[s]}}catch(e){t={error:e}}finally{try{n&&!n.done&&(o=i.return)&&o.call(i)}finally{if(t)throw t.error}}return e}function ht(e){return gt(ze({},e))}function ft(e){return Be(e)&&"bid"in e&&"transport"in e}function yt(e){return gt(ze({},e))}var bt=function(e,t){return void 0===t&&(t="/monitor_browser/collect/batch/"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},vt=function(e,t){return void 0===t&&(t="/monitor_web/settings/browser-settings"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Ct=function(e){var t,o,i=e,n={},s=xe,r=xe;return{getConfig:function(){return i},setConfig:function(e){return n=ze(ze({},n),e||{}),a(),t||(t=e,i.useLocalConfig||!i.bid?(o={},s()):function(e,t,o,i){if(!e.get)return i({});e.get({withCredentials:!0,url:vt(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,n=void 0===i?1:i;if(!t)return{};var s=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:s*n,sample_granularity:a,rules:(void 0===l?[]:l).reduce(function(e,t){var o=t.name,i=t.enable,n=t.sample_rate,s=t.conditional_sample_rules;return e[o]={enable:i,sample_rate:n,conditional_sample_rules:s},e},{})},serverTimestamp:o}}(e),a(),s()})),i},onChange:function(e){r=e},onReady:function(e){s=e,o&&s()}};function a(){var t=ze(ze(ze({},e),o||{}),n);t.sample=At(At(e.sample,null==o?void 0:o.sample),n.sample),i=t,r()}};function At(e,t){if(!e||!t)return e||t;var o=ze(ze({},e),t);return o.include_users=Ue(Ue([],Le(e.include_users||[]),!1),Le(t.include_users||[]),!1),o.rules=Ue(Ue([],Le(Object.keys(e.rules||{})),!1),Le(Object.keys(t.rules||{})),!1).reduce(function(o,i){var n,s;return i in o||(i in(e.rules||{})&&i in(t.rules||{})?(o[i]=ze(ze({},e.rules[i]),t.rules[i]),o[i].conditional_sample_rules=Ue(Ue([],Le(e.rules[i].conditional_sample_rules||[]),!1),Le(t.rules[i].conditional_sample_rules||[]),!1)):o[i]=(null===(n=e.rules)||void 0===n?void 0:n[i])||(null===(s=t.rules)||void 0===s?void 0:s[i])),o},{}),o}var Pt=function(e){e.on("report",function(t){return function(e,t){var o=t||{},i=o.version,n=o.name,s={url:"",protocol:"",domain:"",path:"",query:"",timestamp:Date.now(),sdk_version:i||"2.1.8",sdk_name:n||"SDK_BASE"};return ze(ze({},e),{extra:ze(ze({},s),e.extra||{})})}(t,e.config())})},jt=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,ze(ze({},e),{extra:ze(ze({},o),e.extra||{})})}(t,e.config())})};var Et=function(e){return{bid:"",pid:"",viewId:(t="_",t+"_"+Date.now()),userId:et(),deviceId:et(),sessionId:et(),domain:"mon.zijieapi.com",release:"",env:"production",sample:mt,plugins:{},transport:{get:xe,post:xe},useLocalConfig:!1};var t},St=function(e){var t=void 0===e?{}:e,o=t.createSender,i=void 0===o?function(e){return function(e){return Oe(e)}({size:20,endpoint:bt(e.domain),transport:e.transport})}:o,n=t.builder,s=void 0===n?_t:n,r=t.createDefaultConfig,a=ot({validateInitConfig:ft,initConfigNormalizer:ht,userConfigNormalizer:yt,createSender:i,builder:s,createDefaultConfig:void 0===r?Et:r,createConfigManager:Ct});return it(a),jt(a),Pt(a),function(e){e.on("init",function(){var t=[],o=function(o){o.forEach(function(o){var i=o.name;Fe(t,i)||(t.push(i),o.setup(e),e.destroyAgent.set(i,i,[function(){t=$e(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&&Be(window)&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__.push(e)}catch(e){}}(a),a},wt=function(e){void 0===e&&(e={});var t=St(e);return function(e){e.on("start",function(){var t=e.config(),o=t.userId,i=t.sample,n=ut(o,i,Qe,Ye,[function(){e.destroy()},function(t){e.destroyAgent.removeByEvType(t)}]);e.on("build",n)})}(t),at(t),t}();const kt=Re("slardar:transport"),Tt=()=>{};function It(e){const{url:t,method:o,data:i,success:n=Tt,fail:s=Tt,getResponseText:r=Tt}=e;if(kt("Making %s request to %s",o,t),i&&kt("Request data: %s",i.slice(0,200)),!t||"string"!=typeof t){const e=new Error(`Invalid URL: ${t}`);return kt("Invalid URL provided: %o",t),void s(e)}try{const e=new URL(t);kt("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?p.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=>{kt("Response callback triggered: status=%s",e.statusCode);let t="";e.on("data",e=>{kt("Response data chunk received: %s bytes",e.length),t+=e.toString()}),e.on("end",()=>{kt("Response end event fired"),kt("Response received: status=%s, body=%s",e.statusCode,t.slice(0,200)),r(t);try{if(e.statusCode&&e.statusCode>=400)kt("Request failed with status %s: %s",e.statusCode,t),s(new Error(t||e.statusMessage||"Request failed"));else if(t){const e=JSON.parse(t);kt("Request succeeded"),n(e)}else kt("Request succeeded with empty response"),n({})}catch(e){kt("Failed to parse response: %s",e.message),s(e)}})});c.on("error",e=>{kt("Request error: %s",e.message),s(e)}),c.on("timeout",()=>{kt("Request timeout"),c.destroy(),s(new Error("Request timeout"))}),i&&c.write(i),c.end()}catch(e){kt("Exception during request: %s",e.message),s(e)}}function Rt(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const Ot=Re("slardar:reporter");class zt{constructor(){zt.prototype.__init.call(this),zt.prototype.__init2.call(this)}__init(){this.initialized=!1}__init2(){this.client=wt}setup(e){var t,o;if(this.initialized)Ot("Already initialized, skipping setup");else try{Ot("Initializing Slardar with config:",{bid:e.bid,release:e.release,env:e.env,userId:e.userId,projectId:e.projectId});const i={get(e){kt("Transport GET called: %s",e.url),It({method:"GET",...e})},post({url:e,data:t}){kt("Transport POST called: %s",e),It({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=>{Ot("send hook called for event: %s",Rt([e,"optionalAccess",e=>e.ev_type])||"unknown")}),this.client.start(),this.initialized=!0,Ot("Slardar initialized successfully")}catch(e){Ot("Failed to initialize:",e)}}ensureInitialized(){return!!this.initialized||(Ot("Not initialized, call setup() first"),!1)}sendEvent(e,t,o){if(this.ensureInitialized())try{Ot("Sending event:",{name:e,metrics:t,categories:o});const i=t?Object.fromEntries(Object.entries(t).filter(([,e])=>void 0!==e)):void 0,n=o?Object.fromEntries(Object.entries(o).filter(([,e])=>void 0!==e)):void 0;Rt([this,"access",e=>e.client,"access",e=>e.sendEvent,"optionalCall",t=>t({name:e,metrics:i,categories:n})])}catch(e){Ot("Failed to send event:",e)}}sendLog(e,t,o){if(this.ensureInitialized())try{Ot("Sending log:",{level:e,message:t,extra:o}),this.sendEvent("cli_log",void 0,{level:e,message:t,...o})}catch(e){Ot("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"}}};Ot("Reporting JS error:",{name:e.name,message:e.message.slice(0,100),stack:Rt([e,"access",e=>e.stack,"optionalAccess",e=>e.slice,"call",e=>e(0,200)]),extra:t,source:o}),this.client.report(i),Ot("JS error reported successfully")}catch(e){Ot("Failed to report error:",e)}}setContext(e,t){this.ensureInitialized()&&Rt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.set,"call",o=>o(e,t)])}mergeContext(e){this.ensureInitialized()&&(Ot("Merging context:",e),Rt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.merge,"call",t=>t(e)]))}deleteContext(e){this.ensureInitialized()&&Rt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.delete,"call",t=>t(e)])}clearContext(){this.ensureInitialized()&&Rt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.clear,"call",e=>e()])}updateConfig(e){if(this.ensureInitialized())try{Ot("Updating config:",e),this.client.config({userId:e.userId,release:e.release,sessionId:e.sessionId,env:e.env})}catch(e){Ot("Failed to update config:",e)}}async flush(e=1500){this.ensureInitialized()&&(Ot("Flushing Slardar data..."),Rt([this,"access",e=>e.client,"access",e=>e.getSender,"optionalCall",e=>e(),"optionalAccess",e=>e.flush,"call",e=>e()]),Ot("Waiting %dms for events to be sent...",e),await new Promise(t=>setTimeout(t,e)),Ot("Slardar data flushed"))}getRawClient(){return this.client}}const Lt=new zt;function Ut(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const xt="cli_start",Dt="cli_command",Bt="cli_command_complete",qt="cli_error",Mt="network_request",Nt="file_operation",Gt={cliStart:e=>({name:xt,metrics:{duration:0,...e}}),cliCommand:(e,t)=>({name:Dt,categories:{command:e,args:Ut([t,"optionalAccess",e=>e.args]),status:"running",...Ut([t,"optionalAccess",e=>e.categories])},metrics:Ut([t,"optionalAccess",e=>e.metrics])}),cliCommandComplete:(e,t,o,i)=>({name:Bt,categories:{command:e,args:Ut([i,"optionalAccess",e=>e.args]),status:t?"success":"fail",...Ut([i,"optionalAccess",e=>e.categories])},metrics:{duration:o,...Ut([i,"optionalAccess",e=>e.errorCode])&&{errorCode:i.errorCode}}}),networkRequest:(e,t)=>({name:Mt,categories:{url:e,method:Ut([t,"optionalAccess",e=>e.method])||"GET",statusCode:Ut([t,"optionalAccess",e=>e.statusCode,"optionalAccess",e=>e.toString,"call",e=>e()]),status:Ut([t,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:Ut([t,"optionalAccess",e=>e.duration])}}),fileOperation:(e,t,o)=>({name:Nt,categories:{operation:e,filePath:t,status:Ut([o,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:Ut([o,"optionalAccess",e=>e.duration]),fileSize:Ut([o,"optionalAccess",e=>e.fileSize])}}),cliError:(e,t)=>({name:qt,categories:{errorName:e.name,errorMessage:e.message,stack:e.stack||"",...t},metrics:{errorCode:1}})};function Ft(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function $t(e){return(...t)=>{try{const o=e(...t);return o instanceof Promise?o.catch(()=>{}):o}catch(e){}}}const Vt=$t(()=>{var e,t;Lt.setup({bid:"coze_cli",release:se,env:"production",userId:process.env.USER||"",useLocalConfig:!1,domain:"mon.zijieapi.com"}),Lt.mergeContext({platform:process.platform,callerPlatform:(e=process.env.COZE_CLI_PLATFORM,t=()=>"unknown",null!=e?e:t()),nodeVersion:process.version,cliVersion:se})}),Wt=$t(e=>{const t=Gt.cliCommand(e);Lt.sendEvent(t.name,t.metrics,t.categories)}),Ht=$t((e,t,o,i)=>{const n=Gt.cliCommandComplete(e,t,o,{errorCode:Ft([i,"optionalAccess",e=>e.errorCode])});Lt.sendEvent(n.name,n.metrics,n.categories)}),Kt=$t((e,t)=>{Lt.reportError(e,t,{type:"cli",data:t})}),Jt=$t(async()=>{await Lt.flush()});async function Zt(e,t){if(e.config.disableTelemetry)return void await t();Vt();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);Wt(o);const i=Date.now();let n,s=!0;try{await t()}catch(e){throw s=!1,n=e instanceof Error?e:new Error(String(e)),e}finally{const e=Date.now()-i;try{s?Ht(o,!0,e):(n&&Kt(n,{command:o}),Ht(o,!1,e)),await Jt()}catch(e){}}}async function Qt(t,o){const i=await t.auth.getValidAccessToken();e.axiosInstance.defaults.baseURL=t.config.apiBaseUrl;const n=`Bearer ${i}`;e.axiosInstance.defaults.headers.Authorization=n,e.axiosInstance.defaults.headers["x-request-from-coze-cli"]="1",e.customFetch.setHeaders({Authorization:n,"x-request-from-coze-cli":"1"}),t.config.xTTEnv&&(e.axiosInstance.defaults.headers["x-use-ppe"]="1",e.axiosInstance.defaults.headers["x-tt-env"]=t.config.xTTEnv,e.customFetch.setHeaders({"x-use-ppe":"1","x-tt-env":t.config.xTTEnv})),await o()}function Yt(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}var Xt;!function(e){e.AUTHORIZATION_PENDING="authorization_pending";e.SLOW_DOWN="slow_down";e.ACCESS_DENIED="access_denied";e.EXPIRED_TOKEN="expired_token"}(Xt||(Xt={}));const eo=e=>new Promise(t=>setTimeout(t,e)),to=e.createRequestClient({baseURL:"https://api.coze.com",useDefaultPlugins:!0,plugins:[{name:"oauth-error-handler",onError:t=>{if(e.isHttpError(t))throw t;const o=Yt([t,"access",e=>e.response,"optionalAccess",e=>e.data])||{},i=o.error_description||o.error||t.message;throw new e.HttpError(i,{status:Yt([t,"access",e=>e.response,"optionalAccess",e=>e.status]),code:o.error,config:t.config,response:t.response,data:o})}}]});async function oo(e){return(await to.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 io=async(t,o)=>{const i=process.env.HTTP_PROXY||process.env.http_proxy,n=process.env.HTTPS_PROXY||process.env.https_proxy;if(n||i){const o=new d.EnvHttpProxyAgent;e.customFetch.setDispatcher(o);const[{HttpProxyAgent:s},{HttpsProxyAgent:r}]=await Promise.all([import("http-proxy-agent"),import("https-proxy-agent")]);e.axiosInstance.defaults.proxy=!1,to.defaults.proxy=!1,n&&(e.axiosInstance.defaults.httpsAgent=new r(n),to.defaults.httpsAgent=new r(n),t.ui.debug(`HTTPS proxy enabled: ${n}`)),i&&(e.axiosInstance.defaults.httpAgent=new s(i),to.defaults.httpAgent=new s(i),t.ui.debug(`HTTP proxy enabled: ${i}`))}await o()};function no(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 n(s){if(s<=i)return Promise.reject(new Error("next() called multiple times"));i=s;let r=e[s];s===e.length&&(r=o);if(!r)return Promise.resolve();try{return Promise.resolve(r(t,n.bind(null,s+1)))}catch(e){return Promise.reject(e)}}(0)}}var so,ro,ao,co,lo,po,uo,_o,mo,go,ho,fo,yo,bo,vo,Co,Ao,Po,jo,Eo,So,wo,ko,To,Io,Ro,Oo,zo,Lo,Uo,xo,Do,Bo,qo,Mo,No,Go,Fo,$o,Vo,Wo,Ho,Ko,Jo,Zo,Qo,Yo,Xo,ei,ti,oi,ii,ni;function si(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}!function(e){e.app="app";e.pat="pat"}(so||(so={})),function(e){e.can_apply2="CanApply";e.already_applied2="AlreadyApplied";e.joined4="Joined";e.deny3="Deny"}(ro||(ro={})),function(e){e.processing="Processing";e.approved="Approved";e.rejected="Rejected";e.auto_approved="AutoApproved"}(ao||(ao={})),function(e){e.normal="Normal";e.connector="Connector";e.privilege="Privilege"}(co||(co={})),function(e){e.auth_app="AuthApp";e.on_behalf_of_user="OnBehalfOfUser"}(lo||(lo={})),function(e){e.password="Password";e.sms="Sms";e.email="Email";e.unknown3="Unknown"}(po||(po={})),function(e){e.authorized="authorized";e.unauthorized="unauthorized";e.expired4="expired"}(uo||(uo={})),function(e){e.api_key="api_key";e.wechat_official="wechat_official";e.oauth_2="oauth2"}(_o||(_o={})),function(e){e.noncertificated="Noncertificated";e.certificated="Certificated"}(mo||(mo={})),function(e){e.uncertified="Uncertified";e.personal_certification="PersonalCertification";e.enterprise_certification="EnterpriseCertification"}(go||(go={})),function(e){e.obo="Obo";e.app_auth="AppAuth";e.personal_access_token="PersonalAccessToken"}(ho||(ho={})),function(e){e.legacy="Legacy";e.web_backend="WebBackend";e.single_page_or_native="SinglePageOrNative";e.terminal="Terminal";e.service="Service"}(fo||(fo={})),function(e){e.bot_editor="BotEditor";e.bot_developer="BotDeveloper";e.bot_operator="BotOperator"}(yo||(yo={})),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"}(bo||(bo={})),function(e){e.visitors_prohibited="VisitorsProhibited";e.guest_prohibited_by_invited_user_enterprise2="GuestProhibitedByInvitedUserEnterprise";e.prohibited_by_custom_people_management="ProhibitedByCustomPeopleManagement"}(vo||(vo={})),function(e){e.dev2="DEV";e.prod2="PROD"}(Co||(Co={})),function(e){e._1="1";e._30="30";e._90="90";e._180="180";e._365="365";e.customize="customize";e.permanent="permanent"}(Ao||(Ao={})),function(e){e._12="1";e._302="30";e._902="90";e._1802="180";e._3652="365";e.customize2="customize";e.permanent2="permanent"}(Po||(Po={})),function(e){e.aes_256_gcm="AES-256-GCM"}(jo||(jo={})),function(e){e.conversation="Conversation";e.unknown="Unknown"}(Eo||(Eo={})),function(e){e.active3="Active";e.inactive="Inactive"}(So||(So={})),function(e){e.cloud_kms="CloudKMS",e.default="Default";e.unknown2="Unknown"}(wo||(wo={})),function(e){e.user_custom2="user_custom";e.consumer3="consumer"}(ko||(ko={})),function(e){e.super_admin="SuperAdmin";e.admin="Admin";e.member="Member";e.guest="Guest"}(To||(To={})),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"}(Io||(Io={})),function(e){e.string="String";e.boolean="Boolean";e.integer="Integer";e.string_list="StringList"}(Ro||(Ro={})),function(e){e.must_handle="MustHandle";e.no_need_handle="NoNeedHandle"}(Oo||(Oo={})),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"}(zo||(zo={})),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"}(Lo||(Lo={})),function(e){e.confirming2="Confirming";e.joined3="Joined";e.rejected3="Rejected";e.revoked2="Revoked";e.expired3="Expired";e.deny2="Deny"}(Uo||(Uo={})),function(e){e.confirming="Confirming";e.joined2="Joined";e.rejected2="Rejected";e.revoked="Revoked";e.expired2="Expired"}(xo||(xo={})),function(e){e.can_join="CanJoin";e.guest_prohibited_by_enterprise="GuestProhibitedByEnterprise";e.guest_prohibited_by_invited_user_enterprise="GuestProhibitedByInvitedUserEnterprise"}(Do||(Do={})),function(e){e.can_apply="CanApply";e.already_applied="AlreadyApplied";e.joined="Joined";e.expired="Expired";e.deny="Deny"}(Bo||(Bo={})),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"}(qo||(qo={})),function(e){e.user_custom_only="user_custom_only";e.all2="all"}(Mo||(Mo={})),function(e){e.system="system";e.custom="custom"}(No||(No={})),function(e){e.not_in_enterprise="NotInEnterprise";e.prohibited_by_custom_people_management2="ProhibitedByCustomPeopleManagement"}(Go||(Go={})),function(e){e.can_apply3="CanApply";e.already_applied3="AlreadyApplied";e.joined5="Joined";e.deny4="Deny"}(Fo||(Fo={})),function(e){e.super_admin2="SuperAdmin";e.admin2="Admin";e.member2="Member";e.guest2="Guest"}($o||($o={})),function(e){e.member_joining_auto_approved="MemberJoiningAutoApproved"}(Vo||(Vo={})),function(e){e.string2="String";e.boolean2="Boolean";e.integer2="Integer";e.string_list2="StringList"}(Wo||(Wo={})),function(e){e.developer="developer";e.consumer2="consumer"}(Ho||(Ho={})),function(e){e.all="all";e.owned="owned";e.others="others"}(Ko||(Ko={})),function(e){e.enterprise_member="EnterpriseMember";e.enterprise_guest="EnterpriseGuest"}(Jo||(Jo={})),function(e){e.not_created="NotCreated";e.enabled="Enabled";e.disabled="Disabled"}(Zo||(Zo={})),function(e){e.production="Production";e.development="Development"}(Qo||(Qo={})),(Yo||(Yo={})).skill="skill",function(e){e.dev="dev";e.prod="prod"}(Xo||(Xo={})),function(e){e.user_custom="user_custom";e.coze_default="coze_default";e.consumer="consumer"}(ei||(ei={})),function(e){e.active2="Active";e.deactive="Deactive"}(ti||(ti={})),function(e){e.active="active";e.deactivated="deactivated";e.offboarded="offboarded"}(oi||(oi={})),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"}(ii||(ii={})),function(e){e.root_user="RootUser";e.basic_user="BasicUser"}(ni||(ni={}));class ri{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){ri.prototype.__init.call(this),ri.prototype.__init2.call(this),this.request=si([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=si([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"),n={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},s={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}UpdatePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/update_personal_access_token_and_permission"),n={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},s={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}DeletePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/delete_personal_access_token_and_permission"),n={id:o.id};return this.request({url:i,method:"POST",data:n},t)}ListPersonalAccessTokens(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/pat/list_personal_access_tokens"),n={organization_id:o.organization_id,page:o.page,size:o.size,search_option:o.search_option};return this.request({url:i,method:"GET",params:n},t)}GetPersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/get_personal_access_token_and_permission"),n={id:o.id};return this.request({url:i,method:"GET",params:n},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"),n={workspace_id:o.workspace_id};return this.request({url:i,method:"GET",params:n},t)}AddCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/add_collaborator"),n={collaborator_types:o.collaborator_types,principal:o.principal,resource:o.resource};return this.request({url:i,method:"POST",data:n},t)}RemoveCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/remove_collaborator"),n={principal:o.principal,resource:o.resource};return this.request({url:i,method:"POST",data:n},t)}CreateAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/create_app_meta"),n={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:n},t)}ListAppMeta(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/list_app_meta"),n={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:n},t)}GetAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_meta"),n={appid:o.appid},s={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:n,headers:s},t)}UpdateAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/update_app_meta"),n={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},s={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}UploadPublicKey(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/upload_public_key"),n={appid:o.appid,public_key_pem:o.public_key_pem};return this.request({url:i,method:"POST",data:n},t)}DeletePublicKey(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_public_key"),n={fingerprint:o.fingerprint};return this.request({url:i,method:"POST",data:n},t)}CreateClientSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/create_client_secret"),n={appid:o.appid};return this.request({url:i,method:"POST",data:n},t)}DeleteClientSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_client_secret"),n={appid:o.appid,client_secret_id:o.client_secret_id};return this.request({url:i,method:"POST",data:n},t)}PutOAuth2Configuration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/put_oauth2_configuration"),n={oauth2_configuration:o.oauth2_configuration,appid:o.appid};return this.request({url:i,method:"POST",data:n},t)}AuthorizeAppWithDeclaredPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/authorize_app_with_declared_permission"),n={appid:o.appid,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:n},t)}ListAuthorizedApps(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/list_authorized_apps"),n={page:o.page,size:o.size},s={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:n,headers:s},t)}GetAppAuthorizationRequestInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_authorization_request_info"),n={authorize_key:o.authorize_key},s={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:n,headers:s},t)}RevokeAppAuthorizedPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/revoke_app_authorized_permission"),n={authorization_type:o.authorization_type,appid:o.appid,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:n},t)}DeleteApp(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_app"),n={appid:o.appid};return this.request({url:i,method:"POST",data:n},t)}ModifyCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/modify_collaborator"),n={principal:o.principal,resource:o.resource,collaborator_types:o.collaborator_types};return this.request({url:i,method:"POST",data:n},t)}BatchAddCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/batch_add_collaborator"),n={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:n},t)}GetAppInstallationRequestInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_installation_request_info"),n={appid:o.appid},s={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:n,headers:s},t)}AppInstallationConsent(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/app_installation_consent"),n={appid:o.appid,installation_account_hint:o.installation_account_hint};return this.request({url:i,method:"POST",data:n},t)}ImpersonateCozeUser(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/coze_web_app/impersonate_coze_user"),n={duration_seconds:o.duration_seconds,scope:o.scope,connector_info:o.connector_info};return this.request({url:i,method:"POST",data:n},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"),n={appid:o.appid,workspace_list:o.workspace_list,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:n},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`),n={page_num:o.page_num,page_size:o.page_size},s={authorization:o.authorization};return this.request({url:i,method:"GET",params:n,headers:s},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"),n={name:o.name,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:n},t)}ListEnterprise(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/enterprise/list_enterprises"),n={contain_enterprise_of_user:o.contain_enterprise_of_user,contain_organization_of_user:o.contain_organization_of_user};return this.request({url:i,method:"GET",params:n},t)}GetEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_enterprise"),n={enterprise_id:o.enterprise_id};return this.request({url:i,method:"GET",params:n},t)}UpdateEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise"),n={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:n},t)}UpdateEnterpriseSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_settings"),n={enterprise_id:o.enterprise_id,enterprise_settings:o.enterprise_settings};return this.request({url:i,method:"POST",data:n},t)}BatchAddEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_add_enterprise_people"),n={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:n},t)}RemoveEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/remove_enterprise_people"),n={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:n},t)}UpdateEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_people"),n={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:n},t)}CreateEnterpriseInviteLink(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_enterprise_invite_link"),n={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:n},t)}CreateJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_join_application"),n={key:o.key,remark:o.remark};return this.request({url:i,method:"POST",data:n},t)}GetInviteInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_invite_info"),n={invite_key:o.invite_key};return this.request({url:i,method:"GET",params:n},t)}UpdateJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_application"),n={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:n},t)}ListPersonalAccessTokensByCreator(e,t){const o=e,i=this.genBaseURL("/api/permission_api/permission/list_personal_access_tokens_by_creator"),n={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:n},t)}ListAppInstallations(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/list_app_installations"),n={enterprise_id:o.enterprise_id,organization_id:o.organization_id},s={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:n,headers:s},t)}GetEnterpriseSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_enterprise_settings"),n={enterprise_id:o.enterprise_id,enterprise_setting_key_list:o.enterprise_setting_key_list};return this.request({url:i,method:"POST",data:n},t)}SearchCanAddEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_can_add_enterprise_people"),n={people_type:o.people_type,enterprise_id:o.enterprise_id,search_key:o.search_key};return this.request({url:i,method:"POST",data:n},t)}SearchEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_enterprise_people"),n={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:n},t)}ListJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_application"),n={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:n},t)}PostAdapterMpV1Code2Session(e,t){const o=e||{},i=this.genBaseURL("/adapter/mp/v1/code2session"),n={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:n},t)}SubmitAppOboInstallationReview(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/submit_app_obo_installation_review"),n={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:n},t)}InstallAppObo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/install_app_obo"),n={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:n},t)}UninstallAppObo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/uninstall_app_obo"),n={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:n},t)}GetChecklistForWorkspaceMigration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_checklist_for_workspace_migration"),n={workspace_id_list:o.workspace_id_list};return this.request({url:i,method:"POST",data:n},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"),n={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:n},t)}BatchMigrateAuthorization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/batch_migrate_authorization"),n={authorization_list:o.authorization_list,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:n},t)}ListJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_invitation"),n={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:n},t)}RevokeJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/revoke_join_invitation"),n={enterprise_id:o.enterprise_id,join_invitation_id:o.join_invitation_id};return this.request({url:i,method:"POST",data:n},t)}UpdateJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_invitation"),n={enterprise_id:o.enterprise_id,join_invitation_id:o.join_invitation_id,joined:o.joined};return this.request({url:i,method:"POST",data:n},t)}GetJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_join_invitation"),n={join_invitation_id:o.join_invitation_id};return this.request({url:i,method:"POST",data:n},t)}SearchPeopleInOtherEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_people_in_other_enterprise"),n={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:n},t)}CreateApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_application_for_enterprise_member"),n={enterprise_id:o.enterprise_id,remark:o.remark};return this.request({url:i,method:"POST",data:n},t)}GetApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_application_for_enterprise_member"),n={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:n},t)}AuthorizeAppsAndPersonalaccesstokenListWithPersonalAccountPermission(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/authorize_apps_and_patlist_with_personalaccountpermission"),n={crossaccount_authinfo_list:o.crossaccount_authinfo_list};return this.request({url:i,method:"POST",data:n},t)}RevokeAppAndPersonalaccesstokenPersonalAccountPermission(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/revoke_app_and_pat_personalaccountpermission"),n={crossaccount_authinfo:o.crossaccount_authinfo};return this.request({url:i,method:"POST",data:n},t)}GetAppsAndPersonalAccessTokenListForPersonalAccountPermissionAuthorization(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/get_apps_and_patlist_for_personalaccountpermission_authorization"),n={page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:n},t)}create_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/create_service_identity"),n={name:o.name,organization_id:o.organization_id,expire_at:o.expire_at,duration_day:o.duration_day,permission:o.permission},s={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}get_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/get_service_identity"),n={id:o.id};return this.request({url:i,method:"GET",params:n},t)}update_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/update_service_identity"),n={permission:o.permission,id:o.id,name:o.name,expire_at:o.expire_at,duration_day:o.duration_day},s={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}delete_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/delete_service_identity"),n={id:o.id};return this.request({url:i,method:"POST",params:n},t)}list_service_identities(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/service/list_service_identities"),n={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:n},t)}ListEncryptionConfiguration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterpise/list_encryption_configuration"),n={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:n},t)}UpdateEncryptionConfiguration(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/enterpise/update_encryption_configuration"),n={encryption_configuration:o.encryption_configuration};return this.request({url:i,method:"POST",data:n},t)}SearchOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_organization"),n={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:n},t)}CreateOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_organization"),n={enterprise_id:o.enterprise_id,name:o.name,icon_uri:o.icon_uri,description:o.description};return this.request({url:i,method:"POST",data:n},t)}GetOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization"),n={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:n},t)}UpdateOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization"),n={organization_id:o.organization_id,name:o.name,icon_uri:o.icon_uri,description:o.description};return this.request({url:i,method:"POST",data:n},t)}SearchCanAddOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_can_add_organization_people"),n={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:n},t)}SearchOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_organization_people"),n={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:n},t)}CreateJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_join_organization_application"),n={organization_id:o.organization_id,remark:o.remark};return this.request({url:i,method:"POST",data:n},t)}ListJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_organization_application"),n={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:n},t)}UpdateJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_organization_application"),n={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:n},t)}GetOrganizationApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization_application_for_enterprise_member"),n={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:n},t)}CanCustomEncryptionConfiguration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterpise/can_custom_encryption_configuration"),n={enterprise_id:o.enterprise_id};return this.request({url:i,method:"GET",params:n},t)}BatchAddOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_add_organization_people"),n={organization_id:o.organization_id,organization_people:o.organization_people};return this.request({url:i,method:"POST",data:n},t)}RemoveOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/remove_organization_people"),n={organization_id:o.organization_id,user_id:o.user_id,receiver:o.receiver};return this.request({url:i,method:"POST",data:n},t)}UpdateOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization_people"),n={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:n},t)}DownloadRemoteAttestationEvidence(e,t){const o=e,i=this.genBaseURL("/api/permission_api/aicc/download_remote_attestation_evidence"),n={component_name:o.component_name};return this.request({url:i,method:"GET",params:n},t)}GetAgentAiccInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/aicc/get_agent_aicc_info"),n={agent_id:o.agent_id};return this.request({url:i,method:"GET",params:n},t)}CheckDeleteOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/check_delete_organization"),n={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:n},t)}DeleteOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/delete_organization"),n={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:n},t)}ListProjectUsers(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/list_project_users"),n={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:n},t)}DeleteProjectUser(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user"),n={environment:o.environment,project_id:o.project_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:n},t)}GetProjectAuthConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config"),n={project_id:o.project_id};return this.request({url:i,method:"GET",params:n},t)}UpdateProjectAuthConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config"),n={project_id:o.project_id,configuration:o.configuration};return this.request({url:i,method:"POST",data:n},t)}ListProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/list_project_secret"),n={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:n},t)}UpdateProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/update_project_secret"),n={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:n},t)}DeleteProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/delete_project_secret"),n={project_id:o.project_id,keys:o.keys,cred_provider_ids:o.cred_provider_ids};return this.request({url:i,method:"POST",data:n},t)}EncryptProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/encrypt_project_secret"),n={project_id:o.project_id,project_type:o.project_type,encrypt_secrets:o.encrypt_secrets};return this.request({url:i,method:"POST",data:n},t)}InsertProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/insert_project_secret"),n={project_id:o.project_id,insert_secrets:o.insert_secrets};return this.request({url:i,method:"POST",data:n},t)}OutboundAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/outbound_auth/callback"),n={session_id:o.session_id,error:o.error};return this.request({url:i,method:"GET",params:n},t)}CreateAgentAccessToken(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),n={project_id:o.project_id,deployment_env:o.deployment_env};return this.request({url:i,method:"POST",data:n},t)}ListAgentAccessTokens(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),n={project_id:o.project_id};return this.request({url:i,method:"GET",params:n},t)}DeleteAgentAccessToken(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),n={token_id:o.token_id,project_id:o.project_id};return this.request({url:i,method:"DELETE",data:n},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"),n={invite_code:o.invite_code};return this.request({url:i,method:"GET",params:n},t)}AuthorizeCredProvider(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/authorize"),n={provider_id:o.provider_id};return this.request({url:i,method:"GET",params:n},t)}ProjectSecretAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/project_secret/callback"),n={code:o.code,state:o.state,error:o.error};return this.request({url:i,method:"GET",params:n},t)}ListAuthInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/list_auth_info"),n={credential_ids:o.credential_ids};return this.request({url:i,method:"POST",data:n},t)}RevokeAuthorization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/revoke"),n={credential_id:o.credential_id};return this.request({url:i,method:"POST",data:n},t)}VisibilityConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/visibility_config"),n={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:n},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)}BatchGetPeopleJoinedOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_get_people_joined_organization"),n={enterprise_id:o.enterprise_id,user_ids:o.user_ids};return this.request({url:i,method:"POST",data:n},t)}BatchRemoveOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_remove_organization_people"),n={enterprise_id:o.enterprise_id,remove_user_list:o.remove_user_list};return this.request({url:i,method:"POST",data:n},t)}BatchRemoveEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_remove_enterprise_people"),n={enterprise_id:o.enterprise_id,remove_user_list:o.remove_user_list};return this.request({url:i,method:"POST",data:n},t)}GetOrganizationSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization_settings"),n={organization_id:o.organization_id,organization_setting_key_list:o.organization_setting_key_list};return this.request({url:i,method:"POST",data:n},t)}UpdateOrganizationSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization_settings"),n={organization_id:o.organization_id,organization_settings:o.organization_settings};return this.request({url:i,method:"POST",data:n},t)}}const ai=new ri({});function ci(e,t){return null!=e?e:t()}class li{constructor(e){this.ctx=e,this.config=e.config}getOAuthConfig(){return{baseURL:ci(this.config.openApiBaseUrl,()=>Y.openApiBaseUrl),clientId:ci(this.config.clientId,()=>Y.clientId)}}async clearUserContext(){this.config.organizationId=void 0,this.config.enterpriseId=void 0,this.config.spaceId=void 0,await oe({organizationId:void 0,enterpriseId:void 0,spaceId:void 0})}async clearAuthData(){this.config.accessToken=void 0,this.config.refreshToken=void 0,this.config.tokenExpiresAt=void 0,await oe({accessToken:void 0,refreshToken:void 0,tokenExpiresAt:void 0})}async login(o){if(this.ctx.ui.verbose("Initiating login process..."),o.token)return this.ctx.ui.info("Using Personal Access Token (PAT)..."),this.config.accessToken=o.token,await oe({accessToken:o.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:o,clientId:i}=this.getOAuthConfig();this.ctx.ui.verbose("Starting OAuth device flow...");const n=await async function(e){const t=e.workspaceId?`/api/permission/oauth2/workspace_id/${e.workspaceId}/device/code`:"/api/permission/oauth2/device/code";return(await to.post(t,{client_id:e.clientId},{baseURL:e.baseURL})).data}({baseURL:o,clientId:i}),s=`${n.verification_uri}?user_code=${n.user_code}`;this.ctx.ui.info(`Please visit ${t.underline(s)} and authorize the application.\n\nPrivacy Policy: ${t.underline("https://docs.coze.cn/guides/privacy")}\nTerms of Service: ${t.underline("https://docs.coze.cn/guides/terms-of-service")}\n\nIf you are an agent using Coze CLI, please share the authorization link, Privacy Policy, and Terms of Service with your users.\n `);const r=await async function(t,o){if(!t.poll)return oo(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 oo(t);return o.ui.debug(`Polling for device token success: ${JSON.stringify(e)}`),e}catch(t){if(e.isHttpError(t)){o.ui.debug(`Polling for device token error, the error is a HttpError.\n logid: ${Yt([t,"access",e=>e.response,"optionalAccess",e=>e.headers,"access",e=>e["x-tt-logid"]])}`),o.ui.debug(`Polling for device token error: ${JSON.stringify(t.toJSON())}`);const e=t.data;if(Yt([e,"optionalAccess",e=>e.error])===Xt.AUTHORIZATION_PENDING){o.ui.debug("Polling for device token: user has not completed authorization yet."),await eo(i);continue}if(Yt([e,"optionalAccess",e=>e.error])===Xt.SLOW_DOWN){i<3e4&&(i+=5e3),o.ui.debug(`Polling for device token: client is polling too frequently. Increasing interval to ${i}ms`),await eo(i);continue}}throw o.ui.debug(`Polling for device token error, the error is: ${t.message}\n ${t.stack}\n `),t}}({baseURL:o,clientId:i,deviceCode:n.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: ${e.message||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 ai.GetUserProfile({},{baseURL:this.config.openApiBaseUrl}),n={logged_in:!0,user:i,token_expires_at:t?new Date(t).toISOString():o?void 0:"Never (PAT)"};this.ctx.response.print(n)}async getValidAccessToken(){const{accessToken:e,refreshToken:t,tokenExpiresAt:o}=this.config;if(!e)return;if(!t)return e;if(o&&Date.now()<o-3e5)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 to.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: ${e.message||e}`),void await this.clearAuthData()}}async saveOAuthToken(e){const t=1e3*e.expires_in;this.config.accessToken=e.access_token,this.config.refreshToken=e.refresh_token,this.config.tokenExpiresAt=t,await oe({accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:t})}}const pi="",di="",ui="",_i="",mi="",gi="",hi="",fi="",yi="[PROC]",bi="[INFO]",vi="[WARN]",Ci="[ERR]",Ai="[DONE]",Pi="[DBG]",ji={debug:0,verbose:1,info:2,success:3,warn:4,error:5};function Ei(e){return`${ui}${di}${e}${pi}`}class Si{constructor(e,t,o="info"){var i,n;this.log=e,this.silent="json"===t,this.useColor=this.detectColorSupport(),this.level=o,this.levelPriority=(n=()=>2,null!=(i=ji[o])?i:n())}detectColorSupport(){return!0===function(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...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}${pi}`:t}shouldOutput(e){return!this.silent&&ji[e]>=this.levelPriority}verbose(e,...t){this.log.verbose(e,...t),this.shouldOutput("verbose")&&process.stderr.write(`${Ei(yi)} ${this.paint(hi,e)}\n`)}info(e,...t){this.log.info(e,...t),this.shouldOutput("info")&&process.stderr.write(`${Ei(bi)} ${this.paint(pi,e)}\n`)}warn(e,...t){this.log.warn(e,...t),this.shouldOutput("warn")&&process.stderr.write(`${Ei(vi)} ${this.paint(gi,e)}\n`)}error(e,...t){this.log.error(e,...t),this.shouldOutput("error")&&process.stderr.write(`${Ei(Ci)} ${this.paint(_i,e)}\n`)}success(e,...t){this.log.success(e,...t),this.shouldOutput("success")&&process.stderr.write(`${Ei(Ai)} ${this.paint(mi,e)}\n`)}debug(e,...t){this.log.debug(e,...t),this.shouldOutput("debug")&&process.stderr.write(`${Ei(Pi)} ${this.paint(fi,e)}\n`)}}class wi{constructor(e){const{format:t}=e;this.formatter=function(e){return"text"===e?new q:new S}(t)}print(e){const t=this.formatter.format(e);process.stdout.write(t)}eprint(e){const t=this.formatter.formatError(e);process.stderr.write(t)}}function ki(e,t){return null!=e?e:t()}const Ti=s.join(n.homedir(),".coze","logs");class Ii{__init(){this.fileStream=null}__init2(){this.writeError=!1}constructor(e={}){Ii.prototype.__init.call(this),Ii.prototype.__init2.call(this),this.format=ki(e.format,()=>"text"),this.printToStderr=ki(e.printToStderr,()=>!1),this.tags=ki(e.tags,()=>({})),this.startTime=Date.now();const t=ki(e.logFile,()=>this.getDefaultLogPath());this.logFile=t;try{this.ensureLogDir(),this.rotateLogFiles(),this.fileStream=u.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 s.join(Ti,`${e}-${t}.log`)}ensureLogDir(){u.existsSync(Ti)||u.mkdirSync(Ti,{recursive:!0})}rotateLogFiles(){try{const e=u.readdirSync(Ti).filter(e=>e.endsWith(".log")).map(e=>({name:e,path:s.join(Ti,e),mtime:u.statSync(s.join(Ti,e)).mtime.getTime()})).sort((e,t)=>t.mtime-e.mtime);e.length>=10&&e.slice(9).forEach(e=>{try{u.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)}log(e,t,o){const i=this.formatEntry(e,t,o);if(this.fileStream)try{this.fileStream.write(`${i}\n`)}catch(e){!this.writeError&&this.printToStderr&&(process.stderr.write("Warning: Log write failed\n"),this.writeError=!0)}this.printToStderr&&process.stderr.write(`${i}\n`)}formatEntry(e,t,o){const i=(new Date).toISOString(),n=Date.now()-this.startTime;if("json"===this.format){const s={level:e,timestamp:i,delta:n,...this.tags,message:t};return o.length>0&&(s.args=o),JSON.stringify(s)}const s=Object.entries(this.tags).map(([e,t])=>`${e}=${t}`).join(" "),r=o.length>0?` ${o.map(String).join(" ")}`:"";return`${e.toUpperCase().padEnd(7)} [${i}] +${n}ms ${s} ${t}${r}`}close(){if(this.fileStream)try{this.fileStream.end()}catch(e){}}}function Ri(e,t){return null!=e?e:t()}async function Oi(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 zi,Li,Ui,xi,Di,Bi,qi,Mi,Ni,Gi,Fi,$i,Vi,Wi,Hi,Ki,Ji,Zi,Qi,Yi,Xi,en,tn,on,nn,sn,rn,an,cn,ln,pn,dn,un,_n,mn,gn,hn,fn,yn,bn,vn,Cn,An,Pn,jn,En,Sn,wn,kn,Tn,In,Rn,On,zn,Ln,Un,xn,Dn,Bn,qn,Mn,Nn,Gn,Fn,$n,Vn,Wn,Hn,Kn,Jn,Zn,Qn,Yn,Xn,es,ts,os,is,ns,ss,rs,as,cs,ls,ps,ds,us,_s,ms,gs,hs,fs,ys,bs,vs,Cs,As,Ps,js,Es,Ss,ws,ks,Ts,Is,Rs,Os,zs,Ls,Us,xs,Ds,Bs,qs,Ms,Ns,Gs,Fs,$s,Vs,Ws,Hs,Ks,Js,Zs,Qs,Ys,Xs,er,tr,or;function ir(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...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"}(zi||(zi={})),function(e){e[e.OldVersion=0]="OldVersion";e[e.MiddleVersion=1]="MiddleVersion";e[e.NewVersion=2]="NewVersion";e[e.MiddleVersionNotPrompt=3]="MiddleVersionNotPrompt"}(Li||(Li={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(Ui||(Ui={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(xi||(xi={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Di||(Di={})),function(e){e[e.Current=1]="Current";e[e.Previous=2]="Previous";e[e.Start=3]="Start";e[e.MostSuitable=4]="MostSuitable"}(Bi||(Bi={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(qi||(qi={})),function(e){e[e.Default=0]="Default";e[e.Function=1]="Function"}(Mi||(Mi={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned"}(Ni||(Ni={})),function(e){e[e.LimitedReadWrite=1]="LimitedReadWrite";e[e.ReadOnly=2]="ReadOnly";e[e.UnlimitedReadWrite=3]="UnlimitedReadWrite";e[e.RWModeMax=4]="RWModeMax"}(Gi||(Gi={})),function(e){e[e.Default=0]="Default";e[e.DouyinAvatar=1]="DouyinAvatar"}(Fi||(Fi={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}($i||($i={})),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"}(Vi||(Vi={})),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"}(Wi||(Wi={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Hi||(Hi={})),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"}(Ki||(Ki={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Ji||(Ji={})),function(e){e[e.SLM=0]="SLM";e[e.LLM=1]="LLM"}(Zi||(Zi={})),function(e){e[e.Pre=1]="Pre";e[e.Post=2]="Post";e[e.PreAndPost=3]="PreAndPost"}(Qi||(Qi={})),function(e){e[e.Default=0]="Default";e[e.CustomizePrompt=1]="CustomizePrompt"}(Yi||(Yi={})),function(e){e[e.ReplyBottom=0]="ReplyBottom";e[e.CardList=1]="CardList"}(Xi||(Xi={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(en||(en={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(tn||(tn={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(on||(on={})),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"}(nn||(nn={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(sn||(sn={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(rn||(rn={})),function(e){e[e.Curve=0]="Curve";e[e.Straight=1]="Straight"}(an||(an={})),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"}(ln||(ln={})),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"}(pn||(pn={})),function(e){e[e.Input=0]="Input";e[e.Variable=1]="Variable"}(dn||(dn={})),function(e){e[e.Default=0]="Default";e[e.FromSaas=1]="FromSaas"}(un||(un={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(_n||(_n={})),function(e){e[e.FunctionCall=1]="FunctionCall";e[e.Independent=2]="Independent"}(mn||(mn={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(gn||(gn={})),function(e){e[e.ManualUpdate=1]="ManualUpdate";e[e.AutoUpdate=2]="AutoUpdate"}(hn||(hn={})),function(e){e[e.SemanticSearch=0]="SemanticSearch";e[e.HybirdSearch=1]="HybirdSearch";e[e.FullTextSearch=20]="FullTextSearch"}(fn||(fn={})),function(e){e[e.Public=1]="Public";e[e.Anonymous=2]="Anonymous";e[e.Custom=3]="Custom"}(yn||(yn={})),function(e){e[e.Random=0]="Random";e[e.All=1]="All"}(bn||(bn={})),function(e){e[e.System=0]="System";e[e.Custom=1]="Custom";e[e.Disable=2]="Disable";e[e.OriBot=3]="OriBot"}(vn||(vn={})),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"}(Cn||(Cn={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(An||(An={})),function(e){e[e.CozeOldTimeCapsule=0]="CozeOldTimeCapsule";e[e.VolcanoTimeCapsule=1]="VolcanoTimeCapsule"}(Pn||(Pn={})),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"}(jn||(jn={})),function(e){e[e.BotQuery=1]="BotQuery";e[e.Plugin=2]="Plugin";e[e.Workflow=3]="Workflow"}(En||(En={})),function(e){e[e.Unknown=0]="Unknown";e[e.Webhook=1]="Webhook"}(Sn||(Sn={})),function(e){e[e.Unknown=0]="Unknown";e[e.Time=1]="Time";e[e.Event=2]="Event"}(wn||(wn={})),function(e){e[e.NoHistory=0]="NoHistory";e[e.NeedHistory=1]="NeedHistory"}(kn||(kn={})),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"}(Tn||(Tn={})),function(e){e[e.Init=0]="Init";e[e.Activated=1]="Activated";e[e.Deactivated=2]="Deactivated";e[e.Suspended=3]="Suspended"}(In||(In={})),function(e){e[e.Preset=1]="Preset";e[e.UserTask=2]="UserTask";e[e.PluginRunTask=3]="PluginRunTask"}(Rn||(Rn={})),function(e){e[e.Deploying=0]="Deploying";e[e.Successful=1]="Successful";e[e.Failed=2]="Failed"}(On||(On={})),function(e){e[e.All=0]="All";e[e.Bind=1]="Bind";e[e.UnBind=2]="UnBind"}(zn||(zn={})),function(e){e[e.CreateTime=0]="CreateTime";e[e.UpdateTime=1]="UpdateTime"}(Ln||(Ln={})),function(e){e[e.EventMeta=1]="EventMeta";e[e.ProfileMeta=2]="ProfileMeta"}(Un||(Un={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(xn||(xn={})),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"}(Dn||(Dn={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(Bn||(Bn={})),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"}(qn||(qn={})),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"}(Mn||(Mn={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(Nn||(Nn={})),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"}(Gn||(Gn={})),function(e){e[e.Upgrade=1]="Upgrade";e[e.BrowseOldNoPrompt=2]="BrowseOldNoPrompt"}(Fn||(Fn={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}($n||($n={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(Vn||(Vn={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(Wn||(Wn={})),function(e){e[e.Visit=1]="Visit";e[e.Edit=2]="Edit"}(Hn||(Hn={})),function(e){e[e.Online=1]="Online";e[e.Offline=2]="Offline"}(Kn||(Kn={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online"}(Jn||(Jn={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Zn||(Zn={})),function(e){e[e.AutoGenBeforePublish=1]="AutoGenBeforePublish"}(Qn||(Qn={})),function(e){e[e.CozeHome=1]="CozeHome";e[e.Space=2]="Space"}(Yn||(Yn={})),function(e){e[e.Undefined=0]="Undefined";e[e.PersonalDraft=1]="PersonalDraft";e[e.Base=2]="Base";e[e.Publish=3]="Publish"}(Xn||(Xn={})),function(e){e[e.Undefined=0]="Undefined";e[e.Committed=1]="Committed";e[e.Behind=2]="Behind";e[e.NoDraftReplica=3]="NoDraftReplica"}(es||(es={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(ts||(ts={})),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"}(os||(os={})),function(e){e[e.Personal=1]="Personal";e[e.Organization=2]="Organization"}(is||(is={})),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"}(ns||(ns={})),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"}(ss||(ss={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned";e[e.MoveFail=3]="MoveFail"}(rs||(rs={})),function(e){e[e.ByteTree=1]="ByteTree";e[e.GPTAK=2]="GPTAK";e[e.MaasAK=3]="MaasAK"}(as||(as={})),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"}(cs||(cs={})),function(e){e[e.BotStore=1]="BotStore"}(ls||(ls={})),function(e){e[e.shorcutIcon=1]="shorcutIcon"}(ps||(ps={})),function(e){e[e.Onboarding=0]="Onboarding";e[e.BackgroundImage=1]="BackgroundImage"}(ds||(ds={})),function(e){e[e.BasicUser=1]="BasicUser";e[e.ExternalUser=2]="ExternalUser";e[e.RootUser=3]="RootUser"}(us||(us={})),function(e){e[e.GetInfo=1]="GetInfo"}(_s||(_s={})),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"}(ms||(ms={})),function(e){e[e.Apply=1]="Apply";e[e.Invite=2]="Invite";e[e.EnterpriseApply=3]="EnterpriseApply"}(gs||(gs={})),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"}(hs||(hs={})),function(e){e[e.Douyin=1]="Douyin"}(fs||(fs={})),function(e){e[e.GPTOpenAPI=1]="GPTOpenAPI";e[e.Maas=2]="Maas";e[e.LLMFlow=3]="LLMFlow";e[e.Merlin=4]="Merlin"}(ys||(ys={})),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"}(bs||(bs={})),function(e){e[e.All=0]="All";e[e.Unread=1]="Unread"}(vs||(vs={})),function(e){e[e.Bot=1]="Bot"}(Cs||(Cs={})),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"}(As||(As={})),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"}(Ps||(Ps={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ShortcutCommand=3]="ShortcutCommand";e[e.Task=4]="Task"}(js||(js={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Knowledge=4]="Knowledge"}(Es||(Es={})),function(e){e[e.NoPublish=0]="NoPublish";e[e.HadPublished=1]="HadPublished"}(Ss||(Ss={})),function(e){e[e.Success=1]="Success";e[e.Failed=2]="Failed";e[e.InReview=3]="InReview"}(ws||(ws={})),function(e){e[e.Unread=1]="Unread";e[e.Read=2]="Read"}(ks||(ks={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(Ts||(Ts={})),function(e){e[e.UnLimit=1]="UnLimit";e[e.Forbidden=2]="Forbidden"}(Is||(Is={})),function(e){e[e.Plugin=1]="Plugin";e[e.NewBotIDEGuide=2]="NewBotIDEGuide";e[e.NewBeginnerGuide=3]="NewBeginnerGuide"}(Rs||(Rs={})),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"}(Os||(Os={})),function(e){e[e.All=0]="All";e[e.Self=1]="Self"}(zs||(zs={})),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"}(Ls||(Ls={})),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"}(Us||(Us={})),function(e){e[e.EnterpriseUser=1]="EnterpriseUser";e[e.ExternalUser=2]="ExternalUser"}(xs||(xs={})),function(e){e[e.Normal=0]="Normal";e[e.DevMode=1]="DevMode"}(Ds||(Ds={})),function(e){e[e.DraftBot=1]="DraftBot";e[e.Project=2]="Project";e[e.Space=3]="Space";e[e.DouyinAvatarBot=4]="DouyinAvatarBot"}(Bs||(Bs={})),function(e){e[e.Default=0]="Default";e[e.Owner=1]="Owner";e[e.Admin=2]="Admin";e[e.Member=3]="Member"}(qs||(qs={})),function(e){e[e.Professional=1]="Professional"}(Ms||(Ms={})),function(e){e[e.Personal=1]="Personal";e[e.Team=2]="Team"}(Ns||(Ns={})),function(e){e[e.Dark=1]="Dark";e[e.Light=2]="Light"}(Gs||(Gs={})),function(e){e[e.AlwaysOn=0]="AlwaysOn";e[e.AlwaysOff=1]="AlwaysOff"}(Fs||(Fs={})),function(e){e[e.CozeAssistantGuide=1]="CozeAssistantGuide"}($s||($s={})),function(e){e[e.Normal=1]="Normal";e[e.Banned=2]="Banned";e[e.Canceled=3]="Canceled"}(Vs||(Vs={})),function(e){e[e.External=0]="External";e[e.Internal=1]="Internal"}(Ws||(Ws={})),function(e){e[e.Invisible=0]="Invisible";e[e.Visible=1]="Visible";e[e.SocietyInvisible=2]="SocietyInvisible"}(Hs||(Hs={})),function(e){e[e.SingleAgent=1]="SingleAgent";e[e.MultiAgent=2]="MultiAgent";e[e.WorkflowAsAgent=3]="WorkflowAsAgent"}(Ks||(Ks={})),function(e){e[e.Preset=1]="Preset";e[e.Library=2]="Library"}(Js||(Js={})),function(e){e[e.DatasetServiceValid=0]="DatasetServiceValid";e[e.DatasetServiceInvalid=1]="DatasetServiceInvalid"}(Zs||(Zs={})),function(e){e[e.DatasetValid=0]="DatasetValid";e[e.DatasetInvalid=1]="DatasetInvalid"}(Qs||(Qs={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(Ys||(Ys={})),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"}(Xs||(Xs={})),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"}(er||(er={})),function(e){e[e.SendTypeQuery=0]="SendTypeQuery";e[e.SendTypePanel=1]="SendTypePanel"}(tr||(tr={})),function(e){e[e.ToolTypeWorkFlow=1]="ToolTypeWorkFlow";e[e.ToolTypePlugin=2]="ToolTypePlugin"}(or||(or={}));class nr{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){nr.prototype.__init.call(this),nr.prototype.__init2.call(this),this.request=ir([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=ir([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"),n={space_id:o.space_id,join_space_type:o.join_space_type};return this.request({url:i,method:"POST",data:n},t)}DeleteSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/delete"),n={space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}SaveSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/save"),n={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:n},t)}GetSpaceListV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/list"),n={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:n},t)}UpdateAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_agent"),n={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:n},t)}BatchCreateAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/batch_create_agent"),n={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:n},t)}GetPublishBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_publish_bot_list"),n={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:n},t)}MGetBotByVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/mget_bot_by_version"),n={bot_versions:o.bot_versions,space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}BotLastPublishInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_last_publish_info"),n={space_id:o.space_id,bot_id:o.bot_id,bot_mode:o.bot_mode};return this.request({url:i,method:"GET",params:n},t)}ProduceBot(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/produce/create_bot"),n={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:n},t)}UpdateProducedBot(e,t){const o=e,i=this.genBaseURL("/api/playground_api/produce/update_bot"),n={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:n},t)}GetPublishedBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_version/get_published_bot_list"),n={space_id_list:o.space_id_list,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:n},t)}GetBotVersionInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_version/get_bot_version_info"),n={bot_id:o.bot_id,version:o.version,scene:o.scene};return this.request({url:i,method:"POST",data:n},t)}DuplicateBotVersionToSpace(e,t){const o=e,i=this.genBaseURL("/api/playground_api/dup_bot_version"),n={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:n},t)}UpdateUserRiskAlertInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/update_user_risk_alert_info"),n={risk_alert_type:o.risk_alert_type,switch_info:o.switch_info};return this.request({url:i,method:"POST",data:n},t)}GetUserRiskAlertInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_user_risk_alert_info"),n={risk_alert_type_list:o.risk_alert_type_list,switch_type_list:o.switch_type_list},s={Cookie:o.Cookie};return this.request({url:i,method:"POST",data:n,headers:s},t)}DraftBotCollaboration(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/collaboration"),n={space_id:o.space_id,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:n},t)}BotInfoAudit(e,t){const o=e,i=this.genBaseURL("/api/playground_api/audit/bot_info"),n={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:n},t)}TimeCapsuleInvokeEvent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/timecapsule_invoke_event"),n={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:n},t)}InviteMemberLinkV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/invite"),n={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:n},t)}SpaceMemberDetailV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/detail"),n={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:n},t)}JoinSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/join"),n={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:n},t)}UpdateSpaceMemberV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/update"),n={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:n},t)}TransferSpaceV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/transfer"),n={space_id:o.space_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:n},t)}RemoveSpaceMemberV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/remove"),n={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:n},t)}SearchMemberV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/member/search"),n={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:n},t)}AddBotSpaceMemberV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/member/add"),n={member_info_list:o.member_info_list,space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}ExitSpaceV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/exit"),n={space_id:o.space_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:n},t)}GetBotPopupInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/operate/get_bot_popup_info"),n={bot_popup_types:o.bot_popup_types,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:n},t)}UpdateBotPopupInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/operate/update_bot_popup_info"),n={bot_popup_type:o.bot_popup_type,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:n},t)}GenerateDescription(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/generate_description"),n={bot_name:o.bot_name,prompt:o.prompt};return this.request({url:i,method:"POST",data:n},t)}DraftBotPublishHistoryDetail(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/publish_history_detail"),n={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:n},t)}GenerateStoreCategory(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/generate_store_category"),n={bot_name:o.bot_name,bot_description:o.bot_description,prompt:o.prompt};return this.request({url:i,method:"POST",data:n},t)}UpdateMultiAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_multi_agent"),n={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:n},t)}SwitchAgentVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/switch_agent_version"),n={bot_id:o.bot_id,space_id:o.space_id,operate_type:o.operate_type};return this.request({url:i,method:"POST",data:n},t)}LangDetect(e,t){const o=e,i=this.genBaseURL("/api/playground_api/audio/lang/detect"),n={detect_text_list:o.detect_text_list};return this.request({url:i,method:"POST",data:n},t)}GetImagexShortUrl(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_imagex_url"),n={uris:o.uris,scene:o.scene};return this.request({url:i,method:"POST",data:n},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"),n={object_id:o.object_id,shortcuts:o.shortcuts};return this.request({url:i,method:"POST",data:n},t)}MGetUserBasicInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/mget_user_info"),n={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:n},t)}BindVolcanoTrn(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/bind_volcano_trn"),n={space_id:o.space_id,trn:o.trn,account_name:o.account_name};return this.request({url:i,method:"POST",data:n},t)}UnbindVolcanoTrn(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/unbind_volcano_trn"),n={space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}RetrieveFileOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/retrieve"),n={file_id:o.file_id};return this.request({url:i,method:"GET",params:n},t)}RetrieveFileContentOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/content/retrieve"),n={file_id:o.file_id};return this.request({url:i,method:"GET",params:n},t)}UploadFileOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/upload"),n={Data:o.Data},s={"Content-Type":o["Content-Type"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}BotInfoCheck(e,t){const o=e,i=this.genBaseURL("/api/playground_api/check/bot_info_check"),n={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:n},t)}SupportVoiceCall(e,t){const o=e,i=this.genBaseURL("/api/playground_api/support_voice_call"),n={voice_id_list:o.voice_id_list};return this.request({url:i,method:"POST",data:n},t)}CreateUpdateShortcutCommand(e,t){const o=e,i=this.genBaseURL("/api/playground_api/create_update_shortcut_command"),n={object_id:o.object_id,space_id:o.space_id,shortcuts:o.shortcuts};return this.request({url:i,method:"POST",data:n},t)}MoveDraftBot(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/move_draft_bot"),n={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:n},t)}GetShortcutAvailNodes(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_shortcut_avail_nodes"),n={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:n},t)}MarkReadNotice(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/mark_read_notice"),n={bot_id:o.bot_id,pic_type:o.pic_type};return this.request({url:i,method:"POST",data:n},t)}CancelGenerateGif(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/cancel_generate_gif"),n={task_id:o.task_id};return this.request({url:i,method:"POST",data:n},t)}GetPicTask(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/get_pic_task"),n={bot_id:o.bot_id,pic_type:o.pic_type};return this.request({url:i,method:"POST",data:n},t)}GeneratePic(e,t){const o=e,i=this.genBaseURL("/api/playground_api/gen_img/generate_pic"),n={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:n},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"),n={scene:o.scene};return this.request({url:i,method:"POST",data:n},t)}GetDraftBotInfoAgw(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/get_draft_bot_info"),n={bot_id:o.bot_id,version:o.version,commit_version:o.commit_version};return this.request({url:i,method:"POST",data:n},t)}CommitDraftBotInfoAgw(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/commit_draft_bot_info"),n={bot_id:o.bot_id,remark:o.remark};return this.request({url:i,method:"POST",data:n},t)}UpdateDraftBotInfoAgw(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/update_draft_bot_info"),n={bot_info:o.bot_info,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:n},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"),n={bot_id:o.bot_id,developer_name:o.developer_name,contact_information:o.contact_information};return this.request({url:i,method:"POST",data:n},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"),n={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:n},t)}CopyAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/copy_agent_v2"),n={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:n},t)}CreateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/create_agent_v2"),n={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:n},t)}BatchCreateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/batch_create_agent_v2"),n={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:n},t)}CozeProCopyGetLinkMetaInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/get_link_meta_info"),n={auth_code:o.auth_code};return this.request({url:i,method:"POST",data:n},t)}CozeProCopyTaskConfirm(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/copy_task_confirm"),n={auth_code:o.auth_code};return this.request({url:i,method:"POST",data:n},t)}CozeProCopyGenerateAuthLink(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/generate_auth_link"),n={copy_user_id:o.copy_user_id,target_space_id:o.target_space_id};return this.request({url:i,method:"POST",data:n},t)}GetOpVoiceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_op_voice_list"),n={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:n},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"),n={bot_id:o.bot_id,commit_version:o.commit_version};return this.request({url:i,method:"POST",data:n},t)}GetBotCollaborationQuota(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/collaboration_quota"),n={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:n},t)}OpenCreateSpace(e,t){const o=e||{},i=this.genBaseURL("/v1/workspaces"),n={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:n},t)}NoticeMarkRead(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/notice/mark_read"),n={notice_ids:o.notice_ids,mark_all:o.mark_all};return this.request({url:i,method:"POST",data:n},t)}GetNoticeList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/notice/get_list"),n={cursor:o.cursor,count:o.count,notice_rank_type:o.notice_rank_type};return this.request({url:i,method:"POST",data:n},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"),n={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:n},t)}ReportUserBehavior(e,t){const o=e,i=this.genBaseURL("/api/playground_api/report_user_behavior"),n={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:n},t)}GetUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_user_config"),n={risk_alert_type_list:o.risk_alert_type_list,switch_type_list:o.switch_type_list},s={Cookie:o.Cookie};return this.request({url:i,method:"POST",data:n,headers:s},t)}UpdateUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/update_user_config"),n={risk_alert_type:o.risk_alert_type,switch_info:o.switch_info};return this.request({url:i,method:"POST",data:n},t)}GetRecentDraftBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/get_recent_draft_bot"),n={behavior_type:o.behavior_type,limit:o.limit};return this.request({url:i,method:"POST",data:n},t)}GetPromptResourceInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_prompt_resource_info"),n={prompt_resource_id:o.prompt_resource_id};return this.request({url:i,method:"GET",params:n},t)}UpsertPromptResource(e,t){const o=e,i=this.genBaseURL("/api/playground_api/upsert_prompt_resource"),n={prompt:o.prompt};return this.request({url:i,method:"POST",data:n},t)}DeletePromptResource(e,t){const o=e,i=this.genBaseURL("/api/playground_api/delete_prompt_resource"),n={prompt_resource_id:o.prompt_resource_id};return this.request({url:i,method:"POST",data:n},t)}GetPromptReferenceInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_prompt_reference_info"),n={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:n},t)}GetOfficialPromptResourceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_official_prompt_list"),n={keyword:o.keyword};return this.request({url:i,method:"POST",data:n},t)}GetByteTreeByName(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/search_byte_tree"),n={name:o.name},s={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"GET",params:n,headers:s},t)}CreatePrivateModel(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/create_private_model"),n={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},s={"x-inner-auth":o["x-inner-auth"],"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}CheckExemptFormInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/check_exempt_form_info"),n={exempt_form_type:o.exempt_form_type,space_id:o.space_id},s={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}SetByteTreeForSpace(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/set_byte_tree_for_space"),n={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},s={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}GetModelCapability(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bpm/get_model_capability"),n={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},s={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}GetSpaceDetail(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/detail"),n={space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}RevocateSpaceInvite(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/revocate_invite"),n={space_id:o.space_id,invite_user_id:o.invite_user_id};return this.request({url:i,method:"GET",params:n},t)}SaveVolcanoUserManageInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/save_volcano_user_manage_info"),n={volcano_basic_user_config:o.volcano_basic_user_config};return this.request({url:i,method:"POST",data:n},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"),n={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:n},t)}DebugDouYin(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/debug"),n={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:n},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"),n={is_draft:o.is_draft,body:o.body},s={"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:n,headers:s},t)}DouYinAuthUserList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/auth_user_list"),n={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:n},t)}GetDebugDouYinStatus(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/get_debug_status"),n={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:n},t)}CanUserApplyClose(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/coze_pro/can_user_apply_close"),n={AccountId:o.AccountId,EventName:o.EventName,Action:o.Action,Version:o.Version},s={"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:n,headers:s},t)}CreateRoom(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/create_room"),n={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:n},t)}GetVoiceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_list"),n={page_index:o.page_index,page_size:o.page_size,language_code:o.language_code};return this.request({url:i,method:"POST",data:n},t)}GetVoiceByIds(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_by_ids"),n={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:n},t)}GrayVoice(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gray_voice"),n={bot_id:o.bot_id,language_to_voice_id:o.language_to_voice_id};return this.request({url:i,method:"POST",data:n},t)}GetSpaceApplyManageList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/apply_manage_list"),n={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:n},t)}DraftBotCrossSpaceCopy(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/crossspace_copy"),n={bot_id:o.bot_id,to_space_id:o.to_space_id};return this.request({url:i,method:"POST",data:n},t)}RemovePublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/remove_publish_member"),n={space_id:o.space_id,member_list:o.member_list};return this.request({url:i,method:"POST",data:n},t)}AddPublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/add_publish_member"),n={space_id:o.space_id,member_list:o.member_list};return this.request({url:i,method:"POST",data:n},t)}SearchAddablePublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/search_addable_publish_member"),n={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:n},t)}PublishMemberList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/publish_member_list"),n={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:n},t)}OperateSpaceApply(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/operate_apply"),n={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:n},t)}ImportSpaceConfirm(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/confirm"),n={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:n},t)}ImportSpaceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/list"),n={enterprise_id:o.enterprise_id,organization_id:o.organization_id,search_word:o.search_word};return this.request({url:i,method:"GET",params:n},t)}ImportSpaceUserList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/user_list"),n={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:n},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"),n={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:n},t)}LongTermMemoryUpdate(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/update"),n={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:n},t)}LongTermMemoryClearAll(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/clear_all"),n={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:n},t)}LongTermMemoryDelete(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/delete"),n={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:n},t)}LongTermMemoryVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/version"),n={bot_id:o.bot_id};return this.request({url:i,method:"GET",params:n},t)}GetVoiceListV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_list_v2"),n={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:n},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`),n={user_ids:o.user_ids};return this.request({url:i,method:"DELETE",data:n},t)}OpenSpaceMemberList(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),n={page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:n},t)}OpenAddSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),n={users:o.users};return this.request({url:i,method:"POST",data:n},t)}OpenGetBotInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}`),n={is_published:o.is_published,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:n},t)}OpenApplyJoinSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members/apply`),n={user_ids:o.user_ids};return this.request({url:i,method:"POST",data:n},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"),n={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:n},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}`),n={role_type:o.role_type};return this.request({url:i,method:"PUT",data:n},t)}OpenListBotVersions(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}/versions`),n={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:n},t)}OpenSwitchBotDevelopMode(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}/collaboration_mode`),n={collaboration_mode:o.collaboration_mode};return this.request({url:i,method:"POST",data:n},t)}OpenUpdateSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}`),n={name:o.name,description:o.description};return this.request({url:i,method:"PUT",data:n},t)}}const sr=new nr({});function rr(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}async function ar(o,i){if(rr([o,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipAuth]))return void await i();if(!o.config.accessToken)throw new e.CozeError(e.ErrorCode.E2001,"No API token found. Please authenticate first.",void 0,{fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"});if(rr([o,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipOrgCheck]))return void await i();const n=await async function(o){let i=o.config.organizationId,{enterpriseId:n}=o.config,s=!1;const{data:r}=await ai.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0}),a=r.enterprise_info_list||[],c=r.personal_account_info;if(i){if(!a.some(e=>rr([e,"access",e=>e.organization_info_list,"optionalAccess",e=>e.some,"call",e=>e(e=>e.organization_id===i)])))throw new e.CozeError(e.ErrorCode.E1000,`Organization ID ${i} is invalid or not found`,void 0,{fix:"Run `coze organization list` and select a valid organization",example:"coze organization use <organization_id>"})}else{if(c.available)return!1;let r;o.ui.info(t.gray("[Context] Organization ID not found. Attempting to auto-initialize..."));for(const e of a)if(e.organization_info_list&&e.organization_info_list.length>0){const t=e.organization_info_list[0];r={id:t.organization_id,name:t.organization_name,entId:e.enterprise_id};break}if(!r)throw new e.CozeError(e.ErrorCode.E3000,"No organizations found",void 0,{fix:"Create an organization or join an existing one",example:"coze organization list"});i=r.id,n=r.entId,o.config.organizationId=i,o.config.enterpriseId=n,s=!0,o.ui.info(`[Context] Auto-selected Organization: ${r.name} (${r.id})`)}return s}(o);if(rr([o,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipSpaceCheck]))return n&&await cr(o,{organizationId:o.config.organizationId,enterpriseId:o.config.enterpriseId}),void await i();const s=await async function(t){const o=t.config.organizationId,{enterpriseId:i}=t.config;let{spaceId:n}=t.config,s=!1;try{if(n){const{data:t}=await sr.GetSpaceListV2({organization_id:o,enterprise_id:i}),s=rr([t,"optionalAccess",e=>e.bot_space_list])||[];if(!s.some(e=>e.id===n)){const t=o?`[Context] Space ID ${n} is invalid or not found in organization ${o}.`:`[Context] Space ID ${n} 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 sr.GetSpaceListV2({organization_id:o,enterprise_id:i,page:1,size:1}),a=rr([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"})}n=a.id,t.config.spaceId=n,s=!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 s}(o);await lr(o),(n||s)&&await cr(o,{organizationId:o.config.organizationId,enterpriseId:o.config.enterpriseId,spaceId:o.config.spaceId,billingProjectId:o.config.billingProjectId}),await i()}async function cr(e,t){try{await oe(t)}catch(t){e.ui.warn(`Failed to save auto-initialized context: ${t}`)}}const lr=async t=>{const{spaceId:o}=t.config;try{const{data:i}=await e.IdeApi.GetOrCreateBillingProject({space_id:o});if(!rr([i,"optionalAccess",e=>e.project_id]))throw new e.CozeError(e.ErrorCode.E5002,"[Context] Failed to get billing project ID from response.",i);t.config.billingProjectId=i.project_id,t.ui.success(`[Context] Billing Project: ${i.project_id} (space: ${o})`)}catch(e){const t=[`Failed to get billing project, ${e.message}. please check your space context:`," coze space list"," coze space use <space_id>"];throw e.message=`${t.join("\n")}`,e}};function pr(e,t){return null!=e?e:t()}function dr(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const ur=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"}}}}}}}).action(async(e,t)=>{const o=t.getContext(),i=e.orgId||dr([o,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),n=dr([o,"optionalAccess",e=>e.config,"access",e=>e.enterpriseId]);dr([o,"optionalAccess",e=>e.ui,"access",e=>e.verbose,"call",e=>e(`Fetching spaces for organization '${i}'...`)]);const s=await async function(e){const{data:t}=await sr.GetSpaceListV2({organization_id:e.orgId,enterprise_id:e.enterpriseId,page:1,size:100});return pr(function(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}([t,"optionalAccess",e=>e.bot_space_list]),()=>[]).map(t=>({id:pr(t.id,()=>""),name:pr(t.name,()=>""),org_id:pr(e.orgId,()=>"")}))}({orgId:i,enterpriseId:n});dr([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Spaces:")]),dr([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(s)]);const r=["Please use the following command to switch space:"," coze space use <space_id>"];dr([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"},message:{type:"string"}}}}}).action(async(t,o,i)=>{const n=i.getContext();dr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to space '${t}'...`)]),await async function(t){try{await oe({spaceId:t})}catch(o){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set default space to '${t}': ${o.message}`,o.stack)}}(t),dr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default space set to '${t}' successfully.`)]),"json"===dr([n,"optionalAccess",e=>e.format])&&dr([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default space set to '${t}'.`})])})};function _r(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const mr=async t=>{_r([t,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switching to personal account...")]);const{available:o}=await async function(){const[e,{data:t}]=await Promise.all([te(),ai.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);if(!function(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}([t.personal_account_info,"optionalAccess",e=>e.available]))return{available:!1};const o=!!e.organizationId;return await oe({organizationId:void 0,enterpriseId:void 0,...o?{spaceId:void 0}:{}}),{available:!0}}();if(!o)throw new e.CozeError(e.ErrorCode.E1000,"Personal account is not available for the current user.");_r([t,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switched to personal account successfully.")]),"json"===_r([t,"optionalAccess",e=>e.format])&&_r([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:"Switched to personal account."})])},gr=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"}}}}}}}).action(async(e,t)=>{const o=t.getContext();_r([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching organizations...")]);const i=await async function(){const{data:e}=await ai.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})))}();_r([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Organizations (Teams):")]),_r([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(i)]);const n=["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>"];_r([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(n.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 to switch to personal account mode (requires personal account to be available).",examples:[{desc:"Switch organization",cmd:"coze organization use 12345678",tags:["[RECOMMENDED]"]},{desc:"Switch to personal account",cmd:"coze organization use"},{desc:"Switch to personal account (explicit empty string)",cmd:'coze organization use ""'}],errors:[{code:e.ErrorCode.E3001,name:"RESOURCE_NOT_FOUND",desc:"Organization not found",fix:"Run `coze organization list` to see available organizations."},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Personal account not available",fix:"Your account does not have personal account access. Use `coze organization use <org_id>` to switch to an organization instead."}],schema:{input:{org_id:{type:"string",required:!1,description:"Organization ID to switch to. Empty or omitted to switch to personal account."}},output:{status:{type:"string",description:"Operation result status"},message:{type:"string",description:"Human-readable result message"},enterprise_id:{type:"string",description:"Enterprise ID of the selected organization (empty for personal account)"},organization_id:{type:"string",description:"Organization ID that was set (empty for personal account)"}}}}}).action(async(t,o,i)=>{const n=i.getContext();if(!t)return void await mr(n);_r([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to organization '${t}'...`)]);const{enterpriseId:s}=await async function(t){const[o,{data:i}]=await Promise.all([te(),ai.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);let n="",s=!1;for(const e of i.enterprise_info_list)if((e.organization_info_list||[]).find(e=>e.organization_id===t)){n=e.enterprise_id,s=!0;break}if(!s)throw new e.CozeError(e.ErrorCode.E3000,`Organization '${t}' not found in current user's enterprises.`);const r=o.organizationId!==t;return await oe({organizationId:t,enterpriseId:n,...r?{spaceId:void 0}:{}}),{enterpriseId:n}}(t);_r([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Organization '${t}' found in enterprise '${s}'. Config saved.`)]),_r([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default organization set to '${t}' successfully.`)]),"json"===_r([n,"optionalAccess",e=>e.format])&&_r([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default organization set to '${t}'.`,enterprise_id:s,organization_id:t})])})};function hr(e,t){return null!=e?e:t()}const fr=async(e={})=>{const t=hr(e.stdin,()=>process.stdin);return!0===hr(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)},yr=e=>{process.stdout.write(e.endsWith("\n")?e:`${e}\n`)},br=e=>{yr(JSON.stringify(e))},vr=async(e,t)=>{const o=s.resolve(e),n=s.dirname(o);if(await i.mkdir(n,{recursive:!0}),t instanceof Blob){const e=Buffer.from(await t.arrayBuffer());await i.writeFile(o,e)}else Buffer.isBuffer(t)?await i.writeFile(o,t):t instanceof ArrayBuffer?await i.writeFile(o,Buffer.from(t)):await i.writeFile(o,String(t));return o};const Cr=e=>"object"==typeof e&&null!==e,Ar=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},Pr=e=>Cr(e)&&"data"in e&&void 0!==e.data?e.data:e,jr=(e,t)=>{try{const{pathname:o}=new URL(e);return s.extname(o)||t}catch(e){return t}},Er=()=>{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")}`},Sr=e=>{const{outputPath:t,type:o,index:i,ext:n,timestamp:r}=e,a=`${o}_${r}_${i}${n}`;return s.join(t,a)},wr=async(t,o={})=>{let i=null;o.stdin&&(i=await fr());const n=Ar(t),s=Ar(i),r=(c=()=>s,null!=(a=n)?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},kr="720p",Tr="16:9",Ir=!1,Rr=!1;function Or(e,t){return null!=e?e:t()}function zr(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const Lr=(e,t)=>{if(null==e)return 5;const o=Number(e);if(!Number.isFinite(o))return zr([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?(zr([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},Ur=(e,t)=>{if(null==e)return;const o=Number(e);if(Number.isSafeInteger(o)&&o>=0)return o;zr([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --seed '${String(e)}', this parameter will be ignored`)])},xr=e=>{const{content:t,options:o,ctx:i}=e,n=(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]),n=Number(o[2]);if(!Number.isFinite(i)||!Number.isFinite(n)||i<=0)return null;const s=((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,n)||1,r=`${Math.round(i/s)}:${Math.round(n/s)}`,a=Math.max(i,n);return{ratio:r,resolution:a<=854?"480p":a<=1280?"720p":"1080p"}})(o.size),s=((e,t)=>"480p"===e||"720p"===e||"1080p"===e?e:(void 0!==e&&zr([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --resolution '${String(e)}', falling back to '${kr}'`)]),kr))(Or(o.resolution,()=>zr([n,"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&&zr([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --ratio '${String(e)}', falling back to '${Tr}'`)]),Tr})(Or(o.ratio,()=>zr([n,"optionalAccess",e=>e.ratio])),i);return{model:"doubao-seedance-1-5-pro-251215",content:t,callback_url:Or(Ar(o.callbackUrl),()=>{}),return_last_frame:"boolean"==typeof o.returnLastFrame?o.returnLastFrame:Rr,resolution:s,ratio:r,duration:Lr(o.duration,i),watermark:"boolean"!=typeof o.watermark||o.watermark,seed:Ur(o.seed,i),camerafixed:"boolean"==typeof o.camerafixed?o.camerafixed:Ir,generate_audio:"boolean"!=typeof o.generateAudio||o.generateAudio}},Dr=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())},Br=async e=>{const{outputPath:t,videoUrl:o,lastFrameUrl:i,shouldSaveLastFrame:n}=e,r=jr(o,".mp4"),a=Er(),c=Sr({outputPath:t,type:"video",index:0,ext:r,timestamp:a}),l=await Dr(o),p=[await vr(c,l)];if(n&&"string"==typeof i&&i.length>0){const e=(e=>{const{outputPath:t,ext:o,timestamp:i}=e,n=`last_frame_${i}_0${o}`;return s.join(t,n)})({outputPath:t,ext:jr(i,".png"),timestamp:a}),o=await Dr(i),n=await vr(e,o);p.push(n)}return p};var qr,Mr,Nr,Gr,Fr,$r,Vr,Wr,Hr,Kr,Jr,Zr,Qr,Yr,Xr,ea,ta,oa,ia;function na(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...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"}(qr||(qr={})),function(e){e[e.ASC=1]="ASC";e[e.DESC=2]="DESC"}(Mr||(Mr={})),function(e){e[e.None=0]="None";e[e.APIKey=1]="APIKey";e[e.Oauth3LO=2]="Oauth3LO";e[e.Oauth2LO=3]="Oauth2LO"}(Nr||(Nr={})),function(e){e[e.Free=1]="Free";e[e.Trial=2]="Trial";e[e.Paid=3]="Paid"}(Gr||(Gr={})),function(e){e[e.Inactive=1]="Inactive";e[e.Active=2]="Active"}(Fr||(Fr={})),function(e){e[e.CNY=1]="CNY";e[e.ResourcePoint=2]="ResourcePoint"}($r||($r={})),function(e){e[e.Cancellable=0]="Cancellable";e[e.NoCancellable=1]="NoCancellable";e[e.AlwaysDefault=2]="AlwaysDefault"}(Vr||(Vr={})),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"}(Wr||(Wr={})),function(e){e[e.Internal=1]="Internal";e[e.External=2]="External";e[e.Infra=3]="Infra"}(Hr||(Hr={})),function(e){e[e.Text=1]="Text";e[e.Image=2]="Image";e[e.Video=3]="Video";e[e.Audio=4]="Audio"}(Kr||(Kr={})),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"}(Jr||(Jr={})),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"}(Zr||(Zr={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online";e[e.GradualRollout=2]="GradualRollout";e[e.ReadyToOffline=3]="ReadyToOffline"}(Qr||(Qr={})),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"}(Yr||(Yr={})),function(e){e[e.Install=1]="Install";e[e.Uninstall=2]="Uninstall"}(Xr||(Xr={})),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"}(ea||(ea={})),function(e){e[e.Scene=1]="Scene";e[e.Type=2]="Type"}(ta||(ta={})),function(e){e[e.Official=1]="Official";e[e.Community=2]="Community"}(oa||(oa={})),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.CLIBilling=101]="CLIBilling"}(ia||(ia={}));class sa{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){sa.prototype.__init.call(this),sa.prototype.__init2.call(this),this.request=na([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=na([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"),n={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};return this.request({url:i,method:"POST",data:n},t)}SetIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/update"),n={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:n},t)}DeleteIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/delete"),n={integration_id:o.integration_id,space_id:o.space_id,project_id:o.project_id};return this.request({url:i,method:"POST",data:n},t)}AuthIntegrationStatus(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/auth/status"),n={integration_id:o.integration_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}ManageSpaceIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/space/manage"),n={space_ids:o.space_ids,integration_ids:o.integration_ids,op_type:o.op_type};return this.request({url:i,method:"POST",data:n},t)}SubmitVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks"),n={Body:o.Body},s={project_id:o.project_id};return this.request({url:i,method:"POST",data:n,params:s},t)}FlashASR(e,t){const o=e||{},i=this.genBaseURL("/api/v3/auc/bigmodel/recognize/flash"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}ListModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/list"),n={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:n},t)}ChatCompletions(e,t){const o=e||{},i=this.genBaseURL("/api/v3/chat/completions"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}CreateResponses(e,t){const o=e||{},i=this.genBaseURL("/api/v3/responses"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}GenerateImages(e,t){const o=e||{},i=this.genBaseURL("/api/v3/images/generations"),n={Body:o.Body},s={project_id:o.project_id};return this.request({url:i,method:"POST",data:n,params:s},t)}UnidirectionalTTS(e,t){const o=e||{},i=this.genBaseURL("/api/v3/tts/unidirectional"),n={Body:o.Body},s={project_id:o.project_id};return this.request({url:i,method:"POST",data:n,params:s},t)}GetIntegrationOauthConfig(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/auth/oauth_config"),n={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:n},t)}GetVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks/:id"),n={Body:o.Body},s={project_id:o.project_id};return this.request({url:i,method:"GET",data:n,params:s},t)}WebSearch(e,t){const o=e||{},i=this.genBaseURL("/api/search_api/web_search"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}WebSearch(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/search_api/web_search"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}CreateResponses(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/responses"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}GetVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks/:id"),n={Body:o.Body},s={project_id:o.project_id};return this.request({url:i,method:"GET",data:n,params:s},t)}FlashASR(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/auc/bigmodel/recognize/flash"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}SubmitVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks"),n={Body:o.Body},s={project_id:o.project_id};return this.request({url:i,method:"POST",data:n,params:s},t)}GenerateImages(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/images/generations"),n={Body:o.Body},s={project_id:o.project_id};return this.request({url:i,method:"POST",data:n,params:s},t)}UnidirectionalTTS(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/tts/unidirectional"),n={Body:o.Body},s={project_id:o.project_id};return this.request({url:i,method:"POST",data:n,params:s},t)}ChatCompletions(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/chat/completions"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}CancelIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/cancel"),n={integration_id:o.integration_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}Embeddings(e,t){const o=e||{},i=this.genBaseURL("/api/v3/embeddings/multimodal"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}Embeddings(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/embeddings/multimodal"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}VideoEditingUtils(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/video_editing_utils"),n={Body:o.Body},s={tool_name:o.tool_name};return this.request({url:i,method:"POST",data:n,params:s},t)}GetProjectDefaultSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/default"),n={project_type:o.project_type,space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}GetSkillByIDs(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/by_ids"),n={project_type:o.project_type,skill_ids:o.skill_ids,space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}GetSkillCategoryList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/category/list"),n={project_type:o.project_type};return this.request({url:i,method:"POST",data:n},t)}UploadSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload"),n={data:o.data},s={"Content-Type":o["Content-Type"]};return this.request({url:i,method:"POST",data:n,headers:s},t)}GetUserSkillList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/user/list"),n={page:o.page,size:o.size};return this.request({url:i,method:"POST",data:n},t)}DeleteSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/delete"),n={skill_id:o.skill_id};return this.request({url:i,method:"POST",data:n},t)}GetSkillList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/list"),n={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:n},t)}UploadSkillConfirm(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload/confirm"),n={preview_skill_key:o.preview_skill_key};return this.request({url:i,method:"POST",data:n},t)}FetchTool(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/fetch_tool"),n={url:o.url};return this.request({url:i,method:"POST",data:n},t)}GetModelSwitchStatus(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/status"),n={model_id:o.model_id,project_ids:o.project_ids,space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}StartSwitchModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/start"),n={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:n},t)}GetModelUsageList(e,t){const o=e||{},i=this.genBaseURL("/v1/model/usage/list"),n={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:n},t)}GetModelDetails(e,t){const o=e||{},i=this.genBaseURL("/v1/model/details"),n={model_id:o.model_id};return this.request({url:i,method:"POST",data:n},t)}GetModelUsageDetail(e,t){const o=e||{},i=this.genBaseURL("/v1/model/usage/details"),n={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:n},t)}RollbackSwitchModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/rollback"),n={space_id:o.space_id,project_ids:o.project_ids,current_model:o.current_model};return this.request({url:i,method:"POST",data:n},t)}TextEmbeddings(e,t){const o=e||{},i=this.genBaseURL("/api/v3/embeddings"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}TextEmbeddings(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/embeddings"),n={Body:o.Body};return this.request({url:i,method:"POST",data:n},t)}CheckModelReadyToOffline(e,t){const o=e||{},i=this.genBaseURL("/v1/model/ready_to_offline/check"),n={model_type:o.model_type};return this.request({url:i,method:"POST",data:n},t)}Audit(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/audit"),n={content:o.content};return this.request({url:i,method:"POST",data:n},t)}}sa.prototype.UploadSkill=function(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload"),n=o.body;return this.request({url:i,method:"POST",data:n},t)},sa.prototype.GenerateImages=function(e,t){const o=e||{},i=this.genBaseURL("/api/v3/images/generations"),n=o.Body;return this.request({url:i,method:"POST",data:n},t)},sa.prototype.SubmitVideoGenerationsTasks=function(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks"),n=o;return this.request({url:i,method:"POST",data:n},t)},sa.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 ra=new sa({});function aa(e,t){return null!=e?e:t()}const ca=async e=>await new Promise(t=>setTimeout(t,e)),la=async e=>{const{taskId:t,baseURL:o,accessToken:i,projectId:n}=e,s=await ra.GetVideoGenerationsTasks({id:t},{baseURL:o,headers:{Authorization:`Bearer ${i}`},params:{project_id:n}});return Pr(s)};function pa(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const da=e=>`coze generate video status ${e}`,ua=e=>{const{ctx:t,response:o}=e;"json"!==pa([t,"optionalAccess",e=>e.format])?yr((e=>{const t=[e.status],o=pa([e,"access",e=>e.content,"optionalAccess",e=>e.video_url]),i=pa([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)):br(o)},_a=t=>{const o=t.getContext(),{outputPath:i}=t.optsWithGlobals(),n=(s=pa([o,"optionalAccess",e=>e.config,"optionalAccess",e=>e.integrationApiBaseUrl]),r=()=>Y.integrationApiBaseUrl,null!=s?s:r());var s,r;const a=pa([o,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]);if(!a)throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login --oauth` or `coze auth login --token <token>` first");return{accessToken:a,ctx:o,integrationApiBaseUrl:n,outputPath:i}},ma=async(t,o,i)=>{const{accessToken:n,ctx:s,integrationApiBaseUrl:r,outputPath:a}=_a(i);let c=null;o.stdin&&(c=await fr());const{content:l}=(t=>{const{prompt:o,stdinPrompt:i,options:n}=t,s=Or(Ar(o),()=>Ar(i)),r=Ar(n.firstFrame),a=Ar(n.lastFrame),c=Boolean(r)||Boolean(a);if(!s&&!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 s&&l.push({type:"text",text:s}),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}),p=xr({content:l,options:o,ctx:s}),d=s.format,u=pa([s,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!u)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const{createResp:_,taskId:m}=await(async t=>{const{requestBody:o,baseURL:i,accessToken:n,projectId:s}=t,r=await ra.SubmitVideoGenerationsTasks(o,{baseURL:i,headers:{Authorization:`Bearer ${n}`},params:{project_id:s}}),a=Pr(r),c=function(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...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:p,baseURL:r,accessToken:n,projectId:u});if(!o.wait)return"json"===d?void br({query_command:da(m),response:_,task_id:m}):void yr((e=>["Video generation task created successfully.",`taskId: ${e}`,`Use \`${da(e)}\` to query status.`].join("\n"))(m));const g=await(async t=>{const{taskId:o,baseURL:i,accessToken:n,pollIntervalMs:s,pollTimeoutMs:r,projectId:a}=t,c=Date.now();for(;;){const t=await la({taskId:o,baseURL:i,accessToken:n,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}): ${aa(t.error_message,()=>"unknown")}`,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 ca(s)}})({taskId:m,baseURL:r,accessToken:n,pollIntervalMs:2e3,pollTimeoutMs:3e5,projectId:u}),h=pa([g,"access",e=>e.content,"optionalAccess",e=>e.video_url]),f=pa([g,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);if(!h||"string"!=typeof h)throw new e.CozeError(e.ErrorCode.E5002,"Video generated successfully but video_url was not returned");if(a){const e=await Br({outputPath:a,videoUrl:h,lastFrameUrl:f,shouldSaveLastFrame:!0===o.returnLastFrame});return"json"===d?void br({task_id:m,request:p,response:g,saved_paths:e}):void yr(e.join("\n"))}if("json"===d)return void br({task_id:m,request:p,response:g});const y=[h];!0===o.returnLastFrame&&"string"==typeof f&&f.length>0&&y.push(f),yr(y.join("\n"))},ga=(e,t)=>{const o=t.getContext();K(e,o)},ha=t=>{var o;o=t.command("create [prompt]").description("Create a video generation task").config({help:{brief:"Create video generation task",description:"Create a video generation task from text prompts or images. By default the command returns taskId immediately; use `--wait` to poll until completion.",examples:[{desc:"Create video from text",cmd:'coze generate video create "A dancing kitten"'},{desc:"Create task and wait for completion",cmd:'coze generate video create "A dancing kitten" --wait'},{desc:"Save result to file",cmd:'coze generate video create "A dancing kitten" --wait --output-path ./video.mp4'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --first-frame/--last-frame) with -h."},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid access token",fix:"Run `coze auth login --oauth` or set COZE_API_TOKEN/related credentials first"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server returned an error or response parsing failed",fix:"Please retry later. Use --debug for more details"},{code:e.ErrorCode.E5003,name:"TIMEOUT",desc:"Video generation request timed out",fix:"Please retry later or use `coze generate video status <taskId>` to query task status"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text prompt (can also be passed via stdin)"}},output:{type:"object",properties:{query_command:{type:"string"},task_id:{type:"string"},request:{type:"object"},response:{type:"object"},saved_paths:{type:"array",items:{type:"string"}}}}}}}).action(async(e,t,o)=>{try{await ma(e,t,o)}catch(e){ga(e,o)}}),o.option("--callback-url <url>","Callback URL for task status changes").option("--return-last-frame","Return last frame URL (default: disabled)",Rr).option("--resolution <res>","Resolution: 480p|720p|1080p",kr).option("--ratio <ratio>",`Aspect ratio (default: ${Tr})`,Tr).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)",Ir).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")},fa=t=>{t.command("status <taskId>").description("Query video generation task status by task ID").option("--output <format>","Output format: text|json").config({help:{brief:"Query video task status",description:"Query the latest status of a video generation task by task ID. This command does not create a new task.",examples:[{desc:"Query task status",cmd:"coze generate video status task_123"},{desc:"Output full response as JSON",cmd:"coze generate video status task_123 --output json"}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid task ID or request parameters",fix:"Please confirm <taskId> is correct and try again",example:"coze generate video status task_123"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server returned an error or response parsing failed",fix:"Please retry later. Use --debug for more details"},{code:e.ErrorCode.E5003,name:"TIMEOUT",desc:"Request timed out",fix:"Please retry later"}],schema:{input:{taskId:{type:"string",required:!0,description:"Video generation task ID"}},output:{type:"object",properties:{id:{type:"string"},status:{type:"string"},model:{type:"string"},content:{type:"object"},error_message:{type:"string"}}}}}}).action(async(t,o,i)=>{try{await(async(t,o,i)=>{const{accessToken:n,ctx:s,integrationApiBaseUrl:r}=_a(i),a=pa([s,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!a)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const c=await la({taskId:t,baseURL:r,accessToken:n,projectId:a});ua({ctx:s,response:c})})(t,0,i)}catch(e){ga(e,i)}})};function ya(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const ba="2K",va="url",Ca="standard",Aa="disabled",Pa=3686400,ja=16777216,Ea=e=>"object"==typeof e&&null!==e,Sa=e=>{if("string"==typeof e){const t=e.trim();return t.length?t:Ca}return Ca},wa=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},ka=t=>{t.command("image [prompt]").description("Generate images from text prompts").config({help:{brief:"Generate images from text",description:"Generate images based on text prompts. Supports setting size, watermark, and multiple images.",examples:[{desc:"Generate image",cmd:'coze generate image "A futuristic city"'},{desc:"Save to file",cmd:'coze generate image "A cat" --output-path ./cat.png'},{desc:"Specify size",cmd:'coze generate image "A dog" --size 1024x1024'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --size/--max-images) with -h."},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Please configure billing project ID and retry"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"API response parsing failed or server returned an error",fix:"Please retry later. Use --debug for more details"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text prompt (can also be passed via stdin)"}},output:{type:"object",properties:{model:{type:"string"},created:{type:"number"},image_0:{type:"object"},saved_paths:{type:"array",items:{type:"string"}}}}}}}).option("--size <size>","Image size: 2K|4K or WIDTHxHEIGHT (local validation)",ba).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",va).option("--optimize-prompt-mode <mode>",`Prompt optimization mode (default: ${Ca})`,Ca).option("--sequential <mode>","Group image generation mode: auto|disabled",Aa).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:s}=i.optsWithGlobals(),r=await wr(t,{stdin:o.stdin}),a=ya([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!a)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const c=((e,t)=>{if(null==e)return{value:ba};if("string"!=typeof e)return ya([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --size '${String(e)}', falling back to '${ba}'`)]),{value:ba};const o=e.trim();if("2K"===o||"4K"===o)return{value:o};const i=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(o);if(!i)return{value:ba,warning:`Invalid --size '${o}', falling back to '${ba}'. Expected 2K/4K or WIDTHxHEIGHT`};const n=Number(i[1]),s=Number(i[2]),r=n*s,a=n/s;return Number.isFinite(n)&&Number.isFinite(s)&&n>0&&s>0&&r>=Pa&&r<=ja&&a>=.0625&&a<=16?{value:`${n}x${s}`}:{value:ba,warning:`Invalid --size '${o}', falling back to '${ba}'. Total pixels must be in [3686400, 16777216], aspect ratio must be in [1:16, 16:1].`}})(o.size,n),l="url"===(p=o.responseFormat)||"b64_json"===p?{value:p}:void 0!==p?{value:va,warning:`Invalid --response-format '${String(p)}', falling back to '${va}'`}:{value:va};var p;const d=(e=>"auto"===e||"disabled"===e?{value:e}:void 0!==e?{value:Aa,warning:`Invalid --sequential '${String(e)}', falling back to '${Aa}'`}:{value:Aa})(o.sequential),u=(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);c.warning&&ya([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(c.warning)]),l.warning&&ya([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(l.warning)]),d.warning&&ya([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(d.warning)]),u.warning&&ya([n,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(u.warning)]);const _={model:"doubao-seedream-4-5-251128",prompt:r,size:c.value,watermark:"boolean"!=typeof o.watermark||o.watermark,image:wa(o.image),response_format:l.value,optimize_prompt_options:{mode:Sa(o.optimizePromptMode)},sequential_image_generation:d.value,sequential_image_generation_options:{max_images:u.value}},m=(t=>{const o=Ea(t)&&"data"in t?t.data:t;if(Ea(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 ra.GenerateImages({Body:_},{baseURL:Y.integrationApiBaseUrl,params:{project_id:a}}));if(m.error)throw new e.CozeError(e.ErrorCode.E5002,"Image generation failed (top-level error)",m.error);const g=(f=()=>va,null!=(h=_.response_format)?h:f());var h,f;const y=m.data.filter(e=>!e.error&&("url"===g?"string"==typeof e.url&&e.url.length>0:"string"==typeof e.b64_json&&e.b64_json.length>0));if(0===y.length)throw new e.CozeError(e.ErrorCode.E5002,"Image generation succeeded but no valid image data was returned",m);if(s){const t=[],o=Er();for(const[i,n]of y.entries()){const r="url"===g&&n.url?jr(n.url,".png"):".png",a=Sr({outputPath:s,type:"image",index:i,ext:r,timestamp:o});let c;if("url"===g){const t=await e.customFetch.fetch(n.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(n.b64_json,"base64");const l=await vr(a,c);t.push(l)}const{model:i,usage:r,HttpHeader:a,...c}=(e=>{const{data:t,...o}=e,i=Object.fromEntries(t.map((e,t)=>[`image_${t}`,e]));return{...o,...i}})(m);return void ya([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...c,saved_paths:t})])}ya([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(m.data)])})};function Ta(e,t){return null!=e?e:t()}function Ia(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const Ra="cli_user",Oa="zh_female_xiaohe_uranus_bigtts",za="mp3",La=24e3,Ua=(e,t)=>"pcm"===e||"mp3"===e||"ogg_opus"===e?e:(void 0!==e&&Ia([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --audio-format '${String(e)}', falling back to '${za}'`)]),za),xa=(e,t,o,i)=>{if(null==e)return t;const n=Number(e);return Number.isFinite(n)?Math.floor(n):(Ia([i,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",i=>i(`Invalid --${o} '${String(e)}', falling back to ${t}`)]),t)},Da=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 n=i[0];if("{"!==n&&"["!==n)return null;const s=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===s?null:Cr(s)&&"number"==typeof s.code?s:null},Ba=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.",examples:[{desc:"Generate image",cmd:'coze generate image "A cat"'},{desc:"Generate audio",cmd:'coze generate audio "Hello world"'},{desc:"Generate video",cmd:'coze generate video create "A dancing dog"'}],seeAlso:["coze auth"]}}).option("--output-path <path>","Directory path to save the generated media files");ka(o),(t=>{t.command("audio [prompt]").description("Synthesize speech from text or SSML (streaming)").config({help:{brief:"Generate audio from text",description:"Synthesize speech from text or SSML. Supports streaming output and configurable audio encodings.",examples:[{desc:"Basic text to speech",cmd:'coze generate audio "Hello world"'},{desc:"Save to file",cmd:'coze generate audio "Hello" --output-path ./audio.mp3'},{desc:"Use SSML",cmd:'echo "<speak>Hello</speak>" | coze generate audio --ssml'},{desc:"Specify audio encoding",cmd:'coze generate audio "Hello" --audio-format ogg_opus'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --speaker/--audio-format) with -h."},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Configure billing project ID and retry",example:'coze generate audio "Hello"'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid access token",fix:"Run `coze auth login --oauth` or `coze auth login --token <token>` first"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"API response parsing failed or server returned an error",fix:"Please retry later. Use --debug for more details"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text or SSML prompt (can also be passed via stdin)"}},output:{type:"object",properties:{request:{type:"object"},url:{type:"string",description:"Audio download URL"},saved_path:{type:"string",description:"Local path if saved"}}}}}}).option("--output <format>","Output format: text|json").option("--uid <uid>",`User UID (default: ${Ra})`,Ra).option("--speaker <speaker>",`Speaker (default: ${Oa})`,Oa).option("--audio-format <format>","Audio encoding: pcm|mp3|ogg_opus",za).option("--sample-rate <n>","Sample rate (default: 24000)",String(La)).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 n=i.getContext();try{const{outputPath:s}=i.optsWithGlobals(),r=Ia([n,"optionalAccess",e=>e.config,"access",e=>e.integrationApiBaseUrl]);if(!Ia([n,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]))throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login --oauth` or `coze auth login --token <token>` first");const a=await wr(t,{stdin:o.stdin}),c=Ia([n,"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:Ta(Ar(o.uid),()=>Ra)},req_params:{speaker:Ta(Ar(o.speaker),()=>Oa),audio_params:{format:Ua(o.audioFormat,n),sample_rate:xa(o.sampleRate,La,"sample-rate",n),speech_rate:xa(o.speechRate,0,"speech-rate",n),loudness_rate:xa(o.loudnessRate,0,"loudness-rate",n)}}};o.ssml?l.req_params={...l.req_params,ssml:a}:l.req_params={...l.req_params,text:a};const p=new URL("/api/v3/tts/unidirectional",r);p.searchParams.append("project_id",c);const d=await e.customFetch.fetch(p.toString(),{method:"POST",body:JSON.stringify(l)});if(!d.ok)throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis request failed: ${d.status} ${d.statusText}`,{status:d.status,statusText:d.statusText});if(!d.body)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis response is empty (no streaming body returned)");const u=new TextDecoder("utf-8"),_=d.body.getReader(),m=[];let g;const h=t=>{if(0===t.code)return s&&"string"==typeof t.data&&m.push(Buffer.from(t.data,"base64")),!1;if(2e7===t.code)return"string"==typeof t.url&&t.url.length>0&&(g=t.url),!0;throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis failed (code=${t.code}): ${Ta(t.message,()=>"unknown")}`,t)};let f="";for(;;){const{done:e,value:t}=await _.read();if(e)break;f+=u.decode(t,{stream:!0});const o=f.split(/\r?\n/);f=Ta(o.pop(),()=>"");for(const e of o){const t=Da(e);if(t&&h(t)){await _.cancel();break}}if(g)break}if(!g){f+=u.decode();const e=f.split(/\r?\n/);f="";for(const t of e){const e=Da(t);if(e&&h(e))break}}if(s){const t=Ta(Ia([l,"access",e=>e.req_params,"optionalAccess",e=>e.audio_params,"optionalAccess",e=>e.format]),()=>za),o="pcm"===t?".pcm":"ogg_opus"===t?".ogg":".mp3",i=Er(),r=Sr({outputPath:s,type:"audio",index:0,ext:o,timestamp:i});let a=null;if(m.length>0)a=await vr(r,Buffer.concat(m));else if(g){const t=await e.customFetch.fetch(g);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 n=Buffer.from(await t.arrayBuffer()),r=jr(g,o),c=Sr({outputPath:s,type:"audio",index:0,ext:r,timestamp:i});a=await vr(c,n)}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:g});return"json"===Ia([n,"optionalAccess",e=>e.format])?void br({request:l,url:g,saved_path:a}):void yr(a)}if("json"===Ia([n,"optionalAccess",e=>e.format]))return void br({request:l,url:g});if(g)return void yr(g);yr("Speech synthesis completed, but no audio download URL was returned; you can use --output json to view details.")}catch(e){K(e,n)}})})(o),(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);ha(t),fa(t)})(o)};function qa(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const Ma=t=>{(t=>{t.command("upload <path>").description("Upload a local file").config({help:{brief:"Upload a local file",description:"Upload a local file to Coze. The file can be used as an attachment or context in projects.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf",tags:["[RECOMMENDED]"]}],errors:[{code:e.ErrorCode.E3000,name:"RESOURCE_NOT_FOUND",desc:"Local file not found or not readable",fix:"Please confirm the file path exists and you have read permission"}],schema:{input:{path:{type:"string",required:!0,description:"Local file path to upload"}},output:{type:"string",description:"Uploaded file URL"}}}}).action(async(t,o,i)=>{let n;try{n=i.getContext();try{await m.access(t)}catch(o){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${t}`,{filePath:t})}const o=_.basename(t),s=_.extname(t),r=s?o.slice(0,-s.length):o,a=s.slice(1),c=new h;c.append("file_name",r),c.append("file_extension",a),c.append("file_content",g.createReadStream(t)),c.append("biz_type","cli_attachment");const l=await e.IdeApi.UploadFile({data:c},{headers:{...c.getHeaders()}});"json"===qa([n,"optionalAccess",e=>e.format])?qa([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(l.data)]):qa([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(qa([l,"access",e=>e.data,"optionalAccess",e=>e.file_url]))])}catch(e){K(e,n)}})})(t.command("file").description("General file operations").config({help:{brief:"File upload and management",description:"Manage file operations for Coze projects. Currently supports uploading local files to Coze for use as attachments or context.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf"}],seeAlso:["coze code message send"]}}))};function Na(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function Ga(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function Fa(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function $a(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const Va=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 file (`~/.cozerc.json`).",examples:[{desc:"List all configurations",cmd:"coze config list"},{desc:"Set configuration value",cmd:"coze config set base_url https://api.coze.cn"}]}});(e=>{e.command("get <keys...>").description("Get configuration values and their sources").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Get configuration values",description:"Read and output the value of the specified configuration keys from `~/.cozerc.json`. If a key does not exist, prompts that it was not found.",examples:[{desc:"Get BaseURL configuration",cmd:"coze config get baseUrl"},{desc:"Get default Space ID",cmd:"coze config get spaceId"},{desc:"Get multiple configurations",cmd:"coze config get baseUrl spaceId"}],schema:{input:{keys:{type:"array",required:!0,description:"Configuration key names"}},output:{value:{type:"any",description:"Configuration value"}}}}}).action(async(e,t,o)=>{const i=o.getContext(),n=await ne();for(const t of e){const e=n.find(e=>e.key===t);Na(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 local configuration key-value pair. The configuration will be persistently saved in `~/.cozerc.json`.",examples:[{desc:"Modify default workspace",cmd:"coze config set spaceId 123456789"},{desc:"Modify BaseURL",cmd:"coze config set baseUrl https://api.coze.cn"}],errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to set configuration value",fix:"Please check the key/value and retry. Use --debug for more details."}],schema:{input:{key:{type:"string",required:!0,description:"Configuration key name"},value:{type:"string",required:!0,description:"New configuration value"}}}}}).action(async(t,o,i,n)=>{const s=n.getContext();try{const e={};e[t]=o;const i="global";await oe(e,i);const n={key:t,value:o,scope:i,status:"updated",message:`Configuration '${t}' updated successfully in ${i} scope.`};if(Ga([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(n.message)]),"json"===Ga([s,"optionalAccess",e=>e.format]))return void Ga([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)])}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 values from the local configuration file `~/.cozerc.json`.",examples:[{desc:"Delete a specific configuration key",cmd:"coze config delete spaceId"},{desc:"Delete multiple configuration keys",cmd:"coze config delete spaceId baseUrl"}],errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to delete configuration value",fix:"Please check the configuration key and retry. Use --debug for more details."}],schema:{input:{keys:{type:"array",required:!0,description:"Configuration key names"}}}}}).action(async(t,o,i)=>{const n=i.getContext();for(const o of t)try{await ie(o);const e={key:o,status:"deleted",message:`Configuration '${o}' has been removed.`};Fa([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleted ${o} from configuration file successfully.`)]),"json"===Fa([n,"optionalAccess",e=>e.format])&&Fa([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)])}catch(t){throw new e.CozeError(e.ErrorCode.E5000,`Failed to delete config '${o}': ${t.message}`,t.stack)}})})(o),(e=>{e.command("list").description("List all configuration values and their sources").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"List all local configuration values",description:"Print all configuration content stored in `~/.cozerc.json` in JSON format.",examples:[{desc:"List configurations",cmd:"coze config list"}],schema:{output:{type:"object",additionalProperties:!0,description:"Configuration key-value pairs"}}}}).action(async(e,t)=>{const o=t.getContext(),i=(await ne()).map(({key:e,value:t,source:o})=>({key:e,value:t,source:o}));$a([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Configurations found:")]),$a([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(i)])})})(o)},Wa="__COZE_FILE_COMP__";function Ha(){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 Ka(e){const t=n.homedir();switch(e){case"bash":return s.join(t,"darwin"===process.platform?".bash_profile":".bashrc");case"zsh":return s.join(t,".zshrc");case"fish":return s.join(t,".config/fish/config.fish");case"powershell":return function(){const e=["pwsh","powershell"];for(const t of e)try{const e=o.execSync(`${t} -NoProfile -NoLogo -Command "echo $PROFILE"`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim();if(e)return e}catch(e){continue}return}();default:return}}function Ja(){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]}" == "${Wa}" ]]; 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" == "${Wa}" ]]; 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(n.EOL)}function Za(e){switch(e){case"bash":return`\n# begin coze completion\nsource ${s.join(n.homedir(),".coze","completion.sh")}\n# end coze completion\n`;case"zsh":return"\n# begin coze completion\n. <(coze --completion)\n# end coze completion\n";case"fish":return"\n# begin coze completion\ncoze --completion-fish | source\n# end coze completion\n";case"powershell":return`\n# begin coze completion\nRegister-ArgumentCompleter -Native -CommandName coze -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n $tokens = $commandAst.ToString().Split(" ", [StringSplitOptions]::RemoveEmptyEntries)\n $allArgs = @("--comppwsh")\n if ($tokens.Count -gt 1) {\n $allArgs += $tokens[1..($tokens.Count - 1)]\n }\n $result = & coze $allArgs 2>$null\n if ($result -and $result[0] -ne '${Wa}') {\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 Qa(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}let Ya,Xa,ec=!1,tc=!1;function oc(e){const t=e._args||[];if(0===t.length)return!1;const o=/path|file|dir|folder/i;return t.some(e=>o.test(e._name))}function ic(e){Xa=e,function(){const e=process.argv.indexOf("--completion");e>-1&&(ec=!0,process.argv.splice(e,1));const t=process.argv.indexOf("--completion-fish");t>-1&&(tc=!0,process.argv.splice(t,1))}(),Ya=f("coze"),Ya.on("complete",(t,o)=>{const i=o.line.trimStart().split(/\s+/);i.length>0&&(i[0].endsWith("coze")||i[0].endsWith("bin/main"))&&i.shift();let n="";o.line.endsWith(" ")?(n="",""===i[i.length-1]&&i.pop()):n=i.pop()||"";const s=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 oc(i)?[Wa]:[]}const n=[];i.commands.length>0&&i.commands.forEach(e=>{n.push(e.name())}),i.options.forEach(e=>{e.flags.split(/[ ,|]+/).forEach(e=>{e.startsWith("<")||e.startsWith("[")||n.push(e)})}),i!==e&&e.options.forEach(e=>{e.flags.split(/[ ,|]+/).forEach(e=>{e.startsWith("<")||e.startsWith("[")||n.push(e)})});const s=Array.from(new Set(n)).filter(e=>e.startsWith(o));return 0===s.length&&oc(i)?[Wa]:s}(e,i,n);o.reply(s)}),e.command("completion").description("Setup shell auto-completion").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Configure terminal auto-completion",description:"Install or remove the auto-completion script for the current terminal environment (supports bash/zsh/fish/powershell).",examples:[{desc:"Install completion script",cmd:"coze completion --setup"},{desc:"Remove completion script",cmd:"coze completion --cleanup"}]}}).option("--setup","Install shell completion into your startup script (.zshrc / .bashrc / $PROFILE)").option("--cleanup","Remove shell completion from your startup script").action(async e=>{if(e.cleanup)!function(){const e=Ha();if(!e)return;const t=Ka(e);if(!t||!u.existsSync(t))return;const o=Za(e);if(o){const e=u.readFileSync(t,"utf8").replace(new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"");u.writeFileSync(t,e)}if("bash"===e){const e=s.join(n.homedir(),".coze"),t=s.join(e,"completion.sh");u.existsSync(t)&&u.unlinkSync(t),u.existsSync(e)&&0===u.readdirSync(e).length&&u.rmdirSync(e)}}(),await oe({completionInstalled:!1}),console.log("Shell completion removed! Please restart your terminal.");else{const e=Ha();if(!e)return console.error("Could not detect your shell type. Supported shells: bash, zsh, fish, powershell."),void(process.exitCode=1);const t=function(){const e=Ha();if(!e)return!1;const t=Ka(e);if(!t)return!1;if("bash"===e){const e=s.join(n.homedir(),".coze"),t=s.join(e,"completion.sh");u.existsSync(e)||u.mkdirSync(e,{recursive:!0}),u.writeFileSync(t,Ja())}const o=s.dirname(t);u.existsSync(o)||u.mkdirSync(o,{recursive:!0});const i=Za(e);return!!i&&(u.appendFileSync(t,i),!0)}();t?(await oe({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 nc(){return ec?(console.log(Ja()),void process.exit()):tc?(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]" = "${Wa}"`," return"," end"," for c in $completions"," echo $c"," end","end","complete -c coze -a '(_coze_completion)' -n '_coze_completion'","### coze completion - end ###"].join(n.EOL)),void process.exit()):void(process.argv.includes("--comppwsh")?function(){if(!Xa)return void process.exit();const e=process.argv.indexOf("--comppwsh"),t=process.argv.slice(e+1);let o=Xa;const i=[];for(const e of t){const t=Qa([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 n=[];Qa([o,"access",e=>e.commands,"optionalAccess",e=>e.forEach,"call",e=>e(e=>{n.push(e.name())})]),Qa([o,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e(e=>{e.flags.split(/[ ,|]+/).forEach(e=>{e.startsWith("<")||e.startsWith("[")||n.push(e)})})]),o!==Xa&&Qa([Xa,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e(e=>{e.flags.split(/[ ,|]+/).forEach(e=>{e.startsWith("<")||e.startsWith("[")||n.push(e)})})]);const s=i[i.length-1]||"",r=Array.from(new Set(n)).filter(e=>e.startsWith(s));0===r.length&&oc(o)?console.log(Wa):r.length>0&&console.log(r.join("\n")),process.exit()}():Ya&&Ya.init())}function sc(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function rc(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function ac(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const cc=t=>{const o=t.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(t){t.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.E1000,name:"INVALID_ARGUMENT",desc:"Invalid or missing project ID",fix:"Provide a valid project ID with -p <projectId>"}]}}).action(async function(t,o){const i=o.getContext(),{projectId:n}=t,s=await e.IdeApi.GetVibeProject({project_id:n}),r=sc([s,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),a=sc([s,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.agent_tools]),c=sc([await e.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e(e=>e.project_type===r),"optionalAccess",e=>e.tools]);if(!c||0===c.length)return sc([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("No tools available for this project type.")]),void sc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e([])]);const l=c.map(e=>({tool_name:e.name,description:e.description||e.display_name,enabled:sc([a,"optionalAccess",t=>t[e.name]])}));sc([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${l.length} tools.`)]),sc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(l)])})}(o),function(t){t.command("enable <toolName>").description("Enable a project tool").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Enable a project tool",description:"Enable a specified tool in the project 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"}]}}).action(async function(t,o,i){const n=i.getContext(),{projectId:s}=o,r=await e.IdeApi.GetVibeProject({project_id:s}),a=rc([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=rc([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.agent_tools])||{},l=rc([await e.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e(e=>e.project_type===a),"optionalAccess",e=>e.tools]);if(!rc([l,"optionalAccess",e=>e.find,"call",e=>e(e=>e.name===t)]))throw new e.CozeError(e.ErrorCode.E1000,`Tool '${t}' is not available for this project type`,{toolName:t,projectId:s});await e.IdeApi.UpdateVibeProject({project_id:s,project_settings:{agent_tools:{...c,[t]:!0}}}),rc([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Tool '${t}' enabled.`)]),rc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,enable_tool_name:t,message:`Tool '${t}' has been enabled successfully`})])})}(o),function(t){t.command("disable <toolName>").description("Disable a project tool").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Disable a project tool",description:"Disable a specified tool in the project 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"}]}}).action(async function(t,o,i){const n=i.getContext(),{projectId:s}=o,r=await e.IdeApi.GetVibeProject({project_id:s}),a=ac([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=ac([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.agent_tools])||{},l=ac([await e.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e(e=>e.project_type===a),"optionalAccess",e=>e.tools]);if(!ac([l,"optionalAccess",e=>e.find,"call",e=>e(e=>e.name===t)]))throw new e.CozeError(e.ErrorCode.E1000,`Tool '${t}' is not available for this project type`,{toolName:t,projectId:s});await e.IdeApi.UpdateVibeProject({project_id:s,project_settings:{agent_tools:{...c,[t]:!1}}}),ac([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Tool '${t}' disabled.`)]),ac([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,disable_tool_name:t,message:`Tool '${t}' has been disabled successfully`})])})}(o)};function lc(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function pc(t){t.command("remove <skillId>").description("Remove skills from the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Remove skill from project",description:"Remove a configured skill from the specified project.",examples:[{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID to remove"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},removed_skill_ids:{type:"array",items:{type:"string"},description:"Removed skill IDs"},message:{type:"string",description:"Result message"}}}}},errors:[{code:e.ErrorCode.E3004,name:"SKILL_NOT_INSTALLED",desc:"The specified skill is not installed in the project",fix:"Please use `skill list` to confirm installed skills"}]}}).action(async function(t,o,i){const n=i.getContext(),{projectId:s}=o,r=new Set([t]),a=lc([(await e.IdeApi.GetVibeProject({project_id:s})).data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]);var c;const l=(c=lc([a,"optionalAccess",e=>e.skills]),Array.isArray(c)?c.map(e=>{return{skill_id:String((t=lc([e,"optionalAccess",e=>e.skill_id]),o=()=>"",null!=t?t:o())),is_preload:lc([e,"optionalAccess",e=>e.is_preload])};var t,o}).filter(e=>Boolean(e.skill_id)):[]).filter(e=>!r.has(e.skill_id)),p={filter_types:lc([a,"optionalAccess",e=>e.filter_types]),skills:l};await e.IdeApi.UpdateVibeProject({project_id:s,project_settings:{skill_setting:p}}),lc([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill removed.")]),lc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,removed_skill_ids:Array.from(r),message:"removed Skills successfully."})])})}function dc(e,t){return null!=e?e:t()}function uc(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function _c(t){t.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:"array",items:{type:"object",properties:{description:{type:"string",description:"Skill description"},skill_id:{type:"string",description:"Skill ID"},name:{type:"string",description:"Skill name"},icon:{type:"string",description:"Skill icon URL"},is_installed:{type:"boolean",description:"Whether the skill is installed"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}]}}).action(async function(t,o){const i=o.getContext(),{projectId:n}=t;if(t.my){const e=t.page?parseInt(t.page,10):1,o=t.size?parseInt(t.size,10):20,n=await ra.GetUserSkillList({page:e,size:o});return uc([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${uc([n,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} personal skills.`)]),void uc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(uc([n,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e(e=>({skill_id:uc([e,"optionalAccess",e=>e.skill_id]),name:uc([e,"optionalAccess",e=>e.name]),description:uc([e,"optionalAccess",e=>e.description]),icon:uc([e,"optionalAccess",e=>e.icon]),is_installed:!1}))]))])}const s=dc(dc(t.spaceId,()=>uc([i,"optionalAccess",e=>e.config,"access",e=>e.spaceId])),()=>"");if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing spaceId: pass --space-id <spaceId> or set config.spaceId");const r=await e.IdeApi.GetVibeProject({project_id:n}),a=function(e){const t=[],o=uc([e,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_settings]);uc([o,"optionalAccess",e=>e.skill_setting,"optionalAccess",e=>e.skills])&&t.push(...o.skill_setting.skills);const i=t.map(e=>uc([e,"optionalAccess",e=>e.skill_id])).filter(Boolean);return new Set(i)}(r.data||{}),c=uc([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),l=await ra.GetSkillList({project_type:c,space_id:s,category_type_list:[c]});uc([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${uc([l,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} skills.`)]),uc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(uc([l,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e(e=>({description:uc([e,"optionalAccess",e=>e.description]),skill_id:uc([e,"optionalAccess",e=>e.skill_id]),name:uc([e,"optionalAccess",e=>e.name]),icon:uc([e,"optionalAccess",e=>e.icon]),is_installed:a.has(e.skill_id||"")}))]))])})}function mc(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function gc(t){t.command("add <skillId>").description("Add skills to the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add skill to project",description:"Add a specified skill to the project. Skills can extend project capabilities, such as adding search, code execution, etc.",examples:[{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},added_skill_ids:{type:"array",items:{type:"string"},description:"Added skill IDs"},message:{type:"string",description:"Result message"}}}}},errors:[{code:e.ErrorCode.E3002,name:"SKILL_NOT_FOUND",desc:"The specified skill does not exist",fix:"Please use `skill list` to confirm available skills"}]}}).action(async function(t,o,i){const n=i.getContext(),{projectId:s}=o,r=[t],a=(await e.IdeApi.GetVibeProject({project_id:s})).data||{},c=mc([a,"access",e=>e.project_info,"optionalAccess",e=>e.project_type]),l=mc([a,"access",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]),p=function(e){const t=new Map;for(const o of e){const e=mc([o,"optionalAccess",e=>e.skill_id])?String(o.skill_id):"";e&&(t.has(e)||t.set(e,{skill_id:e,is_preload:o.is_preload}))}return Array.from(t.values())}([...Array.isArray(mc([l,"optionalAccess",e=>e.skills]))?l.skills:[],...r.map(e=>({skill_id:String(e),is_preload:!0}))]),d={filter_types:mc([l,"optionalAccess",e=>e.filter_types])&&l.filter_types.length>0?l.filter_types:[c],skills:p};await e.IdeApi.UpdateVibeProject({project_id:s,project_settings:{skill_setting:d}}),mc([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skills added successfully.")]),mc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,added_skill_ids:r,message:"added Skills successfully."})])})}function hc(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function fc(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const yc=t=>{const o=t.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");_c(o),gc(o),pc(o),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"},skill_id:{type:"string",description:"Uploaded skill 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"}]}}).action(async function(t,o,i){const n=i.getContext(),{projectId:s}=o,r=_.resolve(t);if(!g.existsSync(r))throw new e.CozeError(e.ErrorCode.E1000,`File not found: ${r}`,{filePath:r});const a=g.readFileSync(r),c=_.basename(r),l=_.extname(r).replace(".",""),p=new FormData;p.append("file_content",new Blob([a]),c),p.append("file_name",c),p.append("file_extension",l),p.append("biz_type","skill"),hc([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Uploading skill...")]);const d={body:p},u=await ra.UploadSkill(d);if(hc([u,"access",e=>e.data,"optionalAccess",e=>e.naming_conflict])){const e=hc([u,"access",e=>e.data,"optionalAccess",e=>e.conflict_info,"optionalAccess",e=>e.preview_skill_key]);hc([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Naming conflict detected, auto-confirming overwrite...")]),await ra.UploadSkillConfirm({preview_skill_key:e})}hc([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill uploaded successfully.")]),hc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,skill_id:hc([u,"access",e=>e.data,"optionalAccess",e=>e.conflict_info,"optionalAccess",e=>e.preview_skill_key])||"",message:"Skill uploaded successfully"})])})}(o),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"}]}}).action(async function(e,t,o){const i=o.getContext(),{projectId:n}=t;await ra.DeleteSkill({skill_id:e}),fc([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Skill '${e}' deleted.`)]),fc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({project_id:n,message:`Skill '${e}' has been permanently deleted`})])})}(o)};var bc,vc,Cc,Ac,Pc,jc,Ec,Sc,wc,kc,Tc,Ic,Rc,Oc,zc,Lc,Uc,xc,Dc,Bc,qc,Mc,Nc,Gc,Fc,$c,Vc,Wc,Hc,Kc,Jc,Zc,Qc,Yc,Xc,el,tl,ol,il,nl,sl,rl,al,cl,ll,pl,dl,ul,_l,ml,gl,hl,fl,yl,bl,vl,Cl,Al,Pl,jl,El,Sl,wl,kl,Tl,Il,Rl,Ol,zl,Ll,Ul,xl;function Dl(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}!function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(bc||(bc={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(vc||(vc={})),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"}(Cc||(Cc={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(Ac||(Ac={})),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"}(Pc||(Pc={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(jc||(jc={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(Ec||(Ec={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(Sc||(Sc={})),function(e){e[e.Official=1]="Official";e[e.Public=2]="Public";e[e.Custom=3]="Custom";e[e.Others=101]="Others"}(wc||(wc={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(kc||(kc={})),function(e){e[e.App=1]="App";e[e.Resource=2]="Resource"}(Tc||(Tc={})),function(e){e[e.CozeModel=1]="CozeModel";e[e.VolcAccount=2]="VolcAccount";e[e.SelfAccount=3]="SelfAccount";e[e.SelfModel=4]="SelfModel"}(Ic||(Ic={})),function(e){e[e.Asc=1]="Asc";e[e.Desc=2]="Desc"}(Rc||(Rc={})),function(e){e[e.NoDetail=1]="NoDetail";e[e.Detail=2]="Detail";e[e.Operate=3]="Operate"}(Oc||(Oc={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(zc||(zc={})),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"}(Lc||(Lc={})),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"}(Uc||(Uc={})),function(e){e[e.Mobile=1]="Mobile";e[e.Web=2]="Web"}(xc||(xc={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(Dc||(Dc={})),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"}(Bc||(Bc={})),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"}(qc||(qc={})),function(e){e[e.DEFAULT=0]="DEFAULT";e[e.Chux=1]="Chux"}(Mc||(Mc={})),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"}(Nc||(Nc={})),function(e){e[e.PromptDiff=1]="PromptDiff";e[e.ModelDiff=2]="ModelDiff"}(Gc||(Gc={})),function(e){e[e.DraftBot=1]="DraftBot"}(Fc||(Fc={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}($c||($c={})),function(e){e[e.Archive=1]="Archive";e[e.Rollback=2]="Rollback"}(Vc||(Vc={})),function(e){e[e.ProjectCopyCancel=1]="ProjectCopyCancel";e[e.ProjectCopyRetry=2]="ProjectCopyRetry"}(Wc||(Wc={})),function(e){e[e.ProjectCopy=1]="ProjectCopy";e[e.BotCopy=2]="BotCopy";e[e.VibeProjectCopy=3]="VibeProjectCopy"}(Hc||(Hc={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Kc||(Kc={})),function(e){e[e.Bot=1]="Bot";e[e.Workflow=2]="Workflow";e[e.Application=3]="Application"}(Jc||(Jc={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(Zc||(Zc={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(Qc||(Qc={})),function(e){e[e.BatchSize=1]="BatchSize";e[e.LearningRate=2]="LearningRate";e[e.Epochs=3]="Epochs"}(Yc||(Yc={})),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"}(Xc||(Xc={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(el||(el={})),function(e){e[e.Douyin=1]="Douyin"}(tl||(tl={})),function(e){e[e.Terminating=1]="Terminating";e[e.Terminated=2]="Terminated"}(ol||(ol={})),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"}(il||(il={})),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"}(nl||(nl={})),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"}(sl||(sl={})),function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInput=2]="TotalInput";e[e.TotalOutput=3]="TotalOutput"}(rl||(rl={})),function(e){e[e.stop=1]="stop";e[e.resume=2]="resume",e[e.delete=3]="delete"}(al||(al={})),function(e){e[e.Recommend=1]="Recommend"}(cl||(cl={})),function(e){e[e.Default=0]="Default";e[e.Terminate=1]="Terminate"}(ll||(ll={})),function(e){e[e.All=0]="All";e[e.WithBenefit=1]="WithBenefit"}(pl||(pl={})),function(e){e[e.upload=1]="upload";e[e.TrainingSetSplit=2]="TrainingSetSplit"}(dl||(dl={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(ul||(ul={})),function(e){e[e.Using=1]="Using";e[e.Deleted=2]="Deleted"}(_l||(_l={})),function(e){e[e.Publish=0]="Publish";e[e.Archive=1]="Archive"}(ml||(ml={})),function(e){e[e.User=0]="User";e[e.NL2App=1]="NL2App"}(gl||(gl={})),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"}(hl||(hl={})),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"}(fl||(fl={})),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"}(yl||(yl={})),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"}(bl||(bl={})),function(e){e[e.Normal=0]="Normal";e[e.InReview=1]="InReview";e[e.Offline=2]="Offline"}(vl||(vl={})),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"}(Cl||(Cl={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Authorizing=3]="Authorizing"}(Al||(Al={})),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"}(Pl||(Pl={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(jl||(jl={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.Name=2]="Name"}(El||(El={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime"}(Sl||(Sl={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.PublishTime=2]="PublishTime";e[e.OpenTime=3]="OpenTime"}(wl||(wl={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(kl||(kl={})),function(e){e[e.All=0]="All";e[e.CreateByMe=1]="CreateByMe";e[e.AllWithCollaborator=2]="AllWithCollaborator"}(Tl||(Tl={})),function(e){e[e.Desc=0]="Desc";e[e.Asc=1]="Asc"}(Il||(Il={})),function(e){e[e.Copy=1]="Copy";e[e.Move=2]="Move";e[e.Publish=3]="Publish";e[e.ImportExport=4]="ImportExport"}(Rl||(Rl={})),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"}(Ol||(Ol={})),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"}(zl||(zl={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(Ll||(Ll={})),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"}(Ul||(Ul={})),function(e){e[e.Packing=0]="Packing";e[e.PackSuccess=1]="PackSuccess";e[e.PackFail=2]="PackFail"}(xl||(xl={}));class Bl{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Bl.prototype.__init.call(this),Bl.prototype.__init2.call(this),this.request=Dl([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Dl([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"),n={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:n},t)}GetDraftIntelligenceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_list"),n={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_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:n},t)}DraftProjectUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/update"),n={project_id:o.project_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:n},t)}GetDraftIntelligenceInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_info"),n={intelligence_id:o.intelligence_id,intelligence_type:o.intelligence_type,version:o.version};return this.request({url:i,method:"POST",data:n},t)}GetUserRecentlyEditIntelligence(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/search/get_recently_edit_intelligence"),n={size:o.size,types:o.types,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:n},t)}DraftProjectCopy(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/copy"),n={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:n},t)}ProcessEntityTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/entity_task/process"),n={entity_id:o.entity_id,action:o.action,task_id_list:o.task_id_list};return this.request({url:i,method:"POST",data:n},t)}DraftProjectDelete(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/delete"),n={project_id:o.project_id};return this.request({url:i,method:"POST",data:n},t)}EntityTaskSearch(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/entity_task/search"),n={task_list:o.task_list};return this.request({url:i,method:"POST",data:n},t)}ListIntelligenceCollaboration(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/collaboration/list"),n={intelligence_id:o.intelligence_id,intelligence_type:o.intelligence_type};return this.request({url:i,method:"POST",data:n},t)}OceanProjectCreate(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/ocean_project/create"),n={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:n},t)}OceanProjectUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/ocean_project/update"),n={project_id:o.project_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:n},t)}GetOceanProjectList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_list"),n={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:n},t)}PublishProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_project"),n={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:n},t)}GetPublishRecordDetail(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_record_detail"),n={project_id:o.project_id,publish_record_id:o.publish_record_id};return this.request({url:i,method:"POST",data:n},t)}GetPublishRecordList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_record_list"),n={project_id:o.project_id};return this.request({url:i,method:"POST",data:n},t)}PublishConnectorList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/connector_list"),n={project_id:o.project_id};return this.request({url:i,method:"POST",data:n},t)}CheckProjectVersionNumber(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/check_version_number"),n={project_id:o.project_id,version_number:o.version_number};return this.request({url:i,method:"POST",data:n},t)}DraftProjectInnerTaskList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/inner_task_list"),n={project_id:o.project_id};return this.request({url:i,method:"POST",data:n},t)}GetOceanProjectInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_info"),n={project_id:o.project_id};return this.request({url:i,method:"POST",data:n},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"),n={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:n},t)}GetModelList(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_list"),n={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:n},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"),n={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:n},t)}GetEstimatedTrainingCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_training_cost"),n={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:n},t)}CreateFinetuneTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/create_finetune_task"),n={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:n},t)}UploadFinetuneDataset(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/upload_finetune_dataset"),n={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:n},t)}GetModelInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_info"),n={space_id:o.space_id,model_id:o.model_id,is_finetuning:o.is_finetuning};return this.request({url:i,method:"POST",data:n},t)}GetFinetuneTrainingInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_finetune_training_info"),n={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:n},t)}GetModelPerformanceData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_performance_data"),n={space_id:o.space_id,model_id:o.model_id,get_pct:o.get_pct};return this.request({url:i,method:"POST",data:n},t)}OperateFinetuneTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/operate_finetune_task"),n={id:o.id,action:o.action};return this.request({url:i,method:"POST",data:n},t)}DeleteFinetuneModel(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/delete_finetune_model"),n={model_id:o.model_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:n},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"),n={Cookie:o.Cookie};return this.request({url:i,method:"POST",headers:n},t)}GetProjectPublishedConnector(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/get_published_connector"),n={project_id:o.project_id};return this.request({url:i,method:"POST",data:n},t)}PublishIntelligenceUnList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_intelligence_unlist"),n={intelligence_id:o.intelligence_id,connector_ids:o.connector_ids,intelligence_type:o.intelligence_type};return this.request({url:i,method:"POST",data:n},t)}PublishIntelligenceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_publish_intelligence_list"),n={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:n},t)}UpdateDiffModeInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/diff_mode/update_diff_mode_info"),n={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:n},t)}GetDiffModeInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/diff_mode/get_diff_mode_info"),n={target_type:o.target_type,target_id:o.target_id};return this.request({url:i,method:"POST",data:n},t)}GetProjectPublishSummary(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_project_publish_summary"),n={project_id:o.project_id};return this.request({url:i,method:"POST",data:n},t)}DraftProjectCrossSpaceCopy(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/crossspace_copy"),n={project_id:o.project_id,to_space_id:o.to_space_id};return this.request({url:i,method:"POST",data:n},t)}EntityTaskList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/entity_task/list"),n={space_id:o.space_id,task_id_list:o.task_id_list};return this.request({url:i,method:"POST",data:n},t)}ExpansionTpm(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/expansion_tpm"),n={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:n},t)}GetEstimatedTpmExpansionCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion_cost"),n={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:n},t)}GetEstimatedTpmExpansion(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion"),n={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:n},t)}FolderUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/update"),n={folder_id:o.folder_id,name:o.name,description:o.description};return this.request({url:i,method:"POST",data:n},t)}GetFolderList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_folder_list"),n={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:n},t)}FolderMove(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/move"),n={folder_id:o.folder_id,parent_folder_id:o.parent_folder_id};return this.request({url:i,method:"POST",data:n},t)}FolderDelete(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/delete"),n={folder_id:o.folder_id};return this.request({url:i,method:"POST",data:n},t)}FolderCreate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/create"),n={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:n},t)}ArchiveProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/archive"),n={project_id:o.project_id,description:o.description,scene:o.scene};return this.request({url:i,method:"POST",data:n},t)}GetIntelligenceTaskInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/entity_task/task_info"),n={task_id:o.task_id};return this.request({url:i,method:"GET",params:n},t)}ProjectHistoryList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list"),n={project_id:o.project_id,history_type:o.history_type,cursor:o.cursor,size:o.size};return this.request({url:i,method:"POST",data:n},t)}RollbackProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/rollback"),n={project_id:o.project_id,rollback_version:o.rollback_version,scene:o.scene};return this.request({url:i,method:"POST",data:n},t)}GetModelConcurrencyPerformanceData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_concurrency_performance_data"),n={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:n},t)}UpdateModelConfigType(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/update_model_config_type"),n={space_id:o.space_id,model_id:o.model_id,config_type:o.config_type};return this.request({url:i,method:"POST",data:n},t)}GetSpaceModelUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_space_model_user_config"),n={space_id:o.space_id};return this.request({url:i,method:"POST",data:n},t)}OpenGetProjectList(e,t){const o=e||{},i=this.genBaseURL("/v1/apps"),n={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:n},t)}OpenGetBotList(e,t){const o=e||{},i=this.genBaseURL("/v1/bots"),n={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:n},t)}GetFolderTree(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/tree"),n={space_id:o.space_id,type:o.type};return this.request({url:i,method:"POST",data:n},t)}OpenGetSpaceFolder(e,t){const o=e||{},i=this.genBaseURL("/v1/folders"),n={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:n},t)}MoveObjectToFolder(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/move_object"),n={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:n},t)}GetFolderInfoByIds(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/folder/get_by_ids"),n={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:n},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"),n={res_type:o.res_type,id:o.id,commit_id:o.commit_id};return this.request({url:i,method:"POST",data:n},t)}ImportPreCheck(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/import_pre_check"),n={package_uri:o.package_uri};return this.request({url:i,method:"POST",data:n},t)}GetUploadAuthToken(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/upload/auth_token"),n={scene:o.scene};return this.request({url:i,method:"POST",data:n},t)}MarkProjectHistory(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list/read"),n={project_id:o.project_id,version:o.version};return this.request({url:i,method:"POST",data:n},t)}GetCustomModelDetail(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_detail"),n={model_id:o.model_id,org_id:o.org_id};return this.request({url:i,method:"POST",data:n},t)}GetCustomModelList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_list"),n={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:n},t)}GetProjectHistoryNotice(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list/notice"),n={project_id:o.project_id};return this.request({url:i,method:"POST",data:n},t)}BindCustomModelSpace(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/bind_custom_model_space"),n={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:n},t)}GetCustomModelSpaceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_space_list"),n={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:n},t)}GetCustomModelParameterTemplate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_parameter_template"),n={org_id:o.org_id};return this.request({url:i,method:"POST",data:n},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"),n={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:n},t)}ConvertCustomModelParameter(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/convert_custom_model_parameter"),n={parameters:o.parameters,org_id:o.org_id};return this.request({url:i,method:"POST",data:n},t)}CreateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/create_custom_model"),n={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:n},t)}TerminateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/terminate_custom_model"),n={model_id:o.model_id,terminate_time:o.terminate_time,org_id:o.org_id};return this.request({url:i,method:"POST",data:n},t)}UpdateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/update_custom_model"),n={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:n},t)}GetModelUsageRecord(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_usage_record"),n={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:n},t)}GetEntityModelUsage(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_entity_model_usage"),n={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:n},t)}GetTypeList(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/get_type_list"),n={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:n},t)}SaveModelReplacement(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/save_replacement"),n={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:n},t)}GetModelReplacement(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_replacement"),n={space_id:o.space_id,entity_type:o.entity_type,entity_id:o.entity_id};return this.request({url:i,method:"POST",data:n},t)}}const ql=new Bl({}),Ml={agent:qc.VibeProjectAgent,workflow:qc.VibeProjectAutomation,webapp:qc.VibeProjectWebApp,app:qc.VibeProjectApp,skill:qc.VibeProjectSkill,web:qc.VibeProjectGeneralWeb,miniprogram:qc.VibeProjectWechatMiniProgram,assistant:qc.VibeProjectAssistantAgent},Nl={[qc.VibeProjectAgent]:"agent",[qc.VibeProjectAutomation]:"workflow",[qc.VibeProjectWebApp]:"webapp",[qc.VibeProjectApp]:"app",[qc.VibeProjectSkill]:"skill",[qc.VibeProjectGeneralWeb]:"web",[qc.VibeProjectWechatMiniProgram]:"miniprogram",[qc.VibeProjectAssistantAgent]:"assistant"};function Gl(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return Ml[o]}const Fl=e=>Nl[e],$l=[qc.VibeProjectAgent,qc.VibeProjectAutomation,qc.VibeProjectWebApp,qc.VibeProjectApp,qc.VibeProjectSkill,qc.VibeProjectGeneralWeb,qc.VibeProjectWechatMiniProgram,qc.VibeProjectAssistantAgent].map(Fl).filter(Boolean);function Vl(e,t){return null!=e?e:t()}function Wl(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const Hl={agent:e.VibeProjectType.Agent,workflow:e.VibeProjectType.Automation,webapp:e.VibeProjectType.WebApp,app:e.VibeProjectType.App,skill:e.VibeProjectType.Skill,web:e.VibeProjectType.GeneralWeb,miniprogram:e.VibeProjectType.WechatMiniProgram,assistant:e.VibeProjectType.AssistantAgent},Kl={[e.VibeProjectType.Agent]:"agent",[e.VibeProjectType.Automation]:"workflow",[e.VibeProjectType.WebApp]:"webapp",[e.VibeProjectType.App]:"app",[e.VibeProjectType.Skill]:"skill",[e.VibeProjectType.GeneralWeb]:"web",[e.VibeProjectType.WechatMiniProgram]:"miniprogram",[e.VibeProjectType.AssistantAgent]:"assistant"};function Jl(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return Hl[o]}const Zl=e=>Kl[e],Ql={ask:e.ProjectMode.Ask,agent:e.ProjectMode.Agent},Yl={[e.ProjectMode.Ask]:"ask",[e.ProjectMode.Agent]:"agent"};function Xl(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return Ql[o]}function ep(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function tp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}class op{static getInstance(){return op.INSTANCE||(op.INSTANCE=new op),op.INSTANCE}sendMessageRunTask(e){const t=[_.resolve(__dirname,"./send-message.worker.js")],o=process.execPath;b.spawn(o,[...t,JSON.stringify(e)],{detached:!0,stdio:"ignore"}).unref()}async sendMessage(t){return await e.sendProjectChatMessage(t)}}const ip=op.getInstance();function np(e,t){return null!=e?e:t()}function sp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function rp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const ap=t=>{const o=t.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");o.command("create").description("Create a new project").requiredOption("--message <message>","Description/requirements for creating the project").requiredOption("--type <type>","Project type: agent | workflow | app | skill | web | miniprogram | assistant").option("--org-id <orgId>","Organization ID (optional, will read from context automatically)").option("--space-id <spaceId>","Space ID (optional, will read from context automatically)").option("--wait","Wait for project creation to complete").option("--chat-mode <chatMode>","Chat mode for the project (e.g., chat, agent)").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),[]).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(Hl),description:"Project type"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"},chatMode:{type:"string",required:!1,description:"Chat mode for the project (e.g., chat, agent)"},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)"}},output:{project_id:{type:"string",description:"Created project ID"},type:{type:"string",description:"Project type"}}},enums:{type:Object.keys(Hl).reduce((e,t)=>(e[t]=`${t.toUpperCase()} project`,e),{})},errors:[{code:e.ErrorCode.E1005,name:"INVALID_PROJECT_TYPE",desc:"Invalid project type",fix:"Please use a valid project type: agent | workflow | app | skill | web | miniprogram | assistant"},{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Missing Space ID",fix:"Please use the --space-id parameter or run `coze space use <spaceId>` first"},{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Project type is not supported for creation",fix:"Please choose a supported project type and try again"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized or project tool config is missing",fix:"Please retry and run with --debug if the issue persists"}]}}).action(async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=np(np(t.spaceId,()=>sp([i,"optionalAccess",e=>e.config,"access",e=>e.spaceId])),()=>""),{message:s,type:r,wait:a,chatMode:c,modelName:l,toolName:p}=t;sp([i,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e(`Resolving project type '${r}'...`)]);const d=Jl(r);if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!d)throw new e.CozeError(e.ErrorCode.E1005,`Unknown project type: ${r}`,{type:r});sp([i,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching agent tools configuration...")]);const u=sp([await e.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e(e=>e.project_type===d),"optionalAccess",e=>e.tools]);if(!u||0===u.length)throw new e.CozeError(e.ErrorCode.E5000,`No tools config for projectType: ${String(r)}`,{type:r,projectType:d});const _={};u.forEach(e=>{sp([e,"optionalAccess",e=>e.name])&&(_[e.name]=np(sp([p,"optionalAccess",e=>e.includes,"call",t=>t(e.name)]),()=>Boolean(e.enabled)))}),sp([i,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching project default skills...")]);const m={skills:np(sp([await ra.GetProjectDefaultSkill({project_type:d,space_id:String(n)}),"access",e=>e.data,"optionalAccess",e=>e.skill_list]),()=>[]).map(e=>({skill_id:e.skill_id,is_preload:e.is_preload})),filter_types:[d]},g={space_id:String(n),user_query:s,project_type:d,project_settings:{model_setting:{model_name:l||""},agent_tools:_,skill_setting:m,...c?{project_mode:Xl(c)}:{}}};sp([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating project...")]);const h=np((await e.IdeApi.ChatCreateVibeProject(g)).data,()=>({})).project_id,f=await sp([i,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!f)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(i.ui.success(`Project created successfully, please use "coze code message status -p ${h}" to check the status.`),sp([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:h,type:r})]),a){const e=await ip.sendMessage({projectId:np(h,()=>""),prompt:s,apiBaseUrl:i.config.apiBaseUrl,accessToken:f,xTTEnv:i.config.xTTEnv,key:`coze-coding-cli:message:${h}`});i.response.print(e.lastAnswerMessage)}else ip.sendMessageRunTask({projectId:np(h,()=>""),prompt:s,apiBaseUrl:i.config.apiBaseUrl,accessToken:f,xTTEnv:i.config.xTTEnv,key:`coze-coding-cli:message:${h}`})}),function(t){t.command("list").description("List all projects").config({help:{brief:"List all projects in the current space",description:"Get the list of projects in the current space. Supports filtering by type, name, publish status, and supports pagination.",examples:[{desc:"List projects",cmd:"coze code project list",tags:["[RECOMMENDED]"]},{desc:"Filter by type",cmd:"coze code project list --type agent --type workflow"},{desc:"Search by name",cmd:'coze code project list --name "customer service"'}],schema:{input:{size:{type:"number",required:!1,description:"Number of projects to return (default: 10)"},cursorId:{type:"string",required:!1,description:"Cursor for pagination"},type:{type:"array",required:!1,description:"Project type filter (can be passed multiple times)"},name:{type:"string",required:!1,description:"Filter by project name"},hasPublished:{type:"boolean",required:!1,description:"Filter by publish status"},searchScope:{type:"number",required:!1,description:"Created by (All = 0, CreateByMe = 1)"},folderId:{type:"string",required:!1,description:"Folder ID"},orderType:{type:"number",required:!1,description:"Sort type (0 for descending, 1 for ascending)"},isFavFilter:{type:"boolean",required:!1,description:"Filter by favorite status"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Project ID"},name:{type:"string",description:"Project name"},type:{type:"string",description:"Project type"},description:{type:"string",description:"Project description"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}],enums:{type:$l.reduce((e,t)=>(e[t]=`${t.toUpperCase()} project`,e),{}),"search-scope":{0:"All",1:"CreateByMe"},"order-type":{0:"Descending",1:"Ascending"},"order-by":{0:"updated_at",1:"created_at"}}}}).option("--size <size>","Number of projects to return",parseInt).option("--cursor-id <cursorId>","Cursor for pagination").option("--type <type>","Project type filter (can be passed multiple times): agent | workflow | webapp | app | web | miniprogram | assistant",(e,t=[])=>[...t,e],[]).option("--name <name>","Filter by project name").option("--has-published","Filter by publish status").option("--search-scope <searchScope>","Created by (All = 0, CreateByMe = 1, AllWithCollaborator = 2)").option("--folder-id <folderId>","Folder ID").option("--order-type <orderType>","Sort type (0 for descending, 1 for ascending)").option("--order-by <orderBy>","Order by (0 for updated_at, 1 for created_at)").option("--is-fav-filter","Filter by favorite status (true | false)").action(async function(e,t){const o=t.getContext(),i=Vl(Wl([e,"optionalAccess",e=>e.size]),()=>10),n=Vl(Wl([e,"optionalAccess",e=>e.cursorId]),()=>{}),s=Wl([e,"optionalAccess",e=>e.type,"optionalAccess",e=>e.map,"call",e=>e(Gl),"access",e=>e.filter,"call",e=>e(Boolean)]),r=Wl([e,"optionalAccess",e=>e.name]),a=Wl([e,"optionalAccess",e=>e.hasPublished])?Boolean(Wl([e,"optionalAccess",e=>e.hasPublished])):void 0,c=Number(Vl(Wl([e,"optionalAccess",e=>e.searchScope]),()=>Tl.All)),l=Vl(Wl([e,"optionalAccess",e=>e.folderId]),()=>"0"),p=Number(Vl(Wl([e,"optionalAccess",e=>e.orderType]),()=>Il.Desc)),d=Boolean(Wl([e,"optionalAccess",e=>e.isFavFilter])),u=Number(Vl(Wl([e,"optionalAccess",e=>e.orderBy]),()=>wl.UpdateTime));let _=[];Wl([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching project list...")]);const m=await ql.GetDraftIntelligenceList({space_id:Vl(Wl([o,"optionalAccess",e=>e.config,"access",e=>e.spaceId]),()=>""),size:i,cursor_id:n,types:s,name:r,has_published:a,search_scope:c,folder_id:l,order_type:p,order_by:u,is_fav_filter:d,status:[Bc.Using,Bc.Banned,Bc.MoveFailed]});_=Wl([m,"access",e=>e.data,"optionalAccess",e=>e.intelligences])||[],Wl([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetched ${_.length} projects.`)]),Wl([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(_.map(e=>({id:Wl([e,"access",e=>e.basic_info,"optionalAccess",e=>e.id]),name:Wl([e,"access",e=>e.basic_info,"optionalAccess",e=>e.name]),type:Fl(e.type),description:Wl([e,"access",e=>e.basic_info,"optionalAccess",e=>e.description])})))])})}(o),function(t){t.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"}]}}).action(async function(t,o,i){const n=i.getContext();ep([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetching project details for '${t}'...`)]);const s=ep([await e.IdeApi.GetVibeProject({project_id:t}),"access",e=>e.data,"optionalAccess",e=>e.project_info]);if(!s)throw new e.CozeError(e.ErrorCode.E3001,`Project ${t} not found`,{projectId:t});ep([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Project details for '${t}':`)]),ep([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>{return e({...y.omit(s,["project_settings"]),type:Zl(ep([s,"optionalAccess",e=>e.project_type])),tools:ep([s,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.agent_tools]),chat_mode:(t=ep([s,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.project_mode]),Yl[t]),model_name:ep([s,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.model_setting,"optionalAccess",e=>e.model_name]),skills:y.pick(ep([s,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]),["skills"])});var t}])})}(o),function(t){t.command("delete <projectId>").description("Delete a project").config({help:{brief:"Delete project",description:"Delete the specified Coze Coding project. This operation cannot be undone, please use with caution.",examples:[{desc:"Delete project",cmd:"coze code project delete <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID to delete"}},output:{project_id:{type:"string",description:"Deleted project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E3005,name:"DELETE_FAILED",desc:"Failed to delete project",fix:"Please confirm if the project ID is correct and check if you have sufficient permissions"}]}}).action(async function(t,o,i){const n=i.getContext();tp([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleting project '${t}'...`)]),await e.IdeApi.DeleteVibeProject({project_id:t}),tp([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Project '${t}' deleted successfully.`)]),tp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:t,message:`Project '${t}' deleted successfully.`})])})}(o),function(t){t.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)").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>"}]}}).action(async function(t,o){const i=o.getContext(),{projectId:n,env:s}=t,r="prod"===s?e.MemoryEnv.product:e.MemoryEnv.develop,a=[];await Promise.all(["knowledge","public"].map(async t=>{((await e.IdeApi.GetSchemaTables({project_id:n,database_env:r,schema:t})).table_names||[]).forEach(e=>{a.push({schema:t,table_name:e})})})),rp([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${a.length} tables.`)]),rp([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])})}(o)};function cp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const lp=new Set([e.VibeProjectType.WechatMiniProgram,e.VibeProjectType.Agent,e.VibeProjectType.Automation,e.VibeProjectType.Skill,e.VibeProjectType.AssistantAgent]);function pp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function dp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const up=t=>{const o=t.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(t){t.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)"}}}}},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"}]}}).action(async function(t,o){const i=o.getContext(),{projectId:n}=t;let s,r,a;if(n)a=await e.IdeApi.GetVibeProject({project_id:n}),s=dp([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=dp([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.space_id]);else{const o=t.type;if(!o)throw new e.CozeError(e.ErrorCode.E1000,"Project type is required",{projectId:n});s=Jl(o)}if(!s)throw new e.CozeError(e.ErrorCode.E1000,"Project type is required",{projectId:n});const c=dp([await e.BuildAgentApi.GetModelList({project_id:n,project_type:s,space_id:r}),"access",e=>e.model_list,"optionalAccess",e=>e.map,"call",e=>e(e=>({model_name:e.name,display_name:e.display_name,enable:n?dp([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.model_setting,"optionalAccess",e=>e.model_name])===e.name:void 0}))]);dp([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${dp([c,"optionalAccess",e=>e.length])||0} models.`)]),dp([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(c)])})}(o),function(t){t.command("set <modelName>").description("Set project model").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Set project model",description:"Set the model used by the specified project. Use model list to see available models.",examples:[{desc:"Set project 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"}]}}).action(async function(t,o,i){const n=i.getContext(),{projectId:s}=o,r=await e.IdeApi.GetVibeProject({project_id:s}),a=pp([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=pp([r,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.space_id]);if(!pp([await e.BuildAgentApi.GetModelList({project_id:s,project_type:a,space_id:c}),"access",e=>e.model_list,"optionalAccess",e=>e.find,"call",e=>e(e=>e.name===t)]))throw new e.CozeError(e.ErrorCode.E1000,`Model '${t}' is not available. Use 'coze code model list' to see available models.`,{modelName:t,projectId:s});await e.IdeApi.UpdateVibeProject({project_id:s,project_settings:{model_setting:{model_name:t}}}),pp([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Model set to '${t}'.`)]),pp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,model_name:t,message:`Project model has been set to '${t}' successfully`})])})}(o)};function _p(e,t){return null!=e?e:t()}function mp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function gp(e,t){return null!=e?e:t()}function hp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const fp=e=>{if(null==e)return null;return 0===e.trim().length?null:e},yp=t=>{t.command("send [message]").description("Send a prompt message to Coze Coding project chat").option("--wait","Wait for the chat response before returning").option("--stdin","Read additional context from stdin (pipe input)").config({help:{brief:"Send a message to project chat",description:"Send a prompt message to the specified Coze Coding project chat. The message can be provided as a positional argument. Use --stdin to pipe additional context. Use @<path> to mention and upload local files as context.",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug in auth module" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Send and wait for the response",cmd:'coze code message send "Fix the bug in auth module" -p 123456 --wait'},{desc:"Mention a file with @",cmd:'coze code message send "Refactor @src/utils.ts to use async/await" -p 123456'},{desc:"Mention multiple files",cmd:'coze code message send "Compare @src/old.ts and @src/new.ts, list the differences" -p 123456'},{desc:"Send message with stdin context",cmd:'cat error.log | coze code message send "Analyze this error" --stdin -p 123456'},{desc:"Use environment variable for project",cmd:'export COZE_PROJECT_ID=123456 && coze code message send "Hello"'}],errors:[{code:e.ErrorCode.E1000,name:"MISSING_MESSAGE",desc:"No message content provided",fix:"Provide MESSAGE argument or use --stdin with piped content",example:'coze code message send "Your question" -p 123456 # or: echo "context" | coze code message send --stdin "question" -p 123456'},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{message:{type:"string",required:!1,description:"The prompt message to send to the project chat"},wait:{type:"boolean",required:!1,description:"Wait for the chat response before returning. Without this flag, the message is sent in the background."},stdin:{type:"boolean",required:!1,description:"Read additional context from stdin (pipe input)."}},output:{type:"object",properties:{content:{type:"string",description:"The chat response content"}}}}}}).action(async(t,o,i)=>{const n=i.getContext();try{if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=hp([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=gp(hp([s,"optionalAccess",e=>e.projectId]),()=>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 a=await hp([n,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!a)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const{wait:c,stdin:l}=o;let p=null;l&&(p=await fr());const d=fp(t),u=fp(p);if(!d&&!u)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin");const _=d&&u?`${d}\n\n${u}`:gp(gp(d,()=>u),()=>""),m=new Set,g=await e.sendProjectChatMessage({projectId:r,prompt:_,apiBaseUrl:n.config.apiBaseUrl,accessToken:a,xTTEnv:n.config.xTTEnv,key:`coze-coding-cli:message:${r}`,onWarn:e=>n.ui.warn(e),waitForResponse:!!c,onMessageItem:e=>{if(c&&"json"===n.format&&e.finish){const t=(e=>{const t=gp(e.msg_id,()=>""),o=gp(e.sequence_id,()=>"");return`${e.type}:${t}:${String(o)}`})(e);m.has(t)||(m.add(t),n.response.print({content:e.content,role:e.role,finish:e.finish,type:e.type}))}}});if(c)"text"===n.format&&n.response.print(gp(hp([g,"access",e=>e.lastAnswerMessage,"optionalAccess",e=>e.content,"access",e=>e.answer]),()=>""));else{const e=`Message sent. Use \`coze code message status -p ${r}\` to check the result.`;"json"===n.format?n.response.print({status:"sent",project_id:r,message:e}):n.response.print(e),process.exit(0)}}catch(e){K(e,n)}})};function bp(e,t){return null!=e?e:t()}function vp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function Cp(e,t){return null!=e?e:t()}function Ap(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const Pp=async(t,o)=>{const i=o.getContext();try{if(!i)throw new e.CozeError("E5000","CLI context is not initialized");const n=Ap([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),s=Cp(Ap([n,"optionalAccess",e=>e.projectId]),()=>process.env.COZE_PROJECT_ID);if(!s)throw new e.CozeError("E1001","Missing required option: --project-id (or env COZE_PROJECT_ID)");if(!await Ap([i,"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(t.after&&t.before)throw new e.CozeError("E1000","--after and --before cannot be used together. Use only one cursor at a time.");i.ui.verbose(`Fetching conversation history for project ${s}...`);const r=e.createChatCore({key:`coze-coding-cli:history:${s}`,apiBaseUrl:i.config.apiBaseUrl});try{const e=t.after?"loadNext":"loadPrev",o="loadNext"===e?"11":"10",n=await r.getHistoryMessage({limit:o,project_id:s,after:t.after,before:t.before}),a=[],c=new Map,l=new Map;n.histories.forEach(e=>{if(e.user){const t=e.user.msg_id;c.has(t)||a.push(t);const o=(e=>{const t=Ap([e,"optionalAccess",e=>e.content]);return Cp(Cp(Ap([t,"optionalAccess",e=>e.query,"optionalAccess",e=>e.prompt]),()=>Ap([t,"optionalAccess",e=>e.retry,"optionalAccess",e=>e.prompt])),()=>Ap([t,"optionalAccess",e=>e.edit,"optionalAccess",e=>e.prompt]))})(e.user.message);c.set(t,o?(e=>e.map(e=>"text"===e.type?e.content.text:"file"===e.type?`${vp([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.path])} ${bp(vp([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.from,"optionalAccess",e=>e[0]]),()=>"")} ${bp(vp([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.to,"optionalAccess",e=>e[0]]),()=>"")} `:"console"===e.type?vp([e,"access",e=>e.content,"access",e=>e.console,"optionalAccess",e=>e.content]):"node"===e.type?vp([e,"access",e=>e.content,"access",e=>e.node,"optionalAccess",e=>e.node_title]):"upload_file"===e.type?vp([e,"access",e=>e.content,"access",e=>e.upload_file,"optionalAccess",e=>e.file_name]):"page"===e.type?vp([e,"access",e=>e.content,"access",e=>e.page,"optionalAccess",e=>e.page_title]):"page_elements"===e.type?vp([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?vp([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&&l.set(o,i)}});const p=a[0],d=a[a.length-1],u=a.reverse().filter(e=>l.has(e)).map(e=>({userMessage:Cp(c.get(e),()=>""),answer:Cp(l.get(e),()=>"")})),_={histories:u,cursor:{after:p,before:d,has_more:n.has_more,loadDirection:e}};if("json"===i.format)i.response.print(_);else{if(0===u.length)return void i.response.print("No conversation history found.");u.forEach((e,t)=>{i.response.print(`--- #${t+1} ---\nQ: ${e.userMessage}\nA: ${e.answer}\n`)}),i.response.print(`\n[cursor] after=${p}, before=${d}, has_more=${n.has_more}, loadDirection=${e}`)}}finally{r.destroy()}}catch(e){K(e,i)}};function jp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const Ep=t=>{const o=t.command("message");o.description("Manage project chat messages").config({help:{brief:"Manage project chat messages",description:"Manage Coze Coding project chat messages.\n\nThis command group provides:\n- send: Send a new message to the project chat\n- status: Query the status of current chat message (auto-fetch result when completed)\n- cancel: Cancel an ongoing chat message\n- history: View conversation history",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Check message status",cmd:"coze code message status -p 123456"},{desc:"Cancel ongoing message",cmd:"coze code message cancel -p 123456"},{desc:"View conversation history",cmd:"coze code message history -p 123456"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID (can also be set via COZE_PROJECT_ID env)"}}},seeAlso:["coze code project list","coze code project create"]}}).option("-p, --project-id <id>","Coze project id (or env COZE_PROJECT_ID)"),yp(o),(t=>{t.command("status").description("Query current project chat message status and get result when completed").config({help:{brief:"Query chat message status",description:"Get the current status of the chat message for the specified project. Returns status information such as running, completed, or error. When the chat is completed, automatically fetches and returns the result.",examples:[{desc:"Check message status (auto-fetch result when completed)",cmd:"coze code message status -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message status"},{desc:"Output as JSON",cmd:"coze code message status -p 123456 --format json"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Message status (running/completed/error)"},message:{type:"string",description:"Status message or error details"},answer:{type:"string",description:"The chat answer content (only when completed)"}}}}}}).action(async(t,o)=>{const i=o.getContext();try{if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const t=mp([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),n=_p(mp([t,"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)");i.ui.verbose(`Fetching chat status for project ${n}...`);const{code:s,msg:r,reply_id:a,...c}=await e.BuildAgentApi.GetChatCLIMessageStatus({project_id:n});if("done"===c.status){i.ui.verbose(`Chat completed, fetching result for project ${n}...`);const t=await e.BuildAgentApi.GetChatCLIMessageResultContent({project_id:n}),o="data"in t?t.data:t;"json"===i.format?i.response.print({...c,answer:o.answer}):i.response.print(`status: [${c.status}]\nanswer: ${_p(o.answer,()=>"")}`)}else"json"===i.format?i.response.print(c):i.response.print(c.status)}catch(e){K(e,i)}})})(o),function(t){t.command("cancel").description("Cancel current project chat message").config({help:{brief:"Cancel ongoing chat message",description:"Cancel the currently running chat message for the specified project. Useful for stopping long-running or stuck message generation.",examples:[{desc:"Cancel current message",cmd:"coze code message cancel -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message cancel"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Cancel operation status"},message:{type:"string",description:"Result message"}}}}}}).action(async(t,o)=>{const i=o.getContext();try{if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const t=jp([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),s=null!=(n=jp([t,"optionalAccess",e=>e.projectId]))?n:(()=>process.env.COZE_PROJECT_ID)();if(!s)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");const{accessToken:r}=i.config;if(!r)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");i.ui.verbose(`Canceling chat message for project ${s}...`);const{message:a}=await e.BuildAgentApi.CancelChatCLIMessage({project_id:s});"json"===i.format?i.response.print({message:a}):i.response.print(a)}catch(e){K(e,i)}var n})}(o),(e=>{e.command("history").description("View conversation history of the project chat").option("--after <msg_id>","Cursor for fetching newer messages (smaller index)").option("--before <msg_id>","Cursor for fetching older messages (larger index)").config({help:{brief:"View conversation history",description:"Retrieve and display the conversation history for the specified Coze Coding project. Shows each round of user messages and LLM responses. By default, returns the latest 10 rounds of conversation. Use --after or --before cursors for pagination.",examples:[{desc:"View latest 10 rounds of conversation history",cmd:"coze code message history -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message history"},{desc:"Output as JSON with cursor info",cmd:"coze code message history -p 123456 --format json"},{desc:"Fetch newer messages after a cursor",cmd:"coze code message history -p 123456 --after msg_xxx"},{desc:"Fetch older messages before a cursor",cmd:"coze code message history -p 123456 --before msg_yyy"}],errors:[{code:"E1000",name:"INVALID_ARGUMENT",desc:"--after and --before cannot be used together",fix:"Use only one cursor option at a time for pagination"},{code:"E1001",name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:"E2001",name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"},after:{type:"string",description:'Cursor (message ID) for fetching newer messages. Newer messages have smaller index. Use the "after" value from previous output as this parameter.'},before:{type:"string",description:'Cursor (message ID) for fetching older messages. Older messages have larger index. Use the "before" value from previous output as this parameter.'}},output:{type:"object",properties:{histories:{type:"array",items:{type:"object",properties:{userMessage:{type:"string",description:"User's message in this round"},answer:{type:"string",description:"LLM's last answer with content"}}}},cursor:{type:"object",description:"Pagination cursor info for next/prev page requests",properties:{after:{type:"string",description:"Message ID of the newest result, use as --after to fetch newer messages (loadNext)"},before:{type:"string",description:"Message ID of the oldest result, use as --before to fetch older messages (loadPrev)"},has_more:{type:"boolean",description:"Whether there are more messages available"},loadDirection:{type:"string",enum:["loadNext","loadPrev"],description:"Load direction of current request. Defaults to 'loadPrev' (load older messages). 'loadNext' when --after is used, 'loadPrev' when --before is used or on initial request."}}}}}}}}).action(Pp)})(o)};function Sp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function wp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function kp(t){t.command("list").description("List project environment variables").option("--env <scope>","Environment scope: dev | prod","dev").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List project environment variables",description:"Retrieve the list of environment variables for the specified project. Supports filtering by environment (dev/prod) and displays all configured sensitive information key names.",examples:[{desc:"List dev environment variables",cmd:"coze code env list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List prod environment variables",cmd:"coze code env list -p <projectId> --env prod"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},env:{type:"string",required:!1,enum:["dev","prod"],description:"Environment scope (default: dev)"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},project_type:{type:"string",description:"Project type"},env:{type:"string",description:"Environment scope"},secrets:{type:"array",description:"Environment variable list"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action(async function(t,o){const i=o.getContext(),{projectId:n}=t,s=wp([await e.IdeApi.GetVibeProject({project_id:n}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=(a=t.env,"prod"===String(a||"dev").toLowerCase()?Xo.prod:Xo.dev);var a;const c=wp([await ai.ListProjectSecret({env:r,project_id:n,...s===e.VibeProjectType.Skill?{with_providers:!0}:{}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[];wp([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secrets listed successfully.")]),wp([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 Tp(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const Ip=t=>{const o=t.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");kp(o),o.command("set <key> <value>").description("Set a project environment variable").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Set project environment variable",description:"Add or update environment variables for the project. Environment variables are securely stored and used for sensitive information like API keys, passwords, etc.",examples:[{desc:"Set environment variable",cmd:"coze code env set <KEY> <VALUE> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{key:{type:"string",required:!0,description:"Environment variable key"},value:{type:"string",required:!0,description:"Environment variable value"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},key:{type:"string",description:"Set key name"},value:{type:"string",description:"Set value"}}}}},errors:[{code:e.ErrorCode.E3008,name:"SKILL_PROJECT_NOT_SUPPORTED",desc:"Skill project secret_type logic to be supplemented",fix:"This feature is not yet supported for Skill projects"}]}}).action(async function(t,o,i,n){const s=n.getContext(),{projectId:r}=i,a=Sp([await e.IdeApi.GetVibeProject({project_id:r}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(a===e.VibeProjectType.Skill)throw new e.CozeError(e.ErrorCode.E3008,"Skill project secret_type logic to be supplemented",{projectId:r,projectType:a});await ai.InsertProjectSecret({project_id:r,insert_secrets:{secrets:[{secret_key:t,secret_val:o}]}}),Sp([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secret set successfully")]),Sp([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,key:t,value:o})])}),function(t){t.command("delete <key>").description("Delete a project environment variable").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete project environment variable",description:"Delete specified environment variables from the project. Supports deleting multiple variables simultaneously by passing the --key parameter multiple times.",examples:[{desc:"Delete a single environment variable",cmd:"coze code env delete <KEY> -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Delete multiple environment variables",cmd:"coze code env delete <KEY> -p <projectId>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},key:{type:"string",required:!0,description:"Environment variable key name to delete"}},output:{message:{type:"string",description:"Result message"},key:{type:"string",description:"Deleted key"}}},errors:[{code:e.ErrorCode.E3003,name:"SECRET_NOT_FOUND",desc:"The specified environment variable does not exist",fix:"Please use `env list` first to confirm if the variable name is correct"}]}}).action(async function(t,o,i){const n=i.getContext(),{projectId:s}=o,r=[t],a=Tp([await ai.ListProjectSecret({env:Xo.dev,project_id:s}),"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:s,keys:r});await ai.DeleteProjectSecret({project_id:s,keys:l}),Tp([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env has been delete successfully")]),Tp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({message:"env has been delete successfully",key:t,project_id:s,keys:r,secret_ids:l})])})}(o)};var Rp,Op,zp,Lp,Up,xp,Dp,Bp,qp,Mp,Np,Gp,Fp,$p,Vp,Wp,Hp,Kp,Jp,Zp,Qp,Yp,Xp,ed,td,od,id,nd,sd,rd;function ad(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...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"}(Rp||(Rp={})),function(e){e[e.Unknown=0]="Unknown";e[e.FreeCertificate=1]="FreeCertificate"}(Op||(Op={})),function(e){e[e.Unknown=0]="Unknown";e[e.Normal=1]="Normal"}(zp||(zp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Existing=1]="Existing";e[e.Free=2]="Free"}(Lp||(Lp={})),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"}(Up||(Up={})),function(e){e[e.Passed=1]="Passed";e[e.UnPassed=2]="UnPassed";e[e.Auditing=3]="Auditing"}(xp||(xp={})),function(e){e[e.Official=1]="Official"}(Dp||(Dp={})),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"}(Bp||(Bp={})),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"}(qp||(qp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Success=1]="Success";e[e.Pending=2]="Pending";e[e.Failed=3]="Failed"}(Mp||(Mp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Default=1]="Default";e[e.Custom=2]="Custom"}(Np||(Np={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(Gp||(Gp={})),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"}(Fp||(Fp={})),function(e){e[e.Created=1]="Created";e[e.Ready=3]="Ready";e[e.Stopped=4]="Stopped";e[e.Banned=5]="Banned"}($p||($p={})),function(e){e[e.Unknown=0]="Unknown";e[e.VefaasFunction=1]="VefaasFunction"}(Vp||(Vp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Dev=1]="Dev";e[e.Prod=2]="Prod";e[e.Audit=3]="Audit"}(Wp||(Wp={})),function(e){e[e.A=1]="A";e[e.CNAME=2]="CNAME"}(Hp||(Hp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Single=1]="Single";e[e.Wildcard=2]="Wildcard";e[e.Multi=3]="Multi"}(Kp||(Kp={})),function(e){e[e.Unknown=0]="Unknown";e[e.DV=1]="DV";e[e.OV=2]="OV";e[e.EV=3]="EV"}(Jp||(Jp={})),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"}(Zp||(Zp={})),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"}(Qp||(Qp={})),function(e){e[e.NeedAuthorize=1]="NeedAuthorize";e[e.BindSuccess=2]="BindSuccess";e[e.BoundToOtherProject=3]="BoundToOtherProject";e[e.BoundToOtherUser=4]="BoundToOtherUser"}(Yp||(Yp={})),function(e){e[e.BoundToSelf=1]="BoundToSelf";e[e.BoundToOtherUser=2]="BoundToOtherUser";e[e.NotAuthorized=3]="NotAuthorized"}(Xp||(Xp={})),function(e){e[e.Line=1]="Line"}(ed||(ed={})),function(e){e[e.Default=0]="Default";e[e.WechatMini=1]="WechatMini";e[e.DouyinMini=2]="DouyinMini"}(td||(td={})),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"}(od||(od={})),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"}(id||(id={})),function(e){e[e.Recorded=1]="Recorded"}(nd||(nd={})),function(e){e[e.Sum=1]="Sum";e[e.Avg=2]="Avg"}(sd||(sd={})),function(e){e[e.Next=1]="Next";e[e.Third=3]="Third";e[e.Seventh=7]="Seventh"}(rd||(rd={}));class cd{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){cd.prototype.__init.call(this),cd.prototype.__init2.call(this),this.request=ad([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=ad([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"),n={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:n},t)}PublicRollbackDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/rollback"),n={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:n},t)}PublicCancelDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/cancel"),n={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:n},t)}PublicGetDeployConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_config/get"),n={project_id:o.project_id,commit_hash:o.commit_hash};return this.request({url:i,method:"GET",params:n},t)}PublicListDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/list"),n={project_id:o.project_id,page_token:o.page_token,page_size:o.page_size};return this.request({url:i,method:"GET",params:n},t)}PublicSearchRuntimeLog(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/runtime_log/search"),n={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:n},t)}PublicGetDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get"),n={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"GET",params:n},t)}PublicBindCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/bind"),n={project_id:o.project_id,certificate_id:o.certificate_id,domain:o.domain};return this.request({url:i,method:"POST",data:n},t)}PublicApplyFreeCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/apply_free"),n={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:n},t)}PublicListDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/list"),n={project_id:o.project_id,unit_type:o.unit_type};return this.request({url:i,method:"GET",params:n},t)}PublicDeleteDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/delete"),n={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"POST",data:n},t)}PublicCreateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/create"),n={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"POST",data:n},t)}PublicGetDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/get"),n={project_id:o.project_id};return this.request({url:i,method:"GET",params:n},t)}PublicGetCertificateDetail(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/get"),n={project_id:o.project_id,certificate_id:o.certificate_id};return this.request({url:i,method:"GET",params:n},t)}PublicGetDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/get"),n={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:n},t)}PublicListVolcanoDomain(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/volcano_domain/list"),n={project_id:o.project_id};return this.request({url:i,method:"GET",params:n},t)}PublicListVolcanoCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/list_volcano"),n={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:n},t)}PublicListProjectTraces(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/traces/list"),n={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:n},t)}PublicDownloadProjectTraces(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/traces/download"),n={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:n},t)}PublicGetProjectMetrics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/metrics/get"),n={project_id:o.project_id,time_range:o.time_range,retention_days:o.retention_days};return this.request({url:i,method:"GET",params:n},t)}PublicDeleteDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/delete"),n={project_id:o.project_id,deploy_unit_id:o.deploy_unit_id};return this.request({url:i,method:"POST",data:n},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"),n={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"GET",params:n},t)}PublicGetMiniProgramPreview(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/mini_program/preview"),n={project_id:o.project_id,app_id:o.app_id,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:n},t)}PublicSubmitAuthCode(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/submit_code"),n={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:n},t)}PublicGetAuthStatus(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/status"),n={project_id:o.project_id,connector_id:o.connector_id,redirect_url:o.redirect_url};return this.request({url:i,method:"POST",data:n},t)}PublicBindAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/bind"),n={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:n},t)}PublicUnbindAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/unbind"),n={project_id:o.project_id,connector_id:o.connector_id};return this.request({url:i,method:"POST",data:n},t)}PublicGetBoundProject(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/get_bound_project"),n={connector_id:o.connector_id,related_id:o.related_id};return this.request({url:i,method:"GET",params:n},t)}PublicUpdateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/update"),n={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:n},t)}PublicGetCertificateQuota(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/quota"),n={project_id:o.project_id};return this.request({url:i,method:"GET",params:n},t)}PublicListDomainCertificates(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/list"),n={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:n},t)}PublicUnpublishConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/unpublish_project"),n={project_id:o.project_id,connector_ids:o.connector_ids};return this.request({url:i,method:"POST",data:n},t)}PublicListConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/list"),n={project_id:o.project_id,project_publish_status:o.project_publish_status};return this.request({url:i,method:"GET",params:n},t)}PublicPublishConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/publish_project"),n={project_id:o.project_id,connector_configs:o.connector_configs};return this.request({url:i,method:"POST",data:n},t)}PublicGetDeployCount(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get_count"),n={project_id:o.project_id};return this.request({url:i,method:"GET",params:n},t)}GetRuntimeLogCount(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/runtime_log/count"),n={project_id:o.project_id};return this.request({url:i,method:"GET",params:n},t)}PublicExchangeFeishuAuthCode(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/auth/exchange_code"),n={project_id:o.project_id,code:o.code,verify_state:o.verify_state};return this.request({url:i,method:"POST",data:n},t)}PublicRevokeFeishuAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/auth/revoke"),n={project_id:o.project_id};return this.request({url:i,method:"POST",data:n},t)}PublicUpdateDefaultDomainPrefix(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/update_default_prefix"),n={project_id:o.project_id,prefix:o.prefix};return this.request({url:i,method:"POST",data:n},t)}PublicFeishuWebhookEvent(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/webhook/event"),n={body:o.body};return this.request({url:i,method:"POST",data:n},t)}PublicCheckCreateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/check_create"),n={project_id:o.project_id};return this.request({url:i,method:"GET",params:n},t)}PublicGetHostedUsageMonthly(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/hosted_usage/monthly"),n={project_id:o.project_id,bill_month:o.bill_month};return this.request({url:i,method:"GET",params:n},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"),n={deploy_history_id:o.deploy_history_id,key:o.key};return this.request({url:i,method:"GET",params:n},t)}PublicGetMPICPStatus(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/mini_program/icp_status"),n={project_id:o.project_id,app_id:o.app_id,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:n},t)}PublicGetOnlineDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get_online"),n={project_id:o.project_id};return this.request({url:i,method:"GET",params:n},t)}}const ld=new cd({});function pd(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function dd(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function ud(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}const _d=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 <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"}]}}).action(async function(e,t){const o=t.getContext(),{projectId:i}=e,n=dd([await ld.PublicListDomainRelated({project_id:i}),"access",e=>e.data,"optionalAccess",e=>e.items])||[];dd([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Fetched domains List successfully")]),dd([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n.map(e=>({id:e.id,domain_host:e.domain_host})))])}),function(t){t.command("add <domain>").description("Add a custom domain to the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add custom domain to project",description:"Bind a custom domain to a specified project. The domain must follow standard format (e.g., example.com). Once bound, the deployed application can be accessed via this domain.",examples:[{desc:"Add domain",cmd:"coze code domain add <domain> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to add (e.g., example.com)"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},domain:{type:"string",description:"Added domain"}}}}},errors:[{code:e.ErrorCode.E1004,name:"INVALID_DOMAIN",desc:"Incorrect domain format",fix:"Please use a standard domain format, e.g., example.com"}]}}).action(async function(t,o,i){const n=i.getContext(),{projectId:s}=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 ld.PublicCreateDomainRelated({project_id:s,domain:t}),ud([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Domain '${t}' added.`)]),ud([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,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:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},domain:{type:"string",description:"Deleted domain"}}}}},errors:[{code:e.ErrorCode.E1004,name:"INVALID_DOMAIN",desc:"Incorrect domain format",fix:"Please use a standard domain format, e.g., example.com"},{code:e.ErrorCode.E3005,name:"DELETE_FAILED",desc:"Failed to remove domain",fix:"Please confirm the domain is bound to the project and you have sufficient permissions"}]}}).action(async function(e,t,o){const i=o.getContext(),{projectId:n}=t;await ld.PublicDeleteDomainRelated({project_id:n,domain:e}),pd([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Domain '${e}' removed.`)]),pd([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({message:`Domain '${e}' removed.`,domain:e})])})}(o)},md={[qp.Pending]:"Pending",[qp.Running]:"Running",[qp.Succeeded]:"Succeeded",[qp.Failed]:"Failed",[qp.Canceled]:"Canceled",[qp.Interrupted]:"Interrupted"},gd=[qp.Succeeded,qp.Failed,qp.Canceled],hd=e=>e&&md[e]||"Unknown";function fd(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}class yd{static __initStatic(){this.INSTANCE=new yd}static getInstance(){return yd.INSTANCE||(yd.INSTANCE=new yd),this.INSTANCE}async pollDeployStatus(t){const{projectId:o,deployHistoryId:i,onBeforePoll:n,onStatusChange:s}=t;let r;for(;;){fd([n,"optionalCall",e=>e()]);const t=fd([await ld.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,fd([s,"optionalCall",e=>e(t)])),gd.includes(a))return t;await new Promise(e=>setTimeout(e,3e3))}}async getLatestDeployHistoryId(e){const{projectId:t}=e;return fd([await ld.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,n=await ld.PublicGetDeployHistory({project_id:o,deploy_history_id:i});if(!fd([n,"optionalAccess",e=>e.data]))throw new e.CozeError(e.ErrorCode.E5000,"Failed to get deploy history data");return n.data}canDeploy(t){return[e.VibeProjectType.AssistantAgent,e.VibeProjectType.GeneralWeb,e.VibeProjectType.App,e.VibeProjectType.Skill,e.VibeProjectType.Agent,e.VibeProjectType.Automation].includes(t)}async getCommitList({projectId:t}){const o=await e.IdeApi.ProxySandboxMessage({ProjectID:t,Method:"repo_version.commit.list",Params:JSON.stringify({project_id:t})});return e.safeJsonParse(o.data,{commits:[]}).commits||[]}}yd.__initStatic();const bd=yd.getInstance();function vd(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function Cd(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function Ad(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function Pd(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function jd(t){const o=t.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)").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)"}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.E3007,name:"MISSING_COMMIT_HASH",desc:"No commits found in the project",fix:"Please commit your changes first before deploying"},{code:e.ErrorCode.E2002,name:"MINIPROGRAM_NOT_AUTHORIZED",desc:"Mini-program AppID not configured",fix:"Please complete the Mini-program AppID configuration in the project settings"},{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Project type is not supported for deployment",fix:"Please confirm the project type and try again with a supported project"}]}}).description("Deploy the project to production environment").action(async function(t,o,i){const n=i.getContext(),{wait:s,commitId:r,tableName:a,encryptDeploy:c}=o,l=Pd([(await e.IdeApi.GetVibeProject({project_id:t})).data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(!bd.canDeploy(l)){const t=`Project type ${Zl(l)} is not supported for deployment`;throw new e.CozeError(e.ErrorCode.E1006,t,{projectType:l})}if(l===e.VibeProjectType.AssistantAgent){const o=await e.axiosInstance$1.post("/api/sandbox/coze_coding/devbox/open_claw/deploy",{project_id:t},{headers:{"content-type":"application/json"}});return Pd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying (AssistantAgent)...")]),void Pd([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({command:"deploy",status:"ok",data:{type:l,data:Pd([o,"optionalAccess",e=>e.data])}})])}let p=r;if(!p){Pd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching latest commit...")]);const e=await bd.getCommitList({projectId:t});p=Pd([e,"optionalAccess",e=>e[0],"optionalAccess",e=>e.id])}if(!p){const o="Missing commitHash: pass --commit-hash <commitHash>";throw new e.CozeError(e.ErrorCode.E3007,o,{projectId:t})}if(l===e.VibeProjectType.WechatMiniProgram){Pd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking Mini-program authorization...")]);if(!Pd([await ld.PublicGetAuthStatus({project_id:t,connector_id:"10000127"}),"access",e=>e.data,"optionalAccess",e=>e.bound_related_id])){const t="Deployment failed, please complete the Mini-program AppID configuration";throw new e.CozeError(e.ErrorCode.E2002,t)}}Pd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking deploy config...")]),await ld.PublicGetDeployConfig({project_id:t,commit_hash:p},{__disableErrorToast:!0});let d="";const u=await ai.ListProjectSecret({env:Xo.dev,project_id:t,with_providers:!0}),_=Pd([u,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],m=Pd([u,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_cred_providers])||[];Pd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Encrypting secrets...")]);d=Pd([await ai.EncryptProjectSecret({project_id:t,project_type:l===e.VibeProjectType.Skill?Yo.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===ei.consumer?ko.consumer3:ko.user_custom2})),...l===e.VibeProjectType.Skill?{cred_providers:m}:{}}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.sealed_secrets])||"",Pd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying...")]);const g={project_id:t,encrypt_env_variable:d,commit_hash:p,encrypt_deploy:l===e.VibeProjectType.Skill?Boolean(c):void 0};if(a&&a.length>0){const o=new Map,i=["knowledge","public"];await Promise.all(i.map(async i=>{((await e.IdeApi.GetSchemaTables({project_id:t,database_env:e.MemoryEnv.develop,schema:i})).table_names||[]).forEach(e=>{o.set(e,i)})})),g.table_sync_configs=a.map(e=>({table_name:e,schema:o.get(e)||"",sync_data:!0}))}const h=Pd([await ld.PublicCreateDeployHistory(g),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_id]);Pd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploy started.")]),s&&h?await bd.pollDeployStatus({projectId:t,deployHistoryId:h,onBeforePoll:()=>{Pd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const o=hd(e.status);Pd([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",i=>i({projectId:t,status:o,domain:Pd([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:h,commitHash:e.commit_hash})])}}):Pd([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({projectId:t,status:hd(qp.Pending),domain:"",deployHistoryId:h,commitHash:p})])});!function(t){t.command("status <projectId>").description("Check deployment status").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest if omitted)").config({help:{brief:"Query project deployment status",description:"Query the deployment status of a specified project. If no deployment history ID is specified, it automatically queries the latest deployment record. Supports viewing deployment progress, results, and error messages.",examples:[{desc:"Query latest deployment status",cmd:"coze code deploy status <projectId>",tags:["[RECOMMENDED]"]},{desc:"Query specific deployment record",cmd:"coze code deploy status <projectId> --deploy-id <deployHistoryId>"},{desc:"Wait for deployment to complete",cmd:"coze code deploy status <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (optional, queries latest if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.E3006,name:"NO_DEPLOYMENT_HISTORY",desc:"No deployment history found for this project",fix:"Please deploy the project first using `coze code deploy <projectId>`"}]}}).action(async function(t,o,i){const n=i.getContext(),{deployId:s}=o,{wait:r}=vd([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=s;if(!a&&(vd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("get latest deployment record...")]),a=await bd.getLatestDeployHistoryId({projectId:t}),!a))throw new e.CozeError(e.ErrorCode.E3006,"No deployment history found for this project");if(r)await bd.pollDeployStatus({projectId:t,deployHistoryId:a,onBeforePoll:()=>{vd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const o=hd(e.status);vd([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",i=>i({projectId:t,status:o,domain:vd([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:a,commitHash:e.commit_hash})])}});else{vd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Querying deployment status...")]);const e=await bd.getDeployHistory({projectId:t,deployHistoryId:a}),o=hd(e.status),i=e.domain_list||[];vd([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",n=>n({projectId:t,status:o,domain:i[0],deployHistoryId:a,commitHash:e.commit_hash})])}})}(o),function(e){e.command("list <projectId>").description("List deployment history for a project").option("--page-size <pageSize>","Number of records per page","10").option("--page-token <pageToken>","Page token for pagination").config({help:{brief:"List project deployment history",description:"List the deployment history of a specified project. Supports pagination to browse historical deployment records including status, commit hash, domains and timestamps.",examples:[{desc:"List deployment history",cmd:"coze code deploy list <projectId>",tags:["[RECOMMENDED]"]},{desc:"List with custom page size",cmd:"coze code deploy list <projectId> --page-size 20"},{desc:"List next page",cmd:"coze code deploy list <projectId> --page-token <token>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},pageSize:{type:"number",required:!1,description:"Number of records per page (default: 10)"},pageToken:{type:"string",required:!1,description:"Page token for pagination"}},output:{type:"array",items:{deploy_history_id:{type:"string",description:"Deployment history ID"},status:{type:"string",description:"Deployment status"},commit_hash:{type:"string",description:"Commit hash"},domain_list:{type:"array",description:"Deployed domains"},created_at:{type:"string",description:"Creation timestamp"}}}}}}).action(async function(e,t,o){const i=o.getContext(),n=Number(t.pageSize)||10,s=(Cd([await ld.PublicListDeployHistory({project_id:e,page_size:n,page_token:t.pageToken}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list])||[]).map(e=>({deploy_history_id:e.deploy_history_id,project_id:e.project_id,status:hd(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}));Cd([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(s)])})}(o),function(t){t.command("fix <projectId>").description("Fix a failed deployment by sending deploy logs to AI").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest failed if omitted)").option("--wait","Wait for fix message response").config({help:{brief:"Fix a failed deployment",description:"Diagnose and fix a failed deployment. Retrieves deploy logs and sends them to AI for analysis and automatic fix. Only works when the deployment status is Failed.",examples:[{desc:"Fix latest failed deployment",cmd:"coze code deploy fix -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Fix a specific deployment",cmd:"coze code deploy fix <projectId> --deploy-id <deployId>"},{desc:"Fix and wait for result",cmd:"coze code deploy fix <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (queries latest failed if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for fix message response"}},output:{type:"object",properties:{deploy_history_id:{type:"string"},status:{type:"string"},message:{type:"string"}}}},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 --oauth"}]}}).action(async function(t,o,i){const n=i.getContext();if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const{deployId:s}=o,{wait:r}=Ad([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=s;if(s||(a=await bd.getLatestDeployHistoryId({projectId:t})),!a)throw new e.CozeError(e.ErrorCode.E5002,`No deploy history found for project ${t}`,{project_id:t});const c=Ad([await ld.PublicGetDeployHistory({project_id:t,deploy_history_id:a}),"optionalAccess",e=>e.data]);if(Ad([c,"optionalAccess",e=>e.status])!==qp.Failed){const t=hd(Ad([c,"optionalAccess",e=>e.status]));throw new e.CozeError(e.ErrorCode.E3009,`Deployment ${a} is not in Failed status (current: ${t}). Only failed deployments can be fixed.`,{deploy_history_id:a,status:Ad([c,"optionalAccess",e=>e.status])})}const l=c.deploy_log_url;if(!l)throw new e.CozeError(e.ErrorCode.E5002,`No deploy log URL found for deployment ${a}`,{deploy_history_id:a});const p=await e.customFetch.fetch(l,{method:"GET"}),d=await p.text();if(!d)throw new e.CozeError(e.ErrorCode.E5002,`Deploy log is empty for deployment ${a}`,{deploy_history_id:a,deploy_log_url:l});const u=`修复以下部署错误:\n${d}`,_=await Ad([n,"access",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!_)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(r){const e=await ip.sendMessage({projectId:t,prompt:u,apiBaseUrl:n.config.apiBaseUrl,accessToken:_,xTTEnv:n.config.xTTEnv,key:`coze-coding-cli:message:${t}`});Ad([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({deploy_history_id:a,status:"fix_sent",message:e.lastAnswerMessage})])}else ip.sendMessageRunTask({projectId:t,prompt:u,apiBaseUrl:n.config.apiBaseUrl,accessToken:_,xTTEnv:n.config.xTTEnv,key:`coze-coding-cli:message:${t}`})})}(o)}function Ed(t){const o=t.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"]}});Ep(o),jd(o),ap(o),Ip(o),_d(o),yc(o),function(t){t.command("preview <projectId>").description("Get deployment preview info for the project").config({help:{brief:"Get project preview URL",description:"Get the sandbox preview URL for the project. Supports AssistantAgent and GeneralWeb project types, returning an accessible preview URL. Sandbox initialization takes 1-3 minutes.",examples:[{desc:"Get preview URL",cmd:"coze code preview <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:{type:"string",description:"Project type"},preview_url:{type:"string",description:"Preview URL"}}},errors:[{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Unsupported project type for CLI preview",fix:"Preview is not available for Agent, Workflow, MiniProgram, Skill, or Automation projects. Use the Web dashboard: https://code.coze.cn"},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Missing required argument: projectId",fix:"Pass <projectId> as the first argument: `coze code preview <projectId>`",example:"coze code preview 123456"}]}}).action(async function(t,o,i){const n=i.getContext();if(!t)throw new e.CozeError(e.ErrorCode.E1000,"Missing projectId: pass <projectId> as argument");const s=cp([await e.IdeApi.GetVibeProject({project_id:t}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r={type:Zl(s)};if(lp.has(s))return void cp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({type:r.type,message:`Project type '${r.type}' does not support CLI preview. Please use the Web dashboard: https://code.coze.cn`})]);const a=await e.IdeApi.InitSandbox({project_id:t});r.preview_url=a.token?`https://${a.project_host}?token=${a.token}`:`https://${a.project_host}`,cp([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: ${r.preview_url}`)]),cp([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(r)])})}(o),cc(o),up(o)}function Sd(i){i.command("upgrade").description("Upgrade Coze CLI to the latest version").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Upgrade CLI to latest version",description:"Check for the latest version of Coze CLI and upgrade if a newer version is available. Detects the package manager used for the original installation (npm/pnpm/yarn) and runs the appropriate global install command.",examples:[{desc:"Upgrade to latest version",cmd:"coze upgrade",tags:["[RECOMMENDED]"]},{desc:"Force check and upgrade",cmd:"coze upgrade --force"},{desc:"Upgrade to a specific tag",cmd:"coze upgrade --tag beta"}],seeAlso:["coze --version"]}}).option("--force","Force upgrade even if already on the latest version").option("--tag <tag>","Specify the dist-tag to upgrade to","latest").action(async(i,n)=>{const s=n.getContext();s||process.exit(e.ExitCode.FAILURE),s.ui.info("Checking for updates...");try{const e=await le(s,!0,i.tag);if(!e.hasUpdate&&!i.force)return void s.ui.success(`You are already on the latest version (${e.currentVersion}).`);e.hasUpdate&&s.ui.info(`New version available: ${t.gray(e.currentVersion)} → ${t.green(e.latestVersion)}`),s.ui.info("Upgrading Coze CLI...");const n=function(){const e=[{pm:"npm",cmd:"npm ls -g @coze/cli --json 2>/dev/null"},{pm:"pnpm",cmd:"pnpm ls -g @coze/cli --json 2>/dev/null"},{pm:"yarn",cmd:"yarn global list --json 2>/dev/null"}];for(const{pm:t,cmd:i}of e)try{if(o.execSync(i,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).includes("@coze/cli"))return t}catch(e){}return"npm"}(),r=function(e,t){switch(e){case"pnpm":return`pnpm add -g @coze/cli@${t}`;case"yarn":return`yarn global add @coze/cli@${t}`;default:return`npm install -g @coze/cli@${t}`}}(n,i.tag);s.ui.verbose(`Using package manager: ${n}`),s.ui.verbose(`Running: ${r}`),o.execSync(r,{stdio:"inherit"});const a=ae();s.ui.success(`Successfully upgraded Coze CLI to ${e.latestVersion}. (was ${e.currentVersion})`),"json"===s.format&&s.response.print({previousVersion:e.currentVersion,currentVersion:a,latestVersion:e.latestVersion,status:"upgraded"})}catch(t){s.ui.error(`Failed to upgrade: ${t.message}`),s.ui.info("You can try upgrading manually with: npm install -g @coze/cli"),process.exit(e.ExitCode.FAILURE)}})}function wd(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 --oauth",tags:["[RECOMMENDED]"]},{desc:"Check current login status",cmd:"coze auth status"},{desc:"Logout and clear credentials",cmd:"coze auth logout"}],seeAlso:["coze organization","coze space"]}});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 --oauth",tags:["[RECOMMENDED]"]}],errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Authentication failed",fix:"Please try again with `coze auth login --oauth`."}]}}).option("--token <PAT>","Login using an access token").option("--oauth","Start browser-based OAuth device authorization flow").action(async function(t,o){const i=o.getContext();if(!i)return void K(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"));await i.auth.login(t);const n=["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 n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}}([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(n.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"}]}}).action(async(t,o)=>{const i=o.getContext();i?await i.auth.logout():K(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 --oauth` to authenticate."}],seeAlso:["coze auth login","coze auth logout"]}}).action(async(t,o)=>{const i=o.getContext();i?await i.auth.status():K(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))})}(t),ic(t),Ed(t),Ma(t),ur(t),gr(t),Ba(t),Va(t),Sd(t),nc()}function kd(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function Td(e,t){return null!=e?e:t()}function Id(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function Rd(e){const t=[];let o=e;for(;o;)o.name()&&t.unshift(o.name()),o=o.parent;return t.join(" ")}function Od(e){return e._args.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ")}const zd=new Set(["--version","--format","--no-color","--config","--org-id","--space-id","--verbose","--debug","--log-file","--man","--schema","--commands"]);function Ld(e){const t=new Map,o=[];let i=e;for(;i;)o.unshift(i),i=i.parent;for(const e of o)for(const o of e.options){const e=o.flags.split(", ").find(e=>e.startsWith("--"));!e||t.has(e)||zd.has(e)||t.set(e,o)}return Array.from(t.values())}function Ud(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}class xd extends v.Command{__init(){this.middlewares=[]}constructor(e){super(e),xd.prototype.__init.call(this),this.helpInformation=()=>{const e=process.argv.slice(2);if(e.includes("--schema"))return`${JSON.stringify(Ud([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=Id([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),o=Rd(e);let i=`@MAN ${o}\n\n`;i+=`NAME\n ${o} — ${Id([t,"optionalAccess",e=>e.brief])||e.description()}\n\n`,i+=`SYNOPSIS\n ${o} ${Od(e)}\n`,Ld(e).forEach(e=>{i+=` [${e.flags}]\n`}),i+="\n",Id([t,"optionalAccess",e=>e.description])&&(i+=`DESCRIPTION\n ${t.description.replace(/\n/g,"\n ")}\n\n`);const n=Ld(e);return n.length>0&&(i+="OPTIONS\n",n.forEach(e=>{const t=e.flags.split(", "),o=t.find(e=>e.startsWith("-")&&!e.startsWith("--"))||"",n=t.find(e=>e.startsWith("--"))||"";i+=` ${o?`${n}, ${o}`:n}\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`})),Id([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"),Id([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"),Id([t,"optionalAccess",e=>e.caveats])&&t.caveats.length>0&&(i+="CAVEATS\n",t.caveats.forEach(e=>{i+=` - ${e}\n`}),i+="\n"),Id([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")?`${function(e){const t=Id([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),o=Rd(e);let i=`@HELP ${o}\n\n`;return Id([t,"optionalAccess",e=>e.brief])?i+=`BRIEF: ${t.brief}\n\n`:i+=`BRIEF: ${e.description()||"No description provided."}\n\n`,e.parent&&"coze"!==e.parent.name()&&(i+=`PARENT: ${Rd(e.parent)}\n\n`),i+=`SYNTAX:\n ${o} ${Od(e)} [options]\n\n`,Id([t,"optionalAccess",e=>e.description])&&(i+=`DESCRIPTION:\n ${t.description.replace(/\n/g,"\n ")}\n\n`),i+="OPTIONS:\n",i+=" Name Type Required Default Description\n",i+=" ─────────────────────────────────────────────────────────\n",e._args.forEach(e=>{const t=`<${e.name()}>`,o=e.required?"Yes":"No",n=void 0!==e.defaultValue?String(e.defaultValue):"-",s=e.description||"";i+=` ${t.padEnd(16)} ${"string".padEnd(10)} ${o.padEnd(4)} ${n.padEnd(10)} ${s}\n`}),Ld(e).forEach(e=>{const t=e.flags.split(", "),o=t.find(e=>e.startsWith("-")&&!e.startsWith("--"))||"",n=t.find(e=>e.startsWith("--"))||"",s=o?`${n}, ${o}`:n;let r="string";e.isBoolean()&&(r="flag");const a=e.mandatory?"Yes":"No",c=void 0!==e.defaultValue?String(e.defaultValue):"-",l=e.description||"";i+=` ${s.padEnd(16)} ${r.padEnd(10)} ${a.padEnd(4)} ${c.padEnd(10)} ${l}\n`}),i+="\n",Id([t,"optionalAccess",e=>e.enums])&&(i+="ENUMS:\n",Object.keys(t.enums).forEach(e=>{i+=` --${e}:\n`;const o=Td(Id([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),()=>({}));Object.keys(o).forEach(e=>{i+=` ${e.padEnd(12)} ${o[e]}\n`})}),i+="\n"),Id([t,"optionalAccess",e=>e.examples])&&t.examples.length>0&&(i+="COMMON EXAMPLES:\n",t.examples.forEach(e=>{const t=e.tags?` ${e.tags.join(" ")}`:"";i+=` #${t} ${e.desc}\n ${e.cmd}\n\n`})),Id([t,"optionalAccess",e=>e.errors])&&t.errors.length>0&&(i+="COMMON ERRORS:\n",i+=" CODE NAME DESCRIPTION FIX\n",t.errors.slice(0,5).forEach(e=>{i+=` ${e.code.padEnd(6)} ${e.name.padEnd(17)} ${e.desc.padEnd(30)} ${e.fix}\n`}),i+="\n"),Id([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`:`${function(e){const t=Id([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),o=Rd(e);let i=`@USAGE ${o}\n\n`;Id([t,"optionalAccess",e=>e.brief])?i+=`BRIEF: ${t.brief}\n\n`:i+=`BRIEF: ${e.description()||"No description provided."}\n\n`,i+=`SYNTAX:\n ${o} ${Od(e)} [options]\n\n`,e.commands.length>0&&(i+="ACTIONS:\n",e.commands.forEach(e=>{if(!e._hidden){const t=Id([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help,"optionalAccess",e=>e.brief])||e.description()||"";i+=` ${e.name().padEnd(10)} ${t}\n`}}),i+="\n"),Id([t,"optionalAccess",e=>e.examples])&&t.examples.length>0&&(i+="EXAMPLES:\n",t.examples.slice(0,5).forEach(e=>{i+=` # ${e.desc}\n ${e.cmd}\n\n`}));if(Id([t,"optionalAccess",e=>e.enums])){const e=Object.keys(t.enums).filter(e=>Object.keys(Td(Id([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),()=>({}))).length<=7);e.length>0&&(i+="ENUMS:\n",e.forEach(e=>{const o=Object.keys(Td(Id([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),()=>({}))).join(" | ");i+=` --${e}: ${o}\n`}),i+="\n")}return i.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 xd(e);return this.context&&t.setContext(this.context),t}action(e){return super.action(async(...t)=>{const o=this.getContext();let i={},n=[],s=this;if(t.length>0){const e=t[t.length-1];e instanceof xd&&(s=e),t.length>=2&&(i=t[t.length-2],n=t.slice(0,t.length-2))}if(o&&(i&&(o.options=i),n&&(o.args=n),s)){o.commandName=s.name();const e=Ud([s,"access",e=>e.getConfig,"optionalCall",e=>e()]);e&&(o.commandConfig=e),s.setContext(o)}if(this.middlewares.length>0&&o){const i=no(this.middlewares);await i(o,async()=>{await e.apply(this,t)})}else await e.apply(this,t)})}}function Dd(e){let t,o=e[0],i=1;for(;i<e.length;){const n=e[i],s=e[i+1];if(i+=2,("optionalAccess"===n||"optionalCall"===n)&&null==o)return;"access"===n||"optionalAccess"===n?(t=o,o=s(o)):"call"!==n&&"optionalCall"!==n||(o=s((...e)=>o.call(t,...e)),t=void 0)}return o}function Bd(e){e.exitOverride(),e.outputError=()=>{},e.commands.forEach(e=>Bd(e))}async function qd(t){const o=new xd;o.name("coze").description("Coze Coding CLI").version(se,"-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:{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"}]}}),wd(o),await async function(e){e.completionInstalled||process.stdout.isTTY}(t.config),function(e,t,o){const i=new Set;e.setContext(o),function e(n){i.has(n)||(i.add(n),n.setContext(o),t.forEach(e=>n.use(e)),n.commands.forEach(t=>{const o=kd([n,"access",e=>e.getConfig,"optionalCall",e=>e()]),i=kd([t,"access",e=>e.getConfig,"optionalCall",e=>e()]);t.setConfig({...o,...i}),e(t)}))}(e)}(o,[Oi,ar],t),process.on("uncaughtException",e=>{K(e,t)}),process.on("unhandledRejection",e=>{K(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")),Bd(o);try{await o.parseAsync(t.argv,{from:"user"})}catch(s){const r=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},n=t(e,o.commandName);n&&(i=n)}let n=e;for(const e of o.argv){if(e.startsWith("-"))break;const t=n.commands.find(t=>t.name()===e);t&&(n=t,i=n)}return i}(o,s,t);"commander.helpDisplayed"!==s.code&&"commander.help"!==s.code&&"commander.version"!==s.code||process.exit(e.ExitCode.SUCCESS);const a=Dd([r,"optionalAccess",e=>e.getConfig,"optionalCall",e=>e()]),c=Dd([o,"optionalAccess",e=>e.getConfig,"optionalCall",e=>e()]);if(t.commandConfig=(n=()=>c,null!=(i=a)?i:n()),"commander.unknownOption"===s.code){const o=V(new e.CozeError(e.ErrorCode.E1100,s.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),process.exit(e.exitCodeForError(o.code))}if("commander.unknownCommand"===s.code){const o=V(new e.CozeError(e.ErrorCode.E1101,s.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),process.exit(e.exitCodeForError(o.code))}if("commander.missingArgument"===s.code){const o=V(new e.CozeError(e.ErrorCode.E1102,s.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),"json"!==t.format&&process.stderr.write(`\n${r.helpInformation()}`),process.exit(e.exitCodeForError(o.code))}if("commander.missingMandatoryOptionValue"===s.code||"commander.optionMissingArgument"===s.code){const o=V(new e.CozeError(e.ErrorCode.E1103,s.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(o),"json"!==t.format&&process.stderr.write(`\n${r.helpInformation()}`),process.exit(e.exitCodeForError(o.code))}K(s,t)}var i,n}(async function(){const e=process.argv.slice(2),{globalOptions:t}=function(e){const t={};let o;const i=[];let n=!1;for(let s=0;s<e.length;s++){const r=e[s];if("--help"!==r&&"-h"!==r)if("--version"!==r&&"-v"!==r)if("--output"!==r){if("--format"===r){const o=e[++s];"json"!==o&&"text"!==o||(t.format=o);continue}"--no-color"!==r?"--config"!==r?"--org-id"!==r?"--space-id"!==r?"--verbose"!==r?"--debug"!==r?"--log-file"!==r?"--print-logs"!==r?n||r.startsWith("-")?i.push(r):(o=r,n=!0):t.printLogs=!0:t.logFile=e[++s]:t.debug=!0:t.verbose=!0:t.spaceId=e[++s]:t.orgId=e[++s]:t.config=e[++s]:t.noColor=!0}else t.output=e[++s];else t.version=!0;else t.help=!0}return{globalOptions:t,commandName:o,commandArgs:i}}(e),o=function(e){const t=Ri(e.cwd,()=>process.cwd()),o=Ri(e.env,()=>process.env),i=e.globalOptions||{};i.noColor&&(process.env.NO_COLOR="1");let n="text";i.format&&(n=i.format);const s={...e.config};i.orgId&&(s.organizationId=i.orgId),i.spaceId&&(s.spaceId=i.spaceId);const r=new Ii({format:"text",logFile:i.logFile,printToStderr:i.printLogs});let a="info";i.debug?a="debug":i.verbose&&(a="verbose");const c=new Si(r,n,a),l=new wi({format:n}),p={cwd:t,env:o,argv:e.argv,config:s,format:n,log:r,ui:c,response:l,globalOptions:i,auth:void 0};return p.auth=new li(p),p}({argv:e,config:await te(t.config),globalOptions:t}),i=no([Zt,io,Qt,pe]);await i(o,async()=>{await qd(o)})})().catch(e=>{K(e,void 0),process.exitCode=1});
16
+ ***************************************************************************** */var Le=function(){return Le=Object.assign||function(e){for(var t,i=1,o=arguments.length;i<o;i++)for(var s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},Le.apply(this,arguments)};function je(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var o,s,n=i.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(e){s={error:e}}finally{try{o&&!o.done&&(i=n.return)&&i.call(n)}finally{if(s)throw s.error}}return a}function Ue(e,t,i){if(2===arguments.length)for(var o,s=0,n=t.length;s<n;s++)!o&&s in t||(o||(o=Array.prototype.slice.call(t,0,s)),o[s]=t[s]);return e.concat(o||Array.prototype.slice.call(t))}var Be=function(){return{}};function xe(e){return e}function qe(e){return"object"==typeof e&&null!==e}var De=Object.prototype;function Me(e){return"[object Array]"===De.toString.call(e)}function Ge(e){return"number"==typeof e}function Ne(e){return"string"==typeof e}function Fe(e,t){if(!Me(e))return!1;if(0===e.length)return!1;for(var i=0;i<e.length;){if(e[i]===t)return!0;i++}return!1}var $e=function(e,t){if(!Me(e))return e;var i=e.indexOf(t);if(i>=0){var o=e.slice();return o.splice(i,1),o}return e};function Ve(e){try{return Ne(e)?e:JSON.stringify(e)}catch(e){return"[FAILED_TO_STRINGIFY]:"+String(e)}}var We="".padStart?function(e,t){return void 0===t&&(t=8),e.padStart(t," ")}:function(e){return e},He=0,Ke=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,Ue(["[SDK]",Date.now(),We(""+He++)],je(e),!1))},Je=0,Qe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,Ue(["[SDK]",Date.now(),We(""+Je++)],je(e),!1))},Ze=function(e){return Math.random()<Number(e)},Ye=function(e,t){return e<Number(t)},Xe=function(e){return function(t){for(var i=t,o=0;o<e.length&&i;o++)try{i=e[o](i)}catch(e){Ke(e)}return i}};function et(){var e=function(){for(var e=new Array(16),t=0,i=0;i<16;i++)3&i||(t=4294967296*Math.random()),e[i]=t>>>((3&i)<<3)&255;return e}();return e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){for(var t=[],i=0;i<256;++i)t[i]=(i+256).toString(16).substr(1);var o=0,s=t;return[s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],"-",s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]],s[e[o++]]].join("")}(e)}var tt=["init","start","config","beforeDestroy","provide","beforeReport","report","beforeBuild","build","beforeSend","send","beforeConfig"];function it(e){var t,i,o=e.builder,s=e.createSender,n=e.createDefaultConfig,a=e.createConfigManager,r=e.userConfigNormalizer,c=e.initConfigNormalizer,d=e.validateInitConfig,p={};tt.forEach(function(e){return p[e]=[]});var l=!1,u=!1,_=!1,m=[],g=[],h=function(){var e=!1,t={},i=function(e){e.length&&e.forEach(function(e){try{e()}catch(e){}}),e.length=0},o=function(e){t[e]&&t[e].forEach(function(e){i(e[1])}),t[e]=void 0};return{set:function(o,s,n){t[o]?t[o].push([s,n]):t[o]=[[s,n]],e&&i(n)},has:function(e){return!!t[e]},remove:o,removeByEvType:function(e){Object.keys(t).forEach(function(o){t[o]&&t[o].forEach(function(t){t[0]===e&&i(t[1])})})},clear:function(){e=!0,Object.keys(t).forEach(function(e){o(e)})}}}(),f={getBuilder:function(){return o},getSender:function(){return t},getPreStartQueue:function(){return m},init:function(e){if(l)Qe("already inited");else{if(!(e&&qe(e)&&d(e)))throw new Error("invalid InitConfig, init failed");var o=n(e);if(!o)throw new Error("defaultConfig missing");var r=c(e);if((i=a(o)).setConfig(r),i.onChange(function(){y("config")}),!(t=s(i.getConfig())))throw new Error("sender missing");l=!0,y("init",!0)}},set:function(e){l&&e&&qe(e)&&(y("beforeConfig",!1,e),null==i||i.setConfig(e))},config:function(e){if(l)return e&&qe(e)&&(y("beforeConfig",!1,e),null==i||i.setConfig(r(e))),null==i?void 0:i.getConfig()},provide:function(e,t){Fe(g,e)?Qe("cannot provide "+e+", reserved"):(f[e]=t,y("provide",!1,e))},start:function(){l&&(u||null==i||i.onReady(function(){u=!0,y("start",!0),function(e){var t=e.getPreStartQueue();t.forEach(function(t){return e.build(t)}),t.length=0}(f)}))},report:function(e){if(e){var t=Xe(p.beforeReport)(e);if(t){var i=Xe(p.report)(t);i&&(u?this.build(i):function(e,t,i){if(t.push(i),!(t.length<500)){var o=t.splice(0,50);e.savePreStartDataToDb&&e.savePreStartDataToDb(o)}}(f,m,i))}}},build:function(e){if(u){var t=Xe(p.beforeBuild)(e);if(t){var i=o.build(t);if(i){var s=Xe(p.build)(i);s&&this.send(s)}}}},send:function(e){if(u){var i=Xe(p.beforeSend)(e);i&&(t.send(i),y("send",!1,i))}},destroy:function(){h.clear(),_=!0,m.length=0,y("beforeDestroy",!0)},on:function(e,t){if("init"===e&&l||"start"===e&&u||"beforeDestroy"===e&&_)try{t()}catch(e){}else p[e]&&p[e].push(t)},off:function(e,t){p[e]&&(p[e]=$e(p[e],t))},destroyAgent:h};return g=Object.keys(f),f;function y(e,t){void 0===t&&(t=!1);for(var i=[],o=2;o<arguments.length;o++)i[o-2]=arguments[o];p[e].forEach(function(e){try{e.apply(void 0,Ue([],je(i),!1))}catch(e){}}),t&&(p[e].length=0)}}var ot=function(e){var t=function(){var e={},t={},i={set:function(o,s){return e[o]=s,t[o]=Ve(s),i},merge:function(o){return e=Le(Le({},e),o),Object.keys(o).forEach(function(e){t[e]=Ve(o[e])}),i},delete:function(o){return delete e[o],delete t[o],i},clear:function(){return e={},t={},i},get:function(e){return t[e]},toString:function(){return Le({},t)}};return i}();e.provide("context",t),e.on("report",function(e){return e.extra||(e.extra={}),e.extra.context=t.toString(),e})};var st=function(){return Date.now()};var nt=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=function(e){if(e)return e.__SLARDAR_REGISTRY__||(e.__SLARDAR_REGISTRY__={Slardar:{plugins:[],errors:[],subject:{}}}),e.__SLARDAR_REGISTRY__.Slardar}(function(){if("object"==typeof window&&qe(window))return window}());i&&(i.errors||(i.errors=[]),i.errors.push(e))},at="custom",rt=function(e){var t=function(i){var o=function(e){if(e&&qe(e)&&e.name&&Ne(e.name)){var t={name:e.name,type:"event"};if("metrics"in e&&qe(e.metrics)){var i=e.metrics,o={};for(var s in i)Ge(i[s])&&(o[s]=i[s]);t.metrics=o}if("categories"in e&&qe(e.categories)){var n=e.categories,a={};for(var s in n)a[s]=Ve(n[s]);t.categories=a}return"attached_log"in e&&Ne(e.attached_log)&&(t.attached_log=e.attached_log),t}}(i);if(o){var s=function(e){var t;if("object"==typeof window&&window.__perfsee__){var i={};return null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,i,e),i.stack}}(t);s&&(o.stacks=s),e.report({ev_type:at,payload:o,extra:{timestamp:st()}})}};e.provide("sendEvent",t),e.provide("sendLog",function(t){var i=function(e){if(e&&qe(e)&&e.content&&Ne(e.content)){var t={content:Ve(e.content),type:"log",level:"info"};if("level"in e&&(t.level=e.level),"extra"in e&&qe(e.extra)){var i=e.extra,o={},s={};for(var n in i)Ge(i[n])?o[n]=i[n]:s[n]=Ve(i[n]);t.metrics=o,t.categories=s}return"attached_log"in e&&Ne(e.attached_log)&&(t.attached_log=e.attached_log),t}}(t);i&&e.report({ev_type:at,payload:i,extra:{timestamp:st()}})})},ct=function(e,t){var i=e.common||{};return i.sample_rate=t,e.common=i,e},dt=function(e,t,i,o,s){return e?(n=s(o,t),function(){return n}):function(){return i(t)};var n},pt=function(e,t,i,o){var s=function(e,t,i){for(var o,s=je(t.split(".")),n=s[0],a=s.slice(1);e&&a.length>0;)e=e[n],n=(o=je(a))[0],a=o.slice(1);if(e)return i(e,n)}(e,t,function(e,t){return e[t]});return void 0!==s&&function(e,t,i){switch(i){case"eq":return Fe(t,e);case"neq":return!Fe(t,e);case"gt":return e>t[0];case"gte":return e>=t[0];case"lt":return e<t[0];case"lte":return e<=t[0];case"regex":return Boolean(e.match(new RegExp(t.join("|"))));case"not_regex":return!e.match(new RegExp(t.join("|")));default:return!1}}(s,function(e,t){return e.map(function(e){switch(t){case"number":return Number(e);case"boolean":return"1"===e;default:return String(e)}})}(o,"boolean"==typeof s?"bool":Ge(s)?"number":"string"),i)},lt=function(e,t){try{return"rule"===t.type?pt(e,t.field,t.op,t.values):"and"===t.type?t.children.every(function(t){return lt(e,t)}):t.children.some(function(t){return lt(e,t)})}catch(e){return nt(e),!1}},ut=function(e,t,i,o,s){if(!t)return xe;var n=t.sample_rate,a=t.include_users,r=t.sample_granularity,c=t.rules,d=t.r,p=void 0===d?Math.random():d;if(Fe(a,e))return function(e){return ct(e,1)};var l="session"===r,u=dt(l,n,i,p,o),_=function(e,t,i,o,s,n){var a={};return Object.keys(e).forEach(function(r){var c=e[r],d=c.enable,p=c.sample_rate,l=c.conditional_sample_rules;d?(a[r]={enable:d,sample_rate:p,effectiveSampleRate:p*i,hit:dt(t,p,o,s,n)},l&&(a[r].conditional_hit_rules=l.map(function(e){var a=e.sample_rate,r=e.filter;return{sample_rate:a,hit:dt(t,a,o,s,n),effectiveSampleRate:a*i,filter:r}}))):a[r]={enable:d,hit:function(){return!1},sample_rate:0,effectiveSampleRate:0}}),a}(c,l,n,i,p,o);return function(e){var t;if(!u())return l&&s[0](),!1;if(!(e.ev_type in _))return ct(e,n);if(!_[e.ev_type].enable)return l&&s[1](e.ev_type),!1;if(null===(t=e.common)||void 0===t?void 0:t.sample_rate)return e;var i=_[e.ev_type],o=i.conditional_hit_rules;if(o)for(var a=0;a<o.length;a++)if(lt(e,o[a].filter))return!!o[a].hit()&&ct(e,o[a].effectiveSampleRate);return i.hit()?ct(e,i.effectiveSampleRate):((!o||!o.length)&&l&&s[1](e.ev_type),!1)}},_t={build:function(e){return{ev_type:e.ev_type,payload:e.payload,common:Le(Le({},e.extra||{}),e.overrides||{})}}},mt={sample_rate:1,include_users:[],sample_granularity:"session",rules:{}};function gt(e){var t,i;try{for(var o=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],o=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&o>=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(["userId","deviceId","sessionId","env"]),s=o.next();!s.done;s=o.next()){var n=s.value;e[n]||delete e[n]}}catch(e){t={error:e}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}return e}function ht(e){return gt(Le({},e))}function ft(e){return qe(e)&&"bid"in e&&"transport"in e}function yt(e){return gt(Le({},e))}var bt=function(e,t){return void 0===t&&(t="/monitor_browser/collect/batch/"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},vt=function(e,t){return void 0===t&&(t="/monitor_web/settings/browser-settings"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Ct=function(e){var t,i,o=e,s={},n=Be,a=Be;return{getConfig:function(){return o},setConfig:function(e){return s=Le(Le({},s),e||{}),r(),t||(t=e,o.useLocalConfig||!o.bid?(i={},n()):function(e,t,i,o){if(!e.get)return o({});e.get({withCredentials:!0,url:vt(t)+"?bid="+i+"&store=1",success:function(e){o(e.data||{})},fail:function(){o({sample:{sample_rate:.001}})}})}(o.transport,o.domain,o.bid,function(e){i=function(e){if(!e)return{};var t=e.sample,i=e.timestamp,o=e.quota_rate,s=void 0===o?1:o;if(!t)return{};var n=t.sample_rate,a=t.sample_granularity,r=void 0===a?"session":a,c=t.include_users,d=t.rules;return{sample:{include_users:c,sample_rate:n*s,sample_granularity:r,rules:(void 0===d?[]:d).reduce(function(e,t){var i=t.name,o=t.enable,s=t.sample_rate,n=t.conditional_sample_rules;return e[i]={enable:o,sample_rate:s,conditional_sample_rules:n},e},{})},serverTimestamp:i}}(e),r(),n()})),o},onChange:function(e){a=e},onReady:function(e){n=e,i&&n()}};function r(){var t=Le(Le(Le({},e),i||{}),s);t.sample=St(St(e.sample,null==i?void 0:i.sample),s.sample),o=t,a()}};function St(e,t){if(!e||!t)return e||t;var i=Le(Le({},e),t);return i.include_users=Ue(Ue([],je(e.include_users||[]),!1),je(t.include_users||[]),!1),i.rules=Ue(Ue([],je(Object.keys(e.rules||{})),!1),je(Object.keys(t.rules||{})),!1).reduce(function(i,o){var s,n;return o in i||(o in(e.rules||{})&&o in(t.rules||{})?(i[o]=Le(Le({},e.rules[o]),t.rules[o]),i[o].conditional_sample_rules=Ue(Ue([],je(e.rules[o].conditional_sample_rules||[]),!1),je(t.rules[o].conditional_sample_rules||[]),!1)):i[o]=(null===(s=e.rules)||void 0===s?void 0:s[o])||(null===(n=t.rules)||void 0===n?void 0:n[o])),i},{}),i}var Pt=function(e){e.on("report",function(t){return function(e,t){var i=t||{},o=i.version,s=i.name,n={url:"",protocol:"",domain:"",path:"",query:"",timestamp:Date.now(),sdk_version:o||"2.1.8",sdk_name:s||"SDK_BASE"};return Le(Le({},e),{extra:Le(Le({},n),e.extra||{})})}(t,e.config())})},Et=function(e){e.on("beforeBuild",function(t){return function(e,t){var i={};return i.bid=t.bid,i.pid=t.pid,i.view_id=t.viewId,i.user_id=t.userId,i.device_id=t.deviceId,i.session_id=t.sessionId,i.release=t.release,i.env=t.env,Le(Le({},e),{extra:Le(Le({},i),e.extra||{})})}(t,e.config())})};var Tt=function(e){return{bid:"",pid:"",viewId:(t="_",t+"_"+Date.now()),userId:et(),deviceId:et(),sessionId:et(),domain:"mon.zijieapi.com",release:"",env:"production",sample:mt,plugins:{},transport:{get:Be,post:Be},useLocalConfig:!1};var t},At=function(e){var t=void 0===e?{}:e,i=t.createSender,o=void 0===i?function(e){return function(e){return Oe(e)}({size:20,endpoint:bt(e.domain),transport:e.transport})}:i,s=t.builder,n=void 0===s?_t:s,a=t.createDefaultConfig,r=it({validateInitConfig:ft,initConfigNormalizer:ht,userConfigNormalizer:yt,createSender:o,builder:n,createDefaultConfig:void 0===a?Tt:a,createConfigManager:Ct});return ot(r),Et(r),Pt(r),function(e){e.on("init",function(){var t=[],i=function(i){i.forEach(function(i){var o=i.name;Fe(t,o)||(t.push(o),i.setup(e),e.destroyAgent.set(o,o,[function(){t=$e(t,o),i.tearDown&&i.tearDown()}]))})};e.provide("applyIntegrations",i);var o=e.config();o&&o.integrations&&i(o.integrations)})}(r),function(e){try{"object"==typeof window&&qe(window)&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__.push(e)}catch(e){}}(r),r},kt=function(e){void 0===e&&(e={});var t=At(e);return function(e){e.on("start",function(){var t=e.config(),i=t.userId,o=t.sample,s=ut(i,o,Ze,Ye,[function(){e.destroy()},function(t){e.destroyAgent.removeByEvType(t)}]);e.on("build",s)})}(t),rt(t),t}();const wt=Ie("slardar:transport"),Rt=()=>{};function zt(e){const{url:t,method:i,data:o,success:s=Rt,fail:n=Rt,getResponseText:a=Rt}=e;if(wt("Making %s request to %s",i,t),o&&wt("Request data: %s",o.slice(0,200)),!t||"string"!=typeof t){const e=new Error(`Invalid URL: ${t}`);return wt("Invalid URL provided: %o",t),void n(e)}try{const e=new URL(t);wt("Parsed URL - protocol: %s, hostname: %s, port: %s, path: %s",e.protocol,e.hostname,e.port,e.pathname);const r="https:"===e.protocol,c=(r?p.request:d.request)({hostname:e.hostname,port:e.port,path:e.pathname+e.search,method:i,headers:{"Content-Type":"application/json",...o&&{"Content-Length":Buffer.byteLength(o)}}},e=>{wt("Response callback triggered: status=%s",e.statusCode);let t="";e.on("data",e=>{wt("Response data chunk received: %s bytes",e.length),t+=e.toString()}),e.on("end",()=>{wt("Response end event fired"),wt("Response received: status=%s, body=%s",e.statusCode,t.slice(0,200)),a(t);try{if(e.statusCode&&e.statusCode>=400)wt("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);wt("Request succeeded"),s(e)}else wt("Request succeeded with empty response"),s({})}catch(e){wt("Failed to parse response: %s",e.message),n(e)}})});c.on("error",e=>{wt("Request error: %s",e.message),n(e)}),c.on("timeout",()=>{wt("Request timeout"),c.destroy(),n(new Error("Request timeout"))}),o&&c.write(o),c.end()}catch(e){wt("Exception during request: %s",e.message),n(e)}}function It(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Ot=Ie("slardar:reporter");class Lt{constructor(){Lt.prototype.__init.call(this),Lt.prototype.__init2.call(this)}__init(){this.initialized=!1}__init2(){this.client=kt}setup(e){var t,i;if(this.initialized)Ot("Already initialized, skipping setup");else try{Ot("Initializing Slardar with config:",{bid:e.bid,release:e.release,env:e.env,userId:e.userId,projectId:e.projectId});const o={get(e){wt("Transport GET called: %s",e.url),zt({method:"GET",...e})},post({url:e,data:t}){wt("Transport POST called: %s",e),zt({method:"POST",url:e,data:t?"string"==typeof t?t:JSON.stringify(t):void 0})}};this.client.init({bid:e.bid,transport:o,userId:e.userId,pid:e.projectId,deviceId:e.deviceId,sessionId:e.sessionId,release:e.release,env:e.env,name:e.name,useLocalConfig:(t=e.useLocalConfig,i=()=>!1,null!=t?t:i()),domain:e.domain,sample:{sample_rate:1,include_users:[],sample_granularity:"session",rules:{}}}),this.client.on("send",e=>{Ot("send hook called for event: %s",It([e,"optionalAccess",e=>e.ev_type])||"unknown")}),this.client.start(),this.initialized=!0,Ot("Slardar initialized successfully")}catch(e){Ot("Failed to initialize:",e)}}ensureInitialized(){return!!this.initialized||(Ot("Not initialized, call setup() first"),!1)}sendEvent(e,t,i){if(this.ensureInitialized())try{Ot("Sending event:",{name:e,metrics:t,categories:i});const o=t?Object.fromEntries(Object.entries(t).filter(([,e])=>void 0!==e)):void 0,s=i?Object.fromEntries(Object.entries(i).filter(([,e])=>void 0!==e)):void 0;It([this,"access",e=>e.client,"access",e=>e.sendEvent,"optionalCall",t=>t({name:e,metrics:o,categories:s})])}catch(e){Ot("Failed to send event:",e)}}sendLog(e,t,i){if(this.ensureInitialized())try{Ot("Sending log:",{level:e,message:t,extra:i}),this.sendEvent("cli_log",void 0,{level:e,message:t,...i})}catch(e){Ot("Failed to send log:",e)}}reportError(e,t,i){if(this.ensureInitialized())try{const o={ev_type:"js_error",payload:{error:{name:e.name,message:e.message,stack:e.stack},breadcrumbs:[],extra:t,source:i||{type:"manual"}}};Ot("Reporting JS error:",{name:e.name,message:e.message.slice(0,100),stack:It([e,"access",e=>e.stack,"optionalAccess",e=>e.slice,"call",e=>e(0,200)]),extra:t,source:i}),this.client.report(o),Ot("JS error reported successfully")}catch(e){Ot("Failed to report error:",e)}}setContext(e,t){this.ensureInitialized()&&It([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.set,"call",i=>i(e,t)])}mergeContext(e){this.ensureInitialized()&&(Ot("Merging context:",e),It([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.merge,"call",t=>t(e)]))}deleteContext(e){this.ensureInitialized()&&It([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.delete,"call",t=>t(e)])}clearContext(){this.ensureInitialized()&&It([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.clear,"call",e=>e()])}updateConfig(e){if(this.ensureInitialized())try{Ot("Updating config:",e),this.client.config({userId:e.userId,release:e.release,sessionId:e.sessionId,env:e.env})}catch(e){Ot("Failed to update config:",e)}}async flush(e=1500){this.ensureInitialized()&&(Ot("Flushing Slardar data..."),It([this,"access",e=>e.client,"access",e=>e.getSender,"optionalCall",e=>e(),"optionalAccess",e=>e.flush,"call",e=>e()]),Ot("Waiting %dms for events to be sent...",e),await new Promise(t=>setTimeout(t,e)),Ot("Slardar data flushed"))}getRawClient(){return this.client}}const jt=new Lt;function Ut(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Bt="cli_start",xt="cli_command",qt="cli_command_complete",Dt="cli_error",Mt="network_request",Gt="file_operation",Nt={cliStart:e=>({name:Bt,metrics:{duration:0,...e}}),cliCommand:(e,t)=>({name:xt,categories:{command:e,args:Ut([t,"optionalAccess",e=>e.args]),status:"running",...Ut([t,"optionalAccess",e=>e.categories])},metrics:Ut([t,"optionalAccess",e=>e.metrics])}),cliCommandComplete:(e,t,i,o)=>({name:qt,categories:{command:e,args:Ut([o,"optionalAccess",e=>e.args]),status:t?"success":"fail",...Ut([o,"optionalAccess",e=>e.categories])},metrics:{duration:i,...Ut([o,"optionalAccess",e=>e.errorCode])&&{errorCode:o.errorCode}}}),networkRequest:(e,t)=>({name:Mt,categories:{url:e,method:Ut([t,"optionalAccess",e=>e.method])||"GET",statusCode:Ut([t,"optionalAccess",e=>e.statusCode,"optionalAccess",e=>e.toString,"call",e=>e()]),status:Ut([t,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:Ut([t,"optionalAccess",e=>e.duration])}}),fileOperation:(e,t,i)=>({name:Gt,categories:{operation:e,filePath:t,status:Ut([i,"optionalAccess",e=>e.success])?"success":"fail"},metrics:{duration:Ut([i,"optionalAccess",e=>e.duration]),fileSize:Ut([i,"optionalAccess",e=>e.fileSize])}}),cliError:(e,t)=>({name:Dt,categories:{errorName:e.name,errorMessage:e.message,stack:e.stack||"",...t},metrics:{errorCode:1}})};function Ft(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function $t(e){return(...t)=>{try{const i=e(...t);return i instanceof Promise?i.catch(()=>{}):i}catch(e){}}}const Vt=$t(()=>{var e,t;jt.setup({bid:"coze_cli",release:ne,env:"production",userId:process.env.USER||"",useLocalConfig:!1,domain:"mon.zijieapi.com"}),jt.mergeContext({platform:process.platform,callerPlatform:(e=process.env.COZE_CLI_PLATFORM,t=()=>"unknown",null!=e?e:t()),nodeVersion:process.version,cliVersion:ne})}),Wt=$t(e=>{const t=Nt.cliCommand(e);jt.sendEvent(t.name,t.metrics,t.categories)}),Ht=$t((e,t,i,o)=>{const s=Nt.cliCommandComplete(e,t,i,{errorCode:Ft([o,"optionalAccess",e=>e.errorCode])});jt.sendEvent(s.name,s.metrics,s.categories)}),Kt=$t((e,t)=>{jt.reportError(e,t,{type:"cli",data:t})}),Jt=$t(async()=>{await jt.flush()});async function Qt(e,t){if(e.config.disableTelemetry)return void await t();Vt();const i=function(e){if(e.commandName)return e.commandName;const t=[];for(const i of e.argv){if(i.startsWith("-"))break;t.push(i)}return t.join(" ")||"unknown"}(e);Wt(i);const o=Date.now();let s,n=!0;try{await t()}catch(e){throw n=!1,s=e instanceof Error?e:new Error(String(e)),e}finally{const e=Date.now()-o;try{n?Ht(i,!0,e):(s&&Kt(s,{command:i}),Ht(i,!1,e)),await Jt()}catch(e){}}}async function Zt(t,i){const o=await t.auth.getValidAccessToken();e.axiosInstance.defaults.baseURL=t.config.apiBaseUrl;const s=`Bearer ${o}`;e.axiosInstance.defaults.headers.Authorization=s,e.axiosInstance.defaults.headers["x-request-from-coze-cli"]="1",e.customFetch.setHeaders({Authorization:s,"x-request-from-coze-cli":"1"}),t.config.xTTEnv&&(e.axiosInstance.defaults.headers["x-use-ppe"]="1",e.axiosInstance.defaults.headers["x-tt-env"]=t.config.xTTEnv,e.customFetch.setHeaders({"x-use-ppe":"1","x-tt-env":t.config.xTTEnv})),await i()}function Yt(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}var Xt;!function(e){e.AUTHORIZATION_PENDING="authorization_pending";e.SLOW_DOWN="slow_down";e.ACCESS_DENIED="access_denied";e.EXPIRED_TOKEN="expired_token"}(Xt||(Xt={}));const ei=e=>new Promise(t=>setTimeout(t,e)),ti=e.createRequestClient({baseURL:"https://api.coze.com",useDefaultPlugins:!0,plugins:[{name:"oauth-error-handler",onError:t=>{if(e.isHttpError(t))throw t;const i=Yt([t,"access",e=>e.response,"optionalAccess",e=>e.data])||{},o=i.error_description||i.error||t.message;throw new e.HttpError(o,{status:Yt([t,"access",e=>e.response,"optionalAccess",e=>e.status]),code:i.error,config:t.config,response:t.response,data:i})}}]});async function ii(e){return(await ti.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 oi=async(t,i)=>{const o=process.env.HTTP_PROXY||process.env.http_proxy,s=process.env.HTTPS_PROXY||process.env.https_proxy;if(s||o){const i=new l.EnvHttpProxyAgent;e.customFetch.setDispatcher(i);const[{HttpProxyAgent:n},{HttpsProxyAgent:a}]=await Promise.all([import("http-proxy-agent"),import("https-proxy-agent")]);e.axiosInstance.defaults.proxy=!1,ti.defaults.proxy=!1,s&&(e.axiosInstance.defaults.httpsAgent=new a(s),ti.defaults.httpsAgent=new a(s),t.ui.debug(`HTTPS proxy enabled: ${s}`)),o&&(e.axiosInstance.defaults.httpAgent=new n(o),ti.defaults.httpAgent=new n(o),t.ui.debug(`HTTP proxy enabled: ${o}`))}await i()};function si(e){if(!Array.isArray(e))throw new TypeError("Middleware stack must be an array!");for(const t of e)if("function"!=typeof t)throw new TypeError("Middleware must be composed of functions!");return function(t,i){let o=-1;return function s(n){if(n<=o)return Promise.reject(new Error("next() called multiple times"));o=n;let a=e[n];n===e.length&&(a=i);if(!a)return Promise.resolve();try{return Promise.resolve(a(t,s.bind(null,n+1)))}catch(e){return Promise.reject(e)}}(0)}}var ni,ai,ri,ci,di,pi,li,ui,_i,mi,gi,hi,fi,yi,bi,vi,Ci,Si,Pi,Ei,Ti,Ai,ki,wi,Ri,zi,Ii,Oi,Li,ji,Ui,Bi,xi,qi,Di,Mi,Gi,Ni,Fi,$i,Vi,Wi,Hi,Ki,Ji,Qi,Zi,Yi,Xi,eo,to,io,oo;function so(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}!function(e){e.app="app";e.pat="pat"}(ni||(ni={})),function(e){e.can_apply2="CanApply";e.already_applied2="AlreadyApplied";e.joined4="Joined";e.deny3="Deny"}(ai||(ai={})),function(e){e.processing="Processing";e.approved="Approved";e.rejected="Rejected";e.auto_approved="AutoApproved"}(ri||(ri={})),function(e){e.normal="Normal";e.connector="Connector";e.privilege="Privilege"}(ci||(ci={})),function(e){e.auth_app="AuthApp";e.on_behalf_of_user="OnBehalfOfUser"}(di||(di={})),function(e){e.password="Password";e.sms="Sms";e.email="Email";e.unknown3="Unknown"}(pi||(pi={})),function(e){e.authorized="authorized";e.unauthorized="unauthorized";e.expired4="expired"}(li||(li={})),function(e){e.api_key="api_key";e.wechat_official="wechat_official";e.oauth_2="oauth2"}(ui||(ui={})),function(e){e.noncertificated="Noncertificated";e.certificated="Certificated"}(_i||(_i={})),function(e){e.uncertified="Uncertified";e.personal_certification="PersonalCertification";e.enterprise_certification="EnterpriseCertification"}(mi||(mi={})),function(e){e.obo="Obo";e.app_auth="AppAuth";e.personal_access_token="PersonalAccessToken"}(gi||(gi={})),function(e){e.legacy="Legacy";e.web_backend="WebBackend";e.single_page_or_native="SinglePageOrNative";e.terminal="Terminal";e.service="Service"}(hi||(hi={})),function(e){e.bot_editor="BotEditor";e.bot_developer="BotDeveloper";e.bot_operator="BotOperator"}(fi||(fi={})),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"}(yi||(yi={})),function(e){e.visitors_prohibited="VisitorsProhibited";e.guest_prohibited_by_invited_user_enterprise2="GuestProhibitedByInvitedUserEnterprise";e.prohibited_by_custom_people_management="ProhibitedByCustomPeopleManagement"}(bi||(bi={})),function(e){e.dev2="DEV";e.prod2="PROD"}(vi||(vi={})),function(e){e._1="1";e._30="30";e._90="90";e._180="180";e._365="365";e.customize="customize";e.permanent="permanent"}(Ci||(Ci={})),function(e){e._12="1";e._302="30";e._902="90";e._1802="180";e._3652="365";e.customize2="customize";e.permanent2="permanent"}(Si||(Si={})),function(e){e.aes_256_gcm="AES-256-GCM"}(Pi||(Pi={})),function(e){e.conversation="Conversation";e.unknown="Unknown"}(Ei||(Ei={})),function(e){e.active3="Active";e.inactive="Inactive"}(Ti||(Ti={})),function(e){e.cloud_kms="CloudKMS",e.default="Default";e.unknown2="Unknown"}(Ai||(Ai={})),function(e){e.user_custom2="user_custom";e.consumer3="consumer"}(ki||(ki={})),function(e){e.super_admin="SuperAdmin";e.admin="Admin";e.member="Member";e.guest="Guest"}(wi||(wi={})),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"}(Ri||(Ri={})),function(e){e.string="String";e.boolean="Boolean";e.integer="Integer";e.string_list="StringList"}(zi||(zi={})),function(e){e.must_handle="MustHandle";e.no_need_handle="NoNeedHandle"}(Ii||(Ii={})),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"}(Oi||(Oi={})),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"}(Li||(Li={})),function(e){e.confirming2="Confirming";e.joined3="Joined";e.rejected3="Rejected";e.revoked2="Revoked";e.expired3="Expired";e.deny2="Deny"}(ji||(ji={})),function(e){e.confirming="Confirming";e.joined2="Joined";e.rejected2="Rejected";e.revoked="Revoked";e.expired2="Expired"}(Ui||(Ui={})),function(e){e.can_join="CanJoin";e.guest_prohibited_by_enterprise="GuestProhibitedByEnterprise";e.guest_prohibited_by_invited_user_enterprise="GuestProhibitedByInvitedUserEnterprise"}(Bi||(Bi={})),function(e){e.can_apply="CanApply";e.already_applied="AlreadyApplied";e.joined="Joined";e.expired="Expired";e.deny="Deny"}(xi||(xi={})),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"}(qi||(qi={})),function(e){e.user_custom_only="user_custom_only";e.all2="all"}(Di||(Di={})),function(e){e.system="system";e.custom="custom"}(Mi||(Mi={})),function(e){e.not_in_enterprise="NotInEnterprise";e.prohibited_by_custom_people_management2="ProhibitedByCustomPeopleManagement"}(Gi||(Gi={})),function(e){e.can_apply3="CanApply";e.already_applied3="AlreadyApplied";e.joined5="Joined";e.deny4="Deny"}(Ni||(Ni={})),function(e){e.super_admin2="SuperAdmin";e.admin2="Admin";e.member2="Member";e.guest2="Guest"}(Fi||(Fi={})),function(e){e.member_joining_auto_approved="MemberJoiningAutoApproved"}($i||($i={})),function(e){e.string2="String";e.boolean2="Boolean";e.integer2="Integer";e.string_list2="StringList"}(Vi||(Vi={})),function(e){e.developer="developer";e.consumer2="consumer"}(Wi||(Wi={})),function(e){e.all="all";e.owned="owned";e.others="others"}(Hi||(Hi={})),function(e){e.enterprise_member="EnterpriseMember";e.enterprise_guest="EnterpriseGuest"}(Ki||(Ki={})),function(e){e.not_created="NotCreated";e.enabled="Enabled";e.disabled="Disabled"}(Ji||(Ji={})),function(e){e.production="Production";e.development="Development"}(Qi||(Qi={})),(Zi||(Zi={})).skill="skill",function(e){e.dev="dev";e.prod="prod"}(Yi||(Yi={})),function(e){e.user_custom="user_custom";e.coze_default="coze_default";e.consumer="consumer"}(Xi||(Xi={})),function(e){e.active2="Active";e.deactive="Deactive"}(eo||(eo={})),function(e){e.active="active";e.deactivated="deactivated";e.offboarded="offboarded"}(to||(to={})),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"}(io||(io={})),function(e){e.root_user="RootUser";e.basic_user="BasicUser"}(oo||(oo={}));class no{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){no.prototype.__init.call(this),no.prototype.__init2.call(this),this.request=so([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=so([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}CreatePersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/create_personal_access_token_and_permission"),s={name:i.name,expire_at:i.expire_at,duration_day:i.duration_day,organization_id:i.organization_id,workspace_permission:i.workspace_permission,account_permission:i.account_permission,workspace_permission_v2:i.workspace_permission_v2,enterprise_permission:i.enterprise_permission},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}UpdatePersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/update_personal_access_token_and_permission"),s={workspace_permission:i.workspace_permission,account_permission:i.account_permission,workspace_permission_v2:i.workspace_permission_v2,enterprise_permission:i.enterprise_permission,id:i.id,name:i.name},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}DeletePersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/delete_personal_access_token_and_permission"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}ListPersonalAccessTokens(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/pat/list_personal_access_tokens"),s={organization_id:i.organization_id,page:i.page,size:i.size,search_option:i.search_option};return this.request({url:o,method:"GET",params:s},t)}GetPersonalAccessTokenAndPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/get_personal_access_token_and_permission"),s={id:i.id};return this.request({url:o,method:"GET",params:s},t)}ListPersonalAccessTokenSupportPermissions(e,t){const i=this.genBaseURL("/api/permission_api/pat/list_personal_access_token_support_permissions");return this.request({url:i,method:"GET"},t)}CheckPersonalAccessTokenInWorkspace(e,t){const i=e,o=this.genBaseURL("/api/permission_api/pat/check_personal_access_token_in_workspace"),s={workspace_id:i.workspace_id};return this.request({url:o,method:"GET",params:s},t)}AddCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/add_collaborator"),s={collaborator_types:i.collaborator_types,principal:i.principal,resource:i.resource};return this.request({url:o,method:"POST",data:s},t)}RemoveCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/remove_collaborator"),s={principal:i.principal,resource:i.resource};return this.request({url:o,method:"POST",data:s},t)}CreateAppMeta(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/create_app_meta"),s={app_type:i.app_type,client_type:i.client_type,name:i.name,description:i.description,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListAppMeta(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/list_app_meta"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}GetAppMeta(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_app_meta"),s={appid:i.appid},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}UpdateAppMeta(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/update_app_meta"),s={status:i.status,oauth2_configuration:i.oauth2_configuration,appid:i.appid,name:i.name,description:i.description,declared_permission:i.declared_permission,declared_permission_v2:i.declared_permission_v2},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}UploadPublicKey(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/upload_public_key"),s={appid:i.appid,public_key_pem:i.public_key_pem};return this.request({url:o,method:"POST",data:s},t)}DeletePublicKey(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/delete_public_key"),s={fingerprint:i.fingerprint};return this.request({url:o,method:"POST",data:s},t)}CreateClientSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/create_client_secret"),s={appid:i.appid};return this.request({url:o,method:"POST",data:s},t)}DeleteClientSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/delete_client_secret"),s={appid:i.appid,client_secret_id:i.client_secret_id};return this.request({url:o,method:"POST",data:s},t)}PutOAuth2Configuration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/put_oauth2_configuration"),s={oauth2_configuration:i.oauth2_configuration,appid:i.appid};return this.request({url:o,method:"POST",data:s},t)}AuthorizeAppWithDeclaredPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/authorize_app_with_declared_permission"),s={appid:i.appid,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListAuthorizedApps(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/list_authorized_apps"),s={page:i.page,size:i.size},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}GetAppAuthorizationRequestInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_app_authorization_request_info"),s={authorize_key:i.authorize_key},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}RevokeAppAuthorizedPermission(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/revoke_app_authorized_permission"),s={authorization_type:i.authorization_type,appid:i.appid,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}DeleteApp(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/delete_app"),s={appid:i.appid};return this.request({url:o,method:"POST",data:s},t)}ModifyCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/modify_collaborator"),s={principal:i.principal,resource:i.resource,collaborator_types:i.collaborator_types};return this.request({url:o,method:"POST",data:s},t)}BatchAddCollaborator(e,t){const i=e,o=this.genBaseURL("/api/permission/authz/batch_add_collaborator"),s={principal_type:i.principal_type,resource:i.resource,principal_ids:i.principal_ids,collaborator_types:i.collaborator_types};return this.request({url:o,method:"POST",data:s},t)}GetAppInstallationRequestInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_app_installation_request_info"),s={appid:i.appid},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}AppInstallationConsent(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/app_installation_consent"),s={appid:i.appid,installation_account_hint:i.installation_account_hint};return this.request({url:o,method:"POST",data:s},t)}ImpersonateCozeUser(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/coze_web_app/impersonate_coze_user"),s={duration_seconds:i.duration_seconds,scope:i.scope,connector_info:i.connector_info};return this.request({url:o,method:"POST",data:s},t)}GetVolcanoConnectInfoWithInsName(e,t){const i=this.genBaseURL("/api/permission_api/volcano/get_volcano_connect_info_with_ins_name");return this.request({url:i,method:"GET"},t)}GetVolcanoMaskedMobile(e,t){const i=this.genBaseURL("/api/permission_api/volcano/get_volcano_masked_mobile");return this.request({url:i,method:"GET"},t)}BindVolcano(e,t){const i=this.genBaseURL("/api/permission_api/volcano/bind_volcano");return this.request({url:i,method:"POST"},t)}AuthorizeAppWithSpecifiedWorkspace(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/authorize_app_with_specified_permission"),s={appid:i.appid,workspace_list:i.workspace_list,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}GetUserProfile(e,t){const i=this.genBaseURL("/v1/users/me");return this.request({url:i,method:"GET"},t)}ListAppAuthorizations(e,t){const i=e,o=this.genBaseURL(`/v1/oauth-apps/${i.appid}/authorizations`),s={page_num:i.page_num,page_size:i.page_size},n={authorization:i.authorization};return this.request({url:o,method:"GET",params:s,headers:n},t)}GetCertificationInfo(e,t){const i=this.genBaseURL("/api/permission_api/enterprise/get_certification_info");return this.request({url:i,method:"GET"},t)}NeedCreateEnterprise(e,t){const i=this.genBaseURL("/api/permission_api/enterprise/need_create_enterprise");return this.request({url:i,method:"GET"},t)}CreateEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_enterprise"),s={name:i.name,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}ListEnterprise(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/enterprise/list_enterprises"),s={contain_enterprise_of_user:i.contain_enterprise_of_user,contain_organization_of_user:i.contain_organization_of_user};return this.request({url:o,method:"GET",params:s},t)}GetEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_enterprise"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"GET",params:s},t)}UpdateEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_enterprise"),s={enterprise_id:i.enterprise_id,name:i.name,icon_uri:i.icon_uri,replace_logo:i.replace_logo};return this.request({url:o,method:"POST",data:s},t)}UpdateEnterpriseSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_settings"),s={enterprise_id:i.enterprise_id,enterprise_settings:i.enterprise_settings};return this.request({url:o,method:"POST",data:s},t)}BatchAddEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_add_enterprise_people"),s={enterprise_id:i.enterprise_id,enterprise_people:i.enterprise_people,need_check_people_valid:i.need_check_people_valid};return this.request({url:o,method:"POST",data:s},t)}RemoveEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/remove_enterprise_people"),s={enterprise_id:i.enterprise_id,user_id:i.user_id,receiver:i.receiver,sync_default_organization:i.sync_default_organization};return this.request({url:o,method:"POST",data:s},t)}UpdateEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_people"),s={enterprise_id:i.enterprise_id,user_id:i.user_id,enterprise_role_type_list:i.enterprise_role_type_list,sync_default_organization:i.sync_default_organization};return this.request({url:o,method:"POST",data:s},t)}CreateEnterpriseInviteLink(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_enterprise_invite_link"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}CreateJoinApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_join_application"),s={key:i.key,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}GetInviteInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_invite_info"),s={invite_key:i.invite_key};return this.request({url:o,method:"GET",params:s},t)}UpdateJoinApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_join_application"),s={application_status:i.application_status,enterprise_id:i.enterprise_id,join_application_id_list:i.join_application_id_list};return this.request({url:o,method:"POST",data:s},t)}ListPersonalAccessTokensByCreator(e,t){const i=e,o=this.genBaseURL("/api/permission_api/permission/list_personal_access_tokens_by_creator"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}ListAppInstallations(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/list_app_installations"),s={enterprise_id:i.enterprise_id,organization_id:i.organization_id},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}GetEnterpriseSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_enterprise_settings"),s={enterprise_id:i.enterprise_id,enterprise_setting_key_list:i.enterprise_setting_key_list};return this.request({url:o,method:"POST",data:s},t)}SearchCanAddEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_can_add_enterprise_people"),s={people_type:i.people_type,enterprise_id:i.enterprise_id,search_key:i.search_key};return this.request({url:o,method:"POST",data:s},t)}SearchEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_enterprise_people"),s={people_type:i.people_type,enterprise_id:i.enterprise_id,search_key:i.search_key,enterprise_role_type_list:i.enterprise_role_type_list,need_volcano_user_info:i.need_volcano_user_info,need_people_number:i.need_people_number,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}ListJoinApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/list_join_application"),s={application_status:i.application_status,enterprise_id:i.enterprise_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}PostAdapterMpV1Code2Session(e,t){const i=e||{},o=this.genBaseURL("/adapter/mp/v1/code2session"),s={bot_id:i.bot_id,app_id:i.app_id,connector_id:i.connector_id,code:i.code,with_userinfo:i.with_userinfo,execute_mode:i.execute_mode,agent_type:i.agent_type,agent_version:i.agent_version};return this.request({url:o,method:"POST",data:s},t)}SubmitAppOboInstallationReview(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/submit_app_obo_installation_review"),s={appid:i.appid,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}InstallAppObo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/install_app_obo"),s={appid:i.appid,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}UninstallAppObo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/uninstall_app_obo"),s={appid:i.appid,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}GetChecklistForWorkspaceMigration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/get_checklist_for_workspace_migration"),s={workspace_id_list:i.workspace_id_list};return this.request({url:o,method:"POST",data:s},t)}CheckEnterpriseExist(e,t){const i=this.genBaseURL("/api/permission_api/enterprise/check_enterprise_exist");return this.request({url:i,method:"GET"},t)}GetSSOSetting(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_sso_setting"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}BatchMigrateAuthorization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/app/batch_migrate_authorization"),s={authorization_list:i.authorization_list,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/list_join_invitation"),s={invitation_status:i.invitation_status,enterprise_id:i.enterprise_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}RevokeJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/revoke_join_invitation"),s={enterprise_id:i.enterprise_id,join_invitation_id:i.join_invitation_id};return this.request({url:o,method:"POST",data:s},t)}UpdateJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_join_invitation"),s={enterprise_id:i.enterprise_id,join_invitation_id:i.join_invitation_id,joined:i.joined};return this.request({url:o,method:"POST",data:s},t)}GetJoinInvitation(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_join_invitation"),s={join_invitation_id:i.join_invitation_id};return this.request({url:o,method:"POST",data:s},t)}SearchPeopleInOtherEnterprise(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_people_in_other_enterprise"),s={enterprise_id:i.enterprise_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}CreateApplicationForEnterpriseMember(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_application_for_enterprise_member"),s={enterprise_id:i.enterprise_id,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}GetApplicationForEnterpriseMember(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_application_for_enterprise_member"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}AuthorizeAppsAndPersonalaccesstokenListWithPersonalAccountPermission(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/authorize_apps_and_patlist_with_personalaccountpermission"),s={crossaccount_authinfo_list:i.crossaccount_authinfo_list};return this.request({url:o,method:"POST",data:s},t)}RevokeAppAndPersonalaccesstokenPersonalAccountPermission(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/revoke_app_and_pat_personalaccountpermission"),s={crossaccount_authinfo:i.crossaccount_authinfo};return this.request({url:o,method:"POST",data:s},t)}GetAppsAndPersonalAccessTokenListForPersonalAccountPermissionAuthorization(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/app/get_apps_and_patlist_for_personalaccountpermission_authorization"),s={page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}create_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/create_service_identity"),s={name:i.name,organization_id:i.organization_id,expire_at:i.expire_at,duration_day:i.duration_day,permission:i.permission},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}get_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/get_service_identity"),s={id:i.id};return this.request({url:o,method:"GET",params:s},t)}update_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/update_service_identity"),s={permission:i.permission,id:i.id,name:i.name,expire_at:i.expire_at,duration_day:i.duration_day},n={"x-tt-env":i["x-tt-env"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}delete_service_identity(e,t){const i=e,o=this.genBaseURL("/api/permission_api/service/delete_service_identity"),s={id:i.id};return this.request({url:o,method:"POST",params:s},t)}list_service_identities(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/service/list_service_identities"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}ListEncryptionConfiguration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterpise/list_encryption_configuration"),s={organization_id:i.organization_id};return this.request({url:o,method:"GET",params:s},t)}UpdateEncryptionConfiguration(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/enterpise/update_encryption_configuration"),s={encryption_configuration:i.encryption_configuration};return this.request({url:o,method:"POST",data:s},t)}SearchOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_organization"),s={enterprise_id:i.enterprise_id,search_key:i.search_key,joined:i.joined,need_people_number:i.need_people_number,need_workspace_number:i.need_workspace_number,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}CreateOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_organization"),s={enterprise_id:i.enterprise_id,name:i.name,icon_uri:i.icon_uri,description:i.description};return this.request({url:o,method:"POST",data:s},t)}GetOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_organization"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}UpdateOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_organization"),s={organization_id:i.organization_id,name:i.name,icon_uri:i.icon_uri,description:i.description};return this.request({url:o,method:"POST",data:s},t)}SearchCanAddOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_can_add_organization_people"),s={organization_id:i.organization_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}SearchOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/search_organization_people"),s={organization_role_type:i.organization_role_type,people_type:i.people_type,organization_id:i.organization_id,search_key:i.search_key,page:i.page,page_size:i.page_size,organization_role_type_list:i.organization_role_type_list};return this.request({url:o,method:"POST",data:s},t)}CreateJoinOrganizationApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/create_join_organization_application"),s={organization_id:i.organization_id,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}ListJoinOrganizationApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/list_join_organization_application"),s={application_status:i.application_status,organization_id:i.organization_id,search_key:i.search_key,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}UpdateJoinOrganizationApplication(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_join_organization_application"),s={application_status:i.application_status,organization_id:i.organization_id,join_application_id_list:i.join_application_id_list};return this.request({url:o,method:"POST",data:s},t)}GetOrganizationApplicationForEnterpriseMember(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_organization_application_for_enterprise_member"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}CanCustomEncryptionConfiguration(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterpise/can_custom_encryption_configuration"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"GET",params:s},t)}BatchAddOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_add_organization_people"),s={organization_id:i.organization_id,organization_people:i.organization_people};return this.request({url:o,method:"POST",data:s},t)}RemoveOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/remove_organization_people"),s={organization_id:i.organization_id,user_id:i.user_id,receiver:i.receiver};return this.request({url:o,method:"POST",data:s},t)}UpdateOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_organization_people"),s={organization_role_type:i.organization_role_type,organization_id:i.organization_id,user_id:i.user_id};return this.request({url:o,method:"POST",data:s},t)}DownloadRemoteAttestationEvidence(e,t){const i=e,o=this.genBaseURL("/api/permission_api/aicc/download_remote_attestation_evidence"),s={component_name:i.component_name};return this.request({url:o,method:"GET",params:s},t)}GetAgentAiccInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/aicc/get_agent_aicc_info"),s={agent_id:i.agent_id};return this.request({url:o,method:"GET",params:s},t)}CheckDeleteOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/check_delete_organization"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}DeleteOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/delete_organization"),s={organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}ListProjectUsers(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/list_project_users"),s={project_id:i.project_id,page_size:i.page_size,page_number:i.page_number,environment:i.environment,filter:i.filter};return this.request({url:o,method:"POST",data:s},t)}DeleteProjectUser(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user"),s={environment:i.environment,project_id:i.project_id,user_id:i.user_id};return this.request({url:o,method:"POST",data:s},t)}GetProjectAuthConfig(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}UpdateProjectAuthConfig(e,t){const i=e,o=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config"),s={project_id:i.project_id,configuration:i.configuration};return this.request({url:o,method:"POST",data:s},t)}ListProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/list_project_secret"),s={env:i.env,project_id:i.project_id,with_providers:i.with_providers,deploy_id:i.deploy_id,option:i.option};return this.request({url:o,method:"POST",data:s},t)}UpdateProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/update_project_secret"),s={project_id:i.project_id,update_secrets:i.update_secrets,update_cred_provider:i.update_cred_provider};return this.request({url:o,method:"POST",data:s},t)}DeleteProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/delete_project_secret"),s={project_id:i.project_id,keys:i.keys,cred_provider_ids:i.cred_provider_ids};return this.request({url:o,method:"POST",data:s},t)}EncryptProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/encrypt_project_secret"),s={project_id:i.project_id,project_type:i.project_type,encrypt_secrets:i.encrypt_secrets};return this.request({url:o,method:"POST",data:s},t)}InsertProjectSecret(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/insert_project_secret"),s={project_id:i.project_id,insert_secrets:i.insert_secrets};return this.request({url:o,method:"POST",data:s},t)}OutboundAuthCallback(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/outbound_auth/callback"),s={session_id:i.session_id,error:i.error};return this.request({url:o,method:"GET",params:s},t)}CreateAgentAccessToken(e,t){const i=e,o=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:i.project_id,deployment_env:i.deployment_env};return this.request({url:o,method:"POST",data:s},t)}ListAgentAccessTokens(e,t){const i=e,o=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}DeleteAgentAccessToken(e,t){const i=e,o=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={token_id:i.token_id,project_id:i.project_id};return this.request({url:o,method:"DELETE",data:s},t)}GenerateInviteCode(e,t){const i=this.genBaseURL("/api/permission_api/coze_user/generate_invite_code");return this.request({url:i,method:"POST"},t)}GetInviteCodeInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/coze_user/get_invite_code_info"),s={invite_code:i.invite_code};return this.request({url:o,method:"GET",params:s},t)}AuthorizeCredProvider(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/authorize"),s={provider_id:i.provider_id};return this.request({url:o,method:"GET",params:s},t)}ProjectSecretAuthCallback(e,t){const i=e||{},o=this.genBaseURL("/api/permission_api/project_secret/callback"),s={code:i.code,state:i.state,error:i.error};return this.request({url:o,method:"GET",params:s},t)}ListAuthInfo(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/list_auth_info"),s={credential_ids:i.credential_ids};return this.request({url:o,method:"POST",data:s},t)}RevokeAuthorization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/project_secret/revoke"),s={credential_id:i.credential_id};return this.request({url:o,method:"POST",data:s},t)}VisibilityConfig(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/visibility_config"),s={enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}GetVolcanoLoginMaskedMobile(e,t){const i=this.genBaseURL("/api/permission_api/volcano/get_volcano_login_masked_mobile");return this.request({url:i,method:"GET"},t)}BatchGetPeopleJoinedOrganization(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_get_people_joined_organization"),s={enterprise_id:i.enterprise_id,user_ids:i.user_ids};return this.request({url:o,method:"POST",data:s},t)}BatchRemoveOrganizationPeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_remove_organization_people"),s={enterprise_id:i.enterprise_id,remove_user_list:i.remove_user_list};return this.request({url:o,method:"POST",data:s},t)}BatchRemoveEnterprisePeople(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/batch_remove_enterprise_people"),s={enterprise_id:i.enterprise_id,remove_user_list:i.remove_user_list};return this.request({url:o,method:"POST",data:s},t)}GetOrganizationSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/get_organization_settings"),s={organization_id:i.organization_id,organization_setting_key_list:i.organization_setting_key_list};return this.request({url:o,method:"POST",data:s},t)}UpdateOrganizationSettings(e,t){const i=e,o=this.genBaseURL("/api/permission_api/enterprise/update_organization_settings"),s={organization_id:i.organization_id,organization_settings:i.organization_settings};return this.request({url:o,method:"POST",data:s},t)}}const ao=new no({});function ro(e,t){return null!=e?e:t()}class co{constructor(e){this.ctx=e,this.config=e.config}getOAuthConfig(){return{baseURL:ro(this.config.openApiBaseUrl,()=>Y.openApiBaseUrl),clientId:ro(this.config.clientId,()=>Y.clientId)}}async clearUserContext(){this.config.organizationId=void 0,this.config.enterpriseId=void 0,this.config.spaceId=void 0,await ie({organizationId:void 0,enterpriseId:void 0,spaceId:void 0})}async clearAuthData(){this.config.accessToken=void 0,this.config.refreshToken=void 0,this.config.tokenExpiresAt=void 0,await ie({accessToken:void 0,refreshToken:void 0,tokenExpiresAt:void 0})}async login(i){if(this.ctx.ui.verbose("Initiating login process..."),i.token)return this.ctx.ui.info("Using Personal Access Token (PAT)..."),this.config.accessToken=i.token,await ie({accessToken:i.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:i,clientId:o}=this.getOAuthConfig();this.ctx.ui.verbose("Starting OAuth device flow...");const s=await async function(e){const t=e.workspaceId?`/api/permission/oauth2/workspace_id/${e.workspaceId}/device/code`:"/api/permission/oauth2/device/code";return(await ti.post(t,{client_id:e.clientId},{baseURL:e.baseURL})).data}({baseURL:i,clientId:o}),n=`${s.verification_uri}?user_code=${s.user_code}`;this.ctx.ui.info(`Please visit ${t.underline(n)} and authorize the application.\n\nPrivacy Policy: ${t.underline("https://docs.coze.cn/guides/privacy")}\nTerms of Service: ${t.underline("https://docs.coze.cn/guides/terms-of-service")}\n\nIf you are an agent using Coze CLI, please share the authorization link, Privacy Policy, and Terms of Service with your users.\n `);const a=await async function(t,i){if(!t.poll)return ii(t);let o=5e3;for(i.ui.debug("Start Polling for device token..."),i.ui.debug(`Polling interval: ${o}ms`),i.ui.debug("Polling timeout: 30000ms");;)try{i.ui.debug(`Polling for device token..., ${JSON.stringify(t)}`);const e=await ii(t);return i.ui.debug(`Polling for device token success: ${JSON.stringify(e)}`),e}catch(t){if(e.isHttpError(t)){i.ui.debug(`Polling for device token error, the error is a HttpError.\n logid: ${Yt([t,"access",e=>e.response,"optionalAccess",e=>e.headers,"access",e=>e["x-tt-logid"]])}`),i.ui.debug(`Polling for device token error: ${JSON.stringify(t.toJSON())}`);const e=t.data;if(Yt([e,"optionalAccess",e=>e.error])===Xt.AUTHORIZATION_PENDING){i.ui.debug("Polling for device token: user has not completed authorization yet."),await ei(o);continue}if(Yt([e,"optionalAccess",e=>e.error])===Xt.SLOW_DOWN){o<3e4&&(o+=5e3),i.ui.debug(`Polling for device token: client is polling too frequently. Increasing interval to ${o}ms`),await ei(o);continue}}throw i.ui.debug(`Polling for device token error, the error is: ${t.message}\n ${t.stack}\n `),t}}({baseURL:i,clientId:o,deviceCode:s.device_code,poll:!0},this.ctx);this.ctx.ui.debug(`Polling for device token success: ${JSON.stringify(a)}`),await this.saveOAuthToken(a),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: ${e.message||e}`),e}}async logout(){await this.clearAuthData(),await this.clearUserContext(),this.ctx.ui.info("You have been logged out. Credentials cleared."),"json"===this.ctx.format&&this.ctx.response.print({success:!0,logged_out:!0})}async whoami(){if(!await this.getValidAccessToken())return void this.ctx.response.print({logged_in:!1});this.ctx.ui.info("Fetching user information...");this.ctx.response.print({logged_in:!0,user:"mock-user@coze.io",org:"mock-org",profile:"default"})}async status(){const e=await this.getValidAccessToken();if(this.ctx.ui.info("Checking authentication status..."),!e)return void this.ctx.response.print({logged_in:!1});const t=this.config.tokenExpiresAt,i=!!this.config.refreshToken,{data:o}=await ao.GetUserProfile({},{baseURL:this.config.openApiBaseUrl}),s={logged_in:!0,user:o,token_expires_at:t?new Date(t).toISOString():i?void 0:"Never (PAT)"};this.ctx.response.print(s)}async getValidAccessToken(){const{accessToken:e,refreshToken:t,tokenExpiresAt:i}=this.config;if(!e)return;if(!t)return e;if(i&&Date.now()<i-3e5)return e;this.ctx.ui.verbose("Access token is expired or expiring soon, refreshing...");try{const{baseURL:e,clientId:i}=this.getOAuthConfig(),o=await async function(e){const t={};return e.clientSecret&&(t.Authorization=`Bearer ${e.clientSecret}`),(await ti.post("/api/permission/oauth2/token",{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken},{baseURL:e.baseURL,headers:t})).data}({baseURL:e,clientId:i,refreshToken:t});return await this.saveOAuthToken(o),this.ctx.ui.verbose("Token refreshed successfully."),o.access_token}catch(e){return this.ctx.ui.error(`Failed to refresh token: ${e.message||e}`),void await this.clearAuthData()}}async saveOAuthToken(e){const t=1e3*e.expires_in;this.config.accessToken=e.access_token,this.config.refreshToken=e.refresh_token,this.config.tokenExpiresAt=t,await ie({accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:t})}}const po="",lo="",uo="",_o="",mo="",go="",ho="",fo="",yo="[PROC]",bo="[INFO]",vo="[WARN]",Co="[ERR]",So="[DONE]",Po="[DBG]",Eo={debug:0,verbose:1,info:2,success:3,warn:4,error:5};function To(e){return`${uo}${lo}${e}${po}`}class Ao{constructor(e,t,i="info"){var o,s;this.log=e,this.silent="json"===t,this.useColor=this.detectColorSupport(),this.level=i,this.levelPriority=(s=()=>2,null!=(o=Eo[i])?o:s())}detectColorSupport(){return!0===function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}([process,"access",e=>e.stderr,"optionalAccess",e=>e.isTTY])&&void 0===process.env.NO_COLOR}paint(e,t){return this.useColor?`${e}${t}${po}`:t}shouldOutput(e){return!this.silent&&Eo[e]>=this.levelPriority}verbose(e,...t){this.log.verbose(e,...t),this.shouldOutput("verbose")&&process.stderr.write(`${To(yo)} ${this.paint(ho,e)}\n`)}info(e,...t){this.log.info(e,...t),this.shouldOutput("info")&&process.stderr.write(`${To(bo)} ${this.paint(po,e)}\n`)}warn(e,...t){this.log.warn(e,...t),this.shouldOutput("warn")&&process.stderr.write(`${To(vo)} ${this.paint(go,e)}\n`)}error(e,...t){this.log.error(e,...t),this.shouldOutput("error")&&process.stderr.write(`${To(Co)} ${this.paint(_o,e)}\n`)}success(e,...t){this.log.success(e,...t),this.shouldOutput("success")&&process.stderr.write(`${To(So)} ${this.paint(mo,e)}\n`)}debug(e,...t){this.log.debug(e,...t),this.shouldOutput("debug")&&process.stderr.write(`${To(Po)} ${this.paint(fo,e)}\n`)}}class ko{constructor(e){const{format:t}=e;this.formatter=function(e){return"text"===e?new D:new A}(t)}print(e){const t=this.formatter.format(e);process.stdout.write(t)}eprint(e){const t=this.formatter.formatError(e);process.stderr.write(t)}}function wo(e,t){return null!=e?e:t()}const Ro=n.join(s.homedir(),".coze","logs");class zo{__init(){this.fileStream=null}__init2(){this.writeError=!1}constructor(e={}){zo.prototype.__init.call(this),zo.prototype.__init2.call(this),this.format=wo(e.format,()=>"text"),this.printToStderr=wo(e.printToStderr,()=>!1),this.tags=wo(e.tags,()=>({})),this.startTime=Date.now();const t=wo(e.logFile,()=>this.getDefaultLogPath());this.logFile=t;try{this.ensureLogDir(),this.rotateLogFiles(),this.fileStream=u.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(Ro,`${e}-${t}.log`)}ensureLogDir(){u.existsSync(Ro)||u.mkdirSync(Ro,{recursive:!0})}rotateLogFiles(){try{const e=u.readdirSync(Ro).filter(e=>e.endsWith(".log")).map(e=>({name:e,path:n.join(Ro,e),mtime:u.statSync(n.join(Ro,e)).mtime.getTime()})).sort((e,t)=>t.mtime-e.mtime);e.length>=10&&e.slice(9).forEach(e=>{try{u.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)}log(e,t,i){const o=this.formatEntry(e,t,i);if(this.fileStream)try{this.fileStream.write(`${o}\n`)}catch(e){!this.writeError&&this.printToStderr&&(process.stderr.write("Warning: Log write failed\n"),this.writeError=!0)}this.printToStderr&&process.stderr.write(`${o}\n`)}formatEntry(e,t,i){const o=(new Date).toISOString(),s=Date.now()-this.startTime;if("json"===this.format){const n={level:e,timestamp:o,delta:s,...this.tags,message:t};return i.length>0&&(n.args=i),JSON.stringify(n)}const n=Object.entries(this.tags).map(([e,t])=>`${e}=${t}`).join(" "),a=i.length>0?` ${i.map(String).join(" ")}`:"";return`${e.toUpperCase().padEnd(7)} [${o}] +${s}ms ${n} ${t}${a}`}close(){if(this.fileStream)try{this.fileStream.end()}catch(e){}}}function Io(e,t){return null!=e?e:t()}async function Oo(e,t){const i=Date.now();e.ui.verbose(`[Logger] CLI start: ${e.argv.join(" ")}`);try{await t()}finally{const t=Date.now()-i;e.ui.verbose(`[Logger] CLI end (took ${t}ms)`)}}var Lo,jo,Uo,Bo,xo,qo,Do,Mo,Go,No,Fo,$o,Vo,Wo,Ho,Ko,Jo,Qo,Zo,Yo,Xo,es,ts,is,os,ss,ns,as,rs,cs,ds,ps,ls,us,_s,ms,gs,hs,fs,ys,bs,vs,Cs,Ss,Ps,Es,Ts,As,ks,ws,Rs,zs,Is,Os,Ls,js,Us,Bs,xs,qs,Ds,Ms,Gs,Ns,Fs,$s,Vs,Ws,Hs,Ks,Js,Qs,Zs,Ys,Xs,en,tn,on,sn,nn,an,rn,cn,dn,pn,ln,un,_n,mn,gn,hn,fn,yn,bn,vn,Cn,Sn,Pn,En,Tn,An,kn,wn,Rn,zn,In,On,Ln,jn,Un,Bn,xn,qn,Dn,Mn,Gn,Nn,Fn,$n,Vn,Wn,Hn,Kn,Jn,Qn,Zn,Yn,Xn,ea,ta,ia;function oa(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}!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"}(Lo||(Lo={})),function(e){e[e.OldVersion=0]="OldVersion";e[e.MiddleVersion=1]="MiddleVersion";e[e.NewVersion=2]="NewVersion";e[e.MiddleVersionNotPrompt=3]="MiddleVersionNotPrompt"}(jo||(jo={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(Uo||(Uo={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(Bo||(Bo={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(xo||(xo={})),function(e){e[e.Current=1]="Current";e[e.Previous=2]="Previous";e[e.Start=3]="Start";e[e.MostSuitable=4]="MostSuitable"}(qo||(qo={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Do||(Do={})),function(e){e[e.Default=0]="Default";e[e.Function=1]="Function"}(Mo||(Mo={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned"}(Go||(Go={})),function(e){e[e.LimitedReadWrite=1]="LimitedReadWrite";e[e.ReadOnly=2]="ReadOnly";e[e.UnlimitedReadWrite=3]="UnlimitedReadWrite";e[e.RWModeMax=4]="RWModeMax"}(No||(No={})),function(e){e[e.Default=0]="Default";e[e.DouyinAvatar=1]="DouyinAvatar"}(Fo||(Fo={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}($o||($o={})),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"}(Vo||(Vo={})),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"}(Wo||(Wo={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Ho||(Ho={})),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"}(Ko||(Ko={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Jo||(Jo={})),function(e){e[e.SLM=0]="SLM";e[e.LLM=1]="LLM"}(Qo||(Qo={})),function(e){e[e.Pre=1]="Pre";e[e.Post=2]="Post";e[e.PreAndPost=3]="PreAndPost"}(Zo||(Zo={})),function(e){e[e.Default=0]="Default";e[e.CustomizePrompt=1]="CustomizePrompt"}(Yo||(Yo={})),function(e){e[e.ReplyBottom=0]="ReplyBottom";e[e.CardList=1]="CardList"}(Xo||(Xo={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(es||(es={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(ts||(ts={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(is||(is={})),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"}(os||(os={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(ss||(ss={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(ns||(ns={})),function(e){e[e.Curve=0]="Curve";e[e.Straight=1]="Straight"}(as||(as={})),function(e){e[e.Flow=1]="Flow";e[e.Host=2]="Host"}(rs||(rs={})),function(e){e[e.NO_NEED=1]="NO_NEED";e[e.USE_MANUAL=2]="USE_MANUAL";e[e.USE_LLM=3]="USE_LLM"}(cs||(cs={})),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"}(ds||(ds={})),function(e){e[e.Input=0]="Input";e[e.Variable=1]="Variable"}(ps||(ps={})),function(e){e[e.Default=0]="Default";e[e.FromSaas=1]="FromSaas"}(ls||(ls={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(us||(us={})),function(e){e[e.FunctionCall=1]="FunctionCall";e[e.Independent=2]="Independent"}(_s||(_s={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(ms||(ms={})),function(e){e[e.ManualUpdate=1]="ManualUpdate";e[e.AutoUpdate=2]="AutoUpdate"}(gs||(gs={})),function(e){e[e.SemanticSearch=0]="SemanticSearch";e[e.HybirdSearch=1]="HybirdSearch";e[e.FullTextSearch=20]="FullTextSearch"}(hs||(hs={})),function(e){e[e.Public=1]="Public";e[e.Anonymous=2]="Anonymous";e[e.Custom=3]="Custom"}(fs||(fs={})),function(e){e[e.Random=0]="Random";e[e.All=1]="All"}(ys||(ys={})),function(e){e[e.System=0]="System";e[e.Custom=1]="Custom";e[e.Disable=2]="Disable";e[e.OriBot=3]="OriBot"}(bs||(bs={})),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"}(vs||(vs={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Cs||(Cs={})),function(e){e[e.CozeOldTimeCapsule=0]="CozeOldTimeCapsule";e[e.VolcanoTimeCapsule=1]="VolcanoTimeCapsule"}(Ss||(Ss={})),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"}(Ps||(Ps={})),function(e){e[e.BotQuery=1]="BotQuery";e[e.Plugin=2]="Plugin";e[e.Workflow=3]="Workflow"}(Es||(Es={})),function(e){e[e.Unknown=0]="Unknown";e[e.Webhook=1]="Webhook"}(Ts||(Ts={})),function(e){e[e.Unknown=0]="Unknown";e[e.Time=1]="Time";e[e.Event=2]="Event"}(As||(As={})),function(e){e[e.NoHistory=0]="NoHistory";e[e.NeedHistory=1]="NeedHistory"}(ks||(ks={})),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"}(ws||(ws={})),function(e){e[e.Init=0]="Init";e[e.Activated=1]="Activated";e[e.Deactivated=2]="Deactivated";e[e.Suspended=3]="Suspended"}(Rs||(Rs={})),function(e){e[e.Preset=1]="Preset";e[e.UserTask=2]="UserTask";e[e.PluginRunTask=3]="PluginRunTask"}(zs||(zs={})),function(e){e[e.Deploying=0]="Deploying";e[e.Successful=1]="Successful";e[e.Failed=2]="Failed"}(Is||(Is={})),function(e){e[e.All=0]="All";e[e.Bind=1]="Bind";e[e.UnBind=2]="UnBind"}(Os||(Os={})),function(e){e[e.CreateTime=0]="CreateTime";e[e.UpdateTime=1]="UpdateTime"}(Ls||(Ls={})),function(e){e[e.EventMeta=1]="EventMeta";e[e.ProfileMeta=2]="ProfileMeta"}(js||(js={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Us||(Us={})),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"}(Bs||(Bs={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(xs||(xs={})),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"}(qs||(qs={})),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"}(Ds||(Ds={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(Ms||(Ms={})),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"}(Gs||(Gs={})),function(e){e[e.Upgrade=1]="Upgrade";e[e.BrowseOldNoPrompt=2]="BrowseOldNoPrompt"}(Ns||(Ns={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(Fs||(Fs={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}($s||($s={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(Vs||(Vs={})),function(e){e[e.Visit=1]="Visit";e[e.Edit=2]="Edit"}(Ws||(Ws={})),function(e){e[e.Online=1]="Online";e[e.Offline=2]="Offline"}(Hs||(Hs={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online"}(Ks||(Ks={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Js||(Js={})),function(e){e[e.AutoGenBeforePublish=1]="AutoGenBeforePublish"}(Qs||(Qs={})),function(e){e[e.CozeHome=1]="CozeHome";e[e.Space=2]="Space"}(Zs||(Zs={})),function(e){e[e.Undefined=0]="Undefined";e[e.PersonalDraft=1]="PersonalDraft";e[e.Base=2]="Base";e[e.Publish=3]="Publish"}(Ys||(Ys={})),function(e){e[e.Undefined=0]="Undefined";e[e.Committed=1]="Committed";e[e.Behind=2]="Behind";e[e.NoDraftReplica=3]="NoDraftReplica"}(Xs||(Xs={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(en||(en={})),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"}(tn||(tn={})),function(e){e[e.Personal=1]="Personal";e[e.Organization=2]="Organization"}(on||(on={})),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"}(sn||(sn={})),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"}(nn||(nn={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned";e[e.MoveFail=3]="MoveFail"}(an||(an={})),function(e){e[e.ByteTree=1]="ByteTree";e[e.GPTAK=2]="GPTAK";e[e.MaasAK=3]="MaasAK"}(rn||(rn={})),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"}(cn||(cn={})),function(e){e[e.BotStore=1]="BotStore"}(dn||(dn={})),function(e){e[e.shorcutIcon=1]="shorcutIcon"}(pn||(pn={})),function(e){e[e.Onboarding=0]="Onboarding";e[e.BackgroundImage=1]="BackgroundImage"}(ln||(ln={})),function(e){e[e.BasicUser=1]="BasicUser";e[e.ExternalUser=2]="ExternalUser";e[e.RootUser=3]="RootUser"}(un||(un={})),function(e){e[e.GetInfo=1]="GetInfo"}(_n||(_n={})),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"}(mn||(mn={})),function(e){e[e.Apply=1]="Apply";e[e.Invite=2]="Invite";e[e.EnterpriseApply=3]="EnterpriseApply"}(gn||(gn={})),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"}(hn||(hn={})),function(e){e[e.Douyin=1]="Douyin"}(fn||(fn={})),function(e){e[e.GPTOpenAPI=1]="GPTOpenAPI";e[e.Maas=2]="Maas";e[e.LLMFlow=3]="LLMFlow";e[e.Merlin=4]="Merlin"}(yn||(yn={})),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"}(bn||(bn={})),function(e){e[e.All=0]="All";e[e.Unread=1]="Unread"}(vn||(vn={})),function(e){e[e.Bot=1]="Bot"}(Cn||(Cn={})),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"}(Sn||(Sn={})),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"}(Pn||(Pn={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ShortcutCommand=3]="ShortcutCommand";e[e.Task=4]="Task"}(En||(En={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Knowledge=4]="Knowledge"}(Tn||(Tn={})),function(e){e[e.NoPublish=0]="NoPublish";e[e.HadPublished=1]="HadPublished"}(An||(An={})),function(e){e[e.Success=1]="Success";e[e.Failed=2]="Failed";e[e.InReview=3]="InReview"}(kn||(kn={})),function(e){e[e.Unread=1]="Unread";e[e.Read=2]="Read"}(wn||(wn={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(Rn||(Rn={})),function(e){e[e.UnLimit=1]="UnLimit";e[e.Forbidden=2]="Forbidden"}(zn||(zn={})),function(e){e[e.Plugin=1]="Plugin";e[e.NewBotIDEGuide=2]="NewBotIDEGuide";e[e.NewBeginnerGuide=3]="NewBeginnerGuide"}(In||(In={})),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"}(On||(On={})),function(e){e[e.All=0]="All";e[e.Self=1]="Self"}(Ln||(Ln={})),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"}(jn||(jn={})),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"}(Un||(Un={})),function(e){e[e.EnterpriseUser=1]="EnterpriseUser";e[e.ExternalUser=2]="ExternalUser"}(Bn||(Bn={})),function(e){e[e.Normal=0]="Normal";e[e.DevMode=1]="DevMode"}(xn||(xn={})),function(e){e[e.DraftBot=1]="DraftBot";e[e.Project=2]="Project";e[e.Space=3]="Space";e[e.DouyinAvatarBot=4]="DouyinAvatarBot"}(qn||(qn={})),function(e){e[e.Default=0]="Default";e[e.Owner=1]="Owner";e[e.Admin=2]="Admin";e[e.Member=3]="Member"}(Dn||(Dn={})),function(e){e[e.Professional=1]="Professional"}(Mn||(Mn={})),function(e){e[e.Personal=1]="Personal";e[e.Team=2]="Team"}(Gn||(Gn={})),function(e){e[e.Dark=1]="Dark";e[e.Light=2]="Light"}(Nn||(Nn={})),function(e){e[e.AlwaysOn=0]="AlwaysOn";e[e.AlwaysOff=1]="AlwaysOff"}(Fn||(Fn={})),function(e){e[e.CozeAssistantGuide=1]="CozeAssistantGuide"}($n||($n={})),function(e){e[e.Normal=1]="Normal";e[e.Banned=2]="Banned";e[e.Canceled=3]="Canceled"}(Vn||(Vn={})),function(e){e[e.External=0]="External";e[e.Internal=1]="Internal"}(Wn||(Wn={})),function(e){e[e.Invisible=0]="Invisible";e[e.Visible=1]="Visible";e[e.SocietyInvisible=2]="SocietyInvisible"}(Hn||(Hn={})),function(e){e[e.SingleAgent=1]="SingleAgent";e[e.MultiAgent=2]="MultiAgent";e[e.WorkflowAsAgent=3]="WorkflowAsAgent"}(Kn||(Kn={})),function(e){e[e.Preset=1]="Preset";e[e.Library=2]="Library"}(Jn||(Jn={})),function(e){e[e.DatasetServiceValid=0]="DatasetServiceValid";e[e.DatasetServiceInvalid=1]="DatasetServiceInvalid"}(Qn||(Qn={})),function(e){e[e.DatasetValid=0]="DatasetValid";e[e.DatasetInvalid=1]="DatasetInvalid"}(Zn||(Zn={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(Yn||(Yn={})),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"}(Xn||(Xn={})),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"}(ea||(ea={})),function(e){e[e.SendTypeQuery=0]="SendTypeQuery";e[e.SendTypePanel=1]="SendTypePanel"}(ta||(ta={})),function(e){e[e.ToolTypeWorkFlow=1]="ToolTypeWorkFlow";e[e.ToolTypePlugin=2]="ToolTypePlugin"}(ia||(ia={}));class sa{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){sa.prototype.__init.call(this),sa.prototype.__init2.call(this),this.request=oa([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=oa([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}GetSpaceInfoV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/info"),s={space_id:i.space_id,join_space_type:i.join_space_type};return this.request({url:o,method:"POST",data:s},t)}DeleteSpaceV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/delete"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}SaveSpaceV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/save"),s={space_id:i.space_id,name:i.name,description:i.description,icon_uri:i.icon_uri,space_type:i.space_type,space_mode:i.space_mode,space_config:i.space_config,enterprise_id:i.enterprise_id,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}GetSpaceListV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/list"),s={search_word:i.search_word,enterprise_id:i.enterprise_id,organization_id:i.organization_id,scope_type:i.scope_type,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}UpdateAgent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/update_agent"),s={id:i.id,reference_id:i.reference_id,current_version:i.current_version,space_id:i.space_id,bot_id:i.bot_id,base_commit_version:i.base_commit_version,name:i.name,description:i.description,position:i.position,icon_uri:i.icon_uri,intents:i.intents,work_info:i.work_info,is_delete:i.is_delete};return this.request({url:o,method:"POST",data:s},t)}BatchCreateAgent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/batch_create_agent"),s={space_id:i.space_id,bot_id:i.bot_id,agent_type:i.agent_type,position:i.position,references:i.references,agent_cnt:i.agent_cnt,base_commit_version:i.base_commit_version,version_compat:i.version_compat};return this.request({url:o,method:"POST",data:s},t)}GetPublishBotList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_publish_bot_list"),s={space_id:i.space_id,bot_mode:i.bot_mode,page_num:i.page_num,page_size:i.page_size,name:i.name,login_user_create:i.login_user_create,bot_id:i.bot_id};return this.request({url:o,method:"GET",params:s},t)}MGetBotByVersion(e,t){const i=e,o=this.genBaseURL("/api/playground_api/mget_bot_by_version"),s={bot_versions:i.bot_versions,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}BotLastPublishInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bot_last_publish_info"),s={space_id:i.space_id,bot_id:i.bot_id,bot_mode:i.bot_mode};return this.request({url:o,method:"GET",params:s},t)}ProduceBot(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/produce/create_bot"),s={space_id:i.space_id,name:i.name,description:i.description,icon_url:i.icon_url,icon_uri:i.icon_uri,prompt:i.prompt,plugin_apis:i.plugin_apis,prologue:i.prologue,suggested_questions:i.suggested_questions,bot_source:i.bot_source};return this.request({url:o,method:"POST",data:s},t)}UpdateProducedBot(e,t){const i=e,o=this.genBaseURL("/api/playground_api/produce/update_bot"),s={bot_id:i.bot_id,name:i.name,description:i.description,icon_url:i.icon_url,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}GetPublishedBotList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bot_version/get_published_bot_list"),s={space_id_list:i.space_id_list,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}GetBotVersionInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bot_version/get_bot_version_info"),s={bot_id:i.bot_id,version:i.version,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}DuplicateBotVersionToSpace(e,t){const i=e,o=this.genBaseURL("/api/playground_api/dup_bot_version"),s={target_space_id:i.target_space_id,bot_id:i.bot_id,version:i.version,name:i.name,dup_society_host:i.dup_society_host};return this.request({url:o,method:"POST",data:s},t)}UpdateUserRiskAlertInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/update_user_risk_alert_info"),s={risk_alert_type:i.risk_alert_type,switch_info:i.switch_info};return this.request({url:o,method:"POST",data:s},t)}GetUserRiskAlertInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_user_risk_alert_info"),s={risk_alert_type_list:i.risk_alert_type_list,switch_type_list:i.switch_type_list},n={Cookie:i.Cookie};return this.request({url:o,method:"POST",data:s,headers:n},t)}DraftBotCollaboration(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/collaboration"),s={space_id:i.space_id,bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}BotInfoAudit(e,t){const i=e,o=this.genBaseURL("/api/playground_api/audit/bot_info"),s={bot_id:i.bot_id,bot_audit_info:i.bot_audit_info,space_id:i.space_id,bot_mode:i.bot_mode};return this.request({url:o,method:"POST",data:s},t)}TimeCapsuleInvokeEvent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/timecapsule_invoke_event"),s={bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}InviteMemberLinkV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/invite"),s={space_id:i.space_id,team_invite_link_status:i.team_invite_link_status,func:i.func};return this.request({url:o,method:"POST",data:s},t)}SpaceMemberDetailV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/detail"),s={space_id:i.space_id,search_word:i.search_word,space_role_type:i.space_role_type,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}JoinSpaceV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/join"),s={space_id:i.space_id,join_space_type:i.join_space_type,is_reject:i.is_reject};return this.request({url:o,method:"POST",data:s},t)}UpdateSpaceMemberV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/update"),s={space_id:i.space_id,user_id:i.user_id,space_role_type:i.space_role_type};return this.request({url:o,method:"POST",data:s},t)}TransferSpaceV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/transfer"),s={space_id:i.space_id,transfer_user_id:i.transfer_user_id};return this.request({url:o,method:"POST",data:s},t)}RemoveSpaceMemberV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/remove"),s={space_id:i.space_id,remove_user_id:i.remove_user_id,transfer_user_id:i.transfer_user_id};return this.request({url:o,method:"POST",data:s},t)}SearchMemberV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/member/search"),s={search_list:i.search_list,space_id:i.space_id,search_volcano_account_list:i.search_volcano_account_list,page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}AddBotSpaceMemberV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/member/add"),s={member_info_list:i.member_info_list,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}ExitSpaceV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/member/exit"),s={space_id:i.space_id,transfer_user_id:i.transfer_user_id};return this.request({url:o,method:"POST",data:s},t)}GetBotPopupInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/operate/get_bot_popup_info"),s={bot_popup_types:i.bot_popup_types,bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}UpdateBotPopupInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/operate/update_bot_popup_info"),s={bot_popup_type:i.bot_popup_type,bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}GenerateDescription(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/generate_description"),s={bot_name:i.bot_name,prompt:i.prompt};return this.request({url:o,method:"POST",data:s},t)}DraftBotPublishHistoryDetail(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/publish_history_detail"),s={bot_id:i.bot_id,space_id:i.space_id,publish_id:i.publish_id,version:i.version};return this.request({url:o,method:"POST",data:s},t)}GenerateStoreCategory(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/generate_store_category"),s={bot_name:i.bot_name,bot_description:i.bot_description,prompt:i.prompt};return this.request({url:o,method:"POST",data:s},t)}UpdateMultiAgent(e,t){const i=e,o=this.genBaseURL("/api/playground_api/update_multi_agent"),s={space_id:i.space_id,bot_id:i.bot_id,session_type:i.session_type,base_commit_version:i.base_commit_version,connector_type:i.connector_type};return this.request({url:o,method:"POST",data:s},t)}SwitchAgentVersion(e,t){const i=e,o=this.genBaseURL("/api/playground_api/switch_agent_version"),s={bot_id:i.bot_id,space_id:i.space_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}LangDetect(e,t){const i=e,o=this.genBaseURL("/api/playground_api/audio/lang/detect"),s={detect_text_list:i.detect_text_list};return this.request({url:o,method:"POST",data:s},t)}GetImagexShortUrl(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_imagex_url"),s={uris:i.uris,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetPlatformCommonConfig(e,t){const i=this.genBaseURL("/api/playground_api/get_platform_common_config");return this.request({url:i,method:"GET"},t)}CreateShortcutCommand(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/create_shortcut_command"),s={object_id:i.object_id,shortcuts:i.shortcuts};return this.request({url:o,method:"POST",data:s},t)}MGetUserBasicInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/mget_user_info"),s={user_ids:i.user_ids,need_user_status:i.need_user_status,need_enterprise_identity:i.need_enterprise_identity,need_volcano_user_name:i.need_volcano_user_name};return this.request({url:o,method:"POST",data:s},t)}BindVolcanoTrn(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/bind_volcano_trn"),s={space_id:i.space_id,trn:i.trn,account_name:i.account_name};return this.request({url:o,method:"POST",data:s},t)}UnbindVolcanoTrn(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/unbind_volcano_trn"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}RetrieveFileOpen(e,t){const i=e,o=this.genBaseURL("/v1/files/retrieve"),s={file_id:i.file_id};return this.request({url:o,method:"GET",params:s},t)}RetrieveFileContentOpen(e,t){const i=e,o=this.genBaseURL("/v1/files/content/retrieve"),s={file_id:i.file_id};return this.request({url:o,method:"GET",params:s},t)}UploadFileOpen(e,t){const i=e,o=this.genBaseURL("/v1/files/upload"),s={Data:i.Data},n={"Content-Type":i["Content-Type"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}BotInfoCheck(e,t){const i=e,o=this.genBaseURL("/api/playground_api/check/bot_info_check"),s={bot_id:i.bot_id,space_id:i.space_id,bot_audit_info:i.bot_audit_info};return this.request({url:o,method:"POST",data:s},t)}SupportVoiceCall(e,t){const i=e,o=this.genBaseURL("/api/playground_api/support_voice_call"),s={voice_id_list:i.voice_id_list};return this.request({url:o,method:"POST",data:s},t)}CreateUpdateShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/playground_api/create_update_shortcut_command"),s={object_id:i.object_id,space_id:i.space_id,shortcuts:i.shortcuts};return this.request({url:o,method:"POST",data:s},t)}MoveDraftBot(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/move_draft_bot"),s={bot_id:i.bot_id,target_spaceId:i.target_spaceId,from_spaceId:i.from_spaceId,move_action:i.move_action};return this.request({url:o,method:"POST",data:s},t)}GetShortcutAvailNodes(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_shortcut_avail_nodes"),s={bot_id:i.bot_id,space_id:i.space_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}MarkReadNotice(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gen_img/mark_read_notice"),s={bot_id:i.bot_id,pic_type:i.pic_type};return this.request({url:o,method:"POST",data:s},t)}CancelGenerateGif(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gen_img/cancel_generate_gif"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}GetPicTask(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gen_img/get_pic_task"),s={bot_id:i.bot_id,pic_type:i.pic_type};return this.request({url:o,method:"POST",data:s},t)}GeneratePic(e,t){const i=e,o=this.genBaseURL("/api/playground_api/gen_img/generate_pic"),s={gen_prompt:i.gen_prompt,image_url:i.image_url,image_uri:i.image_uri,bot_id:i.bot_id,pic_type:i.pic_type,device_id:i.device_id,bot_name:i.bot_name,bot_desc:i.bot_desc};return this.request({url:o,method:"POST",data:s},t)}GetGenPicTimes(e,t){const i=this.genBaseURL("/api/playground_api/gen_img/get_gen_pic_times");return this.request({url:i,method:"POST"},t)}ListStyle(e,t){const i=this.genBaseURL("/api/playground_api/gen_img/list_style");return this.request({url:i,method:"POST"},t)}GetFileUrls(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_file_list"),s={scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetDraftBotInfoAgw(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/get_draft_bot_info"),s={bot_id:i.bot_id,version:i.version,commit_version:i.commit_version};return this.request({url:o,method:"POST",data:s},t)}CommitDraftBotInfoAgw(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/commit_draft_bot_info"),s={bot_id:i.bot_id,remark:i.remark};return this.request({url:o,method:"POST",data:s},t)}UpdateDraftBotInfoAgw(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/draftbot/update_draft_bot_info"),s={bot_info:i.bot_info,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}GetUserQueryCollectOption(e,t){const i=this.genBaseURL("/api/playground_api/draftbot/get_user_query_collect_option");return this.request({url:i,method:"GET"},t)}GenerateUserQueryCollectPolicy(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/draftbot/generate_user_query_collect_policy"),s={bot_id:i.bot_id,developer_name:i.developer_name,contact_information:i.contact_information};return this.request({url:o,method:"POST",data:s},t)}GetCozeProRights(e,t){const i=this.genBaseURL("/api/playground_api/get_coze_pro_rights");return this.request({url:i,method:"POST"},t)}GetPolicyContent(e,t){const i=e,o=this.genBaseURL(`/api/playground_api/private_policy/${i.secret}`);return this.request({url:o,method:"GET"},t)}UpdateAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/update_agent_v2"),s={id:i.id,reference_id:i.reference_id,current_version:i.current_version,space_id:i.space_id,bot_id:i.bot_id,base_commit_version:i.base_commit_version,name:i.name,description:i.description,position:i.position,icon_uri:i.icon_uri,intents:i.intents,is_delete:i.is_delete,prompt_info:i.prompt_info,model_info:i.model_info,plugin_info_list:i.plugin_info_list,knowledge:i.knowledge,workflow_info_list:i.workflow_info_list,jump_config:i.jump_config,suggest_reply_info:i.suggest_reply_info,hook_info:i.hook_info};return this.request({url:o,method:"POST",data:s},t)}CopyAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/copy_agent_v2"),s={bot_id:i.bot_id,agent_id:i.agent_id,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}CreateAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/create_agent_v2"),s={bot_id:i.bot_id,agent_type:i.agent_type,position:i.position,references:i.references,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}BatchCreateAgentV2(e,t){const i=e,o=this.genBaseURL("/api/playground_api/batch_create_agent_v2"),s={bot_id:i.bot_id,agent_type:i.agent_type,position:i.position,references:i.references,agent_cnt:i.agent_cnt,base_commit_version:i.base_commit_version};return this.request({url:o,method:"POST",data:s},t)}CozeProCopyGetLinkMetaInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/get_link_meta_info"),s={auth_code:i.auth_code};return this.request({url:o,method:"POST",data:s},t)}CozeProCopyTaskConfirm(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/copy_task_confirm"),s={auth_code:i.auth_code};return this.request({url:o,method:"POST",data:s},t)}CozeProCopyGenerateAuthLink(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/generate_auth_link"),s={copy_user_id:i.copy_user_id,target_space_id:i.target_space_id};return this.request({url:o,method:"POST",data:s},t)}GetOpVoiceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_op_voice_list"),s={voice_ids:i.voice_ids,name:i.name,style_id:i.style_id,language_code:i.language_code,status:i.status,page_index:i.page_index,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetSupportLanguage(e,t){const i=this.genBaseURL("/api/playground_api/get_support_language");return this.request({url:i,method:"GET"},t)}SynchronizeVoiceList(e,t){const i=this.genBaseURL("/api/playground_api/synchronize_voice_list");return this.request({url:i,method:"GET"},t)}CheckBotAllModelPluginIds(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/check_bot_all_model_plugin_ids"),s={bot_id:i.bot_id,commit_version:i.commit_version};return this.request({url:o,method:"POST",data:s},t)}GetBotCollaborationQuota(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/collaboration_quota"),s={bot_id:i.bot_id,only_config_item:i.only_config_item,account_type:i.account_type};return this.request({url:o,method:"POST",data:s},t)}OpenCreateSpace(e,t){const i=e||{},o=this.genBaseURL("/v1/workspaces"),s={name:i.name,description:i.description,icon_file_id:i.icon_file_id,coze_account_id:i.coze_account_id,owner_uid:i.owner_uid};return this.request({url:o,method:"POST",data:s},t)}NoticeMarkRead(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/notice/mark_read"),s={notice_ids:i.notice_ids,mark_all:i.mark_all};return this.request({url:o,method:"POST",data:s},t)}GetNoticeList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/notice/get_list"),s={cursor:i.cursor,count:i.count,notice_rank_type:i.notice_rank_type};return this.request({url:o,method:"POST",data:s},t)}GetNoticeUnreadCount(e,t){const i=this.genBaseURL("/api/playground_api/notice/get_unread_count");return this.request({url:i,method:"POST"},t)}OpenSpaceList(e,t){const i=e||{},o=this.genBaseURL("/v1/workspaces"),s={page_num:i.page_num,page_size:i.page_size,enterprise_id:i.enterprise_id,user_id:i.user_id,coze_account_id:i.coze_account_id,scope:i.scope};return this.request({url:o,method:"GET",params:s},t)}ReportUserBehavior(e,t){const i=e,o=this.genBaseURL("/api/playground_api/report_user_behavior"),s={resource_id:i.resource_id,resource_type:i.resource_type,behavior_type:i.behavior_type,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetUserConfig(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_user_config"),s={risk_alert_type_list:i.risk_alert_type_list,switch_type_list:i.switch_type_list},n={Cookie:i.Cookie};return this.request({url:o,method:"POST",data:s,headers:n},t)}UpdateUserConfig(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/update_user_config"),s={risk_alert_type:i.risk_alert_type,switch_info:i.switch_info};return this.request({url:o,method:"POST",data:s},t)}GetRecentDraftBotList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/draftbot/get_recent_draft_bot"),s={behavior_type:i.behavior_type,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}GetPromptResourceInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_prompt_resource_info"),s={prompt_resource_id:i.prompt_resource_id};return this.request({url:o,method:"GET",params:s},t)}UpsertPromptResource(e,t){const i=e,o=this.genBaseURL("/api/playground_api/upsert_prompt_resource"),s={prompt:i.prompt};return this.request({url:o,method:"POST",data:s},t)}DeletePromptResource(e,t){const i=e,o=this.genBaseURL("/api/playground_api/delete_prompt_resource"),s={prompt_resource_id:i.prompt_resource_id};return this.request({url:o,method:"POST",data:s},t)}GetPromptReferenceInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/get_prompt_reference_info"),s={space_id:i.space_id,reference_id:i.reference_id,reference_type:i.reference_type,api_id:i.api_id,project_id:i.project_id,avatar_bot_id:i.avatar_bot_id};return this.request({url:o,method:"POST",data:s},t)}GetOfficialPromptResourceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_official_prompt_list"),s={keyword:i.keyword};return this.request({url:o,method:"POST",data:s},t)}GetByteTreeByName(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/search_byte_tree"),s={name:i.name},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}CreatePrivateModel(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/create_private_model"),s={space_id:i.space_id,model_vendor:i.model_vendor,model_show_name:i.model_show_name,model_arch:i.model_arch,ak:i.ak,token_limit:i.token_limit,upper_limit_of_max_token:i.upper_limit_of_max_token,function_call:i.function_call,multimodal:i.multimodal,multimodal_types:i.multimodal_types,form_detail:i.form_detail,record_id:i.record_id,maas_model_name:i.maas_model_name,maas_model_version:i.maas_model_version,maas_model_customer_id:i.maas_model_customer_id,model_family:i.model_family,space_id_i18n:i.space_id_i18n,operator:i.operator,email:i.email,employee_id:i.employee_id,presence_penalty_config:i.presence_penalty_config,frequency_penalty_config:i.frequency_penalty_config,temperature_config:i.temperature_config,top_p_config:i.top_p_config},n={"x-inner-auth":i["x-inner-auth"],"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}CheckExemptFormInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/check_exempt_form_info"),s={exempt_form_type:i.exempt_form_type,space_id:i.space_id},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}SetByteTreeForSpace(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/bpm/set_byte_tree_for_space"),s={space_id:i.space_id,byte_tree_node_id:i.byte_tree_node_id,byte_tree_node_name:i.byte_tree_node_name,form_detail:i.form_detail,record_id:i.record_id},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}GetModelCapability(e,t){const i=e,o=this.genBaseURL("/api/playground_api/bpm/get_model_capability"),s={vendor:i.vendor,model_arch:i.model_arch,maas_model_name:i.maas_model_name,maas_model_version:i.maas_model_version,maas_customer_id:i.maas_customer_id},n={"x-jwt-token":i["x-jwt-token"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}GetSpaceDetail(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/detail"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}RevocateSpaceInvite(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/revocate_invite"),s={space_id:i.space_id,invite_user_id:i.invite_user_id};return this.request({url:o,method:"GET",params:s},t)}SaveVolcanoUserManageInfo(e,t){const i=e,o=this.genBaseURL("/api/playground_api/coze_pro/save_volcano_user_manage_info"),s={volcano_basic_user_config:i.volcano_basic_user_config};return this.request({url:o,method:"POST",data:s},t)}GetVolcanoUserManageInfo(e,t){const i=this.genBaseURL("/api/playground_api/coze_pro/get_volcano_user_manage_info");return this.request({url:i,method:"POST"},t)}GetSpaceInviteManageList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/invite_manage_list"),s={space_id:i.space_id,space_invite_status:i.space_invite_status,search_word:i.search_word,page:i.page,size:i.size};return this.request({url:o,method:"GET",params:s},t)}DebugDouYin(e,t){const i=e,o=this.genBaseURL("/api/playground_api/douyin/debug"),s={bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}GetDouYinAuthCode(e,t){const i=this.genBaseURL("/api/playground_api/douyin/get_auth_qr_code");return this.request({url:i,method:"GET"},t)}GetDouyinAvatarInfo(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/douyin/v1/get_avatar_info"),s={is_draft:i.is_draft,body:i.body},n={"Open-Platform-App-ID":i["Open-Platform-App-ID"],"Byte-Signature":i["Byte-Signature"],"Byte-Timestamp":i["Byte-Timestamp"],"Byte-Nonce-Str":i["Byte-Nonce-Str"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}DouYinAuthUserList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/douyin/auth_user_list"),s={page_index:i.page_index,page_size:i.page_size,bind_status:i.bind_status,order_by:i.order_by};return this.request({url:o,method:"POST",data:s},t)}GetDebugDouYinStatus(e,t){const i=e,o=this.genBaseURL("/api/playground_api/douyin/get_debug_status"),s={bot_id:i.bot_id};return this.request({url:o,method:"POST",data:s},t)}CanUserApplyClose(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/coze_pro/can_user_apply_close"),s={AccountId:i.AccountId,EventName:i.EventName,Action:i.Action,Version:i.Version},n={"X-Tt-Logid":i["X-Tt-Logid"],"X-Top-Service":i["X-Top-Service"],"X-Top-Region":i["X-Top-Region"]};return this.request({url:o,method:"GET",params:s,headers:n},t)}CreateRoom(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/create_room"),s={bot_id:i.bot_id,conversation_id:i.conversation_id,scene:i.scene,voice_id:i.voice_id,video_config:i.video_config};return this.request({url:o,method:"POST",data:s},t)}GetVoiceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_voice_list"),s={page_index:i.page_index,page_size:i.page_size,language_code:i.language_code};return this.request({url:o,method:"POST",data:s},t)}GetVoiceByIds(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_voice_by_ids"),s={voice_id_map:i.voice_id_map,voice_type:i.voice_type,space_id:i.space_id,emotion_config:i.emotion_config,voice_biz_scene:i.voice_biz_scene};return this.request({url:o,method:"POST",data:s},t)}GrayVoice(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/gray_voice"),s={bot_id:i.bot_id,language_to_voice_id:i.language_to_voice_id};return this.request({url:o,method:"POST",data:s},t)}GetSpaceApplyManageList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/apply_manage_list"),s={space_id:i.space_id,space_apply_status:i.space_apply_status,search_word:i.search_word,page:i.page,size:i.size};return this.request({url:o,method:"GET",params:s},t)}DraftBotCrossSpaceCopy(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/draftbot/crossspace_copy"),s={bot_id:i.bot_id,to_space_id:i.to_space_id};return this.request({url:o,method:"POST",data:s},t)}RemovePublishMember(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/remove_publish_member"),s={space_id:i.space_id,member_list:i.member_list};return this.request({url:o,method:"POST",data:s},t)}AddPublishMember(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/add_publish_member"),s={space_id:i.space_id,member_list:i.member_list};return this.request({url:o,method:"POST",data:s},t)}SearchAddablePublishMember(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/search_addable_publish_member"),s={space_id:i.space_id,search_word:i.search_word,cursor_id:i.cursor_id,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}PublishMemberList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/space/publish_member_list"),s={space_id:i.space_id,search_word:i.search_word,cursor_id:i.cursor_id,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}OperateSpaceApply(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/operate_apply"),s={space_id:i.space_id,enterprise_id:i.enterprise_id,organization_id:i.organization_id,apply_id_list:i.apply_id_list,space_apply_status:i.space_apply_status};return this.request({url:o,method:"POST",data:s},t)}ImportSpaceConfirm(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/import/confirm"),s={space_id_list:i.space_id_list,enterprise_id:i.enterprise_id,organization_id:i.organization_id,personal_space_new_name:i.personal_space_new_name,user_id_list:i.user_id_list};return this.request({url:o,method:"POST",data:s},t)}ImportSpaceList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/import/list"),s={enterprise_id:i.enterprise_id,organization_id:i.organization_id,search_word:i.search_word};return this.request({url:o,method:"GET",params:s},t)}ImportSpaceUserList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/space/import/user_list"),s={space_id_list:i.space_id_list,enterprise_id:i.enterprise_id,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}GetDouYinInfo(e,t){const i=this.genBaseURL("/api/playground_api/douyin/get_douyin_info");return this.request({url:i,method:"POST"},t)}LongTermMemoryList(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/list"),s={bot_id:i.bot_id,connector_id:i.connector_id,offset:i.offset,limit:i.limit,time_capsule_item_type:i.time_capsule_item_type};return this.request({url:o,method:"GET",params:s},t)}LongTermMemoryUpdate(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/update"),s={bot_id:i.bot_id,connector_id:i.connector_id,biz_id:i.biz_id,new_content:i.new_content,event_ms:i.event_ms,ext:i.ext,tags:i.tags,time_capsule_item_type:i.time_capsule_item_type,iid:i.iid,meta_type:i.meta_type,memory_type:i.memory_type};return this.request({url:o,method:"POST",data:s},t)}LongTermMemoryClearAll(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/clear_all"),s={bot_id:i.bot_id,connector_id:i.connector_id,time_capsule_item_type:i.time_capsule_item_type};return this.request({url:o,method:"POST",data:s},t)}LongTermMemoryDelete(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/delete"),s={bot_id:i.bot_id,connector_id:i.connector_id,biz_ids:i.biz_ids,time_capsule_item_type:i.time_capsule_item_type,iids:i.iids,memory_meta_type_map:i.memory_meta_type_map};return this.request({url:o,method:"POST",data:s},t)}LongTermMemoryVersion(e,t){const i=e,o=this.genBaseURL("/api/playground_api/long_term_memory/version"),s={bot_id:i.bot_id};return this.request({url:o,method:"GET",params:s},t)}GetVoiceListV2(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_voice_list_v2"),s={language_code:i.language_code,space_id:i.space_id,voice_type:i.voice_type,page_size:i.page_size,next_cursor:i.next_cursor};return this.request({url:o,method:"POST",data:s},t)}GetUserUpdateProfileTag(e,t){const i=this.genBaseURL("/api/playground_api/get_user_update_profile_tag");return this.request({url:i,method:"GET"},t)}OpenRemoveSpaceMember(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members`),s={user_ids:i.user_ids};return this.request({url:o,method:"DELETE",data:s},t)}OpenSpaceMemberList(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members`),s={page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}OpenAddSpaceMember(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members`),s={users:i.users};return this.request({url:o,method:"POST",data:s},t)}OpenGetBotInfo(e,t){const i=e||{},o=this.genBaseURL(`/v1/bots/${i.bot_id}`),s={is_published:i.is_published,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}OpenApplyJoinSpace(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members/apply`),s={user_ids:i.user_ids};return this.request({url:o,method:"POST",data:s},t)}OpenRemoveSpace(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}`);return this.request({url:o,method:"DELETE"},t)}GetTypeList(e,t){const i=e||{},o=this.genBaseURL("/api/playground_api/get_type_list"),s={model:i.model,voice:i.voice,raw_model:i.raw_model,space_id:i.space_id,cur_model_id:i.cur_model_id,cur_model_ids:i.cur_model_ids,model_scene:i.model_scene,tag_filters:i.tag_filters};return this.request({url:o,method:"POST",data:s},t)}GetCozeLaneInfo(e,t){const i=this.genBaseURL("/api/playground_api/get_coze_lane_info");return this.request({url:i,method:"POST"},t)}OpenUpdateSpaceMember(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}/members/${i.user_id}`),s={role_type:i.role_type};return this.request({url:o,method:"PUT",data:s},t)}OpenListBotVersions(e,t){const i=e||{},o=this.genBaseURL(`/v1/bots/${i.bot_id}/versions`),s={page_num:i.page_num,page_size:i.page_size,publish_status:i.publish_status,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}OpenSwitchBotDevelopMode(e,t){const i=e||{},o=this.genBaseURL(`/v1/bots/${i.bot_id}/collaboration_mode`),s={collaboration_mode:i.collaboration_mode};return this.request({url:o,method:"POST",data:s},t)}OpenUpdateSpace(e,t){const i=e||{},o=this.genBaseURL(`/v1/workspaces/${i.workspace_id}`),s={name:i.name,description:i.description};return this.request({url:o,method:"PUT",data:s},t)}}const na=new sa({});function aa(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}async function ra(i,o){if(aa([i,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipAuth]))return void await o();if(!i.config.accessToken)throw new e.CozeError(e.ErrorCode.E2001,"No API token found. Please authenticate first.",void 0,{fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"});if(aa([i,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipOrgCheck]))return void await o();const s=await async function(i){let o=i.config.organizationId,{enterpriseId:s}=i.config,n=!1;const{data:a}=await ao.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0}),r=a.enterprise_info_list||[],c=a.personal_account_info;if(o){if(!r.some(e=>aa([e,"access",e=>e.organization_info_list,"optionalAccess",e=>e.some,"call",e=>e(e=>e.organization_id===o)])))throw new e.CozeError(e.ErrorCode.E1000,`Organization ID ${o} is invalid or not found`,void 0,{fix:"Run `coze organization list` and select a valid organization",example:"coze organization use <organization_id>"})}else{if(c.available)return!1;let a;i.ui.info(t.gray("[Context] Organization ID not found. Attempting to auto-initialize..."));for(const e of r)if(e.organization_info_list&&e.organization_info_list.length>0){const t=e.organization_info_list[0];a={id:t.organization_id,name:t.organization_name,entId:e.enterprise_id};break}if(!a)throw new e.CozeError(e.ErrorCode.E3000,"No organizations found",void 0,{fix:"Create an organization or join an existing one",example:"coze organization list"});o=a.id,s=a.entId,i.config.organizationId=o,i.config.enterpriseId=s,n=!0,i.ui.info(`[Context] Auto-selected Organization: ${a.name} (${a.id})`)}return n}(i);if(aa([i,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipSpaceCheck]))return s&&await ca(i,{organizationId:i.config.organizationId,enterpriseId:i.config.enterpriseId}),void await o();const n=await async function(t){const i=t.config.organizationId,{enterpriseId:o}=t.config;let{spaceId:s}=t.config,n=!1;try{if(s){const{data:t}=await na.GetSpaceListV2({organization_id:i,enterprise_id:o}),n=aa([t,"optionalAccess",e=>e.bot_space_list])||[];if(!n.some(e=>e.id===s)){const t=i?`[Context] Space ID ${s} is invalid or not found in organization ${i}.`:`[Context] Space ID ${s} is invalid or not found.`;throw new e.CozeError(e.ErrorCode.E1000,t,void 0,{fix:"Run `coze space list` and select a valid space",example:"coze space use <space_id>"})}}else{t.ui.info("[Context] Space ID not found. Attempting to auto-initialize...");const{data:a}=await na.GetSpaceListV2({organization_id:i,enterprise_id:o,page:1,size:1}),r=aa([a,"optionalAccess",e=>e.bot_space_list,"optionalAccess",e=>e[0]]);if(!r){const t=i?`[Context] No spaces found in organization ${i}. Please create one.`:"[Context] No spaces found. Please create one.";throw new e.CozeError(e.ErrorCode.E3000,t,void 0,{fix:"Create a space in the current organization",example:"coze space list"})}s=r.id,t.config.spaceId=s,n=!0,t.ui.success(`[Context] Auto-selected Space: ${r.name} (${r.id})`)}}catch(t){const i=t instanceof e.CozeError?t:new e.CozeError(e.ErrorCode.E5000,t.message,t instanceof Error?t.stack:t);throw i.fix??="Switch organization or space using `coze organization use <organization_id>` or `coze space use <space_id>`",i.example??="coze organization list",i}return n}(i);await da(i),(s||n)&&await ca(i,{organizationId:i.config.organizationId,enterpriseId:i.config.enterpriseId,spaceId:i.config.spaceId,billingProjectId:i.config.billingProjectId}),await o()}async function ca(e,t){try{await ie(t)}catch(t){e.ui.warn(`Failed to save auto-initialized context: ${t}`)}}const da=async t=>{const{spaceId:i}=t.config;try{const{data:o}=await e.IdeApi.GetOrCreateBillingProject({space_id:i});if(!aa([o,"optionalAccess",e=>e.project_id]))throw new e.CozeError(e.ErrorCode.E5002,"[Context] Failed to get billing project ID from response.",o);t.config.billingProjectId=o.project_id,t.ui.success(`[Context] Billing Project: ${o.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 pa(e,t){return null!=e?e:t()}function la(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const ua=t=>{const i=t.command("space").config({skipSpaceCheck:!0,help:{brief:"Workspace (Space) context management commands",description:"Provides workspace viewing and switching functionality, used to set the default Space ID for subsequent commands",examples:[{desc:"List all available workspaces",cmd:"coze space list"},{desc:"Set default space",cmd:"coze space use 123456789"}],seeAlso:["coze organization"]}}).description("Manage workspace (Space) context");i.command("list").description("List all spaces").config({help:{brief:"List all workspaces under the current organization",description:"Retrieve and display a list of all available Spaces under the currently configured Organization or Enterprise. Defaults to fetching up to the first 100.",examples:[{desc:"List space list",cmd:"coze space list",tags:["[RECOMMENDED]"]},{desc:"List in JSON format",cmd:"coze space list --format json"}],schema:{output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Space ID"},name:{type:"string",description:"Space name"},org_id:{type:"string",description:"Belonging Organization ID"}}}}}}}).action(async(e,t)=>{const i=t.getContext(),o=e.orgId||la([i,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),s=la([i,"optionalAccess",e=>e.config,"access",e=>e.enterpriseId]);la([i,"optionalAccess",e=>e.ui,"access",e=>e.verbose,"call",e=>e(`Fetching spaces for organization '${o}'...`)]);const n=await async function(e){const{data:t}=await na.GetSpaceListV2({organization_id:e.orgId,enterprise_id:e.enterpriseId,page:1,size:100});return pa(function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}([t,"optionalAccess",e=>e.bot_space_list]),()=>[]).map(t=>({id:pa(t.id,()=>""),name:pa(t.name,()=>""),org_id:pa(e.orgId,()=>"")}))}({orgId:o,enterpriseId:s});la([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Spaces:")]),la([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)]);const a=["Please use the following command to switch space:"," coze space use <space_id>"];la([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(a.join("\n"))])}),i.command("use").description("Set the default workspace context").argument("<space_id>","Space ID to set as default context").config({help:{brief:"Switch current default Space",description:"Save the specified space_id to the local configuration as the default workspace for subsequent commands.",examples:[{desc:"Switch space",cmd:"coze space use 7349123847123",tags:["[RECOMMENDED]"]}],schema:{input:{space_id:{type:"string",required:!0,description:"Space ID to switch to"}},output:{status:{type:"string"},message:{type:"string"}}}}}).action(async(t,i,o)=>{const s=o.getContext();la([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to space '${t}'...`)]),await async function(t){try{await ie({spaceId:t})}catch(i){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set default space to '${t}': ${i.message}`,i.stack)}}(t),la([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default space set to '${t}' successfully.`)]),"json"===la([s,"optionalAccess",e=>e.format])&&la([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default space set to '${t}'.`})])})};function _a(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const ma=async t=>{_a([t,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switching to personal account...")]);const{available:i}=await async function(){const[e,{data:t}]=await Promise.all([te(),ao.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);if(!function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}([t.personal_account_info,"optionalAccess",e=>e.available]))return{available:!1};const i=!!e.organizationId;return await ie({organizationId:void 0,enterpriseId:void 0,...i?{spaceId:void 0}:{}}),{available:!0}}();if(!i)throw new e.CozeError(e.ErrorCode.E1000,"Personal account is not available for the current user.");_a([t,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switched to personal account successfully.")]),"json"===_a([t,"optionalAccess",e=>e.format])&&_a([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:"Switched to personal account."})])},ga=t=>{const i=t.command("organization").config({skipOrgCheck:!0,help:{brief:"Manage organization context",description:"Provides viewing and switching functions for organizations, used to set the default Organization ID for subsequent commands. Supports switching to personal account by omitting the org_id.",examples:[{desc:"List all accessible organizations",cmd:"coze organization list"},{desc:"Set default organization",cmd:"coze organization use 123456"},{desc:"Switch to personal account",cmd:"coze organization use"},{desc:"List organizations (alias)",cmd:"coze org list"},{desc:"Set default organization (alias)",cmd:"coze org use 123456"}],seeAlso:["coze space"]}}).alias("org").description("Manage organization context");i.command("list").description("List all accessible organizations").config({help:{brief:"List all accessible organizations",description:"Retrieve and display all organizations (Teams) and their corresponding enterprises accessible to the current logged-in user.",examples:[{desc:"List organizations",cmd:"coze organization list",tags:["[RECOMMENDED]"]},{desc:"Output in JSON format",cmd:"coze organization list --format json"}],schema:{output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Organization ID"},name:{type:"string",description:"Organization name"},enterprise_id:{type:"string",description:"Belonging Enterprise ID"},enterprise_name:{type:"string",description:"Belonging Enterprise name"}}}}}}}).action(async(e,t)=>{const i=t.getContext();_a([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching organizations...")]);const o=await async function(){const{data:e}=await ao.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})))}();_a([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Organizations (Teams):")]),_a([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(o)]);const s=["Please use the following command to switch organization:"," coze organization use <organization_id>","Please use the following command to switch space:"," coze space list"," coze space use <space_id>"];_a([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])}),i.command("use").description("Set the default organization context").argument("[org_id]","Organization ID to set as default context (empty to switch to personal account)").config({help:{brief:"Set default organization or switch to personal account",description:"Save the specified org_id to the local configuration as the default organization for subsequent commands. The command will automatically retrieve and save the corresponding Enterprise ID. If the org_id is not found in the user's enterprise list, the command will fail without modifying the configuration. When switching to a different organization, the saved spaceId will be cleared. Omit org_id to switch to personal account mode (requires personal account to be available).",examples:[{desc:"Switch organization",cmd:"coze organization use 12345678",tags:["[RECOMMENDED]"]},{desc:"Switch to personal account",cmd:"coze organization use"},{desc:"Switch to personal account (explicit empty string)",cmd:'coze organization use ""'}],errors:[{code:e.ErrorCode.E3001,name:"RESOURCE_NOT_FOUND",desc:"Organization not found",fix:"Run `coze organization list` to see available organizations."},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Personal account not available",fix:"Your account does not have personal account access. Use `coze organization use <org_id>` to switch to an organization instead."}],schema:{input:{org_id:{type:"string",required:!1,description:"Organization ID to switch to. Empty or omitted to switch to personal account."}},output:{status:{type:"string",description:"Operation result status"},message:{type:"string",description:"Human-readable result message"},enterprise_id:{type:"string",description:"Enterprise ID of the selected organization (empty for personal account)"},organization_id:{type:"string",description:"Organization ID that was set (empty for personal account)"}}}}}).action(async(t,i,o)=>{const s=o.getContext();if(!t)return void await ma(s);_a([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to organization '${t}'...`)]);const{enterpriseId:n}=await async function(t){const[i,{data:o}]=await Promise.all([te(),ao.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);let s="",n=!1;for(const e of o.enterprise_info_list)if((e.organization_info_list||[]).find(e=>e.organization_id===t)){s=e.enterprise_id,n=!0;break}if(!n)throw new e.CozeError(e.ErrorCode.E3000,`Organization '${t}' not found in current user's enterprises.`);const a=i.organizationId!==t;return await ie({organizationId:t,enterpriseId:s,...a?{spaceId:void 0}:{}}),{enterpriseId:s}}(t);_a([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Organization '${t}' found in enterprise '${n}'. Config saved.`)]),_a([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default organization set to '${t}' successfully.`)]),"json"===_a([s,"optionalAccess",e=>e.format])&&_a([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default organization set to '${t}'.`,enterprise_id:n,organization_id:t})])})};function ha(e,t){return null!=e?e:t()}const fa=async(e={})=>{const t=ha(e.stdin,()=>process.stdin);return!0===ha(e.isTTY,()=>t.isTTY)?null:await(async e=>{let t="";e.setEncoding("utf-8");for await(const i of e)t+=i;return t})(t)},ya=e=>{process.stdout.write(e.endsWith("\n")?e:`${e}\n`)},ba=e=>{ya(JSON.stringify(e))},va=async(e,t)=>{const i=n.resolve(e),s=n.dirname(i);if(await o.mkdir(s,{recursive:!0}),t instanceof Blob){const e=Buffer.from(await t.arrayBuffer());await o.writeFile(i,e)}else Buffer.isBuffer(t)?await o.writeFile(i,t):t instanceof ArrayBuffer?await o.writeFile(i,Buffer.from(t)):await o.writeFile(i,String(t));return i};const Ca=e=>"object"==typeof e&&null!==e,Sa=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},Pa=e=>Ca(e)&&"data"in e&&void 0!==e.data?e.data:e,Ea=(e,t)=>{try{const{pathname:i}=new URL(e);return n.extname(i)||t}catch(e){return t}},Ta=()=>{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")}`},Aa=e=>{const{outputPath:t,type:i,index:o,ext:s,timestamp:a}=e,r=`${i}_${a}_${o}${s}`;return n.join(t,r)},ka=async(t,i={})=>{let o=null;i.stdin&&(o=await fa());const s=Sa(t),n=Sa(o),a=(c=()=>n,null!=(r=s)?r:c());var r,c;if(!a)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin with piped content");return a},wa="720p",Ra="16:9",za=!1,Ia=!1;function Oa(e,t){return null!=e?e:t()}function La(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const ja=(e,t)=>{if(null==e)return 5;const i=Number(e);if(!Number.isFinite(i))return La([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --duration '${String(e)}', falling back to 5`)]),5;const o=Math.floor(i);return o<4||o>12?(La([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`--duration '${String(e)}' out of bounds (4..12), falling back to -1 as per documentation (letting the model decide)`)]),-1):o},Ua=(e,t)=>{if(null==e)return;const i=Number(e);if(Number.isSafeInteger(i)&&i>=0)return i;La([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --seed '${String(e)}', this parameter will be ignored`)])},Ba=e=>{const{content:t,options:i,ctx:o}=e,s=(e=>{if("string"!=typeof e)return null;const t=e.trim(),i=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(t);if(!i)return null;const o=Number(i[1]),s=Number(i[2]);if(!Number.isFinite(o)||!Number.isFinite(s)||o<=0)return null;const n=((e,t)=>{let i=Math.abs(e),o=Math.abs(t);for(;0!==o;){const e=i%o;i=o,o=e}return i})(o,s)||1,a=`${Math.round(o/n)}:${Math.round(s/n)}`,r=Math.max(o,s);return{ratio:a,resolution:r<=854?"480p":r<=1280?"720p":"1080p"}})(i.size),n=((e,t)=>"480p"===e||"720p"===e||"1080p"===e?e:(void 0!==e&&La([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --resolution '${String(e)}', falling back to '${wa}'`)]),wa))(Oa(i.resolution,()=>La([s,"optionalAccess",e=>e.resolution])),o),a=((e,t)=>{if("string"==typeof e){const t=e.trim();if(t.length>0)return t}return void 0!==e&&La([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --ratio '${String(e)}', falling back to '${Ra}'`)]),Ra})(Oa(i.ratio,()=>La([s,"optionalAccess",e=>e.ratio])),o);return{model:"doubao-seedance-1-5-pro-251215",content:t,callback_url:Oa(Sa(i.callbackUrl),()=>{}),return_last_frame:"boolean"==typeof i.returnLastFrame?i.returnLastFrame:Ia,resolution:n,ratio:a,duration:ja(i.duration,o),watermark:"boolean"!=typeof i.watermark||i.watermark,seed:Ua(i.seed,o),camerafixed:"boolean"==typeof i.camerafixed?i.camerafixed:za,generate_audio:"boolean"!=typeof i.generateAudio||i.generateAudio}},xa=async t=>{const i=await e.customFetch.fetch(t);if(!i.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download generated resource: ${i.status} ${i.statusText}`,{url:t});return Buffer.from(await i.arrayBuffer())},qa=async e=>{const{outputPath:t,videoUrl:i,lastFrameUrl:o,shouldSaveLastFrame:s}=e,a=Ea(i,".mp4"),r=Ta(),c=Aa({outputPath:t,type:"video",index:0,ext:a,timestamp:r}),d=await xa(i),p=[await va(c,d)];if(s&&"string"==typeof o&&o.length>0){const e=(e=>{const{outputPath:t,ext:i,timestamp:o}=e,s=`last_frame_${o}_0${i}`;return n.join(t,s)})({outputPath:t,ext:Ea(o,".png"),timestamp:r}),i=await xa(o),s=await va(e,i);p.push(s)}return p};var Da,Ma,Ga,Na,Fa,$a,Va,Wa,Ha,Ka,Ja,Qa,Za,Ya,Xa,er,tr,ir,or;function sr(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}!function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInputTokens=2]="TotalInputTokens";e[e.TotalOutputTokens=3]="TotalOutputTokens"}(Da||(Da={})),function(e){e[e.ASC=1]="ASC";e[e.DESC=2]="DESC"}(Ma||(Ma={})),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"}(Ga||(Ga={})),function(e){e[e.Free=1]="Free";e[e.Trial=2]="Trial";e[e.Paid=3]="Paid"}(Na||(Na={})),function(e){e[e.Inactive=1]="Inactive";e[e.Active=2]="Active"}(Fa||(Fa={})),function(e){e[e.CNY=1]="CNY";e[e.ResourcePoint=2]="ResourcePoint"}($a||($a={})),function(e){e[e.Cancellable=0]="Cancellable";e[e.NoCancellable=1]="NoCancellable";e[e.AlwaysDefault=2]="AlwaysDefault"}(Va||(Va={})),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"}(Wa||(Wa={})),function(e){e[e.Internal=1]="Internal";e[e.External=2]="External";e[e.Infra=3]="Infra"}(Ha||(Ha={})),function(e){e[e.Text=1]="Text";e[e.Image=2]="Image";e[e.Video=3]="Video";e[e.Audio=4]="Audio"}(Ka||(Ka={})),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"}(Ja||(Ja={})),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"}(Qa||(Qa={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online";e[e.GradualRollout=2]="GradualRollout";e[e.ReadyToOffline=3]="ReadyToOffline"}(Za||(Za={})),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"}(Ya||(Ya={})),function(e){e[e.Install=1]="Install";e[e.Uninstall=2]="Uninstall"}(Xa||(Xa={})),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"}(er||(er={})),function(e){e[e.Scene=1]="Scene";e[e.Type=2]="Type"}(tr||(tr={})),function(e){e[e.Official=1]="Official";e[e.Community=2]="Community"}(ir||(ir={})),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"}(or||(or={}));class nr{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){nr.prototype.__init.call(this),nr.prototype.__init2.call(this),this.request=sr([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=sr([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}ListIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/list"),s={space_id:i.space_id,project_id:i.project_id,integration_type:i.integration_type,integration_id:i.integration_id,filter_installed:i.filter_installed,org_id:i.org_id,search_words:i.search_words,page_num:i.page_num,page_size:i.page_size,project_type:i.project_type};return this.request({url:o,method:"POST",data:s},t)}SetIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/update"),s={integration_id:i.integration_id,space_id:i.space_id,auth_schema_value:i.auth_schema_value};return this.request({url:o,method:"POST",data:s},t)}DeleteIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/delete"),s={integration_id:i.integration_id,space_id:i.space_id,project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}AuthIntegrationStatus(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/auth/status"),s={integration_id:i.integration_id,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}ManageSpaceIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/space/manage"),s={space_ids:i.space_ids,integration_ids:i.integration_ids,op_type:i.op_type};return this.request({url:o,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/api/v3/contents/generations/tasks"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}FlashASR(e,t){const i=e||{},o=this.genBaseURL("/api/v3/auc/bigmodel/recognize/flash"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}ListModel(e,t){const i=e||{},o=this.genBaseURL("/v1/model/list"),s={model_type:i.model_type,current_model_ids:i.current_model_ids,integration_ids:i.integration_ids,need_model_config_param:i.need_model_config_param,page_size:i.page_size,offset:i.offset};return this.request({url:o,method:"POST",data:s},t)}ChatCompletions(e,t){const i=e||{},o=this.genBaseURL("/api/v3/chat/completions"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CreateResponses(e,t){const i=e||{},o=this.genBaseURL("/api/v3/responses"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}GenerateImages(e,t){const i=e||{},o=this.genBaseURL("/api/v3/images/generations"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const i=e||{},o=this.genBaseURL("/api/v3/tts/unidirectional"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}GetIntegrationOauthConfig(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/auth/oauth_config"),s={integration_id:i.integration_id,space_id:i.space_id,project_id:i.project_id,session_id:i.session_id};return this.request({url:o,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/api/v3/contents/generations/tasks/:id"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"GET",data:s,params:n},t)}WebSearch(e,t){const i=e||{},o=this.genBaseURL("/api/search_api/web_search"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}WebSearch(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/search_api/web_search"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CreateResponses(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/responses"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks/:id"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"GET",data:s,params:n},t)}FlashASR(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/auc/bigmodel/recognize/flash"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}GenerateImages(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/images/generations"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/tts/unidirectional"),s={Body:i.Body},n={project_id:i.project_id};return this.request({url:o,method:"POST",data:s,params:n},t)}ChatCompletions(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/chat/completions"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CancelIntegration(e,t){const i=e||{},o=this.genBaseURL("/v1/integration/cancel"),s={integration_id:i.integration_id,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}Embeddings(e,t){const i=e||{},o=this.genBaseURL("/api/v3/embeddings/multimodal"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}Embeddings(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/embeddings/multimodal"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}VideoEditingUtils(e,t){const i=e||{},o=this.genBaseURL("/api/v1/integration/video_editing_utils"),s={Body:i.Body},n={tool_name:i.tool_name};return this.request({url:o,method:"POST",data:s,params:n},t)}GetProjectDefaultSkill(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/default"),s={project_type:i.project_type,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetSkillByIDs(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/by_ids"),s={project_type:i.project_type,skill_ids:i.skill_ids,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetSkillCategoryList(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/category/list"),s={project_type:i.project_type};return this.request({url:o,method:"POST",data:s},t)}UploadSkill(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/upload"),s={data:i.data},n={"Content-Type":i["Content-Type"]};return this.request({url:o,method:"POST",data:s,headers:n},t)}GetUserSkillList(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/user/list"),s={page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}DeleteSkill(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/delete"),s={skill_id:i.skill_id};return this.request({url:o,method:"POST",data:s},t)}GetSkillList(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/list"),s={project_type:i.project_type,category_type_list:i.category_type_list,space_id:i.space_id,source_list:i.source_list};return this.request({url:o,method:"POST",data:s},t)}UploadSkillConfirm(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/upload/confirm"),s={preview_skill_key:i.preview_skill_key};return this.request({url:o,method:"POST",data:s},t)}FetchTool(e,t){const i=e||{},o=this.genBaseURL("/api/v1/integration/fetch_tool"),s={url:i.url};return this.request({url:o,method:"POST",data:s},t)}GetModelSwitchStatus(e,t){const i=e||{},o=this.genBaseURL("/v1/model/switch/status"),s={model_id:i.model_id,project_ids:i.project_ids,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}StartSwitchModel(e,t){const i=e||{},o=this.genBaseURL("/v1/model/switch/start"),s={space_id:i.space_id,project_ids:i.project_ids,current_model:i.current_model,target_model:i.target_model};return this.request({url:o,method:"POST",data:s},t)}GetModelUsageList(e,t){const i=e||{},o=this.genBaseURL("/v1/model/usage/list"),s={space_id:i.space_id,model_id:i.model_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp,order_by_field:i.order_by_field,order_by_type:i.order_by_type,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetModelDetails(e,t){const i=e||{},o=this.genBaseURL("/v1/model/details"),s={model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}GetModelUsageDetail(e,t){const i=e||{},o=this.genBaseURL("/v1/model/usage/details"),s={space_id:i.space_id,model_id:i.model_id,project_id:i.project_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp};return this.request({url:o,method:"POST",data:s},t)}RollbackSwitchModel(e,t){const i=e||{},o=this.genBaseURL("/v1/model/switch/rollback"),s={space_id:i.space_id,project_ids:i.project_ids,current_model:i.current_model};return this.request({url:o,method:"POST",data:s},t)}TextEmbeddings(e,t){const i=e||{},o=this.genBaseURL("/api/v3/embeddings"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}TextEmbeddings(e,t){const i=e||{},o=this.genBaseURL("/coze-coding/api/v3/embeddings"),s={Body:i.Body};return this.request({url:o,method:"POST",data:s},t)}CheckModelReadyToOffline(e,t){const i=e||{},o=this.genBaseURL("/v1/model/ready_to_offline/check"),s={model_type:i.model_type};return this.request({url:o,method:"POST",data:s},t)}Audit(e,t){const i=e||{},o=this.genBaseURL("/api/v1/integration/audit"),s={content:i.content};return this.request({url:o,method:"POST",data:s},t)}}nr.prototype.UploadSkill=function(e,t){const i=e||{},o=this.genBaseURL("/v1/skill/upload"),s=i.body;return this.request({url:o,method:"POST",data:s},t)},nr.prototype.GenerateImages=function(e,t){const i=e||{},o=this.genBaseURL("/api/v3/images/generations"),s=i.Body;return this.request({url:o,method:"POST",data:s},t)},nr.prototype.SubmitVideoGenerationsTasks=function(e,t){const i=e||{},o=this.genBaseURL("/api/v3/contents/generations/tasks"),s=i;return this.request({url:o,method:"POST",data:s},t)},nr.prototype.GetVideoGenerationsTasks=function(e,t){const i=e||{},o=this.genBaseURL(`/api/v3/contents/generations/tasks/${i.id}`);return this.request({url:o,method:"GET"},t)};const ar=new nr({});function rr(e,t){return null!=e?e:t()}const cr=async e=>await new Promise(t=>setTimeout(t,e)),dr=async e=>{const{taskId:t,baseURL:i,accessToken:o,projectId:s}=e,n=await ar.GetVideoGenerationsTasks({id:t},{baseURL:i,headers:{Authorization:`Bearer ${o}`},params:{project_id:s}});return Pa(n)};function pr(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const lr=e=>`coze generate video status ${e}`,ur=e=>{const{ctx:t,response:i}=e;"json"!==pr([t,"optionalAccess",e=>e.format])?ya((e=>{const t=[e.status],i=pr([e,"access",e=>e.content,"optionalAccess",e=>e.video_url]),o=pr([e,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);return"succeeded"===e.status?("string"==typeof i&&i.length>0&&t.push(i),"string"==typeof o&&o.length>0&&t.push(o),t.join("\n")):("string"==typeof e.error_message&&e.error_message&&t.push(e.error_message),t.join("\n"))})(i)):ba(i)},_r=t=>{const i=t.getContext(),{outputPath:o}=t.optsWithGlobals(),s=(n=pr([i,"optionalAccess",e=>e.config,"optionalAccess",e=>e.integrationApiBaseUrl]),a=()=>Y.integrationApiBaseUrl,null!=n?n:a());var n,a;const r=pr([i,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]);if(!r)throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login --oauth` or `coze auth login --token <token>` first");return{accessToken:r,ctx:i,integrationApiBaseUrl:s,outputPath:o}},mr=async(t,i,o)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:a,outputPath:r}=_r(o);let c=null;i.stdin&&(c=await fa());const{content:d}=(t=>{const{prompt:i,stdinPrompt:o,options:s}=t,n=Oa(Sa(i),()=>Sa(o)),a=Sa(s.firstFrame),r=Sa(s.lastFrame),c=Boolean(a)||Boolean(r);if(!n&&!c)throw new e.CozeError(e.ErrorCode.E1000,"Missing input: Please provide PROMPT/stdin text, or provide images (--first-frame/--last-frame/--reference-image)");const d=[];return n&&d.push({type:"text",text:n}),a&&d.push({type:"image_url",image_url:{url:a},role:"first_frame"}),r&&d.push({type:"image_url",image_url:{url:r},role:"last_frame"}),{content:d}})({prompt:t,stdinPrompt:c,options:i}),p=Ba({content:d,options:i,ctx:n}),l=n.format,u=pr([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!u)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const{createResp:_,taskId:m}=await(async t=>{const{requestBody:i,baseURL:o,accessToken:s,projectId:n}=t,a=await ar.SubmitVideoGenerationsTasks(i,{baseURL:o,headers:{Authorization:`Bearer ${s}`},params:{project_id:n}}),r=Pa(a),c=function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}([r,"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",r);return{taskId:c,createResp:r}})({requestBody:p,baseURL:a,accessToken:s,projectId:u});if(!i.wait)return"json"===l?void ba({query_command:lr(m),response:_,task_id:m}):void ya((e=>["Video generation task created successfully.",`taskId: ${e}`,`Use \`${lr(e)}\` to query status.`].join("\n"))(m));const g=await(async t=>{const{taskId:i,baseURL:o,accessToken:s,pollIntervalMs:n,pollTimeoutMs:a,projectId:r}=t,c=Date.now();for(;;){const t=await dr({taskId:i,baseURL:o,accessToken:s,projectId:r});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}): ${rr(t.error_message,()=>"unknown")}`,t);if(Date.now()-c>a)throw new e.CozeError(e.ErrorCode.E5003,[`Video generation timed out after ${a}ms.`,`taskId: ${i}`,`Use \`coze generate video status ${i}\` to query status.`].join("\n"),{task_id:i,last_status:t.status});await cr(n)}})({taskId:m,baseURL:a,accessToken:s,pollIntervalMs:2e3,pollTimeoutMs:3e5,projectId:u}),h=pr([g,"access",e=>e.content,"optionalAccess",e=>e.video_url]),f=pr([g,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);if(!h||"string"!=typeof h)throw new e.CozeError(e.ErrorCode.E5002,"Video generated successfully but video_url was not returned");if(r){const e=await qa({outputPath:r,videoUrl:h,lastFrameUrl:f,shouldSaveLastFrame:!0===i.returnLastFrame});return"json"===l?void ba({task_id:m,request:p,response:g,saved_paths:e}):void ya(e.join("\n"))}if("json"===l)return void ba({task_id:m,request:p,response:g});const y=[h];!0===i.returnLastFrame&&"string"==typeof f&&f.length>0&&y.push(f),ya(y.join("\n"))},gr=(e,t)=>{const i=t.getContext();K(e,i)},hr=t=>{var i;i=t.command("create [prompt]").description("Create a video generation task").config({help:{brief:"Create video generation task",description:"Create a video generation task from text prompts or images. By default the command returns taskId immediately; use `--wait` to poll until completion.",examples:[{desc:"Create video from text",cmd:'coze generate video create "A dancing kitten"'},{desc:"Create task and wait for completion",cmd:'coze generate video create "A dancing kitten" --wait'},{desc:"Save result to file",cmd:'coze generate video create "A dancing kitten" --wait --output-path ./video.mp4'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --first-frame/--last-frame) with -h."},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid access token",fix:"Run `coze auth login --oauth` or set COZE_API_TOKEN/related credentials first"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server returned an error or response parsing failed",fix:"Please retry later. Use --debug for more details"},{code:e.ErrorCode.E5003,name:"TIMEOUT",desc:"Video generation request timed out",fix:"Please retry later or use `coze generate video status <taskId>` to query task status"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text prompt (can also be passed via stdin)"}},output:{type:"object",properties:{query_command:{type:"string"},task_id:{type:"string"},request:{type:"object"},response:{type:"object"},saved_paths:{type:"array",items:{type:"string"}}}}}}}).action(async(e,t,i)=>{try{await mr(e,t,i)}catch(e){gr(e,i)}}),i.option("--callback-url <url>","Callback URL for task status changes").option("--return-last-frame","Return last frame URL (default: disabled)",Ia).option("--resolution <res>","Resolution: 480p|720p|1080p",wa).option("--ratio <ratio>",`Aspect ratio (default: ${Ra})`,Ra).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)",za).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")},fr=t=>{t.command("status <taskId>").description("Query video generation task status by task ID").option("--output <format>","Output format: text|json").config({help:{brief:"Query video task status",description:"Query the latest status of a video generation task by task ID. This command does not create a new task.",examples:[{desc:"Query task status",cmd:"coze generate video status task_123"},{desc:"Output full response as JSON",cmd:"coze generate video status task_123 --output json"}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid task ID or request parameters",fix:"Please confirm <taskId> is correct and try again",example:"coze generate video status task_123"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"Server returned an error or response parsing failed",fix:"Please retry later. Use --debug for more details"},{code:e.ErrorCode.E5003,name:"TIMEOUT",desc:"Request timed out",fix:"Please retry later"}],schema:{input:{taskId:{type:"string",required:!0,description:"Video generation task ID"}},output:{type:"object",properties:{id:{type:"string"},status:{type:"string"},model:{type:"string"},content:{type:"object"},error_message:{type:"string"}}}}}}).action(async(t,i,o)=>{try{await(async(t,i,o)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:a}=_r(o),r=pr([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!r)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const c=await dr({taskId:t,baseURL:a,accessToken:s,projectId:r});ur({ctx:n,response:c})})(t,0,o)}catch(e){gr(e,o)}})};function yr(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const br="2K",vr="url",Cr="standard",Sr="disabled",Pr=3686400,Er=16777216,Tr=e=>"object"==typeof e&&null!==e,Ar=e=>{if("string"==typeof e){const t=e.trim();return t.length?t:Cr}return Cr},kr=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},wr=t=>{t.command("image [prompt]").description("Generate images from text prompts").config({help:{brief:"Generate images from text",description:"Generate images based on text prompts. Supports setting size, watermark, and multiple images.",examples:[{desc:"Generate image",cmd:'coze generate image "A futuristic city"'},{desc:"Save to file",cmd:'coze generate image "A cat" --output-path ./cat.png'},{desc:"Specify size",cmd:'coze generate image "A dog" --size 1024x1024'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --size/--max-images) with -h."},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Please configure billing project ID and retry"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"API response parsing failed or server returned an error",fix:"Please retry later. Use --debug for more details"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text prompt (can also be passed via stdin)"}},output:{type:"object",properties:{model:{type:"string"},created:{type:"number"},image_0:{type:"object"},saved_paths:{type:"array",items:{type:"string"}}}}}}}).option("--size <size>","Image size: 2K|4K or WIDTHxHEIGHT (local validation)",br).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",vr).option("--optimize-prompt-mode <mode>",`Prompt optimization mode (default: ${Cr})`,Cr).option("--sequential <mode>","Group image generation mode: auto|disabled",Sr).option("--max-images <n>","Maximum number of group images (1-15)",String(15)).option("--stdin","Read prompt from stdin (pipe input)").action(async(t,i,o)=>{const s=o.getContext(),{outputPath:n}=o.optsWithGlobals(),a=await ka(t,{stdin:i.stdin}),r=yr([s,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!r)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const c=((e,t)=>{if(null==e)return{value:br};if("string"!=typeof e)return yr([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --size '${String(e)}', falling back to '${br}'`)]),{value:br};const i=e.trim();if("2K"===i||"4K"===i)return{value:i};const o=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(i);if(!o)return{value:br,warning:`Invalid --size '${i}', falling back to '${br}'. Expected 2K/4K or WIDTHxHEIGHT`};const s=Number(o[1]),n=Number(o[2]),a=s*n,r=s/n;return Number.isFinite(s)&&Number.isFinite(n)&&s>0&&n>0&&a>=Pr&&a<=Er&&r>=.0625&&r<=16?{value:`${s}x${n}`}:{value:br,warning:`Invalid --size '${i}', falling back to '${br}'. Total pixels must be in [3686400, 16777216], aspect ratio must be in [1:16, 16:1].`}})(i.size,s),d="url"===(p=i.responseFormat)||"b64_json"===p?{value:p}:void 0!==p?{value:vr,warning:`Invalid --response-format '${String(p)}', falling back to '${vr}'`}:{value:vr};var p;const l=(e=>"auto"===e||"disabled"===e?{value:e}:void 0!==e?{value:Sr,warning:`Invalid --sequential '${String(e)}', falling back to '${Sr}'`}:{value:Sr})(i.sequential),u=(e=>{if(null==e)return{value:15};const t=Number(e);if(Number.isFinite(t)){const e=Math.floor(t);if(e>=1&&e<=15)return{value:e}}return{value:15,warning:`Invalid --max-images '${String(e)}', falling back to '15'`}})(i.maxImages);c.warning&&yr([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(c.warning)]),d.warning&&yr([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(d.warning)]),l.warning&&yr([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(l.warning)]),u.warning&&yr([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(u.warning)]);const _={model:"doubao-seedream-4-5-251128",prompt:a,size:c.value,watermark:"boolean"!=typeof i.watermark||i.watermark,image:kr(i.image),response_format:d.value,optimize_prompt_options:{mode:Ar(i.optimizePromptMode)},sequential_image_generation:l.value,sequential_image_generation_options:{max_images:u.value}},m=(t=>{const i=Tr(t)&&"data"in t?t.data:t;if(Tr(o=i)&&"string"==typeof o.model&&"number"==typeof o.created&&Array.isArray(o.data))return i;var o;throw new e.CozeError(e.ErrorCode.E5002,"Image generation API returned an unexpected response format",t)})(await ar.GenerateImages({Body:_},{baseURL:Y.integrationApiBaseUrl,params:{project_id:r}}));if(m.error)throw new e.CozeError(e.ErrorCode.E5002,"Image generation failed (top-level error)",m.error);const g=(f=()=>vr,null!=(h=_.response_format)?h:f());var h,f;const y=m.data.filter(e=>!e.error&&("url"===g?"string"==typeof e.url&&e.url.length>0:"string"==typeof e.b64_json&&e.b64_json.length>0));if(0===y.length)throw new e.CozeError(e.ErrorCode.E5002,"Image generation succeeded but no valid image data was returned",m);if(n){const t=[],i=Ta();for(const[o,s]of y.entries()){const a="url"===g&&s.url?Ea(s.url,".png"):".png",r=Aa({outputPath:n,type:"image",index:o,ext:a,timestamp:i});let c;if("url"===g){const t=await e.customFetch.fetch(s.url);if(!t.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download generated image: ${t.status} ${t.statusText}`);c=Buffer.from(await t.arrayBuffer())}else c=Buffer.from(s.b64_json,"base64");const d=await va(r,c);t.push(d)}const{model:o,usage:a,HttpHeader:r,...c}=(e=>{const{data:t,...i}=e,o=Object.fromEntries(t.map((e,t)=>[`image_${t}`,e]));return{...i,...o}})(m);return void yr([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...c,saved_paths:t})])}yr([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(m.data)])})};function Rr(e,t){return null!=e?e:t()}function zr(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Ir="cli_user",Or="zh_female_xiaohe_uranus_bigtts",Lr="mp3",jr=24e3,Ur=(e,t)=>"pcm"===e||"mp3"===e||"ogg_opus"===e?e:(void 0!==e&&zr([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --audio-format '${String(e)}', falling back to '${Lr}'`)]),Lr),Br=(e,t,i,o)=>{if(null==e)return t;const s=Number(e);return Number.isFinite(s)?Math.floor(s):(zr([o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",o=>o(`Invalid --${i} '${String(e)}', falling back to ${t}`)]),t)},xr=t=>{const i=t.trim();if(0===i.length)return null;const o=i.startsWith("data:")?i.slice(5).trim():i;if(0===o.length)return null;const s=o[0];if("{"!==s&&"["!==s)return null;const n=e.safeJsonParse(o,void 0,{onError:t=>{const o=t instanceof Error?t.message:String(t);throw new e.CozeError(e.ErrorCode.E5002,`Failed to parse response: ${o}`,{line:i})}});return void 0===n?null:Ca(n)&&"number"==typeof n.code?n:null},qr=t=>{const i=t.command("generate").description("Media generation commands (API TBD)").config({help:{brief:"Media generation commands",description:"Generate media such as audio, image, and video using Coze APIs.",examples:[{desc:"Generate image",cmd:'coze generate image "A cat"'},{desc:"Generate audio",cmd:'coze generate audio "Hello world"'},{desc:"Generate video",cmd:'coze generate video create "A dancing dog"'}],seeAlso:["coze auth"]}}).option("--output-path <path>","Directory path to save the generated media files");wr(i),(t=>{t.command("audio [prompt]").description("Synthesize speech from text or SSML (streaming)").config({help:{brief:"Generate audio from text",description:"Synthesize speech from text or SSML. Supports streaming output and configurable audio encodings.",examples:[{desc:"Basic text to speech",cmd:'coze generate audio "Hello world"'},{desc:"Save to file",cmd:'coze generate audio "Hello" --output-path ./audio.mp3'},{desc:"Use SSML",cmd:'echo "<speak>Hello</speak>" | coze generate audio --ssml'},{desc:"Specify audio encoding",cmd:'coze generate audio "Hello" --audio-format ogg_opus'}],errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid request parameters or missing prompt",fix:"Provide PROMPT argument or use --stdin with piped content. Check other options (e.g. --speaker/--audio-format) with -h."},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"Missing billing project ID",fix:"Configure billing project ID and retry",example:'coze generate audio "Hello"'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid access token",fix:"Run `coze auth login --oauth` or `coze auth login --token <token>` first"},{code:e.ErrorCode.E5001,name:"NETWORK_ERROR",desc:"Network request failed",fix:"Please check your network connectivity and try again"},{code:e.ErrorCode.E5002,name:"SERVER_ERROR",desc:"API response parsing failed or server returned an error",fix:"Please retry later. Use --debug for more details"}],schema:{input:{prompt:{type:"string",required:!1,description:"Text or SSML prompt (can also be passed via stdin)"}},output:{type:"object",properties:{request:{type:"object"},url:{type:"string",description:"Audio download URL"},saved_path:{type:"string",description:"Local path if saved"}}}}}}).option("--output <format>","Output format: text|json").option("--uid <uid>",`User UID (default: ${Ir})`,Ir).option("--speaker <speaker>",`Speaker (default: ${Or})`,Or).option("--audio-format <format>","Audio encoding: pcm|mp3|ogg_opus",Lr).option("--sample-rate <n>","Sample rate (default: 24000)",String(jr)).option("--speech-rate <n>","Speech rate (-50..100, default: 0)",String(0)).option("--loudness-rate <n>","Loudness (-50..100, default: 0)",String(0)).option("--ssml","Treat input as SSML (defaults to plain text)",!1).option("--stdin","Read prompt from stdin (pipe input)").action(async(t,i,o)=>{const s=o.getContext();try{const{outputPath:n}=o.optsWithGlobals(),a=zr([s,"optionalAccess",e=>e.config,"access",e=>e.integrationApiBaseUrl]);if(!zr([s,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]))throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login --oauth` or `coze auth login --token <token>` first");const r=await ka(t,{stdin:i.stdin}),c=zr([s,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const d={user:{uid:Rr(Sa(i.uid),()=>Ir)},req_params:{speaker:Rr(Sa(i.speaker),()=>Or),audio_params:{format:Ur(i.audioFormat,s),sample_rate:Br(i.sampleRate,jr,"sample-rate",s),speech_rate:Br(i.speechRate,0,"speech-rate",s),loudness_rate:Br(i.loudnessRate,0,"loudness-rate",s)}}};i.ssml?d.req_params={...d.req_params,ssml:r}:d.req_params={...d.req_params,text:r};const p=new URL("/api/v3/tts/unidirectional",a);p.searchParams.append("project_id",c);const l=await e.customFetch.fetch(p.toString(),{method:"POST",body:JSON.stringify(d)});if(!l.ok)throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis request failed: ${l.status} ${l.statusText}`,{status:l.status,statusText:l.statusText});if(!l.body)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis response is empty (no streaming body returned)");const u=new TextDecoder("utf-8"),_=l.body.getReader(),m=[];let g;const h=t=>{if(0===t.code)return n&&"string"==typeof t.data&&m.push(Buffer.from(t.data,"base64")),!1;if(2e7===t.code)return"string"==typeof t.url&&t.url.length>0&&(g=t.url),!0;throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis failed (code=${t.code}): ${Rr(t.message,()=>"unknown")}`,t)};let f="";for(;;){const{done:e,value:t}=await _.read();if(e)break;f+=u.decode(t,{stream:!0});const i=f.split(/\r?\n/);f=Rr(i.pop(),()=>"");for(const e of i){const t=xr(e);if(t&&h(t)){await _.cancel();break}}if(g)break}if(!g){f+=u.decode();const e=f.split(/\r?\n/);f="";for(const t of e){const e=xr(t);if(e&&h(e))break}}if(n){const t=Rr(zr([d,"access",e=>e.req_params,"optionalAccess",e=>e.audio_params,"optionalAccess",e=>e.format]),()=>Lr),i="pcm"===t?".pcm":"ogg_opus"===t?".ogg":".mp3",o=Ta(),a=Aa({outputPath:n,type:"audio",index:0,ext:i,timestamp:o});let r=null;if(m.length>0)r=await va(a,Buffer.concat(m));else if(g){const t=await e.customFetch.fetch(g);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()),a=Ea(g,i),c=Aa({outputPath:n,type:"audio",index:0,ext:a,timestamp:o});r=await va(c,s)}if(!r)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis completed but no savable audio data was obtained (neither chunks nor download URL)",{url:g});return"json"===zr([s,"optionalAccess",e=>e.format])?void ba({request:d,url:g,saved_path:r}):void ya(r)}if("json"===zr([s,"optionalAccess",e=>e.format]))return void ba({request:d,url:g});if(g)return void ya(g);ya("Speech synthesis completed, but no audio download URL was returned; you can use --output json to view details.")}catch(e){K(e,s)}})})(i),(e=>{const t=(e=>e.command("video").description("Create videos or query video generation task status").config({help:{brief:"Generate videos",description:"Use explicit subcommands to create video generation tasks or query task status by task ID.",examples:[{desc:"Create video from text",cmd:'coze generate video create "A dancing kitten"'},{desc:"Query task status",cmd:"coze generate video status task_123"}],seeAlso:["coze generate image","coze generate audio"]}}))(e);hr(t),fr(t)})(i)};function Dr(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Mr=t=>{(t=>{t.command("upload <path>").description("Upload a local file").config({help:{brief:"Upload a local file",description:"Upload a local file to Coze. The file can be used as an attachment or context in projects.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf",tags:["[RECOMMENDED]"]}],errors:[{code:e.ErrorCode.E3000,name:"RESOURCE_NOT_FOUND",desc:"Local file not found or not readable",fix:"Please confirm the file path exists and you have read permission"}],schema:{input:{path:{type:"string",required:!0,description:"Local file path to upload"}},output:{type:"string",description:"Uploaded file URL"}}}}).action(async(t,i,o)=>{let s;try{s=o.getContext();try{await m.access(t)}catch(i){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${t}`,{filePath:t})}const i=_.basename(t),n=_.extname(t),a=n?i.slice(0,-n.length):i,r=n.slice(1),c=new h;c.append("file_name",a),c.append("file_extension",r),c.append("file_content",g.createReadStream(t)),c.append("biz_type","cli_attachment");const d=await e.IdeApi.UploadFile({data:c},{headers:{...c.getHeaders()}});"json"===Dr([s,"optionalAccess",e=>e.format])?Dr([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(d.data)]):Dr([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(Dr([d,"access",e=>e.data,"optionalAccess",e=>e.file_url]))])}catch(e){K(e,s)}})})(t.command("file").description("General file operations").config({help:{brief:"File upload and management",description:"Manage file operations for Coze projects. Currently supports uploading local files to Coze for use as attachments or context.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf"}],seeAlso:["coze code message send"]}}))};function Gr(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Nr(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Fr(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function $r(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Vr=t=>{const i=t.command("config").description("Manage Coze CLI configuration").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Manage local configuration",description:"Provides read, set, list, and delete operations for the CLI local configuration file (`~/.cozerc.json`).",examples:[{desc:"List all configurations",cmd:"coze config list"},{desc:"Set configuration value",cmd:"coze config set base_url https://api.coze.cn"}]}});(e=>{e.command("get <keys...>").description("Get configuration values and their sources").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Get configuration values",description:"Read and output the value of the specified configuration keys from `~/.cozerc.json`. If a key does not exist, prompts that it was not found.",examples:[{desc:"Get BaseURL configuration",cmd:"coze config get baseUrl"},{desc:"Get default Space ID",cmd:"coze config get spaceId"},{desc:"Get multiple configurations",cmd:"coze config get baseUrl spaceId"}],schema:{input:{keys:{type:"array",required:!0,description:"Configuration key names"}},output:{value:{type:"any",description:"Configuration value"}}}}}).action(async(e,t,i)=>{const o=i.getContext(),s=await se();for(const t of e){const e=s.find(e=>e.key===t);Gr(e?[o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)]:[o,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(`Configuration '${t}' not found.`)])}})})(i),(t=>{t.command("set <key> <value>").description("Set a configuration value").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Set a single configuration value",description:"Update or add the specified local configuration key-value pair. The configuration will be persistently saved in `~/.cozerc.json`.",examples:[{desc:"Modify default workspace",cmd:"coze config set spaceId 123456789"},{desc:"Modify BaseURL",cmd:"coze config set baseUrl https://api.coze.cn"}],errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to set configuration value",fix:"Please check the key/value and retry. Use --debug for more details."}],schema:{input:{key:{type:"string",required:!0,description:"Configuration key name"},value:{type:"string",required:!0,description:"New configuration value"}}}}}).action(async(t,i,o,s)=>{const n=s.getContext();try{const e={};e[t]=i;const o="global";await ie(e,o);const s={key:t,value:i,scope:o,status:"updated",message:`Configuration '${t}' updated successfully in ${o} scope.`};if(Nr([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.message)]),"json"===Nr([n,"optionalAccess",e=>e.format]))return void Nr([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(s)])}catch(o){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set '${t}' to '${i}': ${o.message}`,o.stack)}})})(i),(t=>{t.command("delete <keys...>").description("Delete a configuration value").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Delete configuration values",description:"Remove the specified configuration values from the local configuration file `~/.cozerc.json`.",examples:[{desc:"Delete a specific configuration key",cmd:"coze config delete spaceId"},{desc:"Delete multiple configuration keys",cmd:"coze config delete spaceId baseUrl"}],errors:[{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"Failed to delete configuration value",fix:"Please check the configuration key and retry. Use --debug for more details."}],schema:{input:{keys:{type:"array",required:!0,description:"Configuration key names"}}}}}).action(async(t,i,o)=>{const s=o.getContext();for(const i of t)try{await oe(i);const e={key:i,status:"deleted",message:`Configuration '${i}' has been removed.`};Fr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleted ${i} from configuration file successfully.`)]),"json"===Fr([s,"optionalAccess",e=>e.format])&&Fr([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)])}catch(t){throw new e.CozeError(e.ErrorCode.E5000,`Failed to delete config '${i}': ${t.message}`,t.stack)}})})(i),(e=>{e.command("list").description("List all configuration values and their sources").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"List all local configuration values",description:"Print all configuration content stored in `~/.cozerc.json` in JSON format.",examples:[{desc:"List configurations",cmd:"coze config list"}],schema:{output:{type:"object",additionalProperties:!0,description:"Configuration key-value pairs"}}}}).action(async(e,t)=>{const i=t.getContext(),o=(await se()).map(({key:e,value:t,source:i})=>({key:e,value:t,source:i}));$r([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Configurations found:")]),$r([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(o)])})})(i)},Wr="__COZE_FILE_COMP__";function Hr(){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 Kr(e){const t=s.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 Jr(){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]}" == "${Wr}" ]]; 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" == "${Wr}" ]]; 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(s.EOL)}function Qr(e){switch(e){case"bash":return`\n# begin coze completion\nsource ${n.join(s.homedir(),".coze","completion.sh")}\n# end coze completion\n`;case"zsh":return"\n# begin coze completion\n. <(coze --completion)\n# end coze completion\n";case"fish":return"\n# begin coze completion\ncoze --completion-fish | source\n# end coze completion\n";case"powershell":return`\n# begin coze completion\nRegister-ArgumentCompleter -Native -CommandName coze -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n $tokens = $commandAst.ToString().Split(" ", [StringSplitOptions]::RemoveEmptyEntries)\n $allArgs = @("--comppwsh")\n if ($tokens.Count -gt 1) {\n $allArgs += $tokens[1..($tokens.Count - 1)]\n }\n $result = & coze $allArgs 2>$null\n if ($result -and $result[0] -ne '${Wr}') {\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 Zr(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}let Yr,Xr,ec=!1,tc=!1;function ic(e){const t=e._args||[];if(0===t.length)return!1;const i=/path|file|dir|folder/i;return t.some(e=>i.test(e._name))}function oc(e){Xr=e,function(){const e=process.argv.indexOf("--completion");e>-1&&(ec=!0,process.argv.splice(e,1));const t=process.argv.indexOf("--completion-fish");t>-1&&(tc=!0,process.argv.splice(t,1))}(),Yr=f("coze"),Yr.on("complete",(t,i)=>{const o=i.line.trimStart().split(/\s+/);o.length>0&&(o[0].endsWith("coze")||o[0].endsWith("bin/main"))&&o.shift();let s="";i.line.endsWith(" ")?(s="",""===o[o.length-1]&&o.pop()):s=o.pop()||"";const n=function(e,t,i){let o=e;for(const e of t){const t=o.commands.find(t=>t.name()===e||t.alias()===e);if(t)o=t;else if(!e.startsWith("-"))return ic(o)?[Wr]:[]}const s=[];o.commands.length>0&&o.commands.forEach(e=>{s.push(e.name())}),o.options.forEach(e=>{e.flags.split(/[ ,|]+/).forEach(e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)})}),o!==e&&e.options.forEach(e=>{e.flags.split(/[ ,|]+/).forEach(e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)})});const n=Array.from(new Set(s)).filter(e=>e.startsWith(i));return 0===n.length&&ic(o)?[Wr]:n}(e,o,s);i.reply(n)}),e.command("completion").description("Setup shell auto-completion").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Configure terminal auto-completion",description:"Install or remove the auto-completion script for the current terminal environment (supports bash/zsh/fish/powershell).",examples:[{desc:"Install completion script",cmd:"coze completion --setup"},{desc:"Remove completion script",cmd:"coze completion --cleanup"}]}}).option("--setup","Install shell completion into your startup script (.zshrc / .bashrc / $PROFILE)").option("--cleanup","Remove shell completion from your startup script").action(async e=>{if(e.cleanup)!function(){const e=Hr();if(!e)return;const t=Kr(e);if(!t||!u.existsSync(t))return;const i=Qr(e);if(i){const e=u.readFileSync(t,"utf8").replace(new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"");u.writeFileSync(t,e)}if("bash"===e){const e=n.join(s.homedir(),".coze"),t=n.join(e,"completion.sh");u.existsSync(t)&&u.unlinkSync(t),u.existsSync(e)&&0===u.readdirSync(e).length&&u.rmdirSync(e)}}(),await ie({completionInstalled:!1}),console.log("Shell completion removed! Please restart your terminal.");else{const e=Hr();if(!e)return console.error("Could not detect your shell type. Supported shells: bash, zsh, fish, powershell."),void(process.exitCode=1);const t=function(){const e=Hr();if(!e)return!1;const t=Kr(e);if(!t)return!1;if("bash"===e){const e=n.join(s.homedir(),".coze"),t=n.join(e,"completion.sh");u.existsSync(e)||u.mkdirSync(e,{recursive:!0}),u.writeFileSync(t,Jr())}const i=n.dirname(t);u.existsSync(i)||u.mkdirSync(i,{recursive:!0});const o=Qr(e);return!!o&&(u.appendFileSync(t,o),!0)}();t?(await ie({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 sc(){return ec?(console.log(Jr()),void process.exit()):tc?(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]" = "${Wr}"`," return"," end"," for c in $completions"," echo $c"," end","end","complete -c coze -a '(_coze_completion)' -n '_coze_completion'","### coze completion - end ###"].join(s.EOL)),void process.exit()):void(process.argv.includes("--comppwsh")?function(){if(!Xr)return void process.exit();const e=process.argv.indexOf("--comppwsh"),t=process.argv.slice(e+1);let i=Xr;const o=[];for(const e of t){const t=Zr([i,"access",e=>e.commands,"optionalAccess",e=>e.find,"call",t=>t(t=>t.name()===e||t.alias()===e)]);t?i=t:o.push(e)}const s=[];Zr([i,"access",e=>e.commands,"optionalAccess",e=>e.forEach,"call",e=>e(e=>{s.push(e.name())})]),Zr([i,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e(e=>{e.flags.split(/[ ,|]+/).forEach(e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)})})]),i!==Xr&&Zr([Xr,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e(e=>{e.flags.split(/[ ,|]+/).forEach(e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)})})]);const n=o[o.length-1]||"",a=Array.from(new Set(s)).filter(e=>e.startsWith(n));0===a.length&&ic(i)?console.log(Wr):a.length>0&&console.log(a.join("\n")),process.exit()}():Yr&&Yr.init())}function nc(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function ac(t){t.command("remove <skillId>").description("Remove skills from the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Remove skill from project",description:"Remove a configured skill from the specified project.",examples:[{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID to remove"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},removed_skill_ids:{type:"array",items:{type:"string"},description:"Removed skill IDs"},message:{type:"string",description:"Result message"}}}}},errors:[{code:e.ErrorCode.E3004,name:"SKILL_NOT_INSTALLED",desc:"The specified skill is not installed in the project",fix:"Please use `skill list` to confirm installed skills"}]}}).action(async function(t,i,o){const s=o.getContext(),{projectId:n}=i,a=new Set([t]),r=nc([(await e.IdeApi.GetVibeProject({project_id:n})).data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]);var c;const d=(c=nc([r,"optionalAccess",e=>e.skills]),Array.isArray(c)?c.map(e=>{return{skill_id:String((t=nc([e,"optionalAccess",e=>e.skill_id]),i=()=>"",null!=t?t:i())),is_preload:nc([e,"optionalAccess",e=>e.is_preload])};var t,i}).filter(e=>Boolean(e.skill_id)):[]).filter(e=>!a.has(e.skill_id)),p={filter_types:nc([r,"optionalAccess",e=>e.filter_types]),skills:d};await e.IdeApi.UpdateVibeProject({project_id:n,project_settings:{skill_setting:p}}),nc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill removed.")]),nc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,removed_skill_ids:Array.from(a),message:"removed Skills successfully."})])})}function rc(e,t){return null!=e?e:t()}function cc(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function dc(t){t.command("list").description("List available skills for the project").requiredOption("-p, --project-id <projectId>","Project ID").option("--space-id <spaceId>","Space ID (optional, reads from config)").config({help:{brief:"List available skills for the project",description:"Retrieve a list of all available skills for the specified project type, with installation status indicating which skills are already added.",examples:[{desc:"List project skills",cmd:"coze code skill list --project-id <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{type:"array",items:{type:"object",properties:{description:{type:"string",description:"Skill description"},skill_id:{type:"string",description:"Skill ID"},name:{type:"string",description:"Skill name"},icon:{type:"string",description:"Skill icon URL"},is_installed:{type:"boolean",description:"Whether the skill is installed"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}]}}).action(async function(t,i){const o=i.getContext(),{projectId:s}=t,n=rc(rc(t.spaceId,()=>cc([o,"optionalAccess",e=>e.config,"access",e=>e.spaceId])),()=>"");if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing spaceId: pass --space-id <spaceId> or set config.spaceId");const a=await e.IdeApi.GetVibeProject({project_id:s}),r=function(e){const t=[],i=cc([e,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_settings]);cc([i,"optionalAccess",e=>e.skill_setting,"optionalAccess",e=>e.skills])&&t.push(...i.skill_setting.skills);const o=t.map(e=>cc([e,"optionalAccess",e=>e.skill_id])).filter(Boolean);return new Set(o)}(a.data||{}),c=cc([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),d=await ar.GetSkillList({project_type:c,space_id:n,category_type_list:[c]});cc([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${cc([d,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} skills.`)]),cc([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(cc([d,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e(e=>({description:cc([e,"optionalAccess",e=>e.description]),skill_id:cc([e,"optionalAccess",e=>e.skill_id]),name:cc([e,"optionalAccess",e=>e.name]),icon:cc([e,"optionalAccess",e=>e.icon]),is_installed:r.has(e.skill_id||"")}))]))])})}function pc(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function lc(t){t.command("add <skillId>").description("Add skills to the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add skill to project",description:"Add a specified skill to the project. Skills can extend project capabilities, such as adding search, code execution, etc.",examples:[{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},added_skill_ids:{type:"array",items:{type:"string"},description:"Added skill IDs"},message:{type:"string",description:"Result message"}}}}},errors:[{code:e.ErrorCode.E3002,name:"SKILL_NOT_FOUND",desc:"The specified skill does not exist",fix:"Please use `skill list` to confirm available skills"}]}}).action(async function(t,i,o){const s=o.getContext(),{projectId:n}=i,a=[t],r=(await e.IdeApi.GetVibeProject({project_id:n})).data||{},c=pc([r,"access",e=>e.project_info,"optionalAccess",e=>e.project_type]),d=pc([r,"access",e=>e.project_info,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]),p=function(e){const t=new Map;for(const i of e){const e=pc([i,"optionalAccess",e=>e.skill_id])?String(i.skill_id):"";e&&(t.has(e)||t.set(e,{skill_id:e,is_preload:i.is_preload}))}return Array.from(t.values())}([...Array.isArray(pc([d,"optionalAccess",e=>e.skills]))?d.skills:[],...a.map(e=>({skill_id:String(e),is_preload:!0}))]),l={filter_types:pc([d,"optionalAccess",e=>e.filter_types])&&d.filter_types.length>0?d.filter_types:[c],skills:p};await e.IdeApi.UpdateVibeProject({project_id:n,project_settings:{skill_setting:l}}),pc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skills added successfully.")]),pc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,added_skill_ids:a,message:"added Skills successfully."})])})}var uc,_c,mc,gc,hc,fc,yc,bc,vc,Cc,Sc,Pc,Ec,Tc,Ac,kc,wc,Rc,zc,Ic,Oc,Lc,jc,Uc,Bc,xc,qc,Dc,Mc,Gc,Nc,Fc,$c,Vc,Wc,Hc,Kc,Jc,Qc,Zc,Yc,Xc,ed,td,id,od,sd,nd,ad,rd,cd,dd,pd,ld,ud,_d,md,gd,hd,fd,yd,bd,vd,Cd,Sd,Pd,Ed,Td,Ad,kd,wd,Rd;function zd(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}!function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(uc||(uc={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(_c||(_c={})),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"}(mc||(mc={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(gc||(gc={})),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"}(hc||(hc={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(fc||(fc={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(yc||(yc={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(bc||(bc={})),function(e){e[e.Official=1]="Official";e[e.Public=2]="Public";e[e.Custom=3]="Custom";e[e.Others=101]="Others"}(vc||(vc={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(Cc||(Cc={})),function(e){e[e.App=1]="App";e[e.Resource=2]="Resource"}(Sc||(Sc={})),function(e){e[e.CozeModel=1]="CozeModel";e[e.VolcAccount=2]="VolcAccount";e[e.SelfAccount=3]="SelfAccount";e[e.SelfModel=4]="SelfModel"}(Pc||(Pc={})),function(e){e[e.Asc=1]="Asc";e[e.Desc=2]="Desc"}(Ec||(Ec={})),function(e){e[e.NoDetail=1]="NoDetail";e[e.Detail=2]="Detail";e[e.Operate=3]="Operate"}(Tc||(Tc={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(Ac||(Ac={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.Imageflow=3]="Imageflow";e[e.Knowledge=4]="Knowledge";e[e.UI=5]="UI";e[e.Prompt=6]="Prompt";e[e.Database=7]="Database";e[e.Variable=8]="Variable"}(kc||(kc={})),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"}(wc||(wc={})),function(e){e[e.Mobile=1]="Mobile";e[e.Web=2]="Web"}(Rc||(Rc={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(zc||(zc={})),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"}(Ic||(Ic={})),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"}(Oc||(Oc={})),function(e){e[e.DEFAULT=0]="DEFAULT";e[e.Chux=1]="Chux"}(Lc||(Lc={})),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"}(jc||(jc={})),function(e){e[e.PromptDiff=1]="PromptDiff";e[e.ModelDiff=2]="ModelDiff"}(Uc||(Uc={})),function(e){e[e.DraftBot=1]="DraftBot"}(Bc||(Bc={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(xc||(xc={})),function(e){e[e.Archive=1]="Archive";e[e.Rollback=2]="Rollback"}(qc||(qc={})),function(e){e[e.ProjectCopyCancel=1]="ProjectCopyCancel";e[e.ProjectCopyRetry=2]="ProjectCopyRetry"}(Dc||(Dc={})),function(e){e[e.ProjectCopy=1]="ProjectCopy";e[e.BotCopy=2]="BotCopy";e[e.VibeProjectCopy=3]="VibeProjectCopy"}(Mc||(Mc={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Gc||(Gc={})),function(e){e[e.Bot=1]="Bot";e[e.Workflow=2]="Workflow";e[e.Application=3]="Application"}(Nc||(Nc={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(Fc||(Fc={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}($c||($c={})),function(e){e[e.BatchSize=1]="BatchSize";e[e.LearningRate=2]="LearningRate";e[e.Epochs=3]="Epochs"}(Vc||(Vc={})),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"}(Wc||(Wc={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(Hc||(Hc={})),function(e){e[e.Douyin=1]="Douyin"}(Kc||(Kc={})),function(e){e[e.Terminating=1]="Terminating";e[e.Terminated=2]="Terminated"}(Jc||(Jc={})),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"}(Qc||(Qc={})),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"}(Zc||(Zc={})),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"}(Yc||(Yc={})),function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInput=2]="TotalInput";e[e.TotalOutput=3]="TotalOutput"}(Xc||(Xc={})),function(e){e[e.stop=1]="stop";e[e.resume=2]="resume",e[e.delete=3]="delete"}(ed||(ed={})),function(e){e[e.Recommend=1]="Recommend"}(td||(td={})),function(e){e[e.Default=0]="Default";e[e.Terminate=1]="Terminate"}(id||(id={})),function(e){e[e.All=0]="All";e[e.WithBenefit=1]="WithBenefit"}(od||(od={})),function(e){e[e.upload=1]="upload";e[e.TrainingSetSplit=2]="TrainingSetSplit"}(sd||(sd={})),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"}(ad||(ad={})),function(e){e[e.Publish=0]="Publish";e[e.Archive=1]="Archive"}(rd||(rd={})),function(e){e[e.User=0]="User";e[e.NL2App=1]="NL2App"}(cd||(cd={})),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"}(dd||(dd={})),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"}(pd||(pd={})),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"}(ld||(ld={})),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"}(ud||(ud={})),function(e){e[e.Normal=0]="Normal";e[e.InReview=1]="InReview";e[e.Offline=2]="Offline"}(_d||(_d={})),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"}(md||(md={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Authorizing=3]="Authorizing"}(gd||(gd={})),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"}(hd||(hd={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(fd||(fd={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.Name=2]="Name"}(yd||(yd={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime"}(bd||(bd={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.PublishTime=2]="PublishTime";e[e.OpenTime=3]="OpenTime"}(vd||(vd={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(Cd||(Cd={})),function(e){e[e.All=0]="All";e[e.CreateByMe=1]="CreateByMe";e[e.AllWithCollaborator=2]="AllWithCollaborator"}(Sd||(Sd={})),function(e){e[e.Desc=0]="Desc";e[e.Asc=1]="Asc"}(Pd||(Pd={})),function(e){e[e.Copy=1]="Copy";e[e.Move=2]="Move";e[e.Publish=3]="Publish";e[e.ImportExport=4]="ImportExport"}(Ed||(Ed={})),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"}(Td||(Td={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.Imageflow=3]="Imageflow";e[e.Knowledge=4]="Knowledge";e[e.UI=5]="UI";e[e.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"}(Ad||(Ad={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(kd||(kd={})),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"}(wd||(wd={})),function(e){e[e.Packing=0]="Packing";e[e.PackSuccess=1]="PackSuccess";e[e.PackFail=2]="PackFail"}(Rd||(Rd={}));class Id{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Id.prototype.__init.call(this),Id.prototype.__init2.call(this),this.request=zd([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=zd([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}Ping(e,t){const i=this.genBaseURL("/api/intelligence_api/ping");return this.request({url:i,method:"POST"},t)}DraftProjectCreate(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/draft_project/create"),s={space_id:i.space_id,name:i.name,description:i.description,icon_uri:i.icon_uri,monetization_conf:i.monetization_conf,create_from:i.create_from,folder_id:i.folder_id,type:i.type};return this.request({url:o,method:"POST",data:s},t)}GetDraftIntelligenceList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_list"),s={space_id:i.space_id,name:i.name,has_published:i.has_published,status:i.status,types:i.types,search_scope:i.search_scope,folder_id:i.folder_id,folder_include_children:i.folder_include_children,order_type:i.order_type,project_type:i.project_type,is_fav_filter:i.is_fav_filter,is_fav:i.is_fav,recently_open:i.recently_open,option:i.option,order_by:i.order_by,cursor_id:i.cursor_id,size:i.size};return this.request({url:o,method:"POST",data:s},t)}DraftProjectUpdate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/update"),s={project_id:i.project_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}GetDraftIntelligenceInfo(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_info"),s={intelligence_id:i.intelligence_id,intelligence_type:i.intelligence_type,version:i.version};return this.request({url:o,method:"POST",data:s},t)}GetUserRecentlyEditIntelligence(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/search/get_recently_edit_intelligence"),s={size:i.size,types:i.types,enterprise_id:i.enterprise_id,organization_id:i.organization_id};return this.request({url:o,method:"POST",data:s},t)}DraftProjectCopy(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/draft_project/copy"),s={project_id:i.project_id,to_space_id:i.to_space_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}ProcessEntityTask(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/entity_task/process"),s={entity_id:i.entity_id,action:i.action,task_id_list:i.task_id_list};return this.request({url:o,method:"POST",data:s},t)}DraftProjectDelete(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/delete"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}EntityTaskSearch(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/entity_task/search"),s={task_list:i.task_list};return this.request({url:o,method:"POST",data:s},t)}ListIntelligenceCollaboration(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/collaboration/list"),s={intelligence_id:i.intelligence_id,intelligence_type:i.intelligence_type};return this.request({url:o,method:"POST",data:s},t)}OceanProjectCreate(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/ocean_project/create"),s={space_id:i.space_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}OceanProjectUpdate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/ocean_project/update"),s={project_id:i.project_id,name:i.name,description:i.description,icon_uri:i.icon_uri};return this.request({url:o,method:"POST",data:s},t)}GetOceanProjectList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_list"),s={space_id:i.space_id,status:i.status,search_scope:i.search_scope,order_by:i.order_by,page_index:i.page_index,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}PublishProject(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_project"),s={project_id:i.project_id,version_number:i.version_number,description:i.description,connectors:i.connectors,connector_publish_config:i.connector_publish_config};return this.request({url:o,method:"POST",data:s},t)}GetPublishRecordDetail(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_record_detail"),s={project_id:i.project_id,publish_record_id:i.publish_record_id};return this.request({url:o,method:"POST",data:s},t)}GetPublishRecordList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_record_list"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}PublishConnectorList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/connector_list"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}CheckProjectVersionNumber(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/check_version_number"),s={project_id:i.project_id,version_number:i.version_number};return this.request({url:o,method:"POST",data:s},t)}DraftProjectInnerTaskList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/inner_task_list"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}GetOceanProjectInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_info"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}GetModelListFilterParams(e,t){const i=this.genBaseURL("/api/intelligence_api/model/get_model_list_filter_params");return this.request({url:i,method:"POST"},t)}StartEstimatedTrainingCost(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/start_estimated_training_cost"),s={base_model_id:i.base_model_id,space_id:i.space_id,training_dataset_id:i.training_dataset_id,epochs:i.epochs};return this.request({url:o,method:"POST",data:s},t)}GetModelList(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_list"),s={space_id:i.space_id,name:i.name,tag_filters:i.tag_filters,context_len_min:i.context_len_min,context_len_max:i.context_len_max,model_cost_min:i.model_cost_min,model_cost_max:i.model_cost_max,model_vendor:i.model_vendor,statusList:i.statusList,model_show_family_id:i.model_show_family_id,model_source:i.model_source,order_by:i.order_by,cursor_id:i.cursor_id,limit:i.limit};return this.request({url:o,method:"POST",data:s},t)}GetFinetuneTemplateDataset(e,t){const i=this.genBaseURL("/api/intelligence_api/model/get_finetune_template_dataset");return this.request({url:i,method:"POST"},t)}GetModelUsageData(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_usage_data"),s={space_id:i.space_id,model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}GetEstimatedTrainingCost(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_estimated_training_cost"),s={task_id:i.task_id,space_id:i.space_id,base_model_id:i.base_model_id,epochs:i.epochs};return this.request({url:o,method:"POST",data:s},t)}CreateFinetuneTask(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/create_finetune_task"),s={space_id:i.space_id,base_model_id:i.base_model_id,training_dataset_id:i.training_dataset_id,validating_dataset:i.validating_dataset,finetune_configuration:i.finetune_configuration,description:i.description,name:i.name};return this.request({url:o,method:"POST",data:s},t)}UploadFinetuneDataset(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/upload_finetune_dataset"),s={space_id:i.space_id,fileType:i.fileType,fileName:i.fileName,data:i.data,testing_data:i.testing_data};return this.request({url:o,method:"POST",data:s},t)}GetModelInfo(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_info"),s={space_id:i.space_id,model_id:i.model_id,is_finetuning:i.is_finetuning};return this.request({url:o,method:"POST",data:s},t)}GetFinetuneTrainingInfo(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_finetune_training_info"),s={space_id:i.space_id,model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}GetModelPerformanceData(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_performance_data"),s={space_id:i.space_id,model_id:i.model_id,get_pct:i.get_pct};return this.request({url:o,method:"POST",data:s},t)}OperateFinetuneTask(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/operate_finetune_task"),s={id:i.id,action:i.action};return this.request({url:o,method:"POST",data:s},t)}DeleteFinetuneModel(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/delete_finetune_model"),s={model_id:i.model_id,space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}GetUserCompleteProfileRecord(e,t){const i=this.genBaseURL("/api/intelligence_api/user_profile/get_user_complete_profile_record");return this.request({url:i,method:"POST"},t)}DownloadUserProfile(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/user_profile/download_user_profile"),s={Cookie:i.Cookie};return this.request({url:o,method:"POST",headers:s},t)}GetProjectPublishedConnector(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/get_published_connector"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}PublishIntelligenceUnList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/publish/publish_intelligence_unlist"),s={intelligence_id:i.intelligence_id,connector_ids:i.connector_ids,intelligence_type:i.intelligence_type};return this.request({url:o,method:"POST",data:s},t)}PublishIntelligenceList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_publish_intelligence_list"),s={intelligence_type:i.intelligence_type,space_id:i.space_id,owner_id:i.owner_id,name:i.name,order_last_publish_time:i.order_last_publish_time,order_total_token:i.order_total_token,size:i.size,cursor_id:i.cursor_id,intelligence_ids:i.intelligence_ids};return this.request({url:o,method:"POST",data:s},t)}UpdateDiffModeInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/diff_mode/update_diff_mode_info"),s={target_type:i.target_type,target_id:i.target_id,diff_mode_info:i.diff_mode_info,exit_and_save:i.exit_and_save,exit_and_discard:i.exit_and_discard};return this.request({url:o,method:"POST",data:s},t)}GetDiffModeInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/diff_mode/get_diff_mode_info"),s={target_type:i.target_type,target_id:i.target_id};return this.request({url:o,method:"POST",data:s},t)}GetProjectPublishSummary(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_project_publish_summary"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}DraftProjectCrossSpaceCopy(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/draft_project/crossspace_copy"),s={project_id:i.project_id,to_space_id:i.to_space_id};return this.request({url:o,method:"POST",data:s},t)}EntityTaskList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/entity_task/list"),s={space_id:i.space_id,task_id_list:i.task_id_list};return this.request({url:o,method:"POST",data:s},t)}ExpansionTpm(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/expansion_tpm"),s={model_id:i.model_id,enterprise_id:i.enterprise_id,organization_id:i.organization_id,tpm_input_expansion:i.tpm_input_expansion,tpm_output_expansion:i.tpm_output_expansion,start_time:i.start_time,end_time:i.end_time};return this.request({url:o,method:"POST",data:s},t)}GetEstimatedTpmExpansionCost(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion_cost"),s={model_id:i.model_id,enterprise_id:i.enterprise_id,input_tpm:i.input_tpm,output_tpm:i.output_tpm};return this.request({url:o,method:"POST",data:s},t)}GetEstimatedTpmExpansion(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion"),s={model_id:i.model_id,enterprise_id:i.enterprise_id,estimated_rpm:i.estimated_rpm,StartTime:i.StartTime,EndTime:i.EndTime};return this.request({url:o,method:"POST",data:s},t)}FolderUpdate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/update"),s={folder_id:i.folder_id,name:i.name,description:i.description};return this.request({url:o,method:"POST",data:s},t)}GetFolderList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/search/get_folder_list"),s={space_id:i.space_id,type:i.type,name:i.name,search_scope:i.search_scope,parent_folder_id:i.parent_folder_id,parent_include_children:i.parent_include_children,order_by:i.order_by,order_type:i.order_type,size:i.size,page_num:i.page_num};return this.request({url:o,method:"POST",data:s},t)}FolderMove(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/move"),s={folder_id:i.folder_id,parent_folder_id:i.parent_folder_id};return this.request({url:o,method:"POST",data:s},t)}FolderDelete(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/delete"),s={folder_id:i.folder_id};return this.request({url:o,method:"POST",data:s},t)}FolderCreate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/create"),s={space_id:i.space_id,type:i.type,name:i.name,description:i.description,parent_folder_id:i.parent_folder_id};return this.request({url:o,method:"POST",data:s},t)}ArchiveProject(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/archive"),s={project_id:i.project_id,description:i.description,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetIntelligenceTaskInfo(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/entity_task/task_info"),s={task_id:i.task_id};return this.request({url:o,method:"GET",params:s},t)}ProjectHistoryList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/history_list"),s={project_id:i.project_id,history_type:i.history_type,cursor:i.cursor,size:i.size};return this.request({url:o,method:"POST",data:s},t)}RollbackProject(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/rollback"),s={project_id:i.project_id,rollback_version:i.rollback_version,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetModelConcurrencyPerformanceData(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_concurrency_performance_data"),s={space_id:i.space_id,model_id:i.model_id};return this.request({url:o,method:"POST",data:s},t)}UpdateModelConfigType(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/update_model_config_type"),s={space_id:i.space_id,model_id:i.model_id,config_type:i.config_type};return this.request({url:o,method:"POST",data:s},t)}GetSpaceModelUserConfig(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_space_model_user_config"),s={space_id:i.space_id};return this.request({url:o,method:"POST",data:s},t)}OpenGetProjectList(e,t){const i=e||{},o=this.genBaseURL("/v1/apps"),s={workspace_id:i.workspace_id,publish_status:i.publish_status,connector_id:i.connector_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}OpenGetBotList(e,t){const i=e||{},o=this.genBaseURL("/v1/bots"),s={workspace_id:i.workspace_id,publish_status:i.publish_status,connector_id:i.connector_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}GetFolderTree(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/tree"),s={space_id:i.space_id,type:i.type};return this.request({url:o,method:"POST",data:s},t)}OpenGetSpaceFolder(e,t){const i=e||{},o=this.genBaseURL("/v1/folders"),s={workspace_id:i.workspace_id,folder_type:i.folder_type,parent_folder_id:i.parent_folder_id,page_num:i.page_num,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}MoveObjectToFolder(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/folder/move_object"),s={dest_folder_id:i.dest_folder_id,folder_space_id:i.folder_space_id,move_objects:i.move_objects};return this.request({url:o,method:"POST",data:s},t)}GetFolderInfoByIds(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/folder/get_by_ids"),s={space_id:i.space_id,folder_ids:i.folder_ids,get_path_info:i.get_path_info};return this.request({url:o,method:"POST",data:s},t)}OpenGetFolderInfo(e,t){const i=e||{},o=this.genBaseURL(`/v1/folders/${i.folder_id}`);return this.request({url:o,method:"GET"},t)}ExportPreCheck(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/export_pre_check"),s={res_type:i.res_type,id:i.id,commit_id:i.commit_id};return this.request({url:o,method:"POST",data:s},t)}ImportPreCheck(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/import_pre_check"),s={package_uri:i.package_uri};return this.request({url:o,method:"POST",data:s},t)}GetUploadAuthToken(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/upload/auth_token"),s={scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}MarkProjectHistory(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/history_list/read"),s={project_id:i.project_id,version:i.version};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelDetail(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_detail"),s={model_id:i.model_id,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_list"),s={search_key:i.search_key,sort_field:i.sort_field,org_id:i.org_id,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetProjectHistoryNotice(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/draft_project/history_list/notice"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}BindCustomModelSpace(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/bind_custom_model_space"),s={model_id:i.model_id,space_id_list:i.space_id_list,status:i.status,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelSpaceList(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_space_list"),s={model_id:i.model_id,search_key:i.search_key,org_id:i.org_id,cursor_id:i.cursor_id,limit:i.limit,enterprise_id:i.enterprise_id};return this.request({url:o,method:"POST",data:s},t)}GetCustomModelParameterTemplate(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/get_custom_model_parameter_template"),s={org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}OpenCopyTaskInfo(e,t){const i=e||{},o=this.genBaseURL(`/v1/entities/copy_tasks/${i.task_id}`);return this.request({url:o,method:"GET"},t)}OpenDuplicateDraftEntity(e,t){const i=e||{},o=this.genBaseURL("/v1/entities/copy_tasks"),s={entity_id:i.entity_id,entity_type:i.entity_type,to_workspace_id:i.to_workspace_id};return this.request({url:o,method:"POST",data:s},t)}ConvertCustomModelParameter(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/convert_custom_model_parameter"),s={parameters:i.parameters,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}CreateCustomModel(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/create_custom_model"),s={model_name:i.model_name,model_icon_uri:i.model_icon_uri,model_arch:i.model_arch,model_desc:i.model_desc,base_url:i.base_url,secret_name:i.secret_name,model_runtime_tag:i.model_runtime_tag,inputLength:i.inputLength,parameters:i.parameters,api_agreement:i.api_agreement,safety_guardrails:i.safety_guardrails,auth:i.auth,api_mode:i.api_mode,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}TerminateCustomModel(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/terminate_custom_model"),s={model_id:i.model_id,terminate_time:i.terminate_time,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCustomModel(e,t){const i=e,o=this.genBaseURL("/api/intelligence_api/model/update_custom_model"),s={model_name:i.model_name,model_icon_uri:i.model_icon_uri,model_arch:i.model_arch,model_desc:i.model_desc,base_url:i.base_url,secret_name:i.secret_name,model_runtime_tag:i.model_runtime_tag,inputLength:i.inputLength,parameters:i.parameters,model_id:i.model_id,api_agreement:i.api_agreement,safety_guardrails:i.safety_guardrails,auth:i.auth,api_mode:i.api_mode,org_id:i.org_id};return this.request({url:o,method:"POST",data:s},t)}GetModelUsageRecord(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_model_usage_record"),s={space_id:i.space_id,model_id:i.model_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp,order_by_type:i.order_by_type,order_by_field:i.order_by_field,page:i.page,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}GetEntityModelUsage(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_entity_model_usage"),s={space_id:i.space_id,model_id:i.model_id,entity_id:i.entity_id,entity_type:i.entity_type,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp};return this.request({url:o,method:"POST",data:s},t)}GetTypeList(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/get_type_list"),s={model:i.model,voice:i.voice,raw_model:i.raw_model,space_id:i.space_id,cur_model_id:i.cur_model_id,cur_model_ids:i.cur_model_ids,model_scene:i.model_scene,tag_filters:i.tag_filters,user_benefit_filter:i.user_benefit_filter};return this.request({url:o,method:"POST",data:s},t)}SaveModelReplacement(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/save_replacement"),s={space_id:i.space_id,old_model_id:i.old_model_id,new_model_id:i.new_model_id,start_timestamp:i.start_timestamp,end_timestamp:i.end_timestamp};return this.request({url:o,method:"POST",data:s},t)}GetModelReplacement(e,t){const i=e||{},o=this.genBaseURL("/api/intelligence_api/model/get_replacement"),s={space_id:i.space_id,entity_type:i.entity_type,entity_id:i.entity_id};return this.request({url:o,method:"POST",data:s},t)}}const Od=new Id({}),Ld={agent:Oc.VibeProjectAgent,workflow:Oc.VibeProjectAutomation,webapp:Oc.VibeProjectWebApp,app:Oc.VibeProjectApp,skill:Oc.VibeProjectSkill,web:Oc.VibeProjectGeneralWeb,miniprogram:Oc.VibeProjectWechatMiniProgram,assistant:Oc.VibeProjectAssistantAgent},jd={[Oc.VibeProjectAgent]:"agent",[Oc.VibeProjectAutomation]:"workflow",[Oc.VibeProjectWebApp]:"webapp",[Oc.VibeProjectApp]:"app",[Oc.VibeProjectSkill]:"skill",[Oc.VibeProjectGeneralWeb]:"web",[Oc.VibeProjectWechatMiniProgram]:"miniprogram",[Oc.VibeProjectAssistantAgent]:"assistant"};function Ud(e){if(!e)return;const t=String(e).trim();if(!t)return;const i=t.toLowerCase();return Ld[i]}const Bd=e=>jd[e],xd=[Oc.VibeProjectAgent,Oc.VibeProjectAutomation,Oc.VibeProjectWebApp,Oc.VibeProjectApp,Oc.VibeProjectSkill,Oc.VibeProjectGeneralWeb,Oc.VibeProjectWechatMiniProgram,Oc.VibeProjectAssistantAgent].map(Bd).filter(Boolean);function qd(e,t){return null!=e?e:t()}function Dd(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Md={agent:e.VibeProjectType.Agent,workflow:e.VibeProjectType.Automation,webapp:e.VibeProjectType.WebApp,app:e.VibeProjectType.App,skill:e.VibeProjectType.Skill,web:e.VibeProjectType.GeneralWeb,miniprogram:e.VibeProjectType.WechatMiniProgram,assistant:e.VibeProjectType.AssistantAgent},Gd={[e.VibeProjectType.Agent]:"agent",[e.VibeProjectType.Automation]:"workflow",[e.VibeProjectType.WebApp]:"webapp",[e.VibeProjectType.App]:"app",[e.VibeProjectType.Skill]:"skill",[e.VibeProjectType.GeneralWeb]:"web",[e.VibeProjectType.WechatMiniProgram]:"miniprogram",[e.VibeProjectType.AssistantAgent]:"assistant"};const Nd=e=>Gd[e],Fd=[e.VibeProjectType.GeneralWeb,e.VibeProjectType.App],$d=Fd.map(Nd);function Vd(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Wd(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}class Hd{static getInstance(){return Hd.INSTANCE||(Hd.INSTANCE=new Hd),Hd.INSTANCE}sendMessageRunTask(e){const t=[_.resolve(__dirname,"./send-message.worker.js")],i=process.execPath;b.spawn(i,[...t,JSON.stringify(e)],{detached:!0,stdio:"ignore"}).unref()}async sendMessage(t){return await e.sendProjectChatMessage(t)}isValidType(e){return Fd.includes(e)}}const Kd=Hd.getInstance();function Jd(e,t){return null!=e?e:t()}function Qd(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Zd(t){t.command("create").description("Create a new project").requiredOption("--message <message>","Description/requirements for creating the project").requiredOption("--type <type>","Project type: agent | workflow | app | skill | web | miniprogram | assistant").option("--org-id <orgId>","Organization ID (optional, will read from context automatically)").option("--space-id <spaceId>","Space ID (optional, will read from context automatically)").option("--wait","Wait for project creation to complete").config({help:{brief:"Create a new Coze Coding project",description:"Create a new Coze Coding project via natural language description. The system will automatically generate project structure and configuration based on the description, supporting multiple project types.",examples:[{desc:"Create an Agent project",cmd:'coze code project create --message "Create an intelligent customer service robot" --type agent',tags:["[RECOMMENDED]"]},{desc:"Create a Workflow project",cmd:'coze code project create --message "Create a data processing workflow" --type workflow'}],schema:{input:{message:{type:"string",required:!0,description:"Project description/requirements (natural language)"},type:{type:"string",required:!0,enum:$d,description:"Project type"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{project_id:{type:"string",description:"Created project ID"},type:{type:"string",description:"Project type"}}},enums:{type:$d.reduce((e,t)=>(e[t]=`${t.toUpperCase()} project`,e),{})},errors:[{code:e.ErrorCode.E1005,name:"INVALID_PROJECT_TYPE",desc:"Invalid project type",fix:"Please use a valid project type: agent | workflow | app | skill | web | miniprogram | assistant"},{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Missing Space ID",fix:"Please use the --space-id parameter or run `coze space use <spaceId>` first"},{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Project type is not supported for creation",fix:"Please choose a supported project type and try again"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized or project tool config is missing",fix:"Please retry and run with --debug if the issue persists"}]}}).action(async(t,i)=>{const o=i.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Jd(Jd(t.spaceId,()=>Qd([o,"optionalAccess",e=>e.config,"access",e=>e.spaceId])),()=>""),{message:n,type:a,wait:r}=t;Qd([o,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e(`Resolving project type '${a}'...`)]);const c=function(e){if(!e)return;const t=String(e).trim();if(!t)return;const i=t.toLowerCase();return Md[i]}(a);if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!c)throw new e.CozeError(e.ErrorCode.E1005,`Unknown project type: ${a}`,{type:a});if(!Kd.isValidType(c))throw new e.CozeError(e.ErrorCode.E1006,`Project type ${a} is not supported for creation`,{type:a,projectType:c});Qd([o,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching agent tools configuration...")]);const d=Qd([await e.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e(e=>e.project_type===c),"optionalAccess",e=>e.tools]);if(!d||0===d.length)throw new e.CozeError(e.ErrorCode.E5000,`No tools config for projectType: ${String(a)}`,{type:a,projectType:c});const p={};d.forEach(e=>{Qd([e,"optionalAccess",e=>e.name])&&(p[e.name]=Boolean(e.enabled))}),Qd([o,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching project default skills...")]);const l={skills:Jd(Qd([await ar.GetProjectDefaultSkill({project_type:c,space_id:String(s)}),"access",e=>e.data,"optionalAccess",e=>e.skill_list]),()=>[]).map(e=>({skill_id:e.skill_id,is_preload:e.is_preload})),filter_types:[c]},u={space_id:String(s),user_query:n,project_type:c,agent_tools:p,project_settings:{model_setting:{model_name:""},skill_setting:l}};Qd([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating project...")]);const _=Jd((await e.IdeApi.ChatCreateVibeProject(u)).data,()=>({})).project_id,m=await Qd([o,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!m)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(o.ui.success('Project created successfully, please use "coze code message status" to check the status.'),Qd([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:_,type:a})]),r){const e=await Kd.sendMessage({projectId:Jd(_,()=>""),prompt:n,apiBaseUrl:o.config.apiBaseUrl,accessToken:m,xTTEnv:o.config.xTTEnv,key:`coze-coding-cli:message:${_}`});o.response.print(e.lastAnswerMessage)}else Kd.sendMessageRunTask({projectId:Jd(_,()=>""),prompt:n,apiBaseUrl:o.config.apiBaseUrl,accessToken:m,xTTEnv:o.config.xTTEnv,key:`coze-coding-cli:message:${_}`})})}const Yd=t=>{const i=t.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");Zd(i),function(t){t.command("list").description("List all projects").config({help:{brief:"List all projects in the current space",description:"Get the list of projects in the current space. Supports filtering by type, name, publish status, and supports pagination.",examples:[{desc:"List projects",cmd:"coze code project list",tags:["[RECOMMENDED]"]},{desc:"Filter by type",cmd:"coze code project list --type agent --type workflow"},{desc:"Search by name",cmd:'coze code project list --name "customer service"'}],schema:{input:{size:{type:"number",required:!1,description:"Number of projects to return (default: 10)"},cursorId:{type:"string",required:!1,description:"Cursor for pagination"},type:{type:"array",required:!1,description:"Project type filter (can be passed multiple times)"},name:{type:"string",required:!1,description:"Filter by project name"},hasPublished:{type:"boolean",required:!1,description:"Filter by publish status"},searchScope:{type:"number",required:!1,description:"Created by (All = 0, CreateByMe = 1)"},folderId:{type:"string",required:!1,description:"Folder ID"},orderType:{type:"number",required:!1,description:"Sort type (0 for descending, 1 for ascending)"},isFavFilter:{type:"boolean",required:!1,description:"Filter by favorite status"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Project ID"},name:{type:"string",description:"Project name"},type:{type:"string",description:"Project type"},description:{type:"string",description:"Project description"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}],enums:{type:xd.reduce((e,t)=>(e[t]=`${t.toUpperCase()} project`,e),{}),"search-scope":{0:"All",1:"CreateByMe"},"order-type":{0:"Descending",1:"Ascending"},"order-by":{0:"updated_at",1:"created_at"}}}}).option("--size <size>","Number of projects to return",parseInt).option("--cursor-id <cursorId>","Cursor for pagination").option("--type <type>","Project type filter (can be passed multiple times): agent | workflow | webapp | app | web | miniprogram | assistant",(e,t=[])=>[...t,e],[]).option("--name <name>","Filter by project name").option("--has-published","Filter by publish status").option("--search-scope <searchScope>","Created by (All = 0, CreateByMe = 1, AllWithCollaborator = 2)").option("--folder-id <folderId>","Folder ID").option("--order-type <orderType>","Sort type (0 for descending, 1 for ascending)").option("--order-by <orderBy>","Order by (0 for updated_at, 1 for created_at)").option("--is-fav-filter","Filter by favorite status (true | false)").action(async function(e,t){const i=t.getContext(),o=qd(Dd([e,"optionalAccess",e=>e.size]),()=>10),s=qd(Dd([e,"optionalAccess",e=>e.cursorId]),()=>{}),n=Dd([e,"optionalAccess",e=>e.type,"optionalAccess",e=>e.map,"call",e=>e(Ud),"access",e=>e.filter,"call",e=>e(Boolean)]),a=Dd([e,"optionalAccess",e=>e.name]),r=Dd([e,"optionalAccess",e=>e.hasPublished])?Boolean(Dd([e,"optionalAccess",e=>e.hasPublished])):void 0,c=Number(qd(Dd([e,"optionalAccess",e=>e.searchScope]),()=>Sd.All)),d=qd(Dd([e,"optionalAccess",e=>e.folderId]),()=>"0"),p=Number(qd(Dd([e,"optionalAccess",e=>e.orderType]),()=>Pd.Desc)),l=Boolean(Dd([e,"optionalAccess",e=>e.isFavFilter])),u=Number(qd(Dd([e,"optionalAccess",e=>e.orderBy]),()=>vd.UpdateTime));let _=[];Dd([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching project list...")]);const m=await Od.GetDraftIntelligenceList({space_id:qd(Dd([i,"optionalAccess",e=>e.config,"access",e=>e.spaceId]),()=>""),size:o,cursor_id:s,types:n,name:a,has_published:r,search_scope:c,folder_id:d,order_type:p,order_by:u,is_fav_filter:l,status:[Ic.Using,Ic.Banned,Ic.MoveFailed]});_=Dd([m,"access",e=>e.data,"optionalAccess",e=>e.intelligences])||[],Dd([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetched ${_.length} projects.`)]),Dd([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(_.map(e=>({id:Dd([e,"access",e=>e.basic_info,"optionalAccess",e=>e.id]),name:Dd([e,"access",e=>e.basic_info,"optionalAccess",e=>e.name]),type:Bd(e.type),description:Dd([e,"access",e=>e.basic_info,"optionalAccess",e=>e.description])})))])})}(i),function(t){t.command("get <projectId>").description("View project details").config({help:{brief:"Get project details",description:"Get the detailed configuration of the specified project, including project type, settings, skill configurations, etc.",examples:[{desc:"View project details",cmd:"coze code project get <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},project_name:{type:"string",description:"Project name"},project_type:{type:"string",description:"Project type"},skills:{type:"object",description:"Project skill configurations",properties:{skills:{type:"array",items:{type:"object",properties:{skill_id:{type:"string",description:"Skill ID"},is_preload:{type:"boolean",description:"Is preloaded"}}}}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project does not exist",fix:"Please confirm if the project ID is correct, use `project list` to view available projects"}]}}).action(async function(t,i,o){const s=o.getContext();Vd([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetching project details for '${t}'...`)]);const n=Vd([await e.IdeApi.GetVibeProject({project_id:t}),"access",e=>e.data,"optionalAccess",e=>e.project_info]);if(!n)throw new e.CozeError(e.ErrorCode.E3001,`Project ${t} not found`,{projectId:t});Vd([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Project details for '${t}':`)]),Vd([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...y.omit(n,["project_settings"]),skills:y.pick(Vd([n,"optionalAccess",e=>e.project_settings,"optionalAccess",e=>e.skill_setting]),["skills"]),project_type:Nd(Vd([n,"optionalAccess",e=>e.project_type]))})])})}(i),function(t){t.command("delete <projectId>").description("Delete a project").config({help:{brief:"Delete project",description:"Delete the specified Coze Coding project. This operation cannot be undone, please use with caution.",examples:[{desc:"Delete project",cmd:"coze code project delete <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID to delete"}},output:{project_id:{type:"string",description:"Deleted project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E3005,name:"DELETE_FAILED",desc:"Failed to delete project",fix:"Please confirm if the project ID is correct and check if you have sufficient permissions"}]}}).action(async function(t,i,o){const s=o.getContext();Wd([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleting project '${t}'...`)]),await e.IdeApi.DeleteVibeProject({project_id:t}),Wd([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Project '${t}' deleted successfully.`)]),Wd([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:t,message:`Project '${t}' deleted successfully.`})])})}(i)};var Xd,ep,tp,ip,op,sp,np,ap,rp,cp,dp,pp,lp,up,_p,mp,gp,hp,fp,yp,bp,vp,Cp,Sp,Pp,Ep,Tp,Ap,kp,wp,Rp,zp,Ip,Op,Lp,jp,Up,Bp,xp,qp,Dp,Mp,Gp,Np,Fp,$p,Vp,Wp,Hp,Kp,Jp,Qp,Zp,Yp,Xp,el,tl,il,ol,sl,nl,al,rl,cl,dl,pl;function ll(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}!function(e){e[e.Example=0]="Example";e[e.Template=1]="Template"}(Xd||(Xd={})),function(e){e[e.SpaceEvent=1]="SpaceEvent"}(ep||(ep={})),function(e){e[e.Interest=1]="Interest"}(tp||(tp={})),function(e){e[e.General=0]="General";e[e.PPT=1]="PPT";e[e.Podcast=2]="Podcast";e[e.WEB=3]="WEB";e[e.ImageDoc=4]="ImageDoc";e[e.Poster=5]="Poster";e[e.Excel=6]="Excel";e[e.DesignTemplate=7]="DesignTemplate";e[e.PPTTemplate=8]="PPTTemplate";e[e.Chart=9]="Chart";e[e.Video=10]="Video";e[e.ImagePPTTemplate=11]="ImagePPTTemplate"}(ip||(ip={})),function(e){e[e.Chat=1]="Chat";e[e.Fill=2]="Fill"}(op||(op={})),function(e){e[e.Delete=0]="Delete";e[e.Running=1]="Running";e[e.Pause=2]="Pause";e[e.TaskFinish=3]="TaskFinish";e[e.Init=4]="Init";e[e.Stop=5]="Stop";e[e.Interrupt=6]="Interrupt";e[e.IllegalContent=7]="IllegalContent";e[e.AbnormalInterrupt=8]="AbnormalInterrupt";e[e.Sleep=9]="Sleep"}(sp||(sp={})),function(e){e[e.Favorite=1]="Favorite";e[e.Template=2]="Template";e[e.TemplateCover=3]="TemplateCover";e[e.PlanTemplate=4]="PlanTemplate";e[e.Article=5]="Article"}(np||(np={})),function(e){e[e.General=0]="General";e[e.Product=1]="Product"}(ap||(ap={})),function(e){e[e.Unknown=0]="Unknown";e[e.Pending=1]="Pending";e[e.Running=2]="Running";e[e.Completed=3]="Completed";e[e.Failed=4]="Failed";e[e.Cancelled=5]="Cancelled"}(rp||(rp={})),function(e){e[e.HandsOff=0]="HandsOff";e[e.Cooperative=1]="Cooperative";e[e.Auto=2]="Auto"}(cp||(cp={})),function(e){e[e.Modify=1]="Modify";e[e.Clear=2]="Clear";e[e.RemoveBackground=3]="RemoveBackground";e[e.Inpainting=4]="Inpainting";e[e.TextReplacement=5]="TextReplacement"}(dp||(dp={})),function(e){e[e.Unactivated=1]="Unactivated";e[e.Activated=2]="Activated"}(pp||(pp={})),function(e){e[e.hot_city=1]="hot_city";e[e.city=2]="city"}(lp||(lp={})),function(e){e[e.PDF=1]="PDF";e[e.PPT=2]="PPT";e[e.ImageEditablePpt=3]="ImageEditablePpt"}(up||(up={})),function(e){e[e.Chinese=0]="Chinese";e[e.English=1]="English"}(_p||(_p={})),function(e){e[e.Review=1]="Review";e[e.Draft=2]="Draft";e[e.LawQA=3]="LawQA"}(mp||(mp={})),function(e){e[e.Pin=1]="Pin";e[e.UnPin=2]="UnPin";e[e.Use=3]="Use"}(gp||(gp={})),function(e){e[e.Init=1]="Init";e[e.Stock=2]="Stock";e[e.Sector=3]="Sector"}(hp||(hp={})),function(e){e[e.GeneralChat=1]="GeneralChat";e[e.Scheduled=2]="Scheduled"}(fp||(fp={})),function(e){e[e.FieldAnalysis=1]="FieldAnalysis";e[e.Upload=2]="Upload"}(yp||(yp={})),function(e){e[e.Running=1]="Running";e[e.Pause=2]="Pause";e[e.TaskFinish=3]="TaskFinish";e[e.Init=4]="Init";e[e.Stop=5]="Stop";e[e.Interrupt=6]="Interrupt";e[e.IllegalContent=7]="IllegalContent";e[e.AbnormalInterrupt=8]="AbnormalInterrupt";e[e.Sleep=9]="Sleep"}(bp||(bp={})),function(e){e[e.UNKNOWN=0]="UNKNOWN";e[e.HTML=1]="HTML";e[e.WORD=2]="WORD";e[e.PPT=3]="PPT";e[e.EXCEL=4]="EXCEL";e[e.PDF=5]="PDF";e[e.NOTE=6]="NOTE";e[e.IMAGE=7]="IMAGE";e[e.PODCAST=8]="PODCAST"}(vp||(vp={})),function(e){e[e.FavoritePage=1]="FavoritePage";e[e.TASK=2]="TASK"}(Cp||(Cp={})),function(e){e[e.UserUpload=1]="UserUpload";e[e.Explore=2]="Explore";e[e.TASK=3]="TASK"}(Sp||(Sp={})),function(e){e[e.PPT=1]="PPT"}(Pp||(Pp={})),function(e){e[e.Favorite=1]="Favorite";e[e.MultiDocImage=2]="MultiDocImage"}(Ep||(Ep={})),function(e){e[e.Upload=1]="Upload";e[e.Search=2]="Search";e[e.Generate=3]="Generate"}(Tp||(Tp={})),function(e){e[e.PNG=1]="PNG";e[e.JPG=2]="JPG";e[e.MP4=3]="MP4"}(Ap||(Ap={})),function(e){e[e.Modify=1]="Modify";e[e.Clear=2]="Clear";e[e.RemoveBackground=3]="RemoveBackground";e[e.Generate=4]="Generate";e[e.Search=5]="Search";e[e.Blur=6]="Blur"}(kp||(kp={})),function(e){e[e.Image=1]="Image";e[e.Html=2]="Html";e[e.Livephoto=3]="Livephoto"}(wp||(wp={})),function(e){e[e.Chat=1]="Chat";e[e.ApiTemplate=2]="ApiTemplate"}(Rp||(Rp={})),function(e){e[e.Suggest=1]="Suggest"}(zp||(zp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Clarifying=1]="Clarifying";e[e.PendingActivation=2]="PendingActivation";e[e.Running=3]="Running";e[e.PendingConfirm=4]="PendingConfirm";e[e.Terminated=5]="Terminated"}(Ip||(Ip={})),function(e){e[e.Unknown=0]="Unknown";e[e.SystemError=1]="SystemError";e[e.InsufficientBalance=2]="InsufficientBalance";e[e.UserManual=3]="UserManual";e[e.Timeout=4]="Timeout"}(Op||(Op={})),function(e){e[e.DiggTypeDigg=1]="DiggTypeDigg";e[e.DiggTypeBury=2]="DiggTypeBury"}(Lp||(Lp={})),function(e){e[e.Query=1]="Query";e[e.Answer=2]="Answer";e[e.Resume=3]="Resume"}(jp||(jp={})),function(e){e[e.Unknown=0]="Unknown";e[e.ActivatePlan=1]="ActivatePlan";e[e.ResumePlan=2]="ResumePlan"}(Up||(Up={})),function(e){e[e.DocMultiImage=1]="DocMultiImage"}(Bp||(Bp={})),function(e){e[e.PDF=1]="PDF";e[e.DOCX=2]="DOCX"}(xp||(xp={})),function(e){e[e.DeleteCookie=1]="DeleteCookie"}(qp||(qp={})),function(e){e[e.POSITION=0]="POSITION";e[e.ELEMENT=1]="ELEMENT"}(Dp||(Dp={})),function(e){e[e.DiamondMatrix=1]="DiamondMatrix";e[e.BulletPoints=2]="BulletPoints";e[e.StaggeredProcessDiagram=3]="StaggeredProcessDiagram";e[e.ArrowRingDiagram=4]="ArrowRingDiagram";e[e.VerticalTimeline=5]="VerticalTimeline"}(Mp||(Mp={})),function(e){e[e.Init=1]="Init";e[e.Enabled=2]="Enabled";e[e.Disabled=3]="Disabled"}(Gp||(Gp={})),function(e){e[e.Pending=1]="Pending";e[e.Success=2]="Success";e[e.Avoid=3]="Avoid";e[e.Failed=4]="Failed"}(Np||(Np={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Expired=3]="Expired"}(Fp||(Fp={})),function(e){e[e.Query=1]="Query";e[e.Template=2]="Template"}($p||($p={})),function(e){e[e.Pause=1]="Pause";e[e.Resume=2]="Resume";e[e.Pin=3]="Pin";e[e.Unpin=4]="Unpin";e[e.DoNotDisturb=5]="DoNotDisturb";e[e.CancelDoNotDisturb=6]="CancelDoNotDisturb";e[e.Stop=7]="Stop";e[e.Read=8]="Read"}(Vp||(Vp={})),function(e){e[e.Init=0]="Init";e[e.Enable=1]="Enable";e[e.Disable=2]="Disable"}(Wp||(Wp={})),function(e){e[e.Open=1]="Open";e[e.Close=2]="Close"}(Hp||(Hp={})),function(e){e[e.Open=1]="Open";e[e.Close=2]="Close"}(Kp||(Kp={})),function(e){e[e.Online=1]="Online";e[e.Debug=2]="Debug"}(Jp||(Jp={})),function(e){e[e.UserCreate=0]="UserCreate";e[e.Example=1]="Example"}(Qp||(Qp={})),function(e){e[e.Init=0]="Init";e[e.List=1]="List";e[e.Unlist=2]="Unlist"}(Zp||(Zp={})),function(e){e[e.Good=1]="Good";e[e.Bad=2]="Bad"}(Yp||(Yp={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(Xp||(Xp={})),function(e){e[e.Pending=1]="Pending";e[e.Running=2]="Running";e[e.Success=3]="Success";e[e.Failed=4]="Failed";e[e.Cancel=5]="Cancel"}(el||(el={})),function(e){e[e.Video=1]="Video";e[e.Voice=2]="Voice";e[e.Music=3]="Music"}(tl||(tl={})),function(e){e[e.Update=1]="Update";e[e.UpdateAndAdd=2]="UpdateAndAdd";e[e.UpdateAndSync=3]="UpdateAndSync"}(il||(il={})),function(e){e[e.ChatQuery=1]="ChatQuery";e[e.VideoEdit=2]="VideoEdit"}(ol||(ol={})),function(e){e[e.Pin=1]="Pin";e[e.Unpin=2]="Unpin"}(sl||(sl={})),function(e){e[e.Valid=1]="Valid";e[e.Deleted=2]="Deleted"}(nl||(nl={})),function(e){e[e.Narration=1]="Narration";e[e.Music=2]="Music";e[e.Other=3]="Other"}(al||(al={})),function(e){e[e.Video=1]="Video";e[e.Image=2]="Image";e[e.Audio=3]="Audio";e[e.Combination=4]="Combination"}(rl||(rl={})),function(e){e[e.Local=1]="Local";e[e.AiGenerated=2]="AiGenerated";e[e.Asset=3]="Asset";e[e.Search=4]="Search"}(cl||(cl={})),function(e){e[e.Role=1]="Role";e[e.Item=2]="Item";e[e.Scene=3]="Scene";e[e.Other=4]="Other"}(dl||(dl={})),function(e){e[e.VoiceSelection=1]="VoiceSelection";e[e.VoiceDescription=2]="VoiceDescription";e[e.None=3]="None"}(pl||(pl={}));class ul{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){ul.prototype.__init.call(this),ul.prototype.__init2.call(this),this.request=ll([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=ll([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}CreateTaskReplay(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/create_task_replay"),s={task_id:i.task_id,need_qr_code:i.need_qr_code,file_list:i.file_list,doc_multi_img_zip_uri:i.doc_multi_img_zip_uri};return this.request({url:o,method:"POST",data:s},t)}GetTaskReplay(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_replay"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}DeleteCozeSpaceTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/delete_task"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCozeSpaceTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/update_task"),s={task_id:i.task_id,task_name:i.task_name,mcp_tool_list:i.mcp_tool_list,expert_agent_config:i.expert_agent_config,scheduled_task_setting:i.scheduled_task_setting};return this.request({url:o,method:"POST",data:s},t)}CreateCozeSpaceTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/create_task"),s={task_name:i.task_name,task_type:i.task_type,file_uri_list:i.file_uri_list,mcp_tool_list:i.mcp_tool_list,agent_ids:i.agent_ids,scheduled_task_setting:i.scheduled_task_setting,source_from:i.source_from,is_debug:i.is_debug,expert_agent_config:i.expert_agent_config};return this.request({url:o,method:"POST",data:s},t)}CozeSpaceChat(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/chat"),s={task_id:i.task_id,query:i.query,files:i.files,mcp_list:i.mcp_list,chat_type:i.chat_type,pause_reason:i.pause_reason,task_run_mode:i.task_run_mode,expert_agent_run_config:i.expert_agent_run_config,scheduled_task_config:i.scheduled_task_config,disable_team_mode:i.disable_team_mode,resume_data:i.resume_data,ability_type:i.ability_type,all_authorized_mcp:i.all_authorized_mcp,reference_template_list:i.reference_template_list,agent_ids:i.agent_ids,router_control:i.router_control,favorites:i.favorites,extra_info:i.extra_info,reference_content:i.reference_content,guiding_id:i.guiding_id,skill_id_list:i.skill_id_list,is_skill_debug:i.is_skill_debug,thinking:i.thinking,reference_items:i.reference_items,plan_template_id:i.plan_template_id,action:i.action,assets:i.assets};return this.request({url:o,method:"POST",data:s},t)}PollStepList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/poll_step_list"),s={task_id:i.task_id,answer_id:i.answer_id,next_key:i.next_key};return this.request({url:o,method:"POST",data:s},t)}OperateTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_task"),s={task_id:i.task_id,operate_type:i.operate_type,pause_reason:i.pause_reason,browser:i.browser,read_progress:i.read_progress,has_unread:i.has_unread};return this.request({url:o,method:"POST",data:s},t)}GetCozeSpaceTaskList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_list"),s={cursor:i.cursor,size:i.size,long_term:i.long_term};return this.request({url:o,method:"POST",data:s},t)}GetMessageList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_message_list"),s={task_id:i.task_id,cursor:i.cursor,size:i.size,asc_mode:i.asc_mode};return this.request({url:o,method:"POST",data:s},t)}UpdateTaskPlan(e,t){const i=e,o=this.genBaseURL("/api/coze_space/update_task_plan"),s={task_id:i.task_id,action_id:i.action_id,task_plan:i.task_plan};return this.request({url:o,method:"POST",data:s},t)}GetTaskReplayById(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_replay_by_id"),s={task_share_id:i.task_share_id,secret:i.secret};return this.request({url:o,method:"POST",data:s},t)}OperateTaskReplay(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_task_replay"),s={task_id:i.task_id,task_share_id:i.task_share_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}UploadTaskFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/upload_task_file"),s={task_id:i.task_id,file_name:i.file_name,file_content:i.file_content};return this.request({url:o,method:"POST",data:s},t)}UploadUserResearchFile(e,t){const i=e,o=this.genBaseURL("/api/coze_space/upload_user_research_file"),s={task_id:i.task_id,action:i.action,file_type:i.file_type,file_name:i.file_name,file_content:i.file_content,desc:i.desc,fields:i.fields};return this.request({url:o,method:"POST",data:s},t)}LandingPageEmailSubscribe(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/landing_page/email_subscribe"),s={email:i.email};return this.request({url:o,method:"POST",data:s},t)}GetUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_url"),s={uri:i.uri,expire_seconds:i.expire_seconds,is_short_url:i.is_short_url,uri_list:i.uri_list};return this.request({url:o,method:"POST",data:s},t)}LandingPage(e,t){const i=this.genBaseURL("/api/coze_space/landing_page");return this.request({url:i,method:"POST"},t)}ExpertProductDetails(e,t){const i=e,o=this.genBaseURL("/api/coze_space/expert_product_details"),s={agent_id:i.agent_id};return this.request({url:o,method:"POST",data:s},t)}Digg(e,t){const i=e,o=this.genBaseURL("/api/coze_space/digg"),s={agent_id:i.agent_id,action_type:i.action_type,is_cancel:i.is_cancel};return this.request({url:o,method:"POST",data:s},t)}SearchStock(e,t){const i=e,o=this.genBaseURL("/api/coze_space/search_stock"),s={search_type:i.search_type,stock_search_word:i.stock_search_word,sector_search_word:i.sector_search_word};return this.request({url:o,method:"POST",data:s},t)}Text2Image(e,t){const i=e,o=this.genBaseURL("/api/coze_space/text2image"),s={prompt:i.prompt,width:i.width,height:i.height};return this.request({url:o,method:"GET",params:s},t)}GetInviteInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_invite_info");return this.request({url:i,method:"POST"},t)}CheckInviteCode(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/check_invite_code"),s={code:i.code};return this.request({url:o,method:"POST",data:s},t)}ExpertProductList(e,t){const i=this.genBaseURL("/api/coze_space/expert_product_list");return this.request({url:i,method:"POST"},t)}CheckInWaitList(e,t){const i=this.genBaseURL("/api/coze_space/check_in_wait_list");return this.request({url:i,method:"POST"},t)}JoinWaitList(e,t){const i=this.genBaseURL("/api/coze_space/join_wait_list");return this.request({url:i,method:"POST"},t)}GetSandboxToken(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_sandbox_token"),s={task_id:i.task_id,action_url_code:i.action_url_code};return this.request({url:o,method:"POST",data:s},t)}GetUserScheduledTasks(e,t){const i=this.genBaseURL("/api/coze_space/get_user_scheduled_tasks");return this.request({url:i,method:"POST"},t)}GenerateRelatedWords(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/generate_related_words"),s={original_word:i.original_word,describe:i.describe};return this.request({url:o,method:"POST",data:s},t)}CodeRepair(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/code_repair"),s={uri:i.uri,error_msg:i.error_msg};return this.request({url:o,method:"POST",data:s},t)}AuthorizedChannelMatch(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/authorized_channel_match"),s={web_rul:i.web_rul};return this.request({url:o,method:"POST",data:s},t)}UpdateTaskStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_task_status"),s={agent_id:i.agent_id,sk:i.sk,task_id:i.task_id,task_status:i.task_status,result:i.result};return this.request({url:o,method:"POST",data:s},t)}GetWebUrl(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_web_url"),s={original_url:i.original_url,exchange_for_short_url:i.exchange_for_short_url,exchange_for_qr_code:i.exchange_for_qr_code,exchange_for_long_url:i.exchange_for_long_url};return this.request({url:o,method:"POST",data:s},t)}OperateSandbox(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_sandbox"),s={task_id:i.task_id,action:i.action,delete_cookie_info:i.delete_cookie_info};return this.request({url:o,method:"POST",data:s},t)}UpdateTaskName(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_task_name"),s={agent_id:i.agent_id,sk:i.sk,task_id:i.task_id,task_name:i.task_name};return this.request({url:o,method:"POST",data:s},t)}GenDoc(e,t){const i=e,o=this.genBaseURL("/api/coze_space/gen_doc"),s={task_id:i.task_id,target_file_type:i.target_file_type,original_file_uri:i.original_file_uri,original_file_name:i.original_file_name,file_content:i.file_content};return this.request({url:o,method:"POST",data:s},t)}PreGetContractInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/pre_get_contract_info"),s={file_content:i.file_content,task_id:i.task_id,file_name:i.file_name};return this.request({url:o,method:"POST",data:s},t)}GetContractCaseInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_contract_case_info"),s={case_no:i.case_no};return this.request({url:o,method:"POST",data:s},t)}GetContractLawInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_contract_law_info"),s={law:i.law,num:i.num};return this.request({url:o,method:"POST",data:s},t)}GetCozeSpaceUserInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_user_info"),s={need_volcano_info:i.need_volcano_info,need_user_job_info:i.need_user_job_info,need_turn_off_user_data_management:i.need_turn_off_user_data_management,need_user_scenes:i.need_user_scenes,need_user_active_time:i.need_user_active_time,need_turn_off_ai_watermark:i.need_turn_off_ai_watermark,need_dnu_user:i.need_dnu_user};return this.request({url:o,method:"POST",data:s},t)}SearchCityInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/search_city_info"),s={search_type:i.search_type,keyword:i.keyword};return this.request({url:o,method:"POST",data:s},t)}UpdateScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/update_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id,task_type:i.task_type,status:i.status,scheduled_task_name:i.scheduled_task_name,trigger:i.trigger,mcp_tool_list:i.mcp_tool_list,expert_agent_config:i.expert_agent_config,task_plan:i.task_plan,is_need_try_run:i.is_need_try_run,description:i.description,task_id:i.task_id,daily_executed_at:i.daily_executed_at,task_plan_v2:i.task_plan_v2};return this.request({url:o,method:"POST",data:s},t)}GetScheduledTasks(e,t){const i=this.genBaseURL("/api/coze_space/get_scheduled_tasks");return this.request({url:i,method:"POST"},t)}TryRunScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/try_run_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id};return this.request({url:o,method:"POST",data:s},t)}DeleteScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/delete_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id};return this.request({url:o,method:"POST",data:s},t)}CreateScheduledTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/create_scheduled_task"),s={is_need_try_run:i.is_need_try_run,scheduled_task_name:i.scheduled_task_name,trigger:i.trigger,source_task_id:i.source_task_id,task_plan:i.task_plan,description:i.description,daily_executed_at:i.daily_executed_at,task_plan_v2:i.task_plan_v2};return this.request({url:o,method:"POST",data:s},t)}UpdateTeamInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_team_info"),s={switch:i.switch};return this.request({url:o,method:"POST",data:s},t)}GetTeamInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_team_info");return this.request({url:i,method:"POST"},t)}GetTaskInfo(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_task_info"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}FeelGood(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/feel_good"),s={task_id:i.task_id,answer_id:i.answer_id,feel:i.feel,content:i.content};return this.request({url:o,method:"POST",data:s},t)}GetUserScheduledTaskQuota(e,t){const i=this.genBaseURL("/api/coze_space/get_scheduled_task_quota");return this.request({url:i,method:"POST"},t)}GetSingleScheduledTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_single_scheduled_task"),s={scheduled_task_id:i.scheduled_task_id};return this.request({url:o,method:"POST",data:s},t)}DeleteUserAuthorization(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/delete_user_authorization"),s={url:i.url,clear_arg:i.clear_arg};return this.request({url:o,method:"POST",data:s},t)}GetUserAuthorizationList(e,t){const i=this.genBaseURL("/api/coze_space/get_user_authorization_list");return this.request({url:i,method:"POST"},t)}AddUserAuthorization(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/add_user_authorization"),s={task_id:i.task_id,url:i.url,clear_arg:i.clear_arg,add_arg:i.add_arg};return this.request({url:o,method:"POST",data:s},t)}SearchFeelGood(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/search_feel_good"),s={task_id:i.task_id,answer_id:i.answer_id};return this.request({url:o,method:"POST",data:s},t)}GetAuthorizedChannelList(e,t){const i=this.genBaseURL("/api/coze_space/get_authorized_channel_list");return this.request({url:i,method:"GET"},t)}GetTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_task_example"),s={task_example_id:i.task_example_id};return this.request({url:o,method:"POST",data:s},t)}AdminListTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/list_task_example"),s={size:i.size,page:i.page,task_ids:i.task_ids,category_id:i.category_id,ability_type:i.ability_type,status:i.status};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_task_example"),s={example_id:i.example_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCozeSpaceUserInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_user_info"),s={job_id:i.job_id,turn_off_user_data_management:i.turn_off_user_data_management,scene_ids:i.scene_ids,turn_off_ai_watermark:i.turn_off_ai_watermark};return this.request({url:o,method:"POST",data:s},t)}GetTaskExampleList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_example_list"),s={category_id:i.category_id,page_size:i.page_size,page:i.page,ability_type:i.ability_type,scene_ids:i.scene_ids};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_task_example"),s={task_id:i.task_id,example_name:i.example_name,example_description:i.example_description,icon_uri:i.icon_uri,index:i.index,category_id:i.category_id,user_query:i.user_query,share_id:i.share_id,ability_type:i.ability_type,open_app_use:i.open_app_use,app_title:i.app_title,official_recommend:i.official_recommend,file_type:i.file_type,type:i.type,close_make_same:i.close_make_same,product_info:i.product_info,api_template_type:i.api_template_type,attachment_files:i.attachment_files};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTaskExample(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_task_example"),s={example_id:i.example_id,example_name:i.example_name,example_description:i.example_description,icon_uri:i.icon_uri,index:i.index,category_id:i.category_id,user_query:i.user_query,status:i.status,ability_type:i.ability_type,open_app_use:i.open_app_use,app_title:i.app_title,official_recommend:i.official_recommend,type:i.type,close_make_same:i.close_make_same,product_info:i.product_info,file_type:i.file_type,api_template_type:i.api_template_type,attachment_files:i.attachment_files};return this.request({url:o,method:"POST",data:s},t)}GetTaskExampleCategory(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_example_category"),s={ability_type:i.ability_type};return this.request({url:o,method:"GET",params:s},t)}GetUserJobList(e,t){const i=this.genBaseURL("/api/coze_space/get_user_job_list");return this.request({url:i,method:"GET"},t)}AdminParseTaskShareURL(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/parse_task_share_url"),s={share_url:i.share_url};return this.request({url:o,method:"POST",data:s},t)}GetAppInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_app_info");return this.request({url:i,method:"GET"},t)}AdminGetTaskExampleCategory(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/get_task_example_category"),s={ability_type:i.ability_type};return this.request({url:o,method:"GET",params:s},t)}AdminUploadFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/upload_task_file"),s={file_name:i.file_name,file_content:i.file_content,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}UpdateFileContent(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_file_content"),s={task_id:i.task_id,file_uri:i.file_uri,file_content:i.file_content};return this.request({url:o,method:"POST",data:s},t)}ExportPPTAgentFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/export_ppt_agent_file"),s={source_uri:i.source_uri,task_id:i.task_id,export_type:i.export_type};return this.request({url:o,method:"POST",data:s},t)}RestoreExampleFile(e,t){const i=e,o=this.genBaseURL("/api/coze_space/restore_example_file"),s={task_id:i.task_id,example_id:i.example_id,product:i.product};return this.request({url:o,method:"POST",data:s},t)}GetHtmlHeightFix(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_html_height_fix"),s={code:i.code};return this.request({url:o,method:"POST",data:s},t)}PollMessages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/poll_messages"),s={start_next_key:i.start_next_key};return this.request({url:o,method:"GET",params:s},t)}OperatePausedTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_paused_task"),s={task_id:i.task_id,pause_reason:i.pause_reason};return this.request({url:o,method:"POST",data:s},t)}GetFrontierKey(e,t){const i=this.genBaseURL("/api/coze_space/get_frontier_key");return this.request({url:i,method:"GET"},t)}SearchImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/search_image"),s={query:i.query,count:i.count};return this.request({url:o,method:"POST",data:s},t)}GetUserExpertList(e,t){const i=this.genBaseURL("/api/coze_space/get_user_expert_list");return this.request({url:i,method:"POST"},t)}OperateUserExpert(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/operate_user_expert"),s={agent_id:i.agent_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}GetHotQuery(e,t){const i=this.genBaseURL("/api/coze_space/get_hot_query");return this.request({url:i,method:"POST"},t)}ImageDownload(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/download_image"),s={image_infos:i.image_infos,download_type:i.download_type};return this.request({url:o,method:"POST",data:s},t)}ImageEdit(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/edit_image"),s={edit_type:i.edit_type,image_url:i.image_url,query:i.query,count:i.count,task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}CreateImageCopy(e,t){const i=e,o=this.genBaseURL("/api/coze_space/create_image_copy"),s={task_id:i.task_id,image_path:i.image_path,source_image_url:i.source_image_url};return this.request({url:o,method:"POST",data:s},t)}GetLatestImagesWithID(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_latest_images_with_id"),s={task_id:i.task_id,image_paths:i.image_paths};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTaskExampleCategory(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_task_example_category"),s={name:i.name,ability_type:i.ability_type,index:i.index,job_ids:i.job_ids,scene_ids:i.scene_ids};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteTaskExampleCategory(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_task_example_category"),s={category_id:i.category_id};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTaskExampleCategory(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_task_example_category"),s={category_id:i.category_id,name:i.name,index:i.index,job_ids:i.job_ids,scene_ids:i.scene_ids};return this.request({url:o,method:"POST",data:s},t)}BatchHtmlToImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_html_to_image"),s={task_id:i.task_id,html_uri:i.html_uri,device_info:i.device_info,screenshot_info:i.screenshot_info};return this.request({url:o,method:"POST",data:s},t)}GetAppTaskExampleList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_app_task_example_list"),s={ability_type:i.ability_type,need_official_recommended:i.need_official_recommended};return this.request({url:o,method:"POST",data:s},t)}GenCover(e,t){const i=e,o=this.genBaseURL("/api/coze_space/gen_cover"),s={task_id:i.task_id,original_file_uri:i.original_file_uri,resolution:i.resolution,mode:i.mode,selector_str:i.selector_str,task_share_url:i.task_share_url};return this.request({url:o,method:"POST",data:s},t)}CopyResource(e,t){const i=e,o=this.genBaseURL("/api/coze_space/copy_resource"),s={new_task_id:i.new_task_id,uri_list:i.uri_list};return this.request({url:o,method:"POST",data:s},t)}BatchUpdateImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_update_image"),s={task_id:i.task_id,image_info_list:i.image_info_list};return this.request({url:o,method:"POST",data:s},t)}Text2Json(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/text2json"),s={text:i.text,type:i.type};return this.request({url:o,method:"POST",data:s},t)}EditImageWithMsg(e,t){const i=e,o=this.genBaseURL("/api/coze_space/edit_image_with_msg"),s={task_id:i.task_id,source_image_info:i.source_image_info,edit_type:i.edit_type,query:i.query,edit_info:i.edit_info};return this.request({url:o,method:"POST",data:s},t)}GetASRToken(e,t){const i=this.genBaseURL("/api/coze_space/get_asr_token");return this.request({url:i,method:"GET"},t)}QueryRewriting(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/query_rewriting"),s={query:i.query};return this.request({url:o,method:"POST",data:s},t)}GetShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_shortcut_command"),s={ability_type:i.ability_type,need_general_data:i.need_general_data};return this.request({url:o,method:"POST",data:s},t)}ClickPopup(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/click_popup"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}GetPopupInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_popup_info"),s={ability_type:i.ability_type};return this.request({url:o,method:"POST",data:s},t)}AdminCreateExampleDatabaseData(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_example_database_data"),s={data:i.data};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_shortcut_command"),s={id:i.id,title:i.title,app_title:i.app_title,query:i.query,action_type:i.action_type,open_pc:i.open_pc,open_app:i.open_app,job_id:i.job_id,open_time:i.open_time,expire_time:i.expire_time};return this.request({url:o,method:"POST",data:s},t)}AdminCreateShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_shortcut_command"),s={ability_type:i.ability_type,title:i.title,app_title:i.app_title,query:i.query,action_type:i.action_type,open_pc:i.open_pc,open_app:i.open_app,job_id:i.job_id,expire_time:i.expire_time};return this.request({url:o,method:"POST",data:s},t)}AdminGetShortcutCommandList(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/get_shortcut_command_list"),s={size:i.size,ability_type:i.ability_type,page:i.page,open_pc:i.open_pc,open_app:i.open_app,job_id:i.job_id};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteShortcutCommand(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_shortcut_command"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}AdminSyncCrawl(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/sync_crawl"),s={req:i.req,upload:i.upload};return this.request({url:o,method:"POST",data:s},t)}AdminGetUserJobList(e,t){const i=this.genBaseURL("/api/coze_space/admin/get_user_job_list");return this.request({url:i,method:"GET"},t)}AdminListTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/list_template"),s={size:i.size,page:i.page,template_ids:i.template_ids,category_ids:i.category_ids,ability_type:i.ability_type,template_name:i.template_name};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_template"),s={ability_type:i.ability_type,category_id:i.category_id,web_template_conf:i.web_template_conf,template_labels:i.template_labels,original_query:i.original_query,query_template:i.query_template,template_words:i.template_words,open_app_use:i.open_app_use,app_template_conf:i.app_template_conf,template_files:i.template_files,reference_info:i.reference_info,api_template_type:i.api_template_type,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_template"),s={template_id:i.template_id,ability_type:i.ability_type,category_id:i.category_id,web_template_conf:i.web_template_conf,template_labels:i.template_labels,original_query:i.original_query,query_template:i.query_template,template_words:i.template_words,open_app_use:i.open_app_use,app_template_conf:i.app_template_conf,index:i.index,is_selected:i.is_selected,template_files:i.template_files,reference_info:i.reference_info,api_template_type:i.api_template_type,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_template"),s={template_id:i.template_id};return this.request({url:o,method:"POST",data:s},t)}GetTemplateList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_template_list"),s={category_id:i.category_id,page_size:i.page_size,page:i.page,ability_type:i.ability_type};return this.request({url:o,method:"POST",data:s},t)}GetAppTemplateList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_app_template_list"),s={ability_type:i.ability_type};return this.request({url:o,method:"POST",data:s},t)}GetTemplate(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_template_info"),s={template_id:i.template_id};return this.request({url:o,method:"POST",data:s},t)}GetActivityInfo(e,t){const i=this.genBaseURL("/api/coze_space/activity/info");return this.request({url:i,method:"GET"},t)}BindRelation(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/activity/bind"),s={code:i.code};return this.request({url:o,method:"POST",data:s},t)}GetInviteCode(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/activity/invite_code"),s={activity_id:i.activity_id};return this.request({url:o,method:"POST",data:s},t)}GetInviteRecords(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/activity/invite_records"),s={activity_id:i.activity_id};return this.request({url:o,method:"POST",data:s},t)}RollbackFileVersion(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/rollback_file_version"),s={task_id:i.task_id,file_name:i.file_name,target_version:i.target_version};return this.request({url:o,method:"POST",data:s},t)}GetFileVersionInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_file_version_info"),s={task_id:i.task_id,file_name:i.file_name,long_term_plan:i.long_term_plan};return this.request({url:o,method:"POST",data:s},t)}AdminMDelUri(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdel_uri"),s={uris:i.uris,urls:i.urls};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/delete_sem_url"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}AdminCreateSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/create_sem_url"),s={experiment_url:i.experiment_url,compare_url:i.compare_url,description:i.description};return this.request({url:o,method:"POST",data:s},t)}AdminListSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/list_sem_url"),s={size:i.size,page:i.page};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/admin/update_sem_url"),s={id:i.id,experiment_url:i.experiment_url,compare_url:i.compare_url,description:i.description};return this.request({url:o,method:"POST",data:s},t)}GetSEMUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/get_sem_url"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}ClickCompetitionLikes(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/click_competition_likes"),s={competition_task_id:i.competition_task_id,is_like:i.is_like};return this.request({url:o,method:"POST",data:s},t)}SubmitCompetitionTask(e,t){const i=e,o=this.genBaseURL("/api/coze_space/submit_competition_task"),s={task_id:i.task_id,product_url:i.product_url,title:i.title,cover_uri:i.cover_uri,competition_id:i.competition_id};return this.request({url:o,method:"POST",data:s},t)}GetCompetitionInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_competition_info");return this.request({url:i,method:"POST"},t)}GetCompetitionTaskList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_competition_task_list"),s={page_size:i.page_size,cursor:i.cursor,is_create_sorted:i.is_create_sorted,search_title:i.search_title,competition_id:i.competition_id};return this.request({url:o,method:"POST",data:s},t)}FavoriteList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/list"),s={tag_ids:i.tag_ids,name:i.name,need_untagged:i.need_untagged,size:i.size,cursor:i.cursor,exclude_content_types:i.exclude_content_types};return this.request({url:o,method:"POST",data:s},t)}DeleteTags(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/delete_tags"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}DeleteFavorites(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/delete"),s={ids:i.ids,related_uris:i.related_uris};return this.request({url:o,method:"POST",data:s},t)}BatchGetFavoriteInfo(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/batch_get_info"),s={favorite_ids:i.favorite_ids};return this.request({url:o,method:"POST",data:s},t)}UpdateFavoriteInfo(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/update"),s={id:i.id,tag_ids:i.tag_ids};return this.request({url:o,method:"POST",data:s},t)}GetTagList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/get_tag_list"),s={tag_ids:i.tag_ids,tag_name:i.tag_name};return this.request({url:o,method:"POST",data:s},t)}CreateTags(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/create_tag"),s={tag_name:i.tag_name,tag_desc:i.tag_desc,favorite_info_list:i.favorite_info_list};return this.request({url:o,method:"POST",data:s},t)}AddFavorite(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/add"),s={title:i.title,content_uri:i.content_uri,content_text:i.content_text,tag_ids:i.tag_ids,source:i.source,scene:i.scene,product_type:i.product_type};return this.request({url:o,method:"POST",data:s},t)}UpdateTags(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/update_tag"),s={tag_id:i.tag_id,tag_name:i.tag_name,tag_desc:i.tag_desc};return this.request({url:o,method:"POST",data:s},t)}GetMyCompetitionTaskList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_my_competition_task_list"),s={page_size:i.page_size,cursor:i.cursor,competition_id:i.competition_id};return this.request({url:o,method:"POST",data:s},t)}AdminGetUserScenes(e,t){const i=this.genBaseURL("/api/coze_space/admin/get_user_scenes");return this.request({url:i,method:"GET"},t)}GetUserScenes(e,t){const i=this.genBaseURL("/api/coze_space/get_user_scenes");return this.request({url:i,method:"GET"},t)}GetDeepWritingConf(e,t){const i=this.genBaseURL("/api/coze_space/get_deep_writing_conf");return this.request({url:i,method:"GET"},t)}GetCompetitionTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_competition_task"),s={competition_task_id:i.competition_task_id};return this.request({url:o,method:"POST",data:s},t)}GetUnreadCount(e,t){const i=this.genBaseURL("/api/coze_space/get_unread_count");return this.request({url:i,method:"POST"},t)}BatchHtmlCodeToImage(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_html_code_to_image"),s={task_id:i.task_id,html_code:i.html_code,device_info:i.device_info,screenshot_info:i.screenshot_info,zip:i.zip};return this.request({url:o,method:"POST",data:s},t)}GenDocMultiImageMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/gen_doc_multi_image_material"),s={task_id:i.task_id,file_uri:i.file_uri};return this.request({url:o,method:"POST",data:s},t)}GetDerivedProduct(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_derived_product"),s={task_id:i.task_id,derived_product_type:i.derived_product_type};return this.request({url:o,method:"POST",data:s},t)}SaveDerivedProduct(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/save_derived_product"),s={task_id:i.task_id,derived_product:i.derived_product};return this.request({url:o,method:"POST",data:s},t)}TagFavorites(e,t){const i=e,o=this.genBaseURL("/api/coze_space/favorites/tag_favorites"),s={tag_name:i.tag_name,tag_desc:i.tag_desc};return this.request({url:o,method:"POST",data:s},t)}SuggestQuery(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/suggest_query"),s={query:i.query,image_urls:i.image_urls};return this.request({url:o,method:"POST",data:s},t)}BatchGetUrl(e,t){const i=e,o=this.genBaseURL("/api/coze_space/batch_get_url"),s={uri_list:i.uri_list,expire_seconds:i.expire_seconds,is_short_url:i.is_short_url};return this.request({url:o,method:"POST",data:s},t)}UploadFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/upload_file"),s={file_name:i.file_name,file_content:i.file_content,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}BatchGetFavorite(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/favorites/get_count"),s={file_uris:i.file_uris};return this.request({url:o,method:"POST",data:s},t)}GetEarliestQuery(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_earliest_query"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}GetMappingUri(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_mapping_uri"),s={uri:i.uri};return this.request({url:o,method:"POST",data:s},t)}ApiTemplate(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/api_template"),s={prompt:i.prompt,files:i.files,type:i.type,task_id:i.task_id,template_id:i.template_id};return this.request({url:o,method:"POST",data:s},t)}BatchGetMultiMedia(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/batch_get_multimedia"),s={media_uris:i.media_uris};return this.request({url:o,method:"POST",data:s},t)}AdminBatchGetMultiMedia(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/batch_get_multimedia"),s={media_uris:i.media_uris};return this.request({url:o,method:"POST",data:s},t)}AdminCreateMultiMedia(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_multimedia"),s={task_id:i.task_id,media_path:i.media_path,media_uri:i.media_uri,media_url:i.media_url,image_type:i.image_type,media_ext:i.media_ext};return this.request({url:o,method:"POST",data:s},t)}GetPodcastConfig(e,t){const i=this.genBaseURL("/api/coze_space/get_podcast_config");return this.request({url:i,method:"POST"},t)}IntentRecognition(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/intent_recognition"),s={task_id:i.task_id,files:i.files,ability_type:i.ability_type,query:i.query};return this.request({url:o,method:"POST",data:s},t)}ListTemplate(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/list_template"),s={size:i.size,cursor:i.cursor,tags:i.tags,ability_type:i.ability_type,api_template_type:i.api_template_type};return this.request({url:o,method:"POST",data:s},t)}AdminGetTagsByImages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/get_tags_by_images"),s={images:i.images,query:i.query,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}GetTagsByImages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_tags_by_images"),s={images:i.images,query:i.query,scene:i.scene};return this.request({url:o,method:"POST",data:s},t)}AdminCreateTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_template_image"),s={image:i.image,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}ReportSubmit(e,t){const i=e,o=this.genBaseURL("/api/coze_space/report_submit"),s={object_type:i.object_type,object_id:i.object_id,report_detail:i.report_detail};return this.request({url:o,method:"POST",data:s},t)}ListBotChatMessages(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/list_bot_chat_message"),s={bot_chat_type:i.bot_chat_type,cursor:i.cursor,size:i.size};return this.request({url:o,method:"POST",data:s},t)}BotChatWithType(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/bot_chat_with_type"),s={bot_chat_type:i.bot_chat_type,query:i.query};return this.request({url:o,method:"POST",data:s},t)}GenImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/gen_image"),s={task_id:i.task_id,project_id:i.project_id,prompt:i.prompt,count:i.count,video_project_uri:i.video_project_uri,image_url:i.image_url,base_image_urls:i.base_image_urls,skip_save_material:i.skip_save_material};return this.request({url:o,method:"POST",data:s},t)}UploadVideoResource(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/upload_video_resource"),s={task_id:i.task_id,project_id:i.project_id,file_name:i.file_name,file_content:i.file_content,video_project_uri:i.video_project_uri,skip_save_material:i.skip_save_material};return this.request({url:o,method:"POST",data:s},t)}GetVideoConfig(e,t){const i=this.genBaseURL("/api/coze_space/video/get_video_config");return this.request({url:i,method:"POST"},t)}GetCozeSpaceDeviceInfo(e,t){const i=this.genBaseURL("/api/coze_space/get_device_info");return this.request({url:i,method:"POST"},t)}AdminMDeleteReferenceImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdelete_reference_image"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}AdminMDeleteTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdelete_template_image"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}AdminListReferenceImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_reference_image"),s={size:i.size,cursor:i.cursor,tag:i.tag};return this.request({url:o,method:"POST",data:s},t)}AdminListRewriteImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_rewrite_image"),s={size:i.size,cursor:i.cursor,tag:i.tag};return this.request({url:o,method:"POST",data:s},t)}AdminCreateReferenceImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/create_reference_image"),s={tag:i.tag,image:i.image};return this.request({url:o,method:"POST",data:s},t)}AdminTemplateRewrite(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/template_rewrite"),s={template_image_ids:i.template_image_ids,rewrite_image_id:i.rewrite_image_id};return this.request({url:o,method:"POST",data:s},t)}AdminMDeleteRewriteImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/mdelete_rewrite_image"),s={ids:i.ids};return this.request({url:o,method:"POST",data:s},t)}AdminListTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_template_image"),s={size:i.size,cursor:i.cursor,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateRewriteImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/update_rewrite_image"),s={id:i.id,rewrite_result:i.rewrite_result};return this.request({url:o,method:"POST",data:s},t)}GetGuidingMessage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_guiding_message"),s={guiding_id:i.guiding_id};return this.request({url:o,method:"POST",data:s},t)}AdminListImageTag(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_image_tag"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}UpdateProject(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/update_project"),s={GroupId:i.GroupId,ProjectId:i.ProjectId,LatestEditParam:i.LatestEditParam,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri};return this.request({url:o,method:"POST",data:s},t)}DescribeProject(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/describe_project"),s={GroupId:i.GroupId,ProjectId:i.ProjectId,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri};return this.request({url:o,method:"POST",data:s},t)}SubmitEditTaskAsync(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/submit_edit_task_async"),s={GroupId:i.GroupId,ProjectId:i.ProjectId,ProjectType:i.ProjectType,EditParam:i.EditParam,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri};return this.request({url:o,method:"POST",data:s},t)}BatchGetVideoPlayInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/batch_get_video_play_info"),s={vids:i.vids,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri};return this.request({url:o,method:"POST",data:s},t)}GetDirectEditProgress(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/get_direct_edit_progress"),s={ReqId:i.ReqId,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri};return this.request({url:o,method:"POST",data:s},t)}SearchEditMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/search_edit_material"),s={ProjectId:i.ProjectId,EditMids:i.EditMids,Space:i.Space,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri};return this.request({url:o,method:"POST",data:s},t)}ListSnapshots(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video_volc_proxy/list_snapshots"),s={ProjectId:i.ProjectId,Vid:i.Vid,coze_space_task_id:i.coze_space_task_id,coze_space_video_project_uri:i.coze_space_video_project_uri};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTemplateImage(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/update_reference_image"),s={id:i.id,tags:i.tags};return this.request({url:o,method:"POST",data:s},t)}VolcVodCallback(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/volc_vod_callback"),s={RequestId:i.RequestId,Version:i.Version,EventType:i.EventType,EventTime:i.EventTime};return this.request({url:o,method:"POST",data:s},t)}AdminDeleteVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/delete_video_text_style"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}AdminListVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/list_video_text_style"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}AdminSaveVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/save_video_text_style"),s={video_text_style:i.video_text_style};return this.request({url:o,method:"POST",data:s},t)}GetMusicList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/get_music_list"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}ListVideoTextStyle(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/list_video_text_style"),s={size:i.size,cursor:i.cursor};return this.request({url:o,method:"POST",data:s},t)}GetMessageMeta(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_message_meta"),s={task_id:i.task_id};return this.request({url:o,method:"GET",params:s},t)}AdminRunWorkflow(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/run_workflow"),s={id:i.id,input:i.input};return this.request({url:o,method:"POST",data:s},t)}QueryGenResourceStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/query_gen_resource_status"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,gen_resource_task_id:i.gen_resource_task_id};return this.request({url:o,method:"POST",data:s},t)}GenResourceAsync(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/gen_resource_async"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,gen_resource_type:i.gen_resource_type,gen_video_req_payload:i.gen_video_req_payload,gen_voice_audio_req_payload:i.gen_voice_audio_req_payload,gen_music_req_payload:i.gen_music_req_payload,skip_save_material:i.skip_save_material};return this.request({url:o,method:"POST",data:s},t)}GetTaskItemList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/get_task_item_list"),s={task_id:i.task_id,item_ids:i.item_ids,start_time:i.start_time,end_time:i.end_time};return this.request({url:o,method:"POST",data:s},t)}CancelGenResourceTask(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/cancel_gen_resource_task"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri,gen_resource_task_id:i.gen_resource_task_id};return this.request({url:o,method:"POST",data:s},t)}AdminUpdateTemplateTagsFromCSV(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/update_template_tags_from_csv"),s={is_run_wf:i.is_run_wf,is_update:i.is_update,tos_path:i.tos_path};return this.request({url:o,method:"POST",data:s},t)}GetPlanTemplates(e,t){const i=this.genBaseURL("/api/coze_space/get_plan_templates");return this.request({url:i,method:"POST"},t)}DeleteTaskFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/delete_task_file"),s={id:i.id};return this.request({url:o,method:"POST",data:s},t)}ListTaskFile(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/list_task_file"),s={task_id:i.task_id,size:i.size,cursor:i.cursor,plan_file:i.plan_file};return this.request({url:o,method:"POST",data:s},t)}GenPodcastStream(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/gen_podcast"),s={cache_key:i.cache_key};return this.request({url:o,method:"POST",data:s},t)}AdminTemplateTypeIntentBG(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/admin/template_type_intent_bg"),s={files:i.files};return this.request({url:o,method:"POST",data:s},t)}ExportImagePPT(e,t){const i=e,o=this.genBaseURL("/api/coze_space/export_image_ppt_agent_file"),s={task_id:i.task_id,title:i.title,pages:i.pages,export_type:i.export_type};return this.request({url:o,method:"POST",data:s},t)}ExportProject(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/export_project"),s={task_id:i.task_id,project_id:i.project_id,video_project_uri:i.video_project_uri};return this.request({url:o,method:"POST",data:s},t)}GetModelConfig(e,t){const i=this.genBaseURL("/api/coze_space/get_model_config");return this.request({url:i,method:"POST"},t)}ConfirmPlan(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/confirm_plan"),s={task_id:i.task_id};return this.request({url:o,method:"POST",data:s},t)}GetUserSkillAuthorizationInfo(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/skill/get_user_skill_authorization_info"),s={credential_id:i.credential_id};return this.request({url:o,method:"POST",data:s},t)}UpdateCozeUserNickname(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/update_user_nickname"),s={nickname:i.nickname};return this.request({url:o,method:"POST",data:s},t)}CreateCozeUserJobName(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/create_user_job_name"),s={job_name:i.job_name};return this.request({url:o,method:"POST",data:s},t)}EnterpriseCustomer(e,t){const i=this.genBaseURL("/api/coze_space/enterprise_customer");return this.request({url:i,method:"POST"},t)}CreateVideoAsset(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/create_video_asset"),s={base_info:i.base_info,details:i.details};return this.request({url:o,method:"POST",data:s},t)}UpdateVideoAsset(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/update_video_asset"),s={asset_id:i.asset_id,base_info:i.base_info,details:i.details};return this.request({url:o,method:"POST",data:s},t)}DeleteVideoAsset(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/asset/delete_video_asset"),s={asset_id:i.asset_id};return this.request({url:o,method:"POST",data:s},t)}UpdateVideoProduction(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/production/update_video_production"),s={video_production:i.video_production};return this.request({url:o,method:"POST",data:s},t)}CreateVideoProduction(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/production/create_video_production"),s={video_production:i.video_production,ratio:i.ratio};return this.request({url:o,method:"POST",data:s},t)}VideoProductionMaterialList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/video_material_list"),s={production_id:i.production_id,tag_category:i.tag_category,type_category:i.type_category,page:i.page,size:i.size,need_detail_url:i.need_detail_url};return this.request({url:o,method:"POST",data:s},t)}VideoAssetDetail(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/video_asset_detail"),s={asset_id:i.asset_id};return this.request({url:o,method:"POST",data:s},t)}VideoProductionMaterialDetail(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/video_material_detail"),s={material_id:i.material_id};return this.request({url:o,method:"POST",data:s},t)}DeleteVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/delete_video_material"),s={material_id:i.material_id};return this.request({url:o,method:"POST",data:s},t)}CreateVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/create_video_material"),s={production_id:i.production_id,base_info:i.base_info,details:i.details,asset_id:i.asset_id};return this.request({url:o,method:"POST",data:s},t)}UpdateVideoProductionMaterial(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/material/update_video_material"),s={material_id:i.material_id,material_update_type:i.material_update_type,base_info:i.base_info,details:i.details};return this.request({url:o,method:"POST",data:s},t)}DeleteVideoProduction(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/production/delete_video_production"),s={production_id:i.production_id};return this.request({url:o,method:"POST",data:s},t)}VideoAssetList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/asset/video_asset_list"),s={tag_category:i.tag_category,type_category:i.type_category,page:i.page,size:i.size,search_word:i.search_word,need_detail_url:i.need_detail_url};return this.request({url:o,method:"POST",data:s},t)}VideoProductionList(e,t){const i=e||{},o=this.genBaseURL("/api/coze_space/video/production/video_production_list"),s={page:i.page,size:i.size};return this.request({url:o,method:"POST",data:s},t)}OperateVideoProduction(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/production/operate_video_production"),s={production_id:i.production_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}OperateVideoAsset(e,t){const i=e,o=this.genBaseURL("/api/coze_space/video/asset/operate_video_asset"),s={asset_id:i.asset_id,operate_type:i.operate_type};return this.request({url:o,method:"POST",data:s},t)}}const _l=new ul({});var ml,gl,hl,fl,yl,bl,vl,Cl,Sl,Pl,El,Tl,Al,kl,wl,Rl,zl,Il,Ol,Ll,jl,Ul,Bl,xl,ql,Dl,Ml,Gl,Nl,Fl;function $l(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}!function(e){e[e.Image=1]="Image";e[e.Android=2]="Android";e[e.IOS=3]="IOS";e[e.GitCode=4]="GitCode";e[e.FaasRuntimePkg=5]="FaasRuntimePkg";e[e.SkillPkg=6]="SkillPkg";e[e.H5=7]="H5"}(ml||(ml={})),function(e){e[e.Unknown=0]="Unknown";e[e.FreeCertificate=1]="FreeCertificate"}(gl||(gl={})),function(e){e[e.Unknown=0]="Unknown";e[e.Normal=1]="Normal"}(hl||(hl={})),function(e){e[e.Unknown=0]="Unknown";e[e.Existing=1]="Existing";e[e.Free=2]="Free"}(fl||(fl={})),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"}(yl||(yl={})),function(e){e[e.Passed=1]="Passed";e[e.UnPassed=2]="UnPassed";e[e.Auditing=3]="Auditing"}(bl||(bl={})),function(e){e[e.Official=1]="Official"}(vl||(vl={})),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"}(Cl||(Cl={})),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"}(Sl||(Sl={})),function(e){e[e.Unknown=0]="Unknown";e[e.Success=1]="Success";e[e.Pending=2]="Pending";e[e.Failed=3]="Failed"}(Pl||(Pl={})),function(e){e[e.Unknown=0]="Unknown";e[e.Default=1]="Default";e[e.Custom=2]="Custom"}(El||(El={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(Tl||(Tl={})),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"}(Al||(Al={})),function(e){e[e.Created=1]="Created";e[e.Ready=3]="Ready";e[e.Stopped=4]="Stopped";e[e.Banned=5]="Banned"}(kl||(kl={})),function(e){e[e.Unknown=0]="Unknown";e[e.VefaasFunction=1]="VefaasFunction"}(wl||(wl={})),function(e){e[e.Unknown=0]="Unknown";e[e.Dev=1]="Dev";e[e.Prod=2]="Prod";e[e.Audit=3]="Audit"}(Rl||(Rl={})),function(e){e[e.A=1]="A";e[e.CNAME=2]="CNAME"}(zl||(zl={})),function(e){e[e.Unknown=0]="Unknown";e[e.Single=1]="Single";e[e.Wildcard=2]="Wildcard";e[e.Multi=3]="Multi"}(Il||(Il={})),function(e){e[e.Unknown=0]="Unknown";e[e.DV=1]="DV";e[e.OV=2]="OV";e[e.EV=3]="EV"}(Ol||(Ol={})),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"}(Ll||(Ll={})),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"}(jl||(jl={})),function(e){e[e.NeedAuthorize=1]="NeedAuthorize";e[e.BindSuccess=2]="BindSuccess";e[e.BoundToOtherProject=3]="BoundToOtherProject";e[e.BoundToOtherUser=4]="BoundToOtherUser"}(Ul||(Ul={})),function(e){e[e.BoundToSelf=1]="BoundToSelf";e[e.BoundToOtherUser=2]="BoundToOtherUser";e[e.NotAuthorized=3]="NotAuthorized"}(Bl||(Bl={})),function(e){e[e.Line=1]="Line"}(xl||(xl={})),function(e){e[e.Default=0]="Default";e[e.WechatMini=1]="WechatMini";e[e.DouyinMini=2]="DouyinMini"}(ql||(ql={})),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"}(Dl||(Dl={})),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"}(Ml||(Ml={})),function(e){e[e.Recorded=1]="Recorded"}(Gl||(Gl={})),function(e){e[e.Sum=1]="Sum";e[e.Avg=2]="Avg"}(Nl||(Nl={})),function(e){e[e.Next=1]="Next";e[e.Third=3]="Third";e[e.Seventh=7]="Seventh"}(Fl||(Fl={}));class Vl{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Vl.prototype.__init.call(this),Vl.prototype.__init2.call(this),this.request=$l([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=$l([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}PublicCreateDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/create"),s={project_id:i.project_id,is_sync_db_to_prod:i.is_sync_db_to_prod,encrypt_env_variable:i.encrypt_env_variable,table_sync_configs:i.table_sync_configs,encrypt_deploy:i.encrypt_deploy,commit_hash:i.commit_hash,connector_configs:i.connector_configs};return this.request({url:o,method:"POST",data:s},t)}PublicRollbackDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/rollback"),s={project_id:i.project_id,target_deploy_history_id:i.target_deploy_history_id,rollback_database:i.rollback_database};return this.request({url:o,method:"POST",data:s},t)}PublicCancelDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/cancel"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"POST",data:s},t)}PublicGetDeployConfig(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_config/get"),s={project_id:i.project_id,commit_hash:i.commit_hash};return this.request({url:o,method:"GET",params:s},t)}PublicListDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/list"),s={project_id:i.project_id,page_token:i.page_token,page_size:i.page_size};return this.request({url:o,method:"GET",params:s},t)}PublicSearchRuntimeLog(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/runtime_log/search"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id,start_time:i.start_time,end_time:i.end_time,limit:i.limit,cursor:i.cursor,query:i.query,level:i.level};return this.request({url:o,method:"GET",params:s},t)}PublicGetDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/get"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"GET",params:s},t)}PublicBindCertificate(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/bind"),s={project_id:i.project_id,certificate_id:i.certificate_id,domain:i.domain};return this.request({url:o,method:"POST",data:s},t)}PublicApplyFreeCertificate(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/apply_free"),s={project_id:i.project_id,domain:i.domain,auto_renew_free_cert:i.auto_renew_free_cert};return this.request({url:o,method:"POST",data:s},t)}PublicListDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/list"),s={project_id:i.project_id,unit_type:i.unit_type};return this.request({url:o,method:"GET",params:s},t)}PublicDeleteDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/delete"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"POST",data:s},t)}PublicCreateDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/create"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"POST",data:s},t)}PublicGetDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/get"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetCertificateDetail(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/get"),s={project_id:i.project_id,certificate_id:i.certificate_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/get"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"GET",params:s},t)}PublicListVolcanoDomain(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/volcano_domain/list"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicListVolcanoCertificate(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/list_volcano"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"GET",params:s},t)}PublicListProjectTraces(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/traces/list"),s={project_id:i.project_id,start_time:i.start_time,end_time:i.end_time,filter:i.filter,page_token:i.page_token,page_size:i.page_size};return this.request({url:o,method:"POST",data:s},t)}PublicDownloadProjectTraces(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/traces/download"),s={project_id:i.project_id,start_time:i.start_time,end_time:i.end_time,filter:i.filter};return this.request({url:o,method:"POST",data:s},t)}PublicGetProjectMetrics(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/metrics/get"),s={project_id:i.project_id,time_range:i.time_range,retention_days:i.retention_days};return this.request({url:o,method:"GET",params:s},t)}PublicDeleteDeployUnit(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_unit/delete"),s={project_id:i.project_id,deploy_unit_id:i.deploy_unit_id};return this.request({url:o,method:"POST",data:s},t)}PublicGetHelpCenterLink(e,t){const i=this.genBaseURL("/api/coding/deployment/help_center/link");return this.request({url:i,method:"GET"},t)}PublicCheckRollbackDatabase(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/check_rollback_database"),s={project_id:i.project_id,deploy_history_id:i.deploy_history_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetMiniProgramPreview(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/mini_program/preview"),s={project_id:i.project_id,app_id:i.app_id,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}PublicSubmitAuthCode(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/submit_code"),s={project_id:i.project_id,connector_id:i.connector_id,code:i.code,verify_state:i.verify_state,auth_params:i.auth_params};return this.request({url:o,method:"POST",data:s},t)}PublicGetAuthStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/status"),s={project_id:i.project_id,connector_id:i.connector_id,redirect_url:i.redirect_url};return this.request({url:o,method:"POST",data:s},t)}PublicBindAuth(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/bind"),s={project_id:i.project_id,connector_id:i.connector_id,redirect_url:i.redirect_url,auth_params:i.auth_params,override:i.override};return this.request({url:o,method:"POST",data:s},t)}PublicUnbindAuth(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/auth/unbind"),s={project_id:i.project_id,connector_id:i.connector_id};return this.request({url:o,method:"POST",data:s},t)}PublicGetBoundProject(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/get_bound_project"),s={connector_id:i.connector_id,related_id:i.related_id};return this.request({url:o,method:"GET",params:s},t)}PublicUpdateDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/update"),s={project_id:i.project_id,domain:i.domain,auto_renew_free_cert:i.auto_renew_free_cert};return this.request({url:o,method:"POST",data:s},t)}PublicGetCertificateQuota(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/quota"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicListDomainCertificates(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/certificate/list"),s={project_id:i.project_id,domain:i.domain};return this.request({url:o,method:"GET",params:s},t)}PublicUnpublishConnector(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/unpublish_project"),s={project_id:i.project_id,connector_ids:i.connector_ids};return this.request({url:o,method:"POST",data:s},t)}PublicListConnector(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/list"),s={project_id:i.project_id,project_publish_status:i.project_publish_status};return this.request({url:o,method:"GET",params:s},t)}PublicPublishConnector(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/connector/publish_project"),s={project_id:i.project_id,connector_configs:i.connector_configs};return this.request({url:o,method:"POST",data:s},t)}PublicGetDeployCount(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/get_count"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}GetRuntimeLogCount(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/runtime_log/count"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicExchangeFeishuAuthCode(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/feishu/auth/exchange_code"),s={project_id:i.project_id,code:i.code,verify_state:i.verify_state};return this.request({url:o,method:"POST",data:s},t)}PublicRevokeFeishuAuth(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/feishu/auth/revoke"),s={project_id:i.project_id};return this.request({url:o,method:"POST",data:s},t)}PublicUpdateDefaultDomainPrefix(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/update_default_prefix"),s={project_id:i.project_id,prefix:i.prefix};return this.request({url:o,method:"POST",data:s},t)}PublicFeishuWebhookEvent(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/feishu/webhook/event"),s={body:i.body};return this.request({url:o,method:"POST",data:s},t)}PublicCheckCreateDomainRelated(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/domain_related/check_create"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetHostedUsageMonthly(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/hosted_usage/monthly"),s={project_id:i.project_id,bill_month:i.bill_month};return this.request({url:o,method:"GET",params:s},t)}PublicGetEstimateHostedCost(e,t){const i=this.genBaseURL("/api/coding/deployment/hosted_usage/estimate_cost");return this.request({url:i,method:"GET"},t)}PublicGetDeployHistoryLog(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/log"),s={deploy_history_id:i.deploy_history_id,key:i.key};return this.request({url:o,method:"GET",params:s},t)}PublicGetMPICPStatus(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/mini_program/icp_status"),s={project_id:i.project_id,app_id:i.app_id,connector_id:i.connector_id};return this.request({url:o,method:"GET",params:s},t)}PublicGetOnlineDeployHistory(e,t){const i=e||{},o=this.genBaseURL("/api/coding/deployment/deploy_history/get_online"),s={project_id:i.project_id};return this.request({url:o,method:"GET",params:s},t)}}const Wl=new Vl({}),Hl={[Sl.Pending]:"Pending",[Sl.Running]:"Running",[Sl.Succeeded]:"Succeeded",[Sl.Failed]:"Failed",[Sl.Canceled]:"Canceled",[Sl.Interrupted]:"Interrupted"},Kl=[Sl.Succeeded,Sl.Failed,Sl.Canceled],Jl=e=>e&&Hl[e]||"Unknown";function Ql(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}class Zl{static __initStatic(){this.INSTANCE=new Zl}static getInstance(){return Zl.INSTANCE||(Zl.INSTANCE=new Zl),this.INSTANCE}async pollDeployStatus(t){const{projectId:i,deployHistoryId:o,onBeforePoll:s,onStatusChange:n}=t;let a;for(;;){Ql([s,"optionalCall",e=>e()]);const t=Ql([await Wl.PublicGetDeployHistory({project_id:i,deploy_history_id:o}),"optionalAccess",e=>e.data]);if(!t)throw new e.CozeError(e.ErrorCode.E5000,"Failed to get deploy history data during polling");const r=t.status;if(r!==a&&(a=r,Ql([n,"optionalCall",e=>e(t)])),Kl.includes(r))return t;await new Promise(e=>setTimeout(e,3e3))}}async getLatestDeployHistoryId(e){const{projectId:t}=e;return Ql([await Wl.PublicListDeployHistory({page_size:1,project_id:t}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list,"optionalAccess",e=>e[0],"optionalAccess",e=>e.deploy_history_id])}async getDeployHistory(t){const{projectId:i,deployHistoryId:o}=t,s=await Wl.PublicGetDeployHistory({project_id:i,deploy_history_id:o});if(!Ql([s,"optionalAccess",e=>e.data]))throw new e.CozeError(e.ErrorCode.E5000,"Failed to get deploy history data");return s.data}canDeploy(t){return[e.VibeProjectType.AssistantAgent,e.VibeProjectType.GeneralWeb,e.VibeProjectType.App,e.VibeProjectType.Skill,e.VibeProjectType.Agent,e.VibeProjectType.Automation].includes(t)}async getCommitList({projectId:t}){const i=await e.IdeApi.ProxySandboxMessage({ProjectID:t,Method:"repo_version.commit.list",Params:JSON.stringify({project_id:t})});return e.safeJsonParse(i.data,{commits:[]}).commits||[]}}Zl.__initStatic();const Yl=Zl.getInstance();function Xl(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function eu(e,t){return null!=e?e:t()}function tu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function iu(e,t){return null!=e?e:t()}function ou(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const su=e=>{if(null==e)return null;return 0===e.trim().length?null:e},nu=t=>{t.command("send [message]").description("Send a prompt message to Coze Coding project chat").option("--wait","Wait for the chat response before returning").option("--stdin","Read additional context from stdin (pipe input)").config({help:{brief:"Send a message to project chat",description:"Send a prompt message to the specified Coze Coding project chat. The message can be provided as a positional argument. Use --stdin to pipe additional context. Use @<path> to mention and upload local files as context.",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug in auth module" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Send and wait for the response",cmd:'coze code message send "Fix the bug in auth module" -p 123456 --wait'},{desc:"Mention a file with @",cmd:'coze code message send "Refactor @src/utils.ts to use async/await" -p 123456'},{desc:"Mention multiple files",cmd:'coze code message send "Compare @src/old.ts and @src/new.ts, list the differences" -p 123456'},{desc:"Send message with stdin context",cmd:'cat error.log | coze code message send "Analyze this error" --stdin -p 123456'},{desc:"Use environment variable for project",cmd:'export COZE_PROJECT_ID=123456 && coze code message send "Hello"'}],errors:[{code:e.ErrorCode.E1000,name:"MISSING_MESSAGE",desc:"No message content provided",fix:"Provide MESSAGE argument or use --stdin with piped content",example:'coze code message send "Your question" -p 123456 # or: echo "context" | coze code message send --stdin "question" -p 123456'},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{message:{type:"string",required:!1,description:"The prompt message to send to the project chat"},wait:{type:"boolean",required:!1,description:"Wait for the chat response before returning. Without this flag, the message is sent in the background."},stdin:{type:"boolean",required:!1,description:"Read additional context from stdin (pipe input)."}},output:{type:"object",properties:{content:{type:"string",description:"The chat response content"}}}}}}).action(async(t,i,o)=>{const s=o.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=ou([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),a=iu(ou([n,"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 r=await ou([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!r)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const{wait:c,stdin:d}=i;let p=null;d&&(p=await fa());const l=su(t),u=su(p);if(!l&&!u)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin");const _=l&&u?`${l}\n\n${u}`:iu(iu(l,()=>u),()=>""),m=new Set,g=await e.sendProjectChatMessage({projectId:a,prompt:_,apiBaseUrl:s.config.apiBaseUrl,accessToken:r,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${a}`,onWarn:e=>s.ui.warn(e),waitForResponse:!!c,onMessageItem:e=>{if(c&&"json"===s.format&&e.finish){const t=(e=>{const t=iu(e.msg_id,()=>""),i=iu(e.sequence_id,()=>"");return`${e.type}:${t}:${String(i)}`})(e);m.has(t)||(m.add(t),s.response.print({content:e.content,role:e.role,finish:e.finish,type:e.type}))}}});if(c)"text"===s.format&&s.response.print(iu(ou([g,"access",e=>e.lastAnswerMessage,"optionalAccess",e=>e.content,"access",e=>e.answer]),()=>""));else{const e=`Message sent. Use \`coze code message status -p ${a}\` to check the result.`;"json"===s.format?s.response.print({status:"sent",project_id:a,message:e}):s.response.print(e),process.exit(0)}}catch(e){K(e,s)}})};function au(e,t){return null!=e?e:t()}function ru(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function cu(e,t){return null!=e?e:t()}function du(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const pu=async(t,i)=>{const o=i.getContext();try{if(!o)throw new e.CozeError("E5000","CLI context is not initialized");const s=du([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),n=cu(du([s,"optionalAccess",e=>e.projectId]),()=>process.env.COZE_PROJECT_ID);if(!n)throw new e.CozeError("E1001","Missing required option: --project-id (or env COZE_PROJECT_ID)");if(!await du([o,"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(t.after&&t.before)throw new e.CozeError("E1000","--after and --before cannot be used together. Use only one cursor at a time.");o.ui.verbose(`Fetching conversation history for project ${n}...`);const a=e.createChatCore({key:`coze-coding-cli:history:${n}`,apiBaseUrl:o.config.apiBaseUrl});try{const e=t.after?"loadNext":"loadPrev",i="loadNext"===e?"11":"10",s=await a.getHistoryMessage({limit:i,project_id:n,after:t.after,before:t.before}),r=[],c=new Map,d=new Map;s.histories.forEach(e=>{if(e.user){const t=e.user.msg_id;c.has(t)||r.push(t);const i=(e=>{const t=du([e,"optionalAccess",e=>e.content]);return cu(cu(du([t,"optionalAccess",e=>e.query,"optionalAccess",e=>e.prompt]),()=>du([t,"optionalAccess",e=>e.retry,"optionalAccess",e=>e.prompt])),()=>du([t,"optionalAccess",e=>e.edit,"optionalAccess",e=>e.prompt]))})(e.user.message);c.set(t,i?(e=>e.map(e=>"text"===e.type?e.content.text:"file"===e.type?`${ru([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.path])} ${au(ru([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.from,"optionalAccess",e=>e[0]]),()=>"")} ${au(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(" "))(i):"")}if(e.assistant){const t=e.assistant.messages.find(e=>"answer"===e.type&&e.content.answer);if(!t)return;const i=t.query_msg_id,o=t.content.answer;"string"==typeof i&&"string"==typeof o&&d.set(i,o)}});const p=r[0],l=r[r.length-1],u=r.reverse().filter(e=>d.has(e)).map(e=>({userMessage:cu(c.get(e),()=>""),answer:cu(d.get(e),()=>"")})),_={histories:u,cursor:{after:p,before:l,has_more:s.has_more,loadDirection:e}};if("json"===o.format)o.response.print(_);else{if(0===u.length)return void o.response.print("No conversation history found.");u.forEach((e,t)=>{o.response.print(`--- #${t+1} ---\nQ: ${e.userMessage}\nA: ${e.answer}\n`)}),o.response.print(`\n[cursor] after=${p}, before=${l}, has_more=${s.has_more}, loadDirection=${e}`)}}finally{a.destroy()}}catch(e){K(e,o)}};function lu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const uu=t=>{const i=t.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 --oauth"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID (can also be set via COZE_PROJECT_ID env)"}}},seeAlso:["coze code project list","coze code project create"]}}).option("-p, --project-id <id>","Coze project id (or env COZE_PROJECT_ID)"),nu(i),(t=>{t.command("status").description("Query current project chat message status and get result when completed").config({help:{brief:"Query chat message status",description:"Get the current status of the chat message for the specified project. Returns status information such as running, completed, or error. When the chat is completed, automatically fetches and returns the result.",examples:[{desc:"Check message status (auto-fetch result when completed)",cmd:"coze code message status -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message status"},{desc:"Output as JSON",cmd:"coze code message status -p 123456 --format json"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Message status (running/completed/error)"},message:{type:"string",description:"Status message or error details"},answer:{type:"string",description:"The chat answer content (only when completed)"}}}}}}).action(async(t,i)=>{const o=i.getContext();try{if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const t=tu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),s=eu(tu([t,"optionalAccess",e=>e.projectId]),()=>process.env.COZE_PROJECT_ID);if(!s)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");o.ui.verbose(`Fetching chat status for project ${s}...`);const{code:n,msg:a,reply_id:r,...c}=await e.BuildAgentApi.GetChatCLIMessageStatus({project_id:s});if("done"===c.status){o.ui.verbose(`Chat completed, fetching result for project ${s}...`);const t=await e.BuildAgentApi.GetChatCLIMessageResultContent({project_id:s}),i="data"in t?t.data:t;"json"===o.format?o.response.print({...c,answer:i.answer}):o.response.print(`status: [${c.status}]\nanswer: ${eu(i.answer,()=>"")}`)}else"json"===o.format?o.response.print(c):o.response.print(c.status)}catch(e){K(e,o)}})})(i),function(t){t.command("cancel").description("Cancel current project chat message").config({help:{brief:"Cancel ongoing chat message",description:"Cancel the currently running chat message for the specified project. Useful for stopping long-running or stuck message generation.",examples:[{desc:"Cancel current message",cmd:"coze code message cancel -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message cancel"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Cancel operation status"},message:{type:"string",description:"Result message"}}}}}}).action(async(t,i)=>{const o=i.getContext();try{if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const t=lu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),n=null!=(s=lu([t,"optionalAccess",e=>e.projectId]))?s:(()=>process.env.COZE_PROJECT_ID)();if(!n)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");const{accessToken:a}=o.config;if(!a)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");o.ui.verbose(`Canceling chat message for project ${n}...`);const{message:r}=await e.BuildAgentApi.CancelChatCLIMessage({project_id:n});"json"===o.format?o.response.print({message:r}):o.response.print(r)}catch(e){K(e,o)}var s})}(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."}}}}}}}}).action(pu)})(i)};function _u(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function mu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function gu(t){t.command("list").description("List project environment variables").option("--env <scope>","Environment scope: dev | prod","dev").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List project environment variables",description:"Retrieve the list of environment variables for the specified project. Supports filtering by environment (dev/prod) and displays all configured sensitive information key names.",examples:[{desc:"List dev environment variables",cmd:"coze code env list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List prod environment variables",cmd:"coze code env list -p <projectId> --env prod"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},env:{type:"string",required:!1,enum:["dev","prod"],description:"Environment scope (default: dev)"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},project_type:{type:"string",description:"Project type"},env:{type:"string",description:"Environment scope"},secrets:{type:"array",description:"Environment variable list"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action(async function(t,i){const o=i.getContext(),{projectId:s}=t,n=mu([await e.IdeApi.GetVibeProject({project_id:s}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),a=(r=t.env,"prod"===String(r||"dev").toLowerCase()?Yi.prod:Yi.dev);var r;const c=mu([await ao.ListProjectSecret({env:a,project_id:s,...n===e.VibeProjectType.Skill?{with_providers:!0}:{}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[];mu([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secrets listed successfully.")]),mu([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(c.map(e=>({secret_key:e.secret_key,secret_id:e.secret_id,secret_val:e.secret_val,secret_type:e.secret_type})))])})}function hu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const fu=t=>{const i=t.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:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},key:{type:"string",description:"Set key name"},value:{type:"string",description:"Set value"}}}}},errors:[{code:e.ErrorCode.E3008,name:"SKILL_PROJECT_NOT_SUPPORTED",desc:"Skill project secret_type logic to be supplemented",fix:"This feature is not yet supported for Skill projects"}]}}).action(async function(t,i,o,s){const n=s.getContext(),{projectId:a}=o,r=_u([await e.IdeApi.GetVibeProject({project_id:a}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(r===e.VibeProjectType.Skill)throw new e.CozeError(e.ErrorCode.E3008,"Skill project secret_type logic to be supplemented",{projectId:a,projectType:r});await ao.InsertProjectSecret({project_id:a,insert_secrets:{secrets:[{secret_key:t,secret_val:i}]}}),_u([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secret set successfully")]),_u([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:a,key:t,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 specified environment variables from the project. Supports deleting multiple variables simultaneously by passing the --key parameter multiple times.",examples:[{desc:"Delete a single environment variable",cmd:"coze code env delete <KEY> -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Delete multiple environment variables",cmd:"coze code env delete <KEY> -p <projectId>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},key:{type:"string",required:!0,description:"Environment variable key name to delete"}},output:{message:{type:"string",description:"Result message"},key:{type:"string",description:"Deleted key"}}},errors:[{code:e.ErrorCode.E3003,name:"SECRET_NOT_FOUND",desc:"The specified environment variable does not exist",fix:"Please use `env list` first to confirm if the variable name is correct"}]}}).action(async function(t,i,o){const s=o.getContext(),{projectId:n}=i,a=[t],r=hu([await ao.ListProjectSecret({env:Yi.dev,project_id:n}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],c=new Set(a.map(e=>String(e))),d=r.filter(e=>c.has(String(e.secret_key||""))).map(e=>e.secret_id).filter(Boolean);if(0===d.length)throw new e.CozeError(e.ErrorCode.E3003,`No matched secrets by keys: ${a.join(", ")}`,{projectId:n,keys:a});await ao.DeleteProjectSecret({project_id:n,keys:d}),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:a,secret_ids:d})])})}(i)};function yu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function bu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function vu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Cu=t=>{const i=t.command("domain").config({help:{brief:"Manage custom domains for the project",description:"Manage custom domains for deployed projects. Supports adding, listing, and removing domains associated with a project, used to access deployed applications.",examples:[{desc:"List project domains",cmd:"coze code domain list <projectId>"},{desc:"Add custom domain",cmd:"coze code domain add example.com -p <projectId>"},{desc:"Delete domain",cmd:"coze code domain remove example.com -p <projectId>"}],seeAlso:["coze code deploy"]}}).description("Manage custom domains for the project");i.command("list").description("List custom domains of the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List all domains bound to the project",description:"Retrieve a list of all custom domains bound to the specified project.",examples:[{desc:"List domains",cmd:"coze code domain list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Output in JSON format",cmd:"coze code domain list -p <projectId> --format json"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Domain ID"},domain_host:{type:"string",description:"Domain host"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action(async function(e,t){const i=t.getContext(),{projectId:o}=e,s=bu([await Wl.PublicListDomainRelated({project_id:o}),"access",e=>e.data,"optionalAccess",e=>e.items])||[];bu([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Fetched domains List successfully")]),bu([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(s.map(e=>({id:e.id,domain_host:e.domain_host})))])}),function(t){t.command("add <domain>").description("Add a custom domain to the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add custom domain to project",description:"Bind a custom domain to a specified project. The domain must follow standard format (e.g., example.com). Once bound, the deployed application can be accessed via this domain.",examples:[{desc:"Add domain",cmd:"coze code domain add <domain> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to add (e.g., example.com)"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},domain:{type:"string",description:"Added domain"}}}}},errors:[{code:e.ErrorCode.E1004,name:"INVALID_DOMAIN",desc:"Incorrect domain format",fix:"Please use a standard domain format, e.g., example.com"}]}}).action(async function(t,i,o){const s=o.getContext(),{projectId:n}=i;if(!/^[a-zA-Z0-9][a-zA-Z0-9-]*\.[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(t))throw new e.CozeError(e.ErrorCode.E1004,"Invalid domain",{domain:t});await Wl.PublicCreateDomainRelated({project_id:n,domain:t}),vu([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Domain '${t}' added.`)]),vu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,domain:t})])})}(i),function(t){t.command("remove <domain>").description("Remove a custom domain from the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete custom domain of the project",description:"Remove a bound custom domain from the specified project.",examples:[{desc:"Delete domain",cmd:"coze code domain remove example.com -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to delete"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},domain:{type:"string",description:"Deleted domain"}}}}},errors:[{code:e.ErrorCode.E1004,name:"INVALID_DOMAIN",desc:"Incorrect domain format",fix:"Please use a standard domain format, e.g., example.com"},{code:e.ErrorCode.E3005,name:"DELETE_FAILED",desc:"Failed to remove domain",fix:"Please confirm the domain is bound to the project and you have sufficient permissions"}]}}).action(async function(e,t,i){const o=i.getContext(),{projectId:s}=t;await Wl.PublicDeleteDomainRelated({project_id:s,domain:e}),yu([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Domain '${e}' removed.`)]),yu([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({message:`Domain '${e}' removed.`,domain:e})])})}(i)};function Su(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Pu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Eu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Tu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Au(t){const i=t.command("deploy <projectId>").description("Deploy the project to production environment").option("--commit-id <commitId>","Commit ID (optional, queries latest if omitted)").option("--wait","Wait for deployment to complete").config({help:{brief:"Deploy the project to production environment",description:"Deploy the specified project to the production environment. Supports multiple project types (Agent, Workflow, Skill, Web, Mini-program, etc.), automatically fetches the latest commit, and triggers the deployment process.",examples:[{desc:"Deploy latest project",cmd:"coze code deploy <projectId>",tags:["[RECOMMENDED]"]},{desc:"Deploy and wait for completion",cmd:"coze code deploy <projectId> --wait"},{desc:"Deploy a specific commit",cmd:"coze code deploy <projectId> --commit-id <commitId>"},{desc:"View deployment status",cmd:"coze code deploy status <projectId>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.E3007,name:"MISSING_COMMIT_HASH",desc:"No commits found in the project",fix:"Please commit your changes first before deploying"},{code:e.ErrorCode.E2002,name:"MINIPROGRAM_NOT_AUTHORIZED",desc:"Mini-program AppID not configured",fix:"Please complete the Mini-program AppID configuration in the project settings"},{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Project type is not supported for deployment",fix:"Please confirm the project type and try again with a supported project"}]}}).description("Deploy the project to production environment").action(async function(t,i,o){const s=o.getContext(),{wait:n,commitId:a}=i,r=Tu([(await e.IdeApi.GetVibeProject({project_id:t})).data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(!Yl.canDeploy(r)){const t=`Project type ${Nd(r)} is not supported for deployment`;throw new e.CozeError(e.ErrorCode.E1006,t,{projectType:r})}if(r===e.VibeProjectType.AssistantAgent){const i=await e.axiosInstance.post("/api/sandbox/coze_coding/devbox/open_claw/deploy",{project_id:t},{headers:{"content-type":"application/json"}});return Tu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying (AssistantAgent)...")]),void Tu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({command:"deploy",status:"ok",data:{type:r,data:Tu([i,"optionalAccess",e=>e.data])}})])}let c=a;if(!c){Tu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching latest commit...")]);const e=await Yl.getCommitList({projectId:t});c=Tu([e,"optionalAccess",e=>e[0],"optionalAccess",e=>e.id])}if(!c){const i="Missing commitHash: pass --commit-hash <commitHash>";throw new e.CozeError(e.ErrorCode.E3007,i,{projectId:t})}if(r===e.VibeProjectType.WechatMiniProgram){Tu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking Mini-program authorization...")]);if(!Tu([await Wl.PublicGetAuthStatus({project_id:t,connector_id:"10000127"}),"access",e=>e.data,"optionalAccess",e=>e.bound_related_id])){const t="Deployment failed, please complete the Mini-program AppID configuration";throw new e.CozeError(e.ErrorCode.E2002,t)}}Tu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking deploy config...")]),await Wl.PublicGetDeployConfig({project_id:t,commit_hash:c},{__disableErrorToast:!0});let d="";const p=await ao.ListProjectSecret({env:Yi.dev,project_id:t,with_providers:!0}),l=Tu([p,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],u=Tu([p,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_cred_providers])||[];Tu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Encrypting secrets...")]);d=Tu([await ao.EncryptProjectSecret({project_id:t,project_type:r===e.VibeProjectType.Skill?Zi.skill:void 0,encrypt_secrets:{secrets:l.map(e=>({secret_key:e.secret_key||"",secret_val:e.secret_val||"",secret_id:e.secret_id||"",secret_type:e.secret_type===Xi.consumer?ki.consumer3:ki.user_custom2})),...r===e.VibeProjectType.Skill?{cred_providers:u}:{}}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.sealed_secrets])||"",Tu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying...")]);const _=Tu([await Wl.PublicCreateDeployHistory({project_id:t,encrypt_env_variable:d,commit_hash:c}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_id]);Tu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploy started.")]),n&&_?await Yl.pollDeployStatus({projectId:t,deployHistoryId:_,onBeforePoll:()=>{Tu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const i=Jl(e.status);Tu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",o=>o({projectId:t,status:i,domain:Tu([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:_,commitHash:e.commit_hash})])}}):Tu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({projectId:t,status:Jl(Sl.Pending),domain:"",deployHistoryId:_,commitHash:c})])});!function(t){t.command("status <projectId>").description("Check deployment status").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest if omitted)").config({help:{brief:"Query project deployment status",description:"Query the deployment status of a specified project. If no deployment history ID is specified, it automatically queries the latest deployment record. Supports viewing deployment progress, results, and error messages.",examples:[{desc:"Query latest deployment status",cmd:"coze code deploy status <projectId>",tags:["[RECOMMENDED]"]},{desc:"Query specific deployment record",cmd:"coze code deploy status <projectId> --deploy-id <deployHistoryId>"},{desc:"Wait for deployment to complete",cmd:"coze code deploy status <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (optional, queries latest if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.E3006,name:"NO_DEPLOYMENT_HISTORY",desc:"No deployment history found for this project",fix:"Please deploy the project first using `coze code deploy <projectId>`"}]}}).action(async function(t,i,o){const s=o.getContext(),{deployId:n}=i,{wait:a}=Su([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let r=n;if(!r&&(Su([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("get latest deployment record...")]),r=await Yl.getLatestDeployHistoryId({projectId:t}),!r))throw new e.CozeError(e.ErrorCode.E3006,"No deployment history found for this project");if(a)await Yl.pollDeployStatus({projectId:t,deployHistoryId:r,onBeforePoll:()=>{Su([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const i=Jl(e.status);Su([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",o=>o({projectId:t,status:i,domain:Su([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:r,commitHash:e.commit_hash})])}});else{Su([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Querying deployment status...")]);const e=await Yl.getDeployHistory({projectId:t,deployHistoryId:r}),i=Jl(e.status),o=e.domain_list||[];Su([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",s=>s({projectId:t,status:i,domain:o[0],deployHistoryId:r,commitHash:e.commit_hash})])}})}(i),function(e){e.command("list <projectId>").description("List deployment history for a project").option("--page-size <pageSize>","Number of records per page","10").option("--page-token <pageToken>","Page token for pagination").config({help:{brief:"List project deployment history",description:"List the deployment history of a specified project. Supports pagination to browse historical deployment records including status, commit hash, domains and timestamps.",examples:[{desc:"List deployment history",cmd:"coze code deploy list <projectId>",tags:["[RECOMMENDED]"]},{desc:"List with custom page size",cmd:"coze code deploy list <projectId> --page-size 20"},{desc:"List next page",cmd:"coze code deploy list <projectId> --page-token <token>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},pageSize:{type:"number",required:!1,description:"Number of records per page (default: 10)"},pageToken:{type:"string",required:!1,description:"Page token for pagination"}},output:{type:"array",items:{deploy_history_id:{type:"string",description:"Deployment history ID"},status:{type:"string",description:"Deployment status"},commit_hash:{type:"string",description:"Commit hash"},domain_list:{type:"array",description:"Deployed domains"},created_at:{type:"string",description:"Creation timestamp"}}}}}}).action(async function(e,t,i){const o=i.getContext(),s=Number(t.pageSize)||10,n=(Pu([await Wl.PublicListDeployHistory({project_id:e,page_size:s,page_token:t.pageToken}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list])||[]).map(e=>({deploy_history_id:e.deploy_history_id,project_id:e.project_id,status:Jl(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}));Pu([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)])})}(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 -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Fix a specific deployment",cmd:"coze code deploy fix <projectId> --deploy-id <deployId>"},{desc:"Fix and wait for result",cmd:"coze code deploy fix <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (queries latest failed if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for fix message response"}},output:{type:"object",properties:{deploy_history_id:{type:"string"},status:{type:"string"},message:{type:"string"}}}}}}).action(async function(t,i,o){const s=o.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const{deployId:n}=i,{wait:a}=Eu([o,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let r=n;if(n||(r=await Yl.getLatestDeployHistoryId({projectId:t})),!r)throw new e.CozeError(e.ErrorCode.E5002,`No deploy history found for project ${t}`,{project_id:t});const c=Eu([await Wl.PublicGetDeployHistory({project_id:t,deploy_history_id:r}),"optionalAccess",e=>e.data]);if(Eu([c,"optionalAccess",e=>e.status])!==Sl.Failed){const t=Jl(Eu([c,"optionalAccess",e=>e.status]));throw new e.CozeError(e.ErrorCode.E3009,`Deployment ${r} is not in Failed status (current: ${t}). Only failed deployments can be fixed.`,{deploy_history_id:r,status:Eu([c,"optionalAccess",e=>e.status])})}const d=c.deploy_log_url;if(!d)throw new e.CozeError(e.ErrorCode.E5002,`No deploy log URL found for deployment ${r}`,{deploy_history_id:r});const p=await e.customFetch.fetch(d,{method:"GET"}),l=await p.text();if(!l)throw new e.CozeError(e.ErrorCode.E5002,`Deploy log is empty for deployment ${r}`,{deploy_history_id:r,deploy_log_url:d});const u=`修复以下部署错误:\n${l}`,_=await Eu([s,"access",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!_)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(a){const e=await Kd.sendMessage({projectId:t,prompt:u,apiBaseUrl:s.config.apiBaseUrl,accessToken:_,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${t}`});Eu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({deploy_history_id:r,status:"fix_sent",message:e.lastAnswerMessage})])}else Kd.sendMessageRunTask({projectId:t,prompt:u,apiBaseUrl:s.config.apiBaseUrl,accessToken:_,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${t}`})})}(i)}function ku(e,t){return null!=e?e:t()}function wu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Ru={"x-tt-env":"ppe_coze_cli_claw","x-use-ppe":"1"},zu=()=>({headers:{...Ru}});class Iu{static getInstance(){return Iu.INSTANCE||(Iu.INSTANCE=new Iu),Iu.INSTANCE}async createSpaceDatabase(t){const i=await e.IdeApi.CreateSpaceDatabase({space_id:t},zu());if(!i.database)throw new e.CozeError(e.ErrorCode.E5000,"Failed to create database");return i.database}async listSpaceDatabases(t,i){const o=await e.IdeApi.ListSpaceDatabase({space_id:t,cursor_id:wu([i,"optionalAccess",e=>e.cursor_id]),limit:ku(wu([i,"optionalAccess",e=>e.limit]),()=>20)},zu());return{databases:ku(wu([o,"optionalAccess",e=>e.databases]),()=>[]),next_cursor_id:o.next_cursor_id}}async getSpaceDatabase(t,i){const o=await e.IdeApi.GetSpaceDatabase({space_id:t,database_id:i},zu());if(!o.database)throw new e.CozeError(e.ErrorCode.E3010,`Database '${i}' not found or no permission`,{databaseId:i});return o.database}async deleteSpaceDatabase(t,i){await e.IdeApi.DeleteSpaceDatabase({space_id:t,database_id:i},zu())}async rollbackSpaceDatabase(t,i,o){return await e.IdeApi.RollbackSpaceDatabase({space_id:t,database_id:i,timestamp:o},zu())}async getSpaceDatabaseStatus(t,i){return await e.IdeApi.GetSpaceDatabaseStatus({space_id:t,database_id:i},zu())}}const Ou=Iu.getInstance(),Lu={0:"active",1:"creating"},ju={0:"dev",1:"prod"},Uu={0:"restoring",1:"success",2:"failed"},Bu=e=>e&&"0"!==e?new Date(Number(e)).toLocaleString():"-";function xu(e,t){return null!=e?e:t()}function qu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Du(e,t){return null!=e?e:t()}function Mu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Gu=[{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 Nu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Fu(e,t){return null!=e?e:t()}function $u(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Vu=async(t,i,o,s)=>{const n=`${t}/api/platform/pg-meta/default/query`,a=Buffer.from(`${i}:${o}`).toString("base64"),r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify({query:s})});if(!r.ok){const t=await r.text(),i=e.safeJsonParse(t,void 0),o=Fu(Fu($u([i,"optionalAccess",e=>e.message]),()=>$u([i,"optionalAccess",e=>e.error,"optionalAccess",e=>e.message])),()=>`pg-meta request failed: ${r.status}`);throw new Error(o)}const c=await r.json();return Array.isArray(c)?c:[]};function Wu(e,t){return null!=e?e:t()}function Hu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function Ku(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"}]}}).action(async(t,i)=>{const o=i.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Wu(Wu(t.spaceId,()=>o.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 fa(),a=await(async e=>{if(Nu([e,"optionalAccess",e=>e.sql]))return e.sql.trim();if(Nu([e,"optionalAccess",e=>e.file])){const t=_.resolve(e.file),i=(await m.readFile(t,"utf-8")).trim();if(!i)throw new Error(`SQL file is empty: ${t}`);return i}if(Nu([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}),r=(e=>{const t=[];let i="safe";const o=e.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const{pattern:e,level:s,reason:n}of Gu)e.test(o)&&(t.push(n),"critical"===s?i="critical":"safe"===i&&(i="warning"));return{isDangerous:"safe"!==i,level:i,reasons:t}})(a);if(r.isDangerous&&!t.confirm){if("json"===Hu([o,"access",e=>e.options,"optionalAccess",e=>e.format]))throw new e.CozeError(e.ErrorCode.E1007,`SQL contains dangerous operation: ${r.reasons.join(", ")}`,{sql:a.substring(0,200),analysis:r},{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`});o.ui.info(`⚠ Warning: SQL contains dangerous operation:\n ${r.reasons.join("\n ")}`);const{confirm:i}=await import("@inquirer/prompts").then(e=>({confirm:e.confirm}));if(!await i({message:"Are you sure you want to execute this SQL?",default:!1}))return void o.ui.info("Operation cancelled.")}o.ui.info("Fetching database connection info...");const c=await Ou.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 d;o.ui.info("Executing SQL...");try{d=await Vu(c.supabase_url,c.super_user,c.super_user_password,a)}catch(t){throw new e.CozeError(e.ErrorCode.E5004,`SQL execution failed: ${t.message}`,{sql:a.substring(0,200)})}const p=Wu(Hu([a,"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"),l="SELECT"===p,u=r.isDangerous?r.reasons:[],g=d.length>0,h=l||g?d.length:null;l||g?o.response.print("json"===Hu([o,"access",e=>e.options,"optionalAccess",e=>e.format])?{result:d,rows_affected:h,command:p,warnings:u}:d):(o.ui.success("SQL executed successfully (rows_affected unavailable from pg-meta)."),o.response.print("json"===Hu([o,"access",e=>e.options,"optionalAccess",e=>e.format])?{result:[],rows_affected:null,command:p,warnings:u,note:"pg-meta does not expose rows_affected for DDL/DML without RETURNING"}:{command:p,message:"SQL executed successfully."}))})}function Ju(e,t){return null!=e?e:t()}function Qu(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}const Zu=e=>({database_id:e.database_id,name:e.name,status:Ju(Lu[Ju(e.status,()=>0)],()=>String(e.status)),database_env:Ju(ju[Ju(e.database_env,()=>0)],()=>String(e.database_env)),created_at:Bu(e.created_at)});async function Yu(t,i){const o=i.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Ju(Ju(t.spaceId,()=>o.config.spaceId),()=>"");if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const n=Ju(t.limit,()=>20),a="json"!==Qu([o,"access",e=>e.options,"optionalAccess",e=>e.format]);if(a||!0===t.all){const e=Ju(t.maxPages,()=>10),i=[];let r,c=t.cursor,d=0;for(o.ui.info("Fetching databases...");d<e;){const e=await Ou.listSpaceDatabases(s,{cursor_id:c,limit:n});if(i.push(...Ju(e.databases,()=>[]).map(Zu)),d+=1,o.ui.verbose(`Page ${d}: ${Ju(Qu([e,"access",e=>e.databases,"optionalAccess",e=>e.length]),()=>0)} item(s)`),r=e.next_cursor_id,!r||"0"===r){r=void 0;break}c=r}return r&&o.ui.info(`Reached --max-pages=${e}. More results available (cursor: ${r}). Pass --max-pages to fetch more.`),o.ui.info(`Fetched ${i.length} database(s).`),void(a?o.response.print(i):o.response.print({databases:i,next_cursor_id:Ju(r,()=>"0")}))}const r=await Ou.listSpaceDatabases(s,{cursor_id:t.cursor,limit:n});o.response.print({databases:Ju(r.databases,()=>[]).map(Zu),next_cursor_id:r.next_cursor_id})}function Xu(e,t){return null!=e?e:t()}function e_(e,t){return null!=e?e:t()}async function t_(t,i){const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const a=e_(e_(t.spaceId,()=>s.config.spaceId),()=>"");if(!a)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const r=t.includeSchema&&t.includeSchema.length>0?t.includeSchema:["public"];s.ui.info("Fetching database connection info...");const c=await Ou.getSpaceDatabase(a,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});s.ui.info("Fetching OpenAPI schema from PostgREST...");const d=`${c.supabase_url}/rest/v1/`;let p,l;try{const e=await fetch(d,{headers:{apikey:c.anon_key}});if(!e.ok)throw new Error(`PostgREST returned ${e.status}`);p=await e.json()}catch(i){throw new e.CozeError(e.ErrorCode.E5006,`Failed to fetch OpenAPI schema: ${i.message}`,{databaseId:t.dbId})}s.ui.info("Generating TypeScript types...");try{const e=await import("openapi-typescript"),t=await e.default(p,{exportType:!0});l="string"==typeof t?t:e.astToString(t)}catch(i){throw new e.CozeError(e.ErrorCode.E5006,`Type generation failed: ${i.message}`,{databaseId:t.dbId})}const u=n.resolve(e_(t.output,()=>"types/database.ts"));await o.mkdir(n.dirname(u),{recursive:!0}),await o.writeFile(u,"// Auto-generated by coze code db gen-types\n// Do not edit manually\n\n"+l,"utf-8"),s.ui.success(`Types generated: ${u}`),s.response.print({output_path:u,schemas:r})}function i_(e,t){return null!=e?e:t()}const o_=/^[a-zA-Z_][a-zA-Z0-9_$]{0,62}$/,s_=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 n_(e,t){const[i,o,s,n]=await Promise.all([Vu(e.supabaseUrl,e.username,e.password,t.tables),Vu(e.supabaseUrl,e.username,e.password,t.columns),Vu(e.supabaseUrl,e.username,e.password,t.constraints),Vu(e.supabaseUrl,e.username,e.password,t.indexes)]),a=(e=>{const t=new Map;for(const i of e){const e=`${i.table_schema}.${i.table_name}`,o=t.get(e);o?o.push(i):t.set(e,[i])}return t})(o);let r="";for(const e of i){const t=`${e.table_schema}.${e.table_name}`,i=i_(a.get(t),()=>[]);r+=`CREATE TABLE IF NOT EXISTS ${e.table_schema}.${e.table_name} (\n`,r+=i.map(s_).join(",\n"),r+="\n);\n\n"}for(const e of s){const t=e.constraint_type;("p"===t||"u"===t||"f"===t||"c"===t)&&e.definition&&(r+=`ALTER TABLE ${e.schema_name}.${e.table_name} ADD CONSTRAINT ${e.constraint_name} ${e.definition};\n`)}s.length>0&&(r+="\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&&(r+=`${e.indexdef};\n`)}return n.length>0&&(r+="\n"),r}async function a_(t,i){const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const a=i_(i_(t.spaceId,()=>s.config.spaceId),()=>"");if(!a)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 r=!t.dataOnly,c=!0===t.dataOnly,d=c?"data-only":"schema-only",p=(t=>{const i=t&&t.length>0?Array.from(new Set(t)):["public"];for(const t of i)if(!o_.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 i})(t.includeSchema),l=(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 `}})(p);s.ui.info("Fetching database connection info...");const u=await Ou.getSpaceDatabase(a,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 _={supabaseUrl:u.supabase_url,username:u.super_user,password:u.super_user_password};let m="";m+="-- Dump generated by coze code db dump\n",m+=`-- Database: ${t.dbId}\n`,m+=`-- Mode: ${d}\n`,m+=`-- Schemas: ${p.join(", ")}\n`,m+=`-- Date: ${(new Date).toISOString()}\n\n`;try{r&&(s.ui.info("Exporting schema..."),m+=await n_(_,l)),c&&(s.ui.info("Exporting data..."),m+=await async function(e,t){const i=await Vu(e.supabaseUrl,e.username,e.password,t.tables);let o="";for(const t of i){const i=`SELECT * FROM ${t.table_schema}.${t.table_name};`,s=await Vu(e.supabaseUrl,e.username,e.password,i);if(0===s.length)continue;const n=Object.keys(s[0]);for(const e of s){const i=n.map(t=>{return null==(i=e[t])?"NULL":"number"==typeof i?Number.isFinite(i)?String(i):"NULL":"boolean"==typeof i?i?"TRUE":"FALSE":"bigint"==typeof i?String(i):i instanceof Date?`'${i.toISOString()}'`:"object"==typeof i?`'${JSON.stringify(i).replace(/'/g,"''")}'`:`'${String(i).replace(/'/g,"''")}'`;var i});o+=`INSERT INTO ${t.table_schema}.${t.table_name} (${n.join(", ")}) VALUES (${i.join(", ")});\n`}o+="\n"}return o}(_,l))}catch(i){throw new e.CozeError(e.ErrorCode.E5007,`Dump failed: ${i.message}`,{databaseId:t.dbId})}const g=n.resolve(i_(t.output,()=>"db/schema.sql"));await o.mkdir(n.dirname(g),{recursive:!0}),await o.writeFile(g,m,"utf-8"),s.ui.success(`Dump completed: ${g}`),s.response.print({output_path:g,mode:d,schemas:p})}function r_(e,t){return null!=e?e:t()}function c_(e,t){return null!=e?e:t()}const d_=t=>{const i=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`"},{code:e.ErrorCode.E1007,name:"DB_SQL_DANGEROUS",desc:"SQL contains dangerous operation",fix:"Add --confirm flag or modify SQL"}]}});i.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`"}]}}).action(async(t,i)=>{const o=i.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=c_(c_(t.spaceId,()=>o.config.spaceId),()=>"");if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");o.ui.info("Creating database in space...");const n=await Ou.createSpaceDatabase(s);o.ui.success("Database created successfully!"),o.response.print({database_id:n.database_id,database_url:n.database_url,status:c_(Lu[c_(n.status,()=>0)],()=>n.status),database_env:c_(ju[c_(n.database_env,()=>0)],()=>n.database_env),created_at:Bu(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"}]}}).action(Yu)}(i),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"}},output:{database_id:{type:"string",description:"Database ID"},database_url:{type:"string",description:"Connection URL"},supabase_url:{type:"string",description:"Supabase URL"},status:{type:"string",description:"Status"}}},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`"}]}}).action(async(t,i)=>{const o=i.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Xu(Xu(t.spaceId,()=>o.config.spaceId),()=>"");if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");o.ui.info(`Fetching database '${t.dbId}'...`);const n=await Ou.getSpaceDatabase(s,t.dbId);o.ui.success("Database details:"),o.response.print({database_id:n.database_id,database_name:n.name,database_url:n.database_url,supabase_url:n.supabase_url,super_user:n.super_user,super_user_password:n.super_user_password,service_role_key:n.service_role_key,anon_key:n.anon_key,status:Xu(Lu[Xu(n.status,()=>0)],()=>n.status),database_env:Xu(ju[Xu(n.database_env,()=>0)],()=>n.database_env),created_at:Bu(n.created_at)})})}(i),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:!0,description:"Must be set to confirm deletion"}},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`"}]}}).action(async(t,i)=>{const o=i.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!t.confirm){const i="json"===function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}([o,"access",e=>e.options,"optionalAccess",e=>e.format]),s=!0===process.stdin.isTTY;if(i||!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`});o.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 o.ui.info("Operation cancelled.")}const s=r_(r_(t.spaceId,()=>o.config.spaceId),()=>"");if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");o.ui.info(`Deleting database '${t.dbId}'...`),await Ou.deleteSpaceDatabase(s,t.dbId),o.ui.success(`Database '${t.dbId}' deleted successfully.`),o.response.print({deleted:!0,database_id:t.dbId})})}(i),Ku(i),function(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"}]}}).action(async(t,i)=>{const o=i.getContext();if(!o)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`});const s=Du(Du(t.spaceId,()=>o.config.spaceId),()=>"");if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");o.ui.info(`Rolling back database '${t.dbId}' to ${new Date(Number(t.timestamp)).toLocaleString()}...`);const n=await Ou.rollbackSpaceDatabase(s,t.dbId,t.timestamp);o.ui.success(`Rollback initiated. Use 'coze code db status --db-id ${t.dbId}' to check progress.`),o.response.print({restore_history_id:Mu([n,"optionalAccess",e=>e.restore_history_id])})})}(i),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"}]}}).action(async(t,i)=>{const o=i.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=xu(xu(t.spaceId,()=>o.config.spaceId),()=>"");if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");o.ui.info(`Fetching status for database '${t.dbId}'...`);const n=await Ou.getSpaceDatabaseStatus(s,t.dbId);o.ui.success("Database status:"),o.response.print({can_restore:qu([n,"optionalAccess",e=>e.can_restore]),is_restoring:qu([n,"optionalAccess",e=>e.is_restoring]),earliest_restore_time:Bu(qu([n,"optionalAccess",e=>e.earliest_restore_time])),latest_restore_status:xu(Uu[xu(qu([n,"optionalAccess",e=>e.latest_restore_status]),()=>-1)],()=>qu([n,"optionalAccess",e=>e.latest_restore_status])),latest_restore_error:qu([n,"optionalAccess",e=>e.latest_restore_error]),latest_restore_start_time:Bu(qu([n,"optionalAccess",e=>e.latest_restore_start_time])),latest_restore_end_time:Bu(qu([n,"optionalAccess",e=>e.latest_restore_end_time]))})})}(i),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:"Check database is in active status and PostgREST is available"}]}}).action(t_)}(i),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"}]}}).action(a_)}(i)};function p_(t){const i=t.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),Au(i),Yd(i),fu(i),Cu(i),(e=>{const t=e.command("skill").config({help:{brief:"Manage project skills",description:"Manage skills associated with a project. Skills are important components to extend project capabilities, supporting adding, viewing, and removing project skills.",examples:[{desc:"List project skills",cmd:"coze code skill list -p <projectId>"},{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>"},{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>"}],seeAlso:["coze code project"]}}).description("Manage project skills");dc(t),lc(t),ac(t)})(i),function(t){t.command("preview <projectId>").description("Get deployment preview info for the project").config({help:{brief:"Get project preview URL",description:"Get the sandbox preview URL for the project. Supports AssistantAgent and GeneralWeb project types, returning an accessible preview URL. Sandbox initialization takes 1-3 minutes.",examples:[{desc:"Get preview URL",cmd:"coze code preview <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:{type:"string",description:"Project type"},preview_url:{type:"string",description:"Preview URL"}}},errors:[{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Unsupported project type",fix:"Preview feature only supports AssistantAgent and GeneralWeb project types"},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Missing required argument: projectId",fix:"Pass <projectId> as the first argument: `coze code preview <projectId>`",example:"coze code preview 123456"}]}}).action(async function(t,i,o){const s=o.getContext();if(!t)throw new e.CozeError(e.ErrorCode.E1000,"Missing projectId: pass <projectId> as argument");const n=await e.IdeApi.GetVibeProject({project_id:t}),a=Xl([n,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=Xl([n,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.name]),c={type:Nd(a)};if(!Kd.isValidType(a))throw new e.CozeError(e.ErrorCode.E1006,"Unsupported project type",{projectId:t,type:a});if(a===e.VibeProjectType.Skill){const e=await Yl.getCommitList({projectId:t});Xl([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating preview task...")]);const i=await _l.CreateCozeSpaceTask({task_name:`${r}-preview-${Xl([e,"access",e=>e[0],"optionalAccess",e=>e.id])}`,task_type:1,is_debug:!0,source_from:Qp.UserCreate,mcp_tool_list:[]});c.preview_url=`https://www.coze.cn/task-m/${i.data.task.task_id}`,Xl([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Preview task created. Please access the preview URL: ${c.preview_url}`)])}else{const i=await e.IdeApi.InitSandbox({project_id:t});c.preview_url=i.token?`https://${i.project_host}?token=${i.token}`:`https://${i.project_host}`,Xl([s,"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: ${c.preview_url}`)])}Xl([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(c)])})}(i),d_(i)}function l_(o){o.command("upgrade").description("Upgrade Coze CLI to the latest version").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Upgrade CLI to latest version",description:"Check for the latest version of Coze CLI and upgrade if a newer version is available. Detects the package manager used for the original installation (npm/pnpm/yarn) and runs the appropriate global install command.",examples:[{desc:"Upgrade to latest version",cmd:"coze upgrade",tags:["[RECOMMENDED]"]},{desc:"Force check and upgrade",cmd:"coze upgrade --force"},{desc:"Upgrade to a specific tag",cmd:"coze upgrade --tag beta"}],seeAlso:["coze --version"]}}).option("--force","Force upgrade even if already on the latest version").option("--tag <tag>","Specify the dist-tag to upgrade to","latest").action(async(o,s)=>{const n=s.getContext();n||process.exit(e.ExitCode.FAILURE),n.ui.info("Checking for updates...");try{const e=await de(n,!0,o.tag);if(!e.hasUpdate&&!o.force)return void n.ui.success(`You are already on the latest version (${e.currentVersion}).`);e.hasUpdate&&n.ui.info(`New version available: ${t.gray(e.currentVersion)} → ${t.green(e.latestVersion)}`),n.ui.info("Upgrading Coze CLI...");const s=function(){const e=[{pm:"npm",cmd:"npm ls -g @coze/cli --json 2>/dev/null"},{pm:"pnpm",cmd:"pnpm ls -g @coze/cli --json 2>/dev/null"},{pm:"yarn",cmd:"yarn global list --json 2>/dev/null"}];for(const{pm:t,cmd:o}of e)try{if(i.execSync(o,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).includes("@coze/cli"))return t}catch(e){}return"npm"}(),a=function(e,t){switch(e){case"pnpm":return`pnpm add -g @coze/cli@${t}`;case"yarn":return`yarn global add @coze/cli@${t}`;default:return`npm install -g @coze/cli@${t}`}}(s,o.tag);n.ui.verbose(`Using package manager: ${s}`),n.ui.verbose(`Running: ${a}`),i.execSync(a,{stdio:"inherit"});const r=re();n.ui.success(`Successfully upgraded Coze CLI to ${e.latestVersion}. (was ${e.currentVersion})`),"json"===n.format&&n.response.print({previousVersion:e.currentVersion,currentVersion:r,latestVersion:e.latestVersion,status:"upgraded"})}catch(t){n.ui.error(`Failed to upgrade: ${t.message}`),n.ui.info("You can try upgrading manually with: npm install -g @coze/cli"),process.exit(e.ExitCode.FAILURE)}})}function u_(t){!function(t){const i=t.command("auth").description("Manage user authentication and credentials").config({skipAuth:!0,skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Manage authentication and credentials",description:"Manage the full authentication lifecycle for Coze CLI. Supports interactive OAuth login via browser. All other commands require valid authentication.",examples:[{desc:"Interactive login via browser",cmd:"coze auth login --oauth",tags:["[RECOMMENDED]"]},{desc:"Check current login status",cmd:"coze auth status"},{desc:"Logout and clear credentials",cmd:"coze auth logout"}],seeAlso:["coze organization","coze space"]}});i.command("login").description("Login to obtain and persist access credentials").config({skipAuth:!0,help:{brief:"Login to Coze services",description:"Login to Coze services via OAuth authorization. Opens browser to complete authorization.",examples:[{desc:"Interactive login using OAuth",cmd:"coze auth login --oauth",tags:["[RECOMMENDED]"]}],errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Authentication failed",fix:"Please try again with `coze auth login --oauth`."}]}}).option("--token <PAT>","Login using an access token").option("--oauth","Start browser-based OAuth device authorization flow").action(async function(t,i){const o=i.getContext();if(!o)return void K(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"));await o.auth.login(t);const s=["Please use the following commands to manage organizations and spaces:"," coze organization list"," coze organization use <organization_id>"," coze space list"," coze space use <space_id>"];!function(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}}([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])}),i.command("logout").description("Logout and clear stored credentials").config({skipOrgCheck:!0,skipAuth:!0,skipSpaceCheck:!0,help:{brief:"Logout",description:"Clear locally stored access credentials and log out of the current account.",examples:[{desc:"Execute logout",cmd:"coze auth logout"}]}}).action(async(t,i)=>{const o=i.getContext();o?await o.auth.logout():K(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))}),i.command("status").description("Check current login status and credential validity").config({skipOrgCheck:!0,skipSpaceCheck:!0,help:{brief:"Check login status",description:"Verify if the current locally cached credentials are valid and display current login account information. If the token was obtained via OAuth and is about to expire, it will be refreshed automatically.",examples:[{desc:"Check current authentication status",cmd:"coze auth status",tags:["[RECOMMENDED]"]},{desc:"Check status in JSON format",cmd:"coze auth status --format json"}],schema:{output:{type:"object",properties:{logged_in:{type:"boolean",description:"Whether the user is currently logged in"},user:{type:"object",description:"Current user profile information"},token_expires_at:{type:"string",description:"Token expiration time in ISO 8601 format"}}}},errors:[{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"No valid credentials found or token has expired",fix:"Run `coze auth login --oauth` to authenticate."}],seeAlso:["coze auth login","coze auth logout"]}}).action(async(t,i)=>{const o=i.getContext();o?await o.auth.status():K(new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized"))})}(t),oc(t),p_(t),Mr(t),ua(t),ga(t),qr(t),Vr(t),l_(t),sc()}function __(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function m_(e,t){return null!=e?e:t()}function g_(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function h_(e){const t=[];let i=e;for(;i;)i.name()&&t.unshift(i.name()),i=i.parent;return t.join(" ")}function f_(e){return e._args.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ")}const y_=new Set(["--version","--format","--no-color","--config","--org-id","--space-id","--verbose","--debug","--log-file","--man","--schema","--commands"]);function b_(e){const t=new Map,i=[];let o=e;for(;o;)i.unshift(o),o=o.parent;for(const e of i)for(const i of e.options){const e=i.flags.split(", ").find(e=>e.startsWith("--"));!e||t.has(e)||y_.has(e)||t.set(e,i)}return Array.from(t.values())}function v_(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}class C_ extends v.Command{__init(){this.middlewares=[]}constructor(e){super(e),C_.prototype.__init.call(this),this.helpInformation=()=>{const e=process.argv.slice(2);if(e.includes("--schema"))return`${JSON.stringify(v_([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=g_([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=h_(e);let o=`@MAN ${i}\n\n`;o+=`NAME\n ${i} — ${g_([t,"optionalAccess",e=>e.brief])||e.description()}\n\n`,o+=`SYNOPSIS\n ${i} ${f_(e)}\n`,b_(e).forEach(e=>{o+=` [${e.flags}]\n`}),o+="\n",g_([t,"optionalAccess",e=>e.description])&&(o+=`DESCRIPTION\n ${t.description.replace(/\n/g,"\n ")}\n\n`);const s=b_(e);return s.length>0&&(o+="OPTIONS\n",s.forEach(e=>{const t=e.flags.split(", "),i=t.find(e=>e.startsWith("-")&&!e.startsWith("--"))||"",s=t.find(e=>e.startsWith("--"))||"";o+=` ${i?`${s}, ${i}`:s}\n`,o+=` Type: ${e.isBoolean()?"flag":"string"}\n`,o+=` Required: ${e.mandatory?"yes":"no"}\n`,o+=` Default: ${void 0!==e.defaultValue?String(e.defaultValue):"-"}\n`,o+=` Desc: ${e.description}\n\n`})),g_([t,"optionalAccess",e=>e.schema])&&(o+="SCHEMA\n",t.schema.input&&(o+=` Input:\n ${JSON.stringify(t.schema.input,null,2).replace(/\n/g,"\n ")}\n`),t.schema.output&&(o+=` Output:\n ${JSON.stringify(t.schema.output,null,2).replace(/\n/g,"\n ")}\n`),o+="\n"),g_([t,"optionalAccess",e=>e.errors])&&t.errors.length>0&&(o+="ERRORS\n",o+=" CODE NAME TRIGGER RECOVERY\n",t.errors.forEach(e=>{o+=` ${e.code.padEnd(6)} ${e.name.padEnd(17)} ${e.desc.padEnd(37)} ${e.fix}\n`}),o+="\n"),g_([t,"optionalAccess",e=>e.caveats])&&t.caveats.length>0&&(o+="CAVEATS\n",t.caveats.forEach(e=>{o+=` - ${e}\n`}),o+="\n"),g_([t,"optionalAccess",e=>e.seeAlso])&&t.seeAlso.length>0&&(o+="SEE ALSO\n",t.seeAlso.forEach(e=>{o+=` ${e}\n`}),o+="\n"),o.trimEnd()}(this)}\n`;return e.includes("-h")||e.includes("--help")?`${function(e){const t=g_([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=h_(e);let o=`@HELP ${i}\n\n`;return g_([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: ${h_(e.parent)}\n\n`),o+=`SYNTAX:\n ${i} ${f_(e)} [options]\n\n`,g_([t,"optionalAccess",e=>e.description])&&(o+=`DESCRIPTION:\n ${t.description.replace(/\n/g,"\n ")}\n\n`),o+="OPTIONS:\n",o+=" Name Type Required Default Description\n",o+=" ─────────────────────────────────────────────────────────\n",e._args.forEach(e=>{const t=`<${e.name()}>`,i=e.required?"Yes":"No",s=void 0!==e.defaultValue?String(e.defaultValue):"-",n=e.description||"";o+=` ${t.padEnd(16)} ${"string".padEnd(10)} ${i.padEnd(4)} ${s.padEnd(10)} ${n}\n`}),b_(e).forEach(e=>{const t=e.flags.split(", "),i=t.find(e=>e.startsWith("-")&&!e.startsWith("--"))||"",s=t.find(e=>e.startsWith("--"))||"",n=i?`${s}, ${i}`:s;let a="string";e.isBoolean()&&(a="flag");const r=e.mandatory?"Yes":"No",c=void 0!==e.defaultValue?String(e.defaultValue):"-",d=e.description||"";o+=` ${n.padEnd(16)} ${a.padEnd(10)} ${r.padEnd(4)} ${c.padEnd(10)} ${d}\n`}),o+="\n",g_([t,"optionalAccess",e=>e.enums])&&(o+="ENUMS:\n",Object.keys(t.enums).forEach(e=>{o+=` --${e}:\n`;const i=m_(g_([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),()=>({}));Object.keys(i).forEach(e=>{o+=` ${e.padEnd(12)} ${i[e]}\n`})}),o+="\n"),g_([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`})),g_([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"),g_([t,"optionalAccess",e=>e.seeAlso])&&t.seeAlso.length>0&&(o+="SEE ALSO:\n",t.seeAlso.forEach(e=>{o+=` ${e}\n`}),o+="\n"),o.trimEnd()}(this)}\n`:`${function(e){const t=g_([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help]),i=h_(e);let o=`@USAGE ${i}\n\n`;g_([t,"optionalAccess",e=>e.brief])?o+=`BRIEF: ${t.brief}\n\n`:o+=`BRIEF: ${e.description()||"No description provided."}\n\n`,o+=`SYNTAX:\n ${i} ${f_(e)} [options]\n\n`,e.commands.length>0&&(o+="ACTIONS:\n",e.commands.forEach(e=>{if(!e._hidden){const t=g_([e,"access",e=>e.getConfig,"call",e=>e(),"optionalAccess",e=>e.help,"optionalAccess",e=>e.brief])||e.description()||"";o+=` ${e.name().padEnd(10)} ${t}\n`}}),o+="\n"),g_([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(g_([t,"optionalAccess",e=>e.enums])){const e=Object.keys(t.enums).filter(e=>Object.keys(m_(g_([t,"access",e=>e.enums,"optionalAccess",t=>t[e]]),()=>({}))).length<=7);e.length>0&&(o+="ENUMS:\n",e.forEach(e=>{const i=Object.keys(m_(g_([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 C_(e);return this.context&&t.setContext(this.context),t}action(e){return super.action(async(...t)=>{const i=this.getContext();let o={},s=[],n=this;if(t.length>0){const e=t[t.length-1];e instanceof C_&&(n=e),t.length>=2&&(o=t[t.length-2],s=t.slice(0,t.length-2))}if(i&&(o&&(i.options=o),s&&(i.args=s),n)){i.commandName=n.name();const e=v_([n,"access",e=>e.getConfig,"optionalCall",e=>e()]);e&&(i.commandConfig=e),n.setContext(i)}if(this.middlewares.length>0&&i){const o=si(this.middlewares);await o(i,async()=>{await e.apply(this,t)})}else await e.apply(this,t)})}}function S_(e){let t,i=e[0],o=1;for(;o<e.length;){const s=e[o],n=e[o+1];if(o+=2,("optionalAccess"===s||"optionalCall"===s)&&null==i)return;"access"===s||"optionalAccess"===s?(t=i,i=n(i)):"call"!==s&&"optionalCall"!==s||(i=n((...e)=>i.call(t,...e)),t=void 0)}return i}function P_(e){e.exitOverride(),e.outputError=()=>{},e.commands.forEach(e=>P_(e))}async function E_(t){const i=new C_;i.name("coze").description("Coze Coding CLI").version(ne,"-v, --version").option("--format <fmt>","Specify output format (json, text). Default: text").option("--no-color","Disable ANSI color output").option("--config <path>","Specify config file path").option("--org-id <id>","Override Organization ID").option("--space-id <id>","Override Space ID").option("--verbose","Enable verbose mode, output more business process information").option("--debug","Enable debug mode, output all log information for diagnosing CLI execution issues").option("--log-file <path>","Output logs to a file").option("--man","Show full manual information").option("--schema","Output the command's JSON Schema").option("--commands","Output the list of subcommands"),i.config({help:{errors:[{code:e.ErrorCode.E1100,name:"UNKNOWN_OPTION",desc:"Unknown option provided",fix:"Check parameter spelling or use -h for help",example:"coze <command> -h"},{code:e.ErrorCode.E1101,name:"UNKNOWN_COMMAND",desc:"Unknown subcommand provided",fix:"Check subcommand spelling or use -h for help",example:"coze -h"},{code:e.ErrorCode.E1102,name:"MISSING_ARGUMENT",desc:"Missing required argument",fix:"Provide missing required parameters",example:"coze <command> -h"},{code:e.ErrorCode.E1103,name:"MISSING_OPTION",desc:"Missing required option value",fix:"Provide missing required options",example:"coze <command> -h"}]}}),u_(i),await async function(e){e.completionInstalled||process.stdout.isTTY}(t.config),function(e,t,i){const o=new Set;e.setContext(i),function e(s){o.has(s)||(o.add(s),s.setContext(i),t.forEach(e=>s.use(e)),s.commands.forEach(t=>{const i=__([s,"access",e=>e.getConfig,"optionalCall",e=>e()]),o=__([t,"access",e=>e.getConfig,"optionalCall",e=>e()]);t.setConfig({...i,...o}),e(t)}))}(e)}(i,[Oo,ra],t),process.on("uncaughtException",e=>{K(e,t)}),process.on("unhandledRejection",e=>{K(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")),P_(i);try{await i.parseAsync(t.argv,{from:"user"})}catch(n){const a=function(e,t,i){let o=e;if(t.command)o=t.command;else if(i.commandName){const t=(e,i)=>{if(e.name()===i)return e;for(const o of e.commands){const e=t(o,i);if(e)return e}return null},s=t(e,i.commandName);s&&(o=s)}let s=e;for(const e of i.argv){if(e.startsWith("-"))break;const t=s.commands.find(t=>t.name()===e);t&&(s=t,o=s)}return o}(i,n,t);"commander.helpDisplayed"!==n.code&&"commander.help"!==n.code&&"commander.version"!==n.code||process.exit(e.ExitCode.SUCCESS);const r=S_([a,"optionalAccess",e=>e.getConfig,"optionalCall",e=>e()]),c=S_([i,"optionalAccess",e=>e.getConfig,"optionalCall",e=>e()]);if(t.commandConfig=(s=()=>c,null!=(o=r)?o:s()),"commander.unknownOption"===n.code){const i=V(new e.CozeError(e.ErrorCode.E1100,n.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),process.exit(e.exitCodeForError(i.code))}if("commander.unknownCommand"===n.code){const i=V(new e.CozeError(e.ErrorCode.E1101,n.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),process.exit(e.exitCodeForError(i.code))}if("commander.missingArgument"===n.code){const i=V(new e.CozeError(e.ErrorCode.E1102,n.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),"json"!==t.format&&process.stderr.write(`\n${a.helpInformation()}`),process.exit(e.exitCodeForError(i.code))}if("commander.missingMandatoryOptionValue"===n.code||"commander.optionMissingArgument"===n.code){const i=V(new e.CozeError(e.ErrorCode.E1103,n.message),{argv:t.argv,commandConfig:t.commandConfig});t.response.eprint(i),"json"!==t.format&&process.stderr.write(`\n${a.helpInformation()}`),process.exit(e.exitCodeForError(i.code))}K(n,t)}var o,s}(async function(){const e=process.argv.slice(2),{globalOptions:t}=function(e){const t={};let i;const o=[];let s=!1;for(let n=0;n<e.length;n++){const a=e[n];if("--help"!==a&&"-h"!==a)if("--version"!==a&&"-v"!==a)if("--output"!==a){if("--format"===a){const i=e[++n];"json"!==i&&"text"!==i||(t.format=i);continue}"--no-color"!==a?"--config"!==a?"--org-id"!==a?"--space-id"!==a?"--verbose"!==a?"--debug"!==a?"--log-file"!==a?"--print-logs"!==a?s||a.startsWith("-")?o.push(a):(i=a,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 t.output=e[++n];else t.version=!0;else t.help=!0}return{globalOptions:t,commandName:i,commandArgs:o}}(e),i=function(e){const t=Io(e.cwd,()=>process.cwd()),i=Io(e.env,()=>process.env),o=e.globalOptions||{};o.noColor&&(process.env.NO_COLOR="1");let s="text";o.format&&(s=o.format);const n={...e.config};o.orgId&&(n.organizationId=o.orgId),o.spaceId&&(n.spaceId=o.spaceId);const a=new zo({format:"text",logFile:o.logFile,printToStderr:o.printLogs});let r="info";o.debug?r="debug":o.verbose&&(r="verbose");const c=new Ao(a,s,r),d=new ko({format:s}),p={cwd:t,env:i,argv:e.argv,config:n,format:s,log:a,ui:c,response:d,globalOptions:o,auth:void 0};return p.auth=new co(p),p}({argv:e,config:await te(t.config),globalOptions:t}),o=si([Qt,oi,Zt,pe]);await o(i,async()=>{await E_(i)})})().catch(e=>{K(e,void 0),process.exitCode=1});