@coze/cli 0.2.0-alpha.094e22 → 0.2.0-alpha.7e85f4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";const e=require("./fetch-client-DC0c3ox3.js"),t=require("./index-CkTEdvpA.js"),o=require("chalk"),i=require("node:path"),s=require("node:fs/promises"),n=require("node:os"),r=require("node:fs"),a=require("node:crypto"),c=require("node:child_process"),l=require("./task-worker-C2ZfSQY6.js"),d=require("node:http"),p=require("node:https"),u=require("node:buffer"),m=require("undici"),g=require("path"),h=require("fs/promises"),f=require("fs"),_=require("form-data"),y=require("omelette"),b=require("lodash"),v=require("child_process"),w=require("ws"),C=require("commander");function E(e,t){return null!=e?e:t()}require("crypto"),require("url"),require("http"),require("https"),require("http2"),require("util"),require("stream"),require("assert"),require("tty"),require("zlib"),require("events"),require("mitt"),require("process");class I{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 A(e,t){return null!=e?e:t()}function S(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function j(e){const t=String.fromCharCode(27),o=new RegExp(`${t}(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])`,"g");return e.replace(o,"")}function P(e){return e>=4352&&e<=4447||(9001===e||9002===e||(e>=11904&&e<=12350||(e>=12352&&e<=42191||(e>=44032&&e<=55203||(e>=63744&&e<=64255||(e>=65040&&e<=65049||(e>=65072&&e<=65135||(e>=65280&&e<=65376||(e>=65504&&e<=65510||(e>=127744&&e<=129695||e>=131072&&e<=262141))))))))))}function k(e){const t=j(e);if(!t)return 0;const o=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/u;let i=0;const s=Array.from(t);for(let e=0;e<s.length;e+=1){const t=A(s[e],(()=>""));if(o.test(t))continue;const n=t.codePointAt(0);void 0!==n&&(i+=P(n)?2:1)}return i}function T(e,t){const o=k(e);return o>=t?e:`${e}${" ".repeat(t-o)}`}function z(e,t){if(t<=0)return"";if(k(e)<=t)return e;if(1===t)return"…";const o=j(e),i=Array.from(o),s=Math.max(0,t-k("…"));let n="",r=0;for(let e=0;e<i.length;e+=1){const t=A(i[e],(()=>"")),o=k(t);if(r+o>s)break;n+=t,r+=o}return`${n}…`}function R(e,t={}){if(0===e.length)return"";const o=function(e,t){if(0===e.length)return[];const o=new Set,i=[],s=A(e[0],(()=>({})));for(const e of Object.keys(s))o.has(e)||(o.add(e),i.push(e));for(const t of e)for(const e of Object.keys(t))o.has(e)||(o.add(e),i.push(e));const n=[];for(const t of i){let o=k(t);for(const i of e){const e=i[t],s=void 0===e?"":String(e);o=Math.max(o,k(s))}n.push({key:t,width:o})}const r=A(t.columnGap,(()=>2)),a=A(A(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),c=Math.max(1,Math.floor((a+r)/(6+r))),l=Math.min(A(t.maxColumns,(()=>c)),c);n.length>l&&n.splice(l);const d=Math.max(0,a-r*Math.max(0,n.length-1));for(;n.reduce(((e,t)=>e+t.width),0)>d;){let e=-1,t=-1;for(let o=0;o<n.length;o+=1){const i=A(S([n,"access",e=>e[o],"optionalAccess",e=>e.width]),(()=>0));i>t&&(t=i,e=o)}if(-1===e)break;const o=A(S([n,"access",t=>t[e],"optionalAccess",e=>e.width]),(()=>0));if(o<=6)break;n[e]={...n[e],width:o-1}}for(let e=0;e<n.length;e+=1){const t=n[e];t&&(n[e]={...t,width:Math.max(6,t.width)})}return n}(e,t);if(0===o.length)return"";const i=A(t.columnGap,(()=>2)),s=" ".repeat(i),n=o.map((e=>T(z(e.key,e.width),e.width))).join(s),r=o.map((e=>"-".repeat(e.width))).join(s),a=[];for(const t of e){const e=o.map((e=>{const o=t[e.key];return T(z(void 0===o?"":String(o),e.width),e.width)}));a.push(e.join(s))}return`${[n,r,...a].join("\n")}\n`}function x(e,t={}){const o=Object.entries(e);if(0===o.length)return"";let i=0;for(const[e]of o)i=Math.max(i,k(e));const s=A(A(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),n=A(t.columnGap,(()=>2)),r=A(t.minValueWidth,(()=>12));let a=Math.min(i,A(t.keyMaxWidth,(()=>32)));const c=Math.max(6,s-n-r);a=Math.min(a,c);const l=Math.max(0,s-a-n),d=" ".repeat(n);return`${o.map((([e,t])=>{const o=T(z(e,a),a),i=(void 0===t?"undefined":null===t?"null":String(t)).replace(/\s*\n\s*/g," "),s=l>0?z(i,l):"";return`${o}${d}${s}`})).join("\n")}\n`}function L(e,t="",o=0){const i={};if(null==e)return i;if("object"!=typeof(s=e)||null===s||Array.isArray(s))return i;var s;for(const[s,n]of Object.entries(e)){const e=t?`${t}.${s}`:s;if(null!=n)if(Array.isArray(n))o>=5?i[e]="[Array]":0===n.length?i[e]="[]":n.every((e=>"object"!=typeof e||null===e))?i[e]=n.map((e=>{return String((o=()=>"null",null!=(t=e)?t:o()));var t,o})).join(", "):i[e]="[Array]";else if("object"!=typeof n)i[e]=n;else if(o>=5)i[e]="[Object]";else{const t=L(n,e,o+1);Object.assign(i,t)}else i[e]=n}return i}function O(e,t){return null!=e?e:t()}function D(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class U{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(D)){return R(e.map((e=>L(e))))}return function(e){return Array.isArray(e)&&e.length>0&&e.every((e=>null==e||"object"!=typeof e))}(e)?`${e.map((e=>String(O(e,(()=>"null"))))).join("\n")}\n`:"[Array]\n"}var t;if(D(e)){const t=L(e);return 0===Object.keys(t).length?"{}\n":x(t)}return`${String(e)}\n`}formatError(e){const t=[],o=O(e.errorName,(()=>"UNKNOWN_ERROR")),i=O(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?x(L(e)):String(e))).map((e=>`${t}- ${e.trim()}`)).join("\n")}\n`;if(D(e)){const o=L(e);return 0===Object.keys(o).length?"":`${x(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 B(e,t){return null!=e?e:t()}function q(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function M(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 N(e){const t=q([e,"optionalAccess",e=>e.help,"optionalAccess",e=>e.errors]);if(t&&t.length>0)return t;const o=q([e,"optionalAccess",e=>e.errors]);return Array.isArray(o)?o:void 0}function $(t,o){const i=B(t.trigger,(()=>function(e){if(!e||0===e.length)return;return M(("coze"===e[0]?e:["coze",...e]).join(" "),150)}(q([o,"optionalAccess",e=>e.argv])))),s=q([N,"call",e=>e(q([o,"optionalAccess",e=>e.commandConfig])),"optionalAccess",e=>e.find,"call",e=>e((e=>e.code===t.code))]),n=B(q([s,"optionalAccess",e=>e.name]),(()=>e.ErrorNameByCode[t.code])),r=B(M(n,80),(()=>"UNKNOWN_ERROR"));let a=n;t.isMessageExplicit&&t.message.trim()?a=t.message:q([s,"optionalAccess",e=>e.desc])&&(a=s.desc);const c=B(M(a,200),(()=>"An unexpected error occurred")),l=B(M(t.fix,150),(()=>M(q([s,"optionalAccess",e=>e.fix]),150))),d=B(M(t.example,150),(()=>M(q([s,"optionalAccess",e=>e.example]),150)));return{code:t.code,errorName:r,desc:c,trigger:i,fix:l,example:d}}function G(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 F(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}var V;function W(o,i,s,n){if(o instanceof e.CozeError)throw o;if(e.isHttpError(o)){const e=F([o,"access",e=>e.response,"optionalAccess",e=>e.status]);if("ECONNREFUSED"===o.code||"ETIMEDOUT"===o.code||"number"==typeof e&&e>=500)throw o}if(o instanceof t.ChatCoreError&&"number"==typeof F([o,"access",e=>e.ext,"optionalAccess",e=>e.code])&&o.ext.code>=500)throw o;throw new e.CozeError(i,s,{...n,cause:o instanceof Error?o.message:String(o)})}!function(e){e[e.NOT_LOGIN=700012006]="NOT_LOGIN"}(V||(V={}));const H=(o,i)=>{const s=G(function(o){if(o instanceof e.CozeError)return o;if(o instanceof t.ChatCoreError){const{ext:t}=o;let i=e.ErrorCode.E5000;"number"==typeof t.code&&(t.code===V.NOT_LOGIN?i=e.ErrorCode.E2001:t.code>=500&&(i=e.ErrorCode.E5002));const{message:s}=o;return new e.CozeError(i,s,t)}if(e.isHttpError(o)){const t=o.toJSON();let i=e.ErrorCode.E5000;const s=F([o,"access",e=>e.response,"optionalAccess",e=>e.status]);o.code===V.NOT_LOGIN||401===s?i=e.ErrorCode.E2001:"ECONNREFUSED"===o.code||"ETIMEDOUT"===o.code?i=e.ErrorCode.E5001:403===s?i=e.ErrorCode.E2003:404===s?i=e.ErrorCode.E3000:429===s?i=e.ErrorCode.E4001:s&&s>=500&&(i=e.ErrorCode.E5002);const n=F([o,"access",e=>e.response,"optionalAccess",e=>e.headers,"optionalAccess",e=>e["x-tt-logid"]]),{message:r}=o;return new e.CozeError(i,r,{logId:n,...t})}return o instanceof Error?new e.CozeError(e.ErrorCode.E5000,o.message,o.stack):"string"==typeof o?new e.CozeError(e.ErrorCode.E5000,o):new e.CozeError(e.ErrorCode.E5000,"An unexpected error occurred")}(o),i?{argv:i.argv,commandConfig:i.commandConfig}:void 0);var n,r;if(s.code===e.ErrorCode.E2001&&process.stdout.write(`${n=s.desc,r=()=>s.message,null!=n?n:r()}\n`),i)i.response.eprint(s);else{const e=new U;process.stderr.write(e.formatError(s))}process.exit(e.exitCodeForError(s.code))};async function J(e){try{return(await s.stat(e)).isDirectory()}catch(e){return!1}}async function K(e){for(const t of e)if(await J(t))return!0;return!1}const Q=()=>n.homedir(),Y=(...e)=>()=>i.join(Q(),...e),Z=(...e)=>()=>i.join(Q(),".config",...e);function X(e,t,o){return{name:e,get skillsDir(){return t()},detect:()=>K(o.map((e=>e())))}}const ee=[X("antigravity",Y(".gemini","antigravity","skills"),[Y(".gemini","antigravity")]),X("cortex",Y(".snowflake","cortex","skills"),[Y(".snowflake","cortex")]),X("deepagents",Y(".deepagents","agent","skills"),[Y(".deepagents")]),X("github-copilot",Y(".copilot","skills"),[Y(".copilot")]),X("pi",Y(".pi","agent","skills"),[Y(".pi","agent")]),X("tabnine-cli",Y(".tabnine","agent","skills"),[Y(".tabnine")]),X("windsurf",Y(".codeium","windsurf","skills"),[Y(".codeium","windsurf")]),X("kimi-cli",Z("agents","skills"),[Y(".kimi")]),X("amp",Z("agents","skills"),[Z("amp")]),X("crush",Z("crush","skills"),[Z("crush")]),X("devin",Z("devin","skills"),[Z("devin")]),X("goose",Z("goose","skills"),[Z("goose")]),X("opencode",Z("opencode","skills"),[Z("opencode")]),X("cline",Y(".agents","skills"),[Y(".cline")]),X("dexto",Y(".agents","skills"),[Y(".dexto")]),X("warp",Y(".agents","skills"),[Y(".warp")]),X("zed",Y(".agents","skills"),[Z("zed")]),function(){const e=[".openclaw",".clawdbot",".moltbot"];return{name:"openclaw",get skillsDir(){return i.join((()=>{const t=e.find((e=>r.existsSync(i.join(Q(),e))));return i.join(Q(),(s=()=>e[0],null!=(o=t)?o:s()));var o,s})(),"skills")},detect:()=>K(e.map((e=>i.join(Q(),e))))}}()],te=[...[["claude",".claude"],["trae",".trae"],["trae-cn",".trae-cn"],["comate",".comate"],["cursor",".cursor"],["augment",".augment"],["bob",".bob"],["aider-desk",".aider-desk"],["codebuddy",".codebuddy"],["codemaker",".codemaker"],["codestudio",".codestudio"],["codearts-agent",".codeartsdoer"],["command-code",".commandcode"],["continue",".continue"],["forgecode",".forge"],["droid",".factory"],["gemini-cli",".gemini"],["firebender",".firebender"],["hermes-agent",".hermes"],["junie",".junie"],["iflow-cli",".iflow"],["kilo",".kilocode"],["kiro-cli",".kiro"],["kode",".kode"],["mcpjam",".mcpjam"],["mux",".mux"],["openhands",".openhands"],["qoder",".qoder"],["qwen-code",".qwen"],["rovodev",".rovodev"],["roo",".roo"],["zencoder",".zencoder"],["neovate",".neovate"],["pochi",".pochi"],["adal",".adal"]].map((([e,t])=>X(e,Y(t,"skills"),[Y(t)]))),...ee];function oe(e){return te.find((t=>t.name===e))}function ie(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function se(){return i.join(n.homedir(),".coze","skills")}function ne(){return i.join(n.homedir(),".coze",".skill-lock.json")}async function re(e){try{return await s.access(e),!0}catch(e){return!1}}async function ae(){let t=__dirname;for(let o=0;o<12;o++){const o=i.join(t,"package.json");if(await re(o)){if("@coze/cli"===ie([e.safeJsonParse(await s.readFile(o,"utf8")),"optionalAccess",e=>e.name]))return t}const n=i.dirname(t);if(n===t)break;t=n}return i.resolve(__dirname,"..")}const ce=new Set(["SKILL.md","MODULE.md"]);function le(e){return`sha256:${a.createHash("sha256").update(e,"utf8").digest("hex")}`}function de(e){return ce.has(i.basename(e))}async function pe(e,t=e){const o=await s.readdir(e,{withFileTypes:!0}),n=[];for(const s of o){if(s.name.startsWith("."))continue;const o=i.join(e,s.name);s.isDirectory()?n.push(...await pe(o,t)):s.isFile()&&n.push(i.relative(t,o).split(i.sep).join("/"))}return n.sort()}function ue(e,t){const o=ge(e);if(void 0===o)return;const i=new RegExp(`^${t}:\\s*(.+?)\\s*$`,"m"),s=o.match(i);return s?s[1].replace(/^['"]|['"]$/g,"").trim():void 0}function me(e,t){const o=ge(e);if(void 0===o)return e;const i=`version: ${t}`;let s;return s=/^version:\s*.+$/m.test(o)?o.replace(/^version:\s*.+$/m,i):/^name:\s*.+$/m.test(o)?o.replace(/^(name:\s*.+)$/m,`$1\n${i}`):`${i}\n${o}`,e.replace(o,s)}function ge(e){if(!e.startsWith("---"))return;const t=e.match(/^---\n([\s\S]*?)\n---/);return t?t[1]:void 0}function he(e){const t=new Set;for(const o of e){const e=o.rel.split("/")[0];e&&t.add(e)}return[...t].sort()}async function fe(){const t=await async function(){return i.join(await ae(),"skills")}(),o=i.join(t,"manifest.json");if(await re(o)){const n=e.safeJsonParse(await s.readFile(o,"utf8")),r=(await pe(t)).filter((e=>"manifest.json"!==e)),a=[];for(const e of r)a.push({rel:e,content:await s.readFile(i.join(t,e),"utf8")});return{manifest:n,files:a,source:"bundled"}}const n=await async function(){return i.join(await ae(),"docs","skills")}();if(!await re(n))throw new Error(`未找到 skill 来源:既无包内 ${o},也无开发态 ${n}。`);const r=await async function(){const t=i.join(await ae(),"package.json"),o=e.safeJsonParse(await s.readFile(t,"utf8"));return n=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([o,"optionalAccess",e=>e.version]),r=()=>"0.0.0",null!=n?n:r();var n,r}(),{manifest:a,files:c}=await async function(e,t){const o=await pe(e),n=[],r={};for(const l of o){const o=await s.readFile(i.join(e,l),"utf8"),d=de(l),p=d?me(o,t):o;n.push({rel:l,content:p}),d&&(r[(a=ue(p,"name"),c=()=>l,null!=a?a:c())]={path:l,hash:le(p)})}var a,c;return{manifest:{cliVersion:t,skills:r},files:n}}(n,r);return{manifest:a,files:c,source:"docs"}}async function _e(){try{const t=await s.readFile(ne(),"utf8");return e.safeJsonParse(t)}catch(e){return}}function ye(e,t){return null!=e?e:t()}function be(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function ve(e){try{return le(await s.readFile(e,"utf8"))}catch(e){return}}async function we(e){try{return await s.lstat(e)}catch(e){return null}}async function Ce(e,t,o,n){const r=i.join(t,e),a=i.join(o.skillsDir,e);await s.mkdir(o.skillsDir,{recursive:!0});const c=await we(a);if(c)if(c.isSymbolicLink())await s.rm(a,{force:!0});else{if(!n)return`已存在非软链的 ${a}(用户定制?),使用 --force 覆盖`;await s.rm(a,{recursive:!0,force:!0})}return await s.symlink(r,a,"dir"),"linked"}async function Ee(e={}){const{manifest:t,files:o}=await fe(),n=se(),r=await _e(),a=await async function(e,t,o){const s=[];for(const[n,r]of Object.entries(e.skills)){const e=await ve(i.join(t,r.path));if(void 0===e)continue;if(e===r.hash)continue;const a=be([o,"optionalAccess",e=>e.skills,"access",e=>e[n],"optionalAccess",e=>e.hash]);void 0!==a&&e===a||s.push(n)}return s}(t,n,r);if(a.length>0&&!e.force)return{blocked:!0,cliVersion:t.cliVersion,neutralDir:n,linkedTargets:[],skipped:[],unknownTargets:[],modifiedSkills:a};await async function(e,t){const o=he(t);for(const t of o)await s.rm(i.join(e,t),{recursive:!0,force:!0});for(const o of t){const t=i.join(e,o.rel);await s.mkdir(i.dirname(t),{recursive:!0}),await s.writeFile(t,o.content,"utf8")}}(n,o);const{targets:c,unknown:l}=await async function(e){if(!e||0===e.length||e.includes("all")){const e=[];for(const t of te)await t.detect()&&e.push(t);return{targets:e,unknown:[]}}const t=[],o=[];for(const i of e){const e=oe(i);e?t.push(e):o.push(i)}return{targets:t,unknown:o}}(e.targets),d=he(o),p=[],u=[];for(const t of c){const o=[];for(const i of d){const s=await Ce(i,n,t,ye(e.force,(()=>!1)));"linked"!==s&&o.push(s)}0===o.length?p.push(t.name):u.push({target:t.name,reason:o.join("; ")})}const m=(new Date).toISOString(),g={};for(const[e,o]of Object.entries(t.skills))g[e]={hash:o.hash,expectedHash:o.hash,installedAt:m};return await async function(e){const t=ne();await s.mkdir(i.dirname(t),{recursive:!0}),await s.writeFile(t,`${JSON.stringify(e,null,2)}\n`,"utf8")}({version:1,cliVersion:t.cliVersion,installedBin:ye(process.argv[1],(()=>process.execPath)),targets:p,skills:g}),{blocked:!1,cliVersion:t.cliVersion,neutralDir:n,linkedTargets:p,skipped:u,unknownTargets:l,modifiedSkills:[]}}async function Ie(){const e=se(),t=[];let o=[];try{o=(await s.readdir(e,{withFileTypes:!0})).filter((e=>!e.name.startsWith("."))).map((e=>e.name))}catch(e){o=[]}for(const n of te)for(const r of o){const o=i.join(n.skillsDir,r),a=await we(o);if(!a||!a.isSymbolicLink())continue;const c=await s.readlink(o).catch((()=>null));if(null===c)continue;i.resolve(n.skillsDir,c).startsWith(e)&&(await s.rm(o,{force:!0}),t.push({target:n.name,unit:r}))}return await s.rm(e,{recursive:!0,force:!0}),await async function(){await s.rm(ne(),{force:!0})}(),{neutralDir:e,unlinked:t}}const Ae="0.2.0-alpha.094e22",Se="@coze/cli";function je(){return Ae}function Pe(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),s=o(t);return s.major!==i.major?s.major>i.major:s.minor!==i.minor?s.minor>i.minor:s.patch>i.patch}async function ke(t,o=!1,i="latest"){const s=je(),{config:n}=t;if(!o&&n.latestVersion&&n.lastCheckTime&&Date.now()-n.lastCheckTime<864e5)return{currentVersion:s,latestVersion:n.latestVersion,hasUpdate:Pe(s,n.latestVersion)};const r=function(){try{return c.execSync("npm config get registry",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim().replace(/\/+$/,"")}catch(e){return"https://registry.npmjs.org"}}(),a=await async function(t,o="latest"){const i=`${t}/${Se}/${o}`,s=await e.customFetch.fetch(i,{headers:{accept:"application/json"}});if(!s.ok)throw new Error(`Failed to fetch latest version: ${s.status} ${s.statusText}`);return(await s.json()).version}(r,i);return await l.saveConfig({latestVersion:a,lastCheckTime:Date.now()},n.configScope),{currentVersion:s,latestVersion:a,hasUpdate:Pe(s,a)}}async function Te(e,t){if(await t(),!0===e.config.autoCheckUpdate)try{const t=await ke(e);if(t.hasUpdate){const i=`\nUpdate available: ${o.gray(t.currentVersion)} → ${o.green(t.latestVersion)}\nRun ${o.cyan("coze upgrade")} to update\n`;e.ui.info(i)}}catch(e){}await async function(e){if("guide"===e.argv[0])return;try{const t=await async function(){const{manifest:e}=await fe(),{cliVersion:t}=e,o=await _e();return o?o.cliVersion!==t?{state:"mismatch",cliVersion:t,installedVersion:o.cliVersion,message:`Skills (${o.cliVersion}) are out of sync with CLI (${t}). Run \`coze guide sync\`.`}:{state:"ok",cliVersion:t,installedVersion:o.cliVersion}:{state:"missing",cliVersion:t,message:"Bundled skills not installed yet. Run `coze guide sync` to sync them to your AI tools."}}();if("ok"===t.state)return;const o=e.config.autoSyncSkill,i=!0===o||"true"===o;if("mismatch"===t.state&&i){const e=await async function(e){if("mismatch"!==e.state)return!1;try{return!(await Ee({})).blocked}catch(e){return!1}}(t);if(e)return}t.message&&e.ui.info(`\n${t.message}\n`)}catch(e){}}(e)}var ze=e.requireSrc();const Re=e.getDefaultExportFromCjs(ze);function xe(e){var t,o,i=e.transport,s=e.endpoint,n=e.size,r=void 0===n?10:n,a=e.wait,c=void 0===a?1e3:a,l=[],d=0;function p(){if(l.length){var e=this.getBatchData();i.post({url:s,data:e,fail:function(o){t&&t(o,e)},success:function(){o&&o(e)}}),l=[]}}return{getSize:function(){return r},getWait:function(){return c},setSize:function(e){r=e},setWait:function(e){c=e},getEndpoint:function(){return s},setEndpoint:function(e){s=e},send:function(e){l.push(e),l.length>=r&&p.call(this),clearTimeout(d),d=setTimeout(p.bind(this),c)},flush:function(){clearTimeout(d),p.call(this)},getBatchData:function(){return l.length?(e=l,JSON.stringify({ev_type:"batch",list:e})):"";var e},clear:function(){clearTimeout(d),l=[]},fail:function(e){t=e},success:function(e){o=e}}}
2
+ "use strict";const e=require("./fetch-client-DC0c3ox3.js"),t=require("./index-DNmOe3vH.js"),o=require("chalk"),i=require("node:path"),s=require("node:fs/promises"),n=require("node:os"),r=require("node:fs"),a=require("node:crypto"),c=require("node:child_process"),l=require("./task-worker-C2ZfSQY6.js"),d=require("node:http"),p=require("node:https"),u=require("node:buffer"),m=require("undici"),g=require("path"),h=require("fs/promises"),f=require("fs"),_=require("form-data"),y=require("omelette"),b=require("lodash"),v=require("child_process"),w=require("ws"),C=require("commander");function E(e,t){return null!=e?e:t()}require("crypto"),require("url"),require("http"),require("https"),require("http2"),require("util"),require("stream"),require("assert"),require("tty"),require("zlib"),require("events"),require("mitt"),require("process");class I{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 A(e,t){return null!=e?e:t()}function S(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function j(e){const t=String.fromCharCode(27),o=new RegExp(`${t}(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])`,"g");return e.replace(o,"")}function P(e){return e>=4352&&e<=4447||(9001===e||9002===e||(e>=11904&&e<=12350||(e>=12352&&e<=42191||(e>=44032&&e<=55203||(e>=63744&&e<=64255||(e>=65040&&e<=65049||(e>=65072&&e<=65135||(e>=65280&&e<=65376||(e>=65504&&e<=65510||(e>=127744&&e<=129695||e>=131072&&e<=262141))))))))))}function k(e){const t=j(e);if(!t)return 0;const o=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/u;let i=0;const s=Array.from(t);for(let e=0;e<s.length;e+=1){const t=A(s[e],(()=>""));if(o.test(t))continue;const n=t.codePointAt(0);void 0!==n&&(i+=P(n)?2:1)}return i}function T(e,t){const o=k(e);return o>=t?e:`${e}${" ".repeat(t-o)}`}function z(e,t){if(t<=0)return"";if(k(e)<=t)return e;if(1===t)return"…";const o=j(e),i=Array.from(o),s=Math.max(0,t-k("…"));let n="",r=0;for(let e=0;e<i.length;e+=1){const t=A(i[e],(()=>"")),o=k(t);if(r+o>s)break;n+=t,r+=o}return`${n}…`}function R(e,t={}){if(0===e.length)return"";const o=function(e,t){if(0===e.length)return[];const o=new Set,i=[],s=A(e[0],(()=>({})));for(const e of Object.keys(s))o.has(e)||(o.add(e),i.push(e));for(const t of e)for(const e of Object.keys(t))o.has(e)||(o.add(e),i.push(e));const n=[];for(const t of i){let o=k(t);for(const i of e){const e=i[t],s=void 0===e?"":String(e);o=Math.max(o,k(s))}n.push({key:t,width:o})}const r=A(t.columnGap,(()=>2)),a=A(A(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),c=Math.max(1,Math.floor((a+r)/(6+r))),l=Math.min(A(t.maxColumns,(()=>c)),c);n.length>l&&n.splice(l);const d=Math.max(0,a-r*Math.max(0,n.length-1));for(;n.reduce(((e,t)=>e+t.width),0)>d;){let e=-1,t=-1;for(let o=0;o<n.length;o+=1){const i=A(S([n,"access",e=>e[o],"optionalAccess",e=>e.width]),(()=>0));i>t&&(t=i,e=o)}if(-1===e)break;const o=A(S([n,"access",t=>t[e],"optionalAccess",e=>e.width]),(()=>0));if(o<=6)break;n[e]={...n[e],width:o-1}}for(let e=0;e<n.length;e+=1){const t=n[e];t&&(n[e]={...t,width:Math.max(6,t.width)})}return n}(e,t);if(0===o.length)return"";const i=A(t.columnGap,(()=>2)),s=" ".repeat(i),n=o.map((e=>T(z(e.key,e.width),e.width))).join(s),r=o.map((e=>"-".repeat(e.width))).join(s),a=[];for(const t of e){const e=o.map((e=>{const o=t[e.key];return T(z(void 0===o?"":String(o),e.width),e.width)}));a.push(e.join(s))}return`${[n,r,...a].join("\n")}\n`}function x(e,t={}){const o=Object.entries(e);if(0===o.length)return"";let i=0;for(const[e]of o)i=Math.max(i,k(e));const s=A(A(t.maxWidth,(()=>process.stdout.columns)),(()=>120)),n=A(t.columnGap,(()=>2)),r=A(t.minValueWidth,(()=>12));let a=Math.min(i,A(t.keyMaxWidth,(()=>32)));const c=Math.max(6,s-n-r);a=Math.min(a,c);const l=Math.max(0,s-a-n),d=" ".repeat(n);return`${o.map((([e,t])=>{const o=T(z(e,a),a),i=(void 0===t?"undefined":null===t?"null":String(t)).replace(/\s*\n\s*/g," "),s=l>0?z(i,l):"";return`${o}${d}${s}`})).join("\n")}\n`}function L(e,t="",o=0){const i={};if(null==e)return i;if("object"!=typeof(s=e)||null===s||Array.isArray(s))return i;var s;for(const[s,n]of Object.entries(e)){const e=t?`${t}.${s}`:s;if(null!=n)if(Array.isArray(n))o>=5?i[e]="[Array]":0===n.length?i[e]="[]":n.every((e=>"object"!=typeof e||null===e))?i[e]=n.map((e=>{return String((o=()=>"null",null!=(t=e)?t:o()));var t,o})).join(", "):i[e]="[Array]";else if("object"!=typeof n)i[e]=n;else if(o>=5)i[e]="[Object]";else{const t=L(n,e,o+1);Object.assign(i,t)}else i[e]=n}return i}function O(e,t){return null!=e?e:t()}function D(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class U{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(D)){return R(e.map((e=>L(e))))}return function(e){return Array.isArray(e)&&e.length>0&&e.every((e=>null==e||"object"!=typeof e))}(e)?`${e.map((e=>String(O(e,(()=>"null"))))).join("\n")}\n`:"[Array]\n"}var t;if(D(e)){const t=L(e);return 0===Object.keys(t).length?"{}\n":x(t)}return`${String(e)}\n`}formatError(e){const t=[],o=O(e.errorName,(()=>"UNKNOWN_ERROR")),i=O(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?x(L(e)):String(e))).map((e=>`${t}- ${e.trim()}`)).join("\n")}\n`;if(D(e)){const o=L(e);return 0===Object.keys(o).length?"":`${x(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 B(e,t){return null!=e?e:t()}function q(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function M(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 N(e){const t=q([e,"optionalAccess",e=>e.help,"optionalAccess",e=>e.errors]);if(t&&t.length>0)return t;const o=q([e,"optionalAccess",e=>e.errors]);return Array.isArray(o)?o:void 0}function $(t,o){const i=B(t.trigger,(()=>function(e){if(!e||0===e.length)return;return M(("coze"===e[0]?e:["coze",...e]).join(" "),150)}(q([o,"optionalAccess",e=>e.argv])))),s=q([N,"call",e=>e(q([o,"optionalAccess",e=>e.commandConfig])),"optionalAccess",e=>e.find,"call",e=>e((e=>e.code===t.code))]),n=B(q([s,"optionalAccess",e=>e.name]),(()=>e.ErrorNameByCode[t.code])),r=B(M(n,80),(()=>"UNKNOWN_ERROR"));let a=n;t.isMessageExplicit&&t.message.trim()?a=t.message:q([s,"optionalAccess",e=>e.desc])&&(a=s.desc);const c=B(M(a,200),(()=>"An unexpected error occurred")),l=B(M(t.fix,150),(()=>M(q([s,"optionalAccess",e=>e.fix]),150))),d=B(M(t.example,150),(()=>M(q([s,"optionalAccess",e=>e.example]),150)));return{code:t.code,errorName:r,desc:c,trigger:i,fix:l,example:d}}function G(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 F(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}var V;function W(o,i,s,n){if(o instanceof e.CozeError)throw o;if(e.isHttpError(o)){const e=F([o,"access",e=>e.response,"optionalAccess",e=>e.status]);if("ECONNREFUSED"===o.code||"ETIMEDOUT"===o.code||"number"==typeof e&&e>=500)throw o}if(o instanceof t.ChatCoreError&&"number"==typeof F([o,"access",e=>e.ext,"optionalAccess",e=>e.code])&&o.ext.code>=500)throw o;throw new e.CozeError(i,s,{...n,cause:o instanceof Error?o.message:String(o)})}!function(e){e[e.NOT_LOGIN=700012006]="NOT_LOGIN"}(V||(V={}));const H=(o,i)=>{const s=G(function(o){if(o instanceof e.CozeError)return o;if(o instanceof t.ChatCoreError){const{ext:t}=o;let i=e.ErrorCode.E5000;"number"==typeof t.code&&(t.code===V.NOT_LOGIN?i=e.ErrorCode.E2001:t.code>=500&&(i=e.ErrorCode.E5002));const{message:s}=o;return new e.CozeError(i,s,t)}if(e.isHttpError(o)){const t=o.toJSON();let i=e.ErrorCode.E5000;const s=F([o,"access",e=>e.response,"optionalAccess",e=>e.status]);o.code===V.NOT_LOGIN||401===s?i=e.ErrorCode.E2001:"ECONNREFUSED"===o.code||"ETIMEDOUT"===o.code?i=e.ErrorCode.E5001:403===s?i=e.ErrorCode.E2003:404===s?i=e.ErrorCode.E3000:429===s?i=e.ErrorCode.E4001:s&&s>=500&&(i=e.ErrorCode.E5002);const n=F([o,"access",e=>e.response,"optionalAccess",e=>e.headers,"optionalAccess",e=>e["x-tt-logid"]]),{message:r}=o;return new e.CozeError(i,r,{logId:n,...t})}return o instanceof Error?new e.CozeError(e.ErrorCode.E5000,o.message,o.stack):"string"==typeof o?new e.CozeError(e.ErrorCode.E5000,o):new e.CozeError(e.ErrorCode.E5000,"An unexpected error occurred")}(o),i?{argv:i.argv,commandConfig:i.commandConfig}:void 0);var n,r;if(s.code===e.ErrorCode.E2001&&process.stdout.write(`${n=s.desc,r=()=>s.message,null!=n?n:r()}\n`),i)i.response.eprint(s);else{const e=new U;process.stderr.write(e.formatError(s))}process.exit(e.exitCodeForError(s.code))};async function J(e){try{return(await s.stat(e)).isDirectory()}catch(e){return!1}}async function K(e){for(const t of e)if(await J(t))return!0;return!1}const Q=()=>n.homedir(),Y=(...e)=>()=>i.join(Q(),...e),Z=(...e)=>()=>i.join(Q(),".config",...e);function X(e,t,o){return{name:e,get skillsDir(){return t()},detect:()=>K(o.map((e=>e())))}}const ee=[X("antigravity",Y(".gemini","antigravity","skills"),[Y(".gemini","antigravity")]),X("cortex",Y(".snowflake","cortex","skills"),[Y(".snowflake","cortex")]),X("deepagents",Y(".deepagents","agent","skills"),[Y(".deepagents")]),X("github-copilot",Y(".copilot","skills"),[Y(".copilot")]),X("pi",Y(".pi","agent","skills"),[Y(".pi","agent")]),X("tabnine-cli",Y(".tabnine","agent","skills"),[Y(".tabnine")]),X("windsurf",Y(".codeium","windsurf","skills"),[Y(".codeium","windsurf")]),X("kimi-cli",Z("agents","skills"),[Y(".kimi")]),X("amp",Z("agents","skills"),[Z("amp")]),X("crush",Z("crush","skills"),[Z("crush")]),X("devin",Z("devin","skills"),[Z("devin")]),X("goose",Z("goose","skills"),[Z("goose")]),X("opencode",Z("opencode","skills"),[Z("opencode")]),X("cline",Y(".agents","skills"),[Y(".cline")]),X("dexto",Y(".agents","skills"),[Y(".dexto")]),X("warp",Y(".agents","skills"),[Y(".warp")]),X("zed",Y(".agents","skills"),[Z("zed")]),function(){const e=[".openclaw",".clawdbot",".moltbot"];return{name:"openclaw",get skillsDir(){return i.join((()=>{const t=e.find((e=>r.existsSync(i.join(Q(),e))));return i.join(Q(),(s=()=>e[0],null!=(o=t)?o:s()));var o,s})(),"skills")},detect:()=>K(e.map((e=>i.join(Q(),e))))}}()],te=[...[["claude",".claude"],["trae",".trae"],["trae-cn",".trae-cn"],["comate",".comate"],["cursor",".cursor"],["augment",".augment"],["bob",".bob"],["aider-desk",".aider-desk"],["codebuddy",".codebuddy"],["codemaker",".codemaker"],["codestudio",".codestudio"],["codearts-agent",".codeartsdoer"],["command-code",".commandcode"],["continue",".continue"],["forgecode",".forge"],["droid",".factory"],["gemini-cli",".gemini"],["firebender",".firebender"],["hermes-agent",".hermes"],["junie",".junie"],["iflow-cli",".iflow"],["kilo",".kilocode"],["kiro-cli",".kiro"],["kode",".kode"],["mcpjam",".mcpjam"],["mux",".mux"],["openhands",".openhands"],["qoder",".qoder"],["qwen-code",".qwen"],["rovodev",".rovodev"],["roo",".roo"],["zencoder",".zencoder"],["neovate",".neovate"],["pochi",".pochi"],["adal",".adal"]].map((([e,t])=>X(e,Y(t,"skills"),[Y(t)]))),...ee];function oe(e){return te.find((t=>t.name===e))}function ie(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function se(){return i.join(n.homedir(),".coze","skills")}function ne(){return i.join(n.homedir(),".coze",".skill-lock.json")}async function re(e){try{return await s.access(e),!0}catch(e){return!1}}async function ae(){let t=__dirname;for(let o=0;o<12;o++){const o=i.join(t,"package.json");if(await re(o)){if("@coze/cli"===ie([e.safeJsonParse(await s.readFile(o,"utf8")),"optionalAccess",e=>e.name]))return t}const n=i.dirname(t);if(n===t)break;t=n}return i.resolve(__dirname,"..")}const ce=new Set(["SKILL.md","MODULE.md"]);function le(e){return`sha256:${a.createHash("sha256").update(e,"utf8").digest("hex")}`}function de(e){return ce.has(i.basename(e))}async function pe(e,t=e){const o=await s.readdir(e,{withFileTypes:!0}),n=[];for(const s of o){if(s.name.startsWith("."))continue;const o=i.join(e,s.name);s.isDirectory()?n.push(...await pe(o,t)):s.isFile()&&n.push(i.relative(t,o).split(i.sep).join("/"))}return n.sort()}function ue(e,t){const o=ge(e);if(void 0===o)return;const i=new RegExp(`^${t}:\\s*(.+?)\\s*$`,"m"),s=o.match(i);return s?s[1].replace(/^['"]|['"]$/g,"").trim():void 0}function me(e,t){const o=ge(e);if(void 0===o)return e;const i=`version: ${t}`;let s;return s=/^version:\s*.+$/m.test(o)?o.replace(/^version:\s*.+$/m,i):/^name:\s*.+$/m.test(o)?o.replace(/^(name:\s*.+)$/m,`$1\n${i}`):`${i}\n${o}`,e.replace(o,s)}function ge(e){if(!e.startsWith("---"))return;const t=e.match(/^---\n([\s\S]*?)\n---/);return t?t[1]:void 0}function he(e){const t=new Set;for(const o of e){const e=o.rel.split("/")[0];e&&t.add(e)}return[...t].sort()}async function fe(){const t=await async function(){return i.join(await ae(),"skills")}(),o=i.join(t,"manifest.json");if(await re(o)){const n=e.safeJsonParse(await s.readFile(o,"utf8")),r=(await pe(t)).filter((e=>"manifest.json"!==e)),a=[];for(const e of r)a.push({rel:e,content:await s.readFile(i.join(t,e),"utf8")});return{manifest:n,files:a,source:"bundled"}}const n=await async function(){return i.join(await ae(),"docs","skills")}();if(!await re(n))throw new Error(`未找到 skill 来源:既无包内 ${o},也无开发态 ${n}。`);const r=await async function(){const t=i.join(await ae(),"package.json"),o=e.safeJsonParse(await s.readFile(t,"utf8"));return n=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([o,"optionalAccess",e=>e.version]),r=()=>"0.0.0",null!=n?n:r();var n,r}(),{manifest:a,files:c}=await async function(e,t){const o=await pe(e),n=[],r={};for(const l of o){const o=await s.readFile(i.join(e,l),"utf8"),d=de(l),p=d?me(o,t):o;n.push({rel:l,content:p}),d&&(r[(a=ue(p,"name"),c=()=>l,null!=a?a:c())]={path:l,hash:le(p)})}var a,c;return{manifest:{cliVersion:t,skills:r},files:n}}(n,r);return{manifest:a,files:c,source:"docs"}}async function _e(){try{const t=await s.readFile(ne(),"utf8");return e.safeJsonParse(t)}catch(e){return}}function ye(e,t){return null!=e?e:t()}function be(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function ve(e){try{return le(await s.readFile(e,"utf8"))}catch(e){return}}async function we(e){try{return await s.lstat(e)}catch(e){return null}}async function Ce(e,t,o,n){const r=i.join(t,e),a=i.join(o.skillsDir,e);await s.mkdir(o.skillsDir,{recursive:!0});const c=await we(a);if(c)if(c.isSymbolicLink())await s.rm(a,{force:!0});else{if(!n)return`已存在非软链的 ${a}(用户定制?),使用 --force 覆盖`;await s.rm(a,{recursive:!0,force:!0})}return await s.symlink(r,a,"dir"),"linked"}async function Ee(e={}){const{manifest:t,files:o}=await fe(),n=se(),r=await _e(),a=await async function(e,t,o){const s=[];for(const[n,r]of Object.entries(e.skills)){const e=await ve(i.join(t,r.path));if(void 0===e)continue;if(e===r.hash)continue;const a=be([o,"optionalAccess",e=>e.skills,"access",e=>e[n],"optionalAccess",e=>e.hash]);void 0!==a&&e===a||s.push(n)}return s}(t,n,r);if(a.length>0&&!e.force)return{blocked:!0,cliVersion:t.cliVersion,neutralDir:n,linkedTargets:[],skipped:[],unknownTargets:[],modifiedSkills:a};await async function(e,t){const o=he(t);for(const t of o)await s.rm(i.join(e,t),{recursive:!0,force:!0});for(const o of t){const t=i.join(e,o.rel);await s.mkdir(i.dirname(t),{recursive:!0}),await s.writeFile(t,o.content,"utf8")}}(n,o);const{targets:c,unknown:l}=await async function(e){if(!e||0===e.length||e.includes("all")){const e=[];for(const t of te)await t.detect()&&e.push(t);return{targets:e,unknown:[]}}const t=[],o=[];for(const i of e){const e=oe(i);e?t.push(e):o.push(i)}return{targets:t,unknown:o}}(e.targets),d=he(o),p=[],u=[];for(const t of c){const o=[];for(const i of d){const s=await Ce(i,n,t,ye(e.force,(()=>!1)));"linked"!==s&&o.push(s)}0===o.length?p.push(t.name):u.push({target:t.name,reason:o.join("; ")})}const m=(new Date).toISOString(),g={};for(const[e,o]of Object.entries(t.skills))g[e]={hash:o.hash,expectedHash:o.hash,installedAt:m};return await async function(e){const t=ne();await s.mkdir(i.dirname(t),{recursive:!0}),await s.writeFile(t,`${JSON.stringify(e,null,2)}\n`,"utf8")}({version:1,cliVersion:t.cliVersion,installedBin:ye(process.argv[1],(()=>process.execPath)),targets:p,skills:g}),{blocked:!1,cliVersion:t.cliVersion,neutralDir:n,linkedTargets:p,skipped:u,unknownTargets:l,modifiedSkills:[]}}async function Ie(){const e=se(),t=[];let o=[];try{o=(await s.readdir(e,{withFileTypes:!0})).filter((e=>!e.name.startsWith("."))).map((e=>e.name))}catch(e){o=[]}for(const n of te)for(const r of o){const o=i.join(n.skillsDir,r),a=await we(o);if(!a||!a.isSymbolicLink())continue;const c=await s.readlink(o).catch((()=>null));if(null===c)continue;i.resolve(n.skillsDir,c).startsWith(e)&&(await s.rm(o,{force:!0}),t.push({target:n.name,unit:r}))}return await s.rm(e,{recursive:!0,force:!0}),await async function(){await s.rm(ne(),{force:!0})}(),{neutralDir:e,unlinked:t}}const Ae="0.2.0-alpha.7e85f4",Se="@coze/cli";function je(){return Ae}function Pe(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),s=o(t);return s.major!==i.major?s.major>i.major:s.minor!==i.minor?s.minor>i.minor:s.patch>i.patch}async function ke(t,o=!1,i="latest"){const s=je(),{config:n}=t;if(!o&&n.latestVersion&&n.lastCheckTime&&Date.now()-n.lastCheckTime<864e5)return{currentVersion:s,latestVersion:n.latestVersion,hasUpdate:Pe(s,n.latestVersion)};const r=function(){try{return c.execSync("npm config get registry",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim().replace(/\/+$/,"")}catch(e){return"https://registry.npmjs.org"}}(),a=await async function(t,o="latest"){const i=`${t}/${Se}/${o}`,s=await e.customFetch.fetch(i,{headers:{accept:"application/json"}});if(!s.ok)throw new Error(`Failed to fetch latest version: ${s.status} ${s.statusText}`);return(await s.json()).version}(r,i);return await l.saveConfig({latestVersion:a,lastCheckTime:Date.now()},n.configScope),{currentVersion:s,latestVersion:a,hasUpdate:Pe(s,a)}}async function Te(e,t){if(await t(),!0===e.config.autoCheckUpdate)try{const t=await ke(e);if(t.hasUpdate){const i=`\nUpdate available: ${o.gray(t.currentVersion)} → ${o.green(t.latestVersion)}\nRun ${o.cyan("coze upgrade")} to update\n`;e.ui.info(i)}}catch(e){}await async function(e){if("guide"===e.argv[0])return;try{const t=await async function(){const{manifest:e}=await fe(),{cliVersion:t}=e,o=await _e();return o?o.cliVersion!==t?{state:"mismatch",cliVersion:t,installedVersion:o.cliVersion,message:`Skills (${o.cliVersion}) are out of sync with CLI (${t}). Run \`coze guide sync\`.`}:{state:"ok",cliVersion:t,installedVersion:o.cliVersion}:{state:"missing",cliVersion:t,message:"Bundled skills not installed yet. Run `coze guide sync` to sync them to your AI tools."}}();if("ok"===t.state)return;const o=e.config.autoSyncSkill,i=!0===o||"true"===o;if("mismatch"===t.state&&i){const e=await async function(e){if("mismatch"!==e.state)return!1;try{return!(await Ee({})).blocked}catch(e){return!1}}(t);if(e)return}t.message&&e.ui.info(`\n${t.message}\n`)}catch(e){}}(e)}var ze=e.requireSrc();const Re=e.getDefaultExportFromCjs(ze);function xe(e){var t,o,i=e.transport,s=e.endpoint,n=e.size,r=void 0===n?10:n,a=e.wait,c=void 0===a?1e3:a,l=[],d=0;function p(){if(l.length){var e=this.getBatchData();i.post({url:s,data:e,fail:function(o){t&&t(o,e)},success:function(){o&&o(e)}}),l=[]}}return{getSize:function(){return r},getWait:function(){return c},setSize:function(e){r=e},setWait:function(e){c=e},getEndpoint:function(){return s},setEndpoint:function(e){s=e},send:function(e){l.push(e),l.length>=r&&p.call(this),clearTimeout(d),d=setTimeout(p.bind(this),c)},flush:function(){clearTimeout(d),p.call(this)},getBatchData:function(){return l.length?(e=l,JSON.stringify({ev_type:"batch",list:e})):"";var e},clear:function(){clearTimeout(d),l=[]},fail:function(e){t=e},success:function(e){o=e}}}
3
3
  /*! *****************************************************************************
4
4
  Copyright (c) Microsoft Corporation.
5
5
 
@@ -13,7 +13,7 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
13
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
14
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
15
  PERFORMANCE OF THIS SOFTWARE.
16
- ***************************************************************************** */var Le=function(){return Le=Object.assign||function(e){for(var t,o=1,i=arguments.length;o<i;o++)for(var s in t=arguments[o])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},Le.apply(this,arguments)};function Oe(e,t){var o="function"==typeof Symbol&&e[Symbol.iterator];if(!o)return e;var i,s,n=o.call(e),r=[];try{for(;(void 0===t||t-- >0)&&!(i=n.next()).done;)r.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(o=n.return)&&o.call(n)}finally{if(s)throw s.error}}return r}function De(e,t,o){if(2===arguments.length)for(var i,s=0,n=t.length;s<n;s++)!i&&s in t||(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return e.concat(i||Array.prototype.slice.call(t))}var Ue=function(){return{}};function Be(e){return e}function qe(e){return"object"==typeof e&&null!==e}var Me=Object.prototype;function Ne(e){return"[object Array]"===Me.toString.call(e)}function $e(e){return"number"==typeof e}function Ge(e){return"string"==typeof e}function Fe(e,t){if(!Ne(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 Ve=function(e,t){if(!Ne(e))return e;var o=e.indexOf(t);if(o>=0){var i=e.slice();return i.splice(o,1),i}return e};function We(e){try{return Ge(e)?e:JSON.stringify(e)}catch(e){return"[FAILED_TO_STRINGIFY]:"+String(e)}}var He="".padStart?function(e,t){return void 0===t&&(t=8),e.padStart(t," ")}:function(e){return e},Je=0,Ke=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,De(["[SDK]",Date.now(),He(""+Je++)],Oe(e),!1))},Qe=0,Ye=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,De(["[SDK]",Date.now(),He(""+Qe++)],Oe(e),!1))},Ze=function(e){return Math.random()<Number(e)},Xe=function(e,t){return e<Number(t)},et=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 ot(){var e=function(){for(var e=new Array(16),t=0,o=0;o<16;o++)3&o||(t=4294967296*Math.random()),e[o]=t>>>((3&o)<<3)&255;return e}();return e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){for(var t=[],o=0;o<256;++o)t[o]=(o+256).toString(16).substr(1);var i=0,s=t;return[s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]]].join("")}(e)}var it=["init","start","config","beforeDestroy","provide","beforeReport","report","beforeBuild","build","beforeSend","send","beforeConfig"];function st(e){var t,o,i=e.builder,s=e.createSender,n=e.createDefaultConfig,r=e.createConfigManager,a=e.userConfigNormalizer,c=e.initConfigNormalizer,l=e.validateInitConfig,d={};it.forEach((function(e){return d[e]=[]}));var p=!1,u=!1,m=!1,g=[],h=[],f=function(){var e=!1,t={},o=function(e){e.length&&e.forEach((function(e){try{e()}catch(e){}})),e.length=0},i=function(e){t[e]&&t[e].forEach((function(e){o(e[1])})),t[e]=void 0};return{set:function(i,s,n){t[i]?t[i].push([s,n]):t[i]=[[s,n]],e&&o(n)},has:function(e){return!!t[e]},remove:i,removeByEvType:function(e){Object.keys(t).forEach((function(i){t[i]&&t[i].forEach((function(t){t[0]===e&&o(t[1])}))}))},clear:function(){e=!0,Object.keys(t).forEach((function(e){i(e)}))}}}(),_={getBuilder:function(){return i},getSender:function(){return t},getPreStartQueue:function(){return g},init:function(e){if(p)Ye("already inited");else{if(!(e&&qe(e)&&l(e)))throw new Error("invalid InitConfig, init failed");var i=n(e);if(!i)throw new Error("defaultConfig missing");var a=c(e);if((o=r(i)).setConfig(a),o.onChange((function(){y("config")})),!(t=s(o.getConfig())))throw new Error("sender missing");p=!0,y("init",!0)}},set:function(e){p&&e&&qe(e)&&(y("beforeConfig",!1,e),null==o||o.setConfig(e))},config:function(e){if(p)return e&&qe(e)&&(y("beforeConfig",!1,e),null==o||o.setConfig(a(e))),null==o?void 0:o.getConfig()},provide:function(e,t){Fe(h,e)?Ye("cannot provide "+e+", reserved"):(_[e]=t,y("provide",!1,e))},start:function(){p&&(u||null==o||o.onReady((function(){u=!0,y("start",!0),function(e){var t=e.getPreStartQueue();t.forEach((function(t){return e.build(t)})),t.length=0}(_)})))},report:function(e){if(e){var t=et(d.beforeReport)(e);if(t){var o=et(d.report)(t);o&&(u?this.build(o):function(e,t,o){if(t.push(o),!(t.length<500)){var i=t.splice(0,50);e.savePreStartDataToDb&&e.savePreStartDataToDb(i)}}(_,g,o))}}},build:function(e){if(u){var t=et(d.beforeBuild)(e);if(t){var o=i.build(t);if(o){var s=et(d.build)(o);s&&this.send(s)}}}},send:function(e){if(u){var o=et(d.beforeSend)(e);o&&(t.send(o),y("send",!1,o))}},destroy:function(){f.clear(),m=!0,g.length=0,y("beforeDestroy",!0)},on:function(e,t){if("init"===e&&p||"start"===e&&u||"beforeDestroy"===e&&m)try{t()}catch(e){}else d[e]&&d[e].push(t)},off:function(e,t){d[e]&&(d[e]=Ve(d[e],t))},destroyAgent:f};return h=Object.keys(_),_;function y(e,t){void 0===t&&(t=!1);for(var o=[],i=2;i<arguments.length;i++)o[i-2]=arguments[i];d[e].forEach((function(e){try{e.apply(void 0,De([],Oe(o),!1))}catch(e){}})),t&&(d[e].length=0)}}var nt=function(e){var t=function(){var e={},t={},o={set:function(i,s){return e[i]=s,t[i]=We(s),o},merge:function(i){return e=Le(Le({},e),i),Object.keys(i).forEach((function(e){t[e]=We(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 Le({},t)}};return o}();e.provide("context",t),e.on("report",(function(e){return e.extra||(e.extra={}),e.extra.context=t.toString(),e}))};var rt=function(){return Date.now()};var at=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&&qe(window))return window}());o&&(o.errors||(o.errors=[]),o.errors.push(e))},ct="custom",lt=function(e){var t=function(o){var i=function(e){if(e&&qe(e)&&e.name&&Ge(e.name)){var t={name:e.name,type:"event"};if("metrics"in e&&qe(e.metrics)){var o=e.metrics,i={};for(var s in o)$e(o[s])&&(i[s]=o[s]);t.metrics=i}if("categories"in e&&qe(e.categories)){var n=e.categories,r={};for(var s in n)r[s]=We(n[s]);t.categories=r}return"attached_log"in e&&Ge(e.attached_log)&&(t.attached_log=e.attached_log),t}}(o);if(i){var s=function(e){var t;if("object"==typeof window&&window.__perfsee__){var o={};return null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,o,e),o.stack}}(t);s&&(i.stacks=s),e.report({ev_type:ct,payload:i,extra:{timestamp:rt()}})}};e.provide("sendEvent",t),e.provide("sendLog",(function(t){var o=function(e){if(e&&qe(e)&&e.content&&Ge(e.content)){var t={content:We(e.content),type:"log",level:"info"};if("level"in e&&(t.level=e.level),"extra"in e&&qe(e.extra)){var o=e.extra,i={},s={};for(var n in o)$e(o[n])?i[n]=o[n]:s[n]=We(o[n]);t.metrics=i,t.categories=s}return"attached_log"in e&&Ge(e.attached_log)&&(t.attached_log=e.attached_log),t}}(t);o&&e.report({ev_type:ct,payload:o,extra:{timestamp:rt()}})}))},dt=function(e,t){var o=e.common||{};return o.sample_rate=t,e.common=o,e},pt=function(e,t,o,i,s){return e?(n=s(i,t),function(){return n}):function(){return o(t)};var n},ut=function(e,t,o,i){var s=function(e,t,o){for(var i,s=Oe(t.split(".")),n=s[0],r=s.slice(1);e&&r.length>0;)e=e[n],n=(i=Oe(r))[0],r=i.slice(1);if(e)return o(e,n)}(e,t,(function(e,t){return e[t]}));return void 0!==s&&function(e,t,o){switch(o){case"eq":return 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)}}))}(i,"boolean"==typeof s?"bool":$e(s)?"number":"string"),o)},mt=function(e,t){try{return"rule"===t.type?ut(e,t.field,t.op,t.values):"and"===t.type?t.children.every((function(t){return mt(e,t)})):t.children.some((function(t){return mt(e,t)}))}catch(e){return at(e),!1}},gt=function(e,t,o,i,s){if(!t)return Be;var n=t.sample_rate,r=t.include_users,a=t.sample_granularity,c=t.rules,l=t.r,d=void 0===l?Math.random():l;if(Fe(r,e))return function(e){return dt(e,1)};var p="session"===a,u=pt(p,n,o,d,i),m=function(e,t,o,i,s,n){var r={};return Object.keys(e).forEach((function(a){var c=e[a],l=c.enable,d=c.sample_rate,p=c.conditional_sample_rules;l?(r[a]={enable:l,sample_rate:d,effectiveSampleRate:d*o,hit:pt(t,d,i,s,n)},p&&(r[a].conditional_hit_rules=p.map((function(e){var r=e.sample_rate,a=e.filter;return{sample_rate:r,hit:pt(t,r,i,s,n),effectiveSampleRate:r*o,filter:a}})))):r[a]={enable:l,hit:function(){return!1},sample_rate:0,effectiveSampleRate:0}})),r}(c,p,n,o,d,i);return function(e){var t;if(!u())return p&&s[0](),!1;if(!(e.ev_type in m))return dt(e,n);if(!m[e.ev_type].enable)return p&&s[1](e.ev_type),!1;if(null===(t=e.common)||void 0===t?void 0:t.sample_rate)return e;var o=m[e.ev_type],i=o.conditional_hit_rules;if(i)for(var r=0;r<i.length;r++)if(mt(e,i[r].filter))return!!i[r].hit()&&dt(e,i[r].effectiveSampleRate);return o.hit()?dt(e,o.effectiveSampleRate):((!i||!i.length)&&p&&s[1](e.ev_type),!1)}},ht={build:function(e){return{ev_type:e.ev_type,payload:e.payload,common:Le(Le({},e.extra||{}),e.overrides||{})}}},ft={sample_rate:1,include_users:[],sample_granularity:"session",rules:{}};function _t(e){var t,o;try{for(var i=function(e){var t="function"==typeof Symbol&&Symbol.iterator,o=t&&e[t],i=0;if(o)return o.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(["userId","deviceId","sessionId","env"]),s=i.next();!s.done;s=i.next()){var n=s.value;e[n]||delete e[n]}}catch(e){t={error:e}}finally{try{s&&!s.done&&(o=i.return)&&o.call(i)}finally{if(t)throw t.error}}return e}function yt(e){return _t(Le({},e))}function bt(e){return qe(e)&&"bid"in e&&"transport"in e}function vt(e){return _t(Le({},e))}var wt=function(e,t){return void 0===t&&(t="/monitor_browser/collect/batch/"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Ct=function(e,t){return void 0===t&&(t="/monitor_web/settings/browser-settings"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Et=function(e){var t,o,i=e,s={},n=Ue,r=Ue;return{getConfig:function(){return i},setConfig:function(e){return s=Le(Le({},s),e||{}),a(),t||(t=e,i.useLocalConfig||!i.bid?(o={},n()):function(e,t,o,i){if(!e.get)return i({});e.get({withCredentials:!0,url:Ct(t)+"?bid="+o+"&store=1",success:function(e){i(e.data||{})},fail:function(){i({sample:{sample_rate:.001}})}})}(i.transport,i.domain,i.bid,(function(e){o=function(e){if(!e)return{};var t=e.sample,o=e.timestamp,i=e.quota_rate,s=void 0===i?1:i;if(!t)return{};var n=t.sample_rate,r=t.sample_granularity,a=void 0===r?"session":r,c=t.include_users,l=t.rules;return{sample:{include_users:c,sample_rate:n*s,sample_granularity:a,rules:(void 0===l?[]:l).reduce((function(e,t){var o=t.name,i=t.enable,s=t.sample_rate,n=t.conditional_sample_rules;return e[o]={enable:i,sample_rate:s,conditional_sample_rules:n},e}),{})},serverTimestamp:o}}(e),a(),n()}))),i},onChange:function(e){r=e},onReady:function(e){n=e,o&&n()}};function a(){var t=Le(Le(Le({},e),o||{}),s);t.sample=It(It(e.sample,null==o?void 0:o.sample),s.sample),i=t,r()}};function It(e,t){if(!e||!t)return e||t;var o=Le(Le({},e),t);return o.include_users=De(De([],Oe(e.include_users||[]),!1),Oe(t.include_users||[]),!1),o.rules=De(De([],Oe(Object.keys(e.rules||{})),!1),Oe(Object.keys(t.rules||{})),!1).reduce((function(o,i){var s,n;return i in o||(i in(e.rules||{})&&i in(t.rules||{})?(o[i]=Le(Le({},e.rules[i]),t.rules[i]),o[i].conditional_sample_rules=De(De([],Oe(e.rules[i].conditional_sample_rules||[]),!1),Oe(t.rules[i].conditional_sample_rules||[]),!1)):o[i]=(null===(s=e.rules)||void 0===s?void 0:s[i])||(null===(n=t.rules)||void 0===n?void 0:n[i])),o}),{}),o}var At=function(e){e.on("report",(function(t){return function(e,t){var o=t||{},i=o.version,s=o.name,n={url:"",protocol:"",domain:"",path:"",query:"",timestamp:Date.now(),sdk_version:i||"2.1.8",sdk_name:s||"SDK_BASE"};return Le(Le({},e),{extra:Le(Le({},n),e.extra||{})})}(t,e.config())}))},St=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,Le(Le({},e),{extra:Le(Le({},o),e.extra||{})})}(t,e.config())}))};var jt=function(e){return{bid:"",pid:"",viewId:(t="_",t+"_"+Date.now()),userId:ot(),deviceId:ot(),sessionId:ot(),domain:"mon.zijieapi.com",release:"",env:"production",sample:ft,plugins:{},transport:{get:Ue,post:Ue},useLocalConfig:!1};var t},Pt=function(e){var t=void 0===e?{}:e,o=t.createSender,i=void 0===o?function(e){return function(e){return xe(e)}({size:20,endpoint:wt(e.domain),transport:e.transport})}:o,s=t.builder,n=void 0===s?ht:s,r=t.createDefaultConfig,a=st({validateInitConfig:bt,initConfigNormalizer:yt,userConfigNormalizer:vt,createSender:i,builder:n,createDefaultConfig:void 0===r?jt:r,createConfigManager:Et});return nt(a),St(a),At(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=Ve(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&&qe(window)&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__.push(e)}catch(e){}}(a),a},kt=function(e){void 0===e&&(e={});var t=Pt(e);return function(e){e.on("start",(function(){var t=e.config(),o=t.userId,i=t.sample,s=gt(o,i,Ze,Xe,[function(){e.destroy()},function(t){e.destroyAgent.removeByEvType(t)}]);e.on("build",s)}))}(t),lt(t),t}();const Tt=Re("slardar:transport"),zt=()=>{};function Rt(e){const{url:t,method:o,data:i,success:s=zt,fail:n=zt,getResponseText:r=zt}=e;if(Tt("Making %s request to %s",o,t),i&&Tt("Request data: %s",i.slice(0,200)),!t||"string"!=typeof t){const e=new Error(`Invalid URL: ${t}`);return Tt("Invalid URL provided: %o",t),void n(e)}try{const e=new URL(t);Tt("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:d.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=>{Tt("Response callback triggered: status=%s",e.statusCode);let t="";e.on("data",(e=>{Tt("Response data chunk received: %s bytes",e.length),t+=e.toString()})),e.on("end",(()=>{Tt("Response end event fired"),Tt("Response received: status=%s, body=%s",e.statusCode,t.slice(0,200)),r(t);try{if(e.statusCode&&e.statusCode>=400)Tt("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);Tt("Request succeeded"),s(e)}else Tt("Request succeeded with empty response"),s({})}catch(e){Tt("Failed to parse response: %s",e.message),n(e)}}))}));c.on("error",(e=>{Tt("Request error: %s",e.message),n(e)})),c.on("timeout",(()=>{Tt("Request timeout"),c.destroy(),n(new Error("Request timeout"))})),i&&c.write(i),c.end()}catch(e){Tt("Exception during request: %s",e.message),n(e)}}function xt(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Lt=Re("slardar:reporter");class Ot{constructor(){Ot.prototype.__init.call(this),Ot.prototype.__init2.call(this)}__init(){this.initialized=!1}__init2(){this.client=kt}setup(e){var t,o;if(this.initialized)Lt("Already initialized, skipping setup");else try{Lt("Initializing Slardar with config:",{bid:e.bid,release:e.release,env:e.env,userId:e.userId,projectId:e.projectId});const i={get(e){Tt("Transport GET called: %s",e.url),Rt({method:"GET",...e})},post({url:e,data:t}){Tt("Transport POST called: %s",e),Rt({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=>{Lt("send hook called for event: %s",xt([e,"optionalAccess",e=>e.ev_type])||"unknown")})),this.client.start(),this.initialized=!0,Lt("Slardar initialized successfully")}catch(e){Lt("Failed to initialize:",e)}}ensureInitialized(){return!!this.initialized||(Lt("Not initialized, call setup() first"),!1)}sendEvent(e,t,o){if(this.ensureInitialized())try{Lt("Sending event:",{name:e,metrics:t,categories:o});const i=t?Object.fromEntries(Object.entries(t).filter((([,e])=>void 0!==e))):void 0,s=o?Object.fromEntries(Object.entries(o).filter((([,e])=>void 0!==e))):void 0;xt([this,"access",e=>e.client,"access",e=>e.sendEvent,"optionalCall",t=>t({name:e,metrics:i,categories:s})])}catch(e){Lt("Failed to send event:",e)}}sendLog(e,t,o){if(this.ensureInitialized())try{Lt("Sending log:",{level:e,message:t,extra:o}),this.sendEvent("cli_log",void 0,{level:e,message:t,...o})}catch(e){Lt("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"}}};Lt("Reporting JS error:",{name:e.name,message:e.message.slice(0,100),stack:xt([e,"access",e=>e.stack,"optionalAccess",e=>e.slice,"call",e=>e(0,200)]),extra:t,source:o}),this.client.report(i),Lt("JS error reported successfully")}catch(e){Lt("Failed to report error:",e)}}setContext(e,t){this.ensureInitialized()&&xt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.set,"call",o=>o(e,t)])}mergeContext(e){this.ensureInitialized()&&(Lt("Merging context:",e),xt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.merge,"call",t=>t(e)]))}deleteContext(e){this.ensureInitialized()&&xt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.delete,"call",t=>t(e)])}clearContext(){this.ensureInitialized()&&xt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.clear,"call",e=>e()])}updateConfig(e){if(this.ensureInitialized())try{Lt("Updating config:",e),this.client.config({userId:e.userId,release:e.release,sessionId:e.sessionId,env:e.env})}catch(e){Lt("Failed to update config:",e)}}async flush(e=1500){this.ensureInitialized()&&(Lt("Flushing Slardar data..."),xt([this,"access",e=>e.client,"access",e=>e.getSender,"optionalCall",e=>e(),"optionalAccess",e=>e.flush,"call",e=>e()]),Lt("Waiting %dms for events to be sent...",e),await new Promise((t=>setTimeout(t,e))),Lt("Slardar data flushed"))}getRawClient(){return this.client}}const Dt=new Ot;function Ut(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Bt="cli_start",qt="cli_command",Mt="cli_command_complete",Nt="cli_error",$t="network_request",Gt="file_operation",Ft={cliStart:e=>({name:Bt,metrics:{duration:0,...e}}),cliCommand:(e,t)=>({name:qt,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:Mt,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:$t,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:Gt,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:Nt,categories:{errorName:e.name,errorMessage:e.message,stack:e.stack||"",...t},metrics:{errorCode:1}})};function Vt(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Wt(e){return(...t)=>{try{const o=e(...t);return o instanceof Promise?o.catch((()=>{})):o}catch(e){}}}const Ht=Wt((()=>{var e,t;Dt.setup({bid:"coze_cli",release:Ae,env:"production",userId:process.env.USER||"",useLocalConfig:!1,domain:"mon.zijieapi.com"}),Dt.mergeContext({platform:process.platform,callerPlatform:(e=process.env.COZE_CLI_PLATFORM,t=()=>"unknown",null!=e?e:t()),nodeVersion:process.version,cliVersion:Ae})})),Jt=Wt((e=>{const t=Ft.cliCommand(e);Dt.sendEvent(t.name,t.metrics,t.categories)})),Kt=Wt(((e,t,o,i)=>{const s=Ft.cliCommandComplete(e,t,o,{errorCode:Vt([i,"optionalAccess",e=>e.errorCode])});Dt.sendEvent(s.name,s.metrics,s.categories)})),Qt=Wt(((e,t)=>{Dt.reportError(e,t,{type:"cli",data:t})})),Yt=Wt((async()=>{await Dt.flush()}));async function Zt(e,t){if(e.config.disableTelemetry)return void await t();Ht();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);Jt(o);const i=Date.now();let s,n=!0;try{await t()}catch(e){throw n=!1,s=e instanceof Error?e:new Error(String(e)),e}finally{const e=Date.now()-i;try{n?Kt(o,!0,e):(s&&Qt(s,{command:o}),Kt(o,!1,e)),await Yt()}catch(e){}}}function Xt(e,t){return null!=e?e:t()}const eo=i.join(n.homedir(),".coze","logs");class to{__init(){this.fileStream=null}__init2(){this.writeError=!1}constructor(e={}){to.prototype.__init.call(this),to.prototype.__init2.call(this),this.format=Xt(e.format,(()=>"text")),this.printToStderr=Xt(e.printToStderr,(()=>!1)),this.tags=Xt(e.tags,(()=>({}))),this.startTime=Date.now();const t=Xt(e.logFile,(()=>this.getDefaultLogPath()));this.logFile=t;try{this.ensureLogDir(),this.rotateLogFiles(),this.fileStream=r.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 i.join(eo,`${e}-${t}.log`)}ensureLogDir(){r.existsSync(eo)||r.mkdirSync(eo,{recursive:!0})}rotateLogFiles(){try{const e=r.readdirSync(eo).filter((e=>e.endsWith(".log"))).map((e=>({name:e,path:i.join(eo,e),mtime:r.statSync(i.join(eo,e)).mtime.getTime()}))).sort(((e,t)=>t.mtime-e.mtime));e.length>=10&&e.slice(9).forEach((e=>{try{r.unlinkSync(e.path)}catch(e){}}))}catch(e){}}verbose(e,...t){this.log("verbose",e,t)}info(e,...t){this.log("info",e,t)}warn(e,...t){this.log("warn",e,t)}error(e,...t){this.log("error",e,t)}success(e,...t){this.log("success",e,t)}debug(e,...t){this.log("debug",e,t)}debugFileOnly(e,...t){this.log("debug",e,t,!1)}log(e,t,o,i=this.printToStderr){const s=this.formatEntry(e,t,o);if(this.fileStream)try{this.fileStream.write(`${s}\n`)}catch(e){!this.writeError&&i&&(process.stderr.write("Warning: Log write failed\n"),this.writeError=!0)}i&&process.stderr.write(`${s}\n`)}formatEntry(e,t,o){const i=(new Date).toISOString(),s=Date.now()-this.startTime;if("json"===this.format){const n={level:e,timestamp:i,delta:s,...this.tags,message:t};return o.length>0&&(n.args=o),JSON.stringify(n)}const n=Object.entries(this.tags).map((([e,t])=>`${e}=${t}`)).join(" "),r=o.length>0?` ${o.map(String).join(" ")}`:"";return`${e.toUpperCase().padEnd(7)} [${i}] +${s}ms ${n} ${t}${r}`}close(){if(this.fileStream)try{this.fileStream.end()}catch(e){}}}function oo(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const io=new Set(["authorization","cookie","set-cookie"]),so=/(^|_|-)(token|secret|password|authorization|cookie)(_|-|$)/i,no=Symbol("request-debug-json-parse-fallback");let ro=null,ao=!1,co=!1;const lo=e.customFetch.fetch.bind(e.customFetch),po=e=>"[object Object]"===Object.prototype.toString.call(e),uo=e=>{try{return JSON.stringify(e)}catch(t){return JSON.stringify(String(e))}},mo=e=>{if("string"!=typeof e)return"***";const t=e.trim(),o=oo([/^bearer\s+/i,"access",e=>e.exec,"call",e=>e(t),"optionalAccess",e=>e[0]]);return o?`${o}***`:"***"},go=(e,t)=>t&&so.test(t)?mo(e):Array.isArray(e)?e.map((e=>go(e))):po(e)?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,go(t,e)]))):e,ho=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(Array.from(e.entries()).map((([e,t])=>[e.toLowerCase(),t])));if(Array.isArray(e))return Object.fromEntries(e.map((([e,t])=>[e.toLowerCase(),String(t)])));const t=e;return"function"==typeof t.toJSON?ho(t.toJSON()):"function"==typeof t.entries?Object.fromEntries(Array.from(t.entries()).map((([e,t])=>[e.toLowerCase(),t]))):Object.fromEntries(Object.entries(e).map((([e,t])=>[e.toLowerCase(),Array.isArray(t)?t.map((e=>String(e))).join(", "):String(t)])))},fo=(e,t)=>e[t.toLowerCase()],_o=(e,t,o="binary")=>{const i=(e=>"string"==typeof e?u.Buffer.byteLength(e):u.Buffer.isBuffer(e)?e.length:e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:"undefined"!=typeof Blob&&e instanceof Blob?e.size:void 0)(e),s=[o];return t&&s.push(t),"number"==typeof i&&s.push(`${i} bytes`),`[${s.join("; ")}]`},yo=(t,o)=>{if(null==t||""===t)return"<empty>";const i=oo([fo,"call",e=>e(o,"content-type"),"optionalAccess",e=>e.toLowerCase,"call",e=>e()]);if(oo([i,"optionalAccess",e=>e.includes,"call",e=>e("multipart/form-data")]))return _o(t,i,"multipart");if(t instanceof URLSearchParams)return uo(go(Object.fromEntries(Array.from(t.entries()))));if(u.Buffer.isBuffer(t)||t instanceof Uint8Array||t instanceof ArrayBuffer||"undefined"!=typeof Blob&&t instanceof Blob)return _o(t,i);if("string"==typeof t){const o=(t=>{const o=e.safeJsonParse(t,no);if(o!==no)return o})(t);return void 0!==o?uo(go(o)):JSON.stringify(t)}return Array.isArray(t)||po(t)?uo(go(t)):_o(t,i,typeof t)},bo=(e,t)=>{try{return new URL(e,t).toString()}catch(o){return t?`${t}${e}`:e}},vo=e=>{const t=ho(e);return t["x-tt-logid"]||t["x-tt-log-id"]||t.logid||""},wo=e=>(e||"GET").toUpperCase(),Co=e=>{ao&&ro&&(ro instanceof to?ro.debugFileOnly(e):ro.debug(e))},Eo=({method:e,url:t,headers:o,body:i})=>{const s=ho(o);Co(`[DBG][HTTP][REQ] ${e} ${t}\nheaders: ${uo((e=>Object.fromEntries(Object.entries(e).map((([e,t])=>[e,io.has(e)?mo(t):t]))))(s))}\nbody: ${yo(i,s)}`)},Io=({method:e,url:t,status:o,logId:i})=>{Co(`[DBG][HTTP][RES] ${e} ${t} status=${o} logid=${i||"-"}`)},Ao=({method:e,url:t,status:o,logId:i,message:s})=>{const n=(a=()=>"ERR",null!=(r=o)?r:a());var r,a;const c=s?` error=${JSON.stringify(s)}`:"";Co(`[DBG][HTTP][ERR] ${e} ${t} status=${n} logid=${i||"-"}${c}`)},So=(e,t)=>t&&"body"in t?t.body:"object"==typeof e&&e&&"body"in e&&null!==e.body?"[request body stream]":void 0,jo=()=>{e.axiosInstance.interceptors.request.use((e=>((e=>{const t=wo(e.method),o=bo(e.url||"",e.baseURL),i=ho(e.headers);Eo({method:t,url:o,headers:i,body:e.data})})(e),e))),e.axiosInstance.interceptors.response.use((e=>((e=>{const t=wo(oo([e,"access",e=>e.config,"optionalAccess",e=>e.method])),o=bo(oo([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",oo([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Io({method:t,url:o,status:e.status,logId:vo(e.headers)})})(e),e)),(e=>((e=>{const t=wo(oo([e,"access",e=>e.config,"optionalAccess",e=>e.method])),o=bo(oo([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",oo([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Ao({method:t,url:o,status:oo([e,"access",e=>e.response,"optionalAccess",e=>e.status]),logId:vo(oo([e,"access",e=>e.response,"optionalAccess",e=>e.headers])),message:e.message})})(e),Promise.reject(e))))},Po=()=>{e.customFetch.fetch=async(t,o)=>{const i=((e,t)=>oo([t,"optionalAccess",e=>e.method])?wo(t.method):"object"==typeof e&&e&&"method"in e&&"string"==typeof e.method?wo(e.method):"GET")(t,o),s=(e=>"string"==typeof e?e:e instanceof URL?e.toString():"object"==typeof e&&e&&"url"in e&&"string"==typeof e.url?e.url:String(e))(t),n=e.customFetch.getRequestHeaders(t,o);Eo({method:i,url:s,headers:n,body:So(t,o)});try{const e=await lo(t,o);return Io({method:i,url:s,status:e.status,logId:vo(e.headers)}),e}catch(e){throw Ao({method:i,url:s,message:e instanceof Error?e.message:String(e)}),e}}};function ko(e,t){return null!=e?e:t()}function To(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}var zo;!function(e){e.AUTHORIZATION_PENDING="authorization_pending";e.SLOW_DOWN="slow_down";e.ACCESS_DENIED="access_denied";e.EXPIRED_TOKEN="expired_token"}(zo||(zo={}));const Ro=e=>new Promise((t=>setTimeout(t,e))),xo=e.createRequestClient({baseURL:"https://api.coze.com",useDefaultPlugins:!0,plugins:[{name:"oauth-error-handler",onError:t=>{if(e.isHttpError(t))throw t;const o=t,i=ko(To([o,"access",e=>e.response,"optionalAccess",e=>e.data]),(()=>({}))),s=i.error_description||i.error||o.message,n={status:To([o,"access",e=>e.response,"optionalAccess",e=>e.status]),code:i.error,config:o.config,response:o.response,data:i};throw new e.HttpError(ko(s,(()=>"OAuth request failed")),n)}}]});async function Lo(e){return(await xo.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 Oo=async(t,o)=>{const i=process.env.HTTP_PROXY||process.env.http_proxy,s=process.env.HTTPS_PROXY||process.env.https_proxy;if(s||i){const o=new m.EnvHttpProxyAgent;e.customFetch.setDispatcher(o);const[{HttpProxyAgent:n},{HttpsProxyAgent:r}]=await Promise.all([import("http-proxy-agent"),import("https-proxy-agent")]);e.axiosInstance$1.defaults.proxy=!1,xo.defaults.proxy=!1,s&&(e.axiosInstance$1.defaults.httpsAgent=new r(s),xo.defaults.httpsAgent=new r(s),t.ui.debug(`HTTPS proxy enabled: ${s}`)),i&&(e.axiosInstance$1.defaults.httpAgent=new n(i),xo.defaults.httpAgent=new n(i),t.ui.debug(`HTTP proxy enabled: ${i}`))}await o()};let Do=()=>{},Uo=null;const Bo=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),qo=(e,t)=>{return Bo(o=e)&&"function"==typeof o.set?(Object.entries(t).forEach((([t,o])=>{e.set(t,o)})),e):{...Bo(e)?e:{},...t};var o},Mo=t=>{Do=t,null===Uo&&(Uo=e.axiosInstance$1.interceptors.request.use((t=>{const o=l.getCozeAccountHeaders(Do());return 0!==Object.keys(o).length&&l.shouldInjectCozeAccountHeader((t=>{const o=t.url;if(!o)return"";try{return new URL(o,t.baseURL||e.axiosInstance$1.defaults.baseURL).toString()}catch(e){return""}})(t))?(t.headers=qo(t.headers,o),t):t})))};async function No(t,o){Mo((()=>t.config.organizationId)),l.installScopedCozeAccountFetchHeader({getOrganizationId:()=>t.config.organizationId});const i=await t.auth.getValidAccessToken();e.axiosInstance$1.defaults.baseURL=t.config.apiBaseUrl;const s=`Bearer ${i}`;e.axiosInstance$1.defaults.headers.Authorization=s,e.axiosInstance$1.defaults.headers["x-request-from-coze-cli"]="1",e.customFetch.setHeaders({Authorization:s,"x-request-from-coze-cli":"1"}),t.config.xTTEnv&&(e.axiosInstance$1.defaults.headers["x-use-ppe"]="1",e.axiosInstance$1.defaults.headers["x-tt-env"]=t.config.xTTEnv,e.customFetch.setHeaders({"x-use-ppe":"1","x-tt-env":t.config.xTTEnv})),await o()}function $o(e){if(!Array.isArray(e))throw new TypeError("Middleware stack must be an array!");for(const t of e)if("function"!=typeof t)throw new TypeError("Middleware must be composed of functions!");return function(t,o){let i=-1;return function s(n){if(n<=i)return Promise.reject(new Error("next() called multiple times"));i=n;let r=e[n];n===e.length&&(r=o);if(!r)return Promise.resolve();try{return Promise.resolve(r(t,s.bind(null,n+1)))}catch(e){return Promise.reject(e)}}(0)}}var Go,Fo,Vo,Wo,Ho,Jo,Ko,Qo,Yo,Zo,Xo,ei,ti,oi,ii,si,ni,ri,ai,ci,li,di,pi,ui,mi,gi,hi,fi,_i,yi,bi,vi,wi,Ci,Ei,Ii,Ai,Si,ji,Pi,ki,Ti,zi,Ri,xi,Li,Oi,Di,Ui,Bi,qi,Mi,Ni,$i,Gi;function Fi(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e.app="app";e.pat="pat"}(Go||(Go={})),function(e){e.can_apply2="CanApply";e.already_applied2="AlreadyApplied";e.joined4="Joined";e.deny3="Deny"}(Fo||(Fo={})),function(e){e.processing="Processing";e.approved="Approved";e.rejected="Rejected";e.auto_approved="AutoApproved"}(Vo||(Vo={})),function(e){e.normal="Normal";e.connector="Connector";e.privilege="Privilege"}(Wo||(Wo={})),function(e){e.auth_app="AuthApp";e.on_behalf_of_user="OnBehalfOfUser"}(Ho||(Ho={})),function(e){e.password="Password";e.sms="Sms";e.email="Email";e.unknown3="Unknown"}(Jo||(Jo={})),function(e){e.email2="Email";e.phone="Phone";e.unknown4="Unknown"}(Ko||(Ko={})),function(e){e.authorized="authorized";e.unauthorized="unauthorized";e.expired4="expired"}(Qo||(Qo={})),function(e){e.api_key="api_key";e.wechat_official="wechat_official";e.oauth_2="oauth2"}(Yo||(Yo={})),function(e){e.noncertificated="Noncertificated";e.certificated="Certificated"}(Zo||(Zo={})),function(e){e.uncertified="Uncertified";e.personal_certification="PersonalCertification";e.enterprise_certification="EnterpriseCertification"}(Xo||(Xo={})),function(e){e.obo="Obo";e.app_auth="AppAuth";e.personal_access_token="PersonalAccessToken"}(ei||(ei={})),function(e){e.legacy="Legacy";e.web_backend="WebBackend";e.single_page_or_native="SinglePageOrNative";e.terminal="Terminal";e.service="Service"}(ti||(ti={})),function(e){e.bot_editor="BotEditor";e.bot_developer="BotDeveloper";e.bot_operator="BotOperator"}(oi||(oi={})),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"}(ii||(ii={})),function(e){e.visitors_prohibited="VisitorsProhibited";e.guest_prohibited_by_invited_user_enterprise2="GuestProhibitedByInvitedUserEnterprise";e.prohibited_by_custom_people_management="ProhibitedByCustomPeopleManagement"}(si||(si={})),function(e){e.dev2="DEV";e.prod2="PROD"}(ni||(ni={})),function(e){e._1="1";e._30="30";e._90="90";e._180="180";e._365="365";e.customize="customize";e.permanent="permanent"}(ri||(ri={})),function(e){e._12="1";e._302="30";e._902="90";e._1802="180";e._3652="365";e.customize2="customize";e.permanent2="permanent"}(ai||(ai={})),function(e){e.aes_256_gcm="AES-256-GCM"}(ci||(ci={})),function(e){e.conversation="Conversation";e.unknown="Unknown"}(li||(li={})),function(e){e.active3="Active";e.inactive="Inactive"}(di||(di={})),function(e){e.cloud_kms="CloudKMS",e.default="Default";e.unknown2="Unknown"}(pi||(pi={})),function(e){e.user_custom2="user_custom";e.consumer3="consumer"}(ui||(ui={})),function(e){e.super_admin="SuperAdmin";e.admin="Admin";e.member="Member";e.guest="Guest"}(mi||(mi={})),function(e){e.join_enterprise_share_link_expiration_time="JoinEnterpriseShareLinkExpirationTime";e.sso="SSO";e.forbid_guest_join_enterprise="ForbidGuestJoinEnterprise";e.forbid_member_join_other_enterprise="ForbidMemberJoinOtherEnterprise";e.replace_enterprise_logo="ReplaceEnterpriseLogo";e.forbid_custom_people_management="ForbidCustomPeopleManagement";e.forbid_coze_store_plugin_access="ForbidCozeStorePluginAccess";e.enterprise_member_listing_skill_coze_store="EnterpriseMemberListingSkillCozeStore";e.listing_skill_enterprise_store_audit="ListingSkillEnterpriseStoreAudit"}(gi||(gi={})),function(e){e.string="String";e.boolean="Boolean";e.integer="Integer";e.string_list="StringList"}(hi||(hi={})),function(e){e.must_handle="MustHandle";e.no_need_handle="NoNeedHandle"}(fi||(fi={})),function(e){e.pending_review_app_auth="pending_review_app_auth";e.pending_review_app_obo="pending_review_app_obo";e.approved_app_auth="approved_app_auth";e.approved_app_obo="approved_app_obo"}(_i||(_i={})),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"}(yi||(yi={})),function(e){e.confirming2="Confirming";e.joined3="Joined";e.rejected3="Rejected";e.revoked2="Revoked";e.expired3="Expired";e.deny2="Deny"}(bi||(bi={})),function(e){e.confirming="Confirming";e.joined2="Joined";e.rejected2="Rejected";e.revoked="Revoked";e.expired2="Expired"}(vi||(vi={})),function(e){e.can_join="CanJoin";e.guest_prohibited_by_enterprise="GuestProhibitedByEnterprise";e.guest_prohibited_by_invited_user_enterprise="GuestProhibitedByInvitedUserEnterprise"}(wi||(wi={})),function(e){e.can_apply="CanApply";e.already_applied="AlreadyApplied";e.joined="Joined";e.expired="Expired";e.deny="Deny"}(Ci||(Ci={})),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"}(Ei||(Ei={})),function(e){e.user_custom_only="user_custom_only";e.all2="all"}(Ii||(Ii={})),function(e){e.system="system";e.custom="custom"}(Ai||(Ai={})),function(e){e.not_in_enterprise="NotInEnterprise";e.prohibited_by_custom_people_management2="ProhibitedByCustomPeopleManagement"}(Si||(Si={})),function(e){e.can_apply3="CanApply";e.already_applied3="AlreadyApplied";e.joined5="Joined";e.deny4="Deny"}(ji||(ji={})),function(e){e.super_admin2="SuperAdmin";e.admin2="Admin";e.member2="Member";e.guest2="Guest"}(Pi||(Pi={})),function(e){e.member_joining_auto_approved="MemberJoiningAutoApproved"}(ki||(ki={})),function(e){e.string2="String";e.boolean2="Boolean";e.integer2="Integer";e.string_list2="StringList"}(Ti||(Ti={})),function(e){e.developer="developer";e.consumer2="consumer"}(zi||(zi={})),function(e){e.all="all";e.owned="owned";e.others="others"}(Ri||(Ri={})),function(e){e.enterprise_member="EnterpriseMember";e.enterprise_guest="EnterpriseGuest"}(xi||(xi={})),function(e){e.not_created="NotCreated";e.enabled="Enabled";e.disabled="Disabled"}(Li||(Li={})),function(e){e.not_created2="NotCreated";e.not_support_not_supabase="NotSupportNotSupabase";e.enabled2="Enabled";e.disabled2="Disabled";e.not_support_project_type="NotSupportProjectType"}(Oi||(Oi={})),function(e){e.production="Production";e.development="Development"}(Di||(Di={})),(Ui||(Ui={})).skill="skill",function(e){e.dev="dev";e.prod="prod"}(Bi||(Bi={})),function(e){e.user_custom="user_custom";e.coze_default="coze_default";e.consumer="consumer"}(qi||(qi={})),function(e){e.active2="Active";e.deactive="Deactive"}(Mi||(Mi={})),function(e){e.active="active";e.deactivated="deactivated";e.offboarded="offboarded"}(Ni||(Ni={})),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"}($i||($i={})),function(e){e.root_user="RootUser";e.basic_user="BasicUser"}(Gi||(Gi={}));class Vi{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Vi.prototype.__init.call(this),Vi.prototype.__init2.call(this),this.request=Fi([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Fi([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}CreatePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/create_personal_access_token_and_permission"),s={name:o.name,expire_at:o.expire_at,duration_day:o.duration_day,organization_id:o.organization_id,workspace_permission:o.workspace_permission,account_permission:o.account_permission,workspace_permission_v2:o.workspace_permission_v2,enterprise_permission:o.enterprise_permission},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}UpdatePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/update_personal_access_token_and_permission"),s={workspace_permission:o.workspace_permission,account_permission:o.account_permission,workspace_permission_v2:o.workspace_permission_v2,enterprise_permission:o.enterprise_permission,id:o.id,name:o.name},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}DeletePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/delete_personal_access_token_and_permission"),s={id:o.id};return this.request({url:i,method:"POST",data:s},t)}ListPersonalAccessTokens(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/pat/list_personal_access_tokens"),s={organization_id:o.organization_id,page:o.page,size:o.size,search_option:o.search_option};return this.request({url:i,method:"GET",params:s},t)}GetPersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/get_personal_access_token_and_permission"),s={id:o.id};return this.request({url:i,method:"GET",params:s},t)}ListPersonalAccessTokenSupportPermissions(e,t){const o=this.genBaseURL("/api/permission_api/pat/list_personal_access_token_support_permissions");return this.request({url:o,method:"GET"},t)}CheckPersonalAccessTokenInWorkspace(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/check_personal_access_token_in_workspace"),s={workspace_id:o.workspace_id};return this.request({url:i,method:"GET",params:s},t)}AddCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/add_collaborator"),s={collaborator_types:o.collaborator_types,principal:o.principal,resource:o.resource};return this.request({url:i,method:"POST",data:s},t)}RemoveCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/remove_collaborator"),s={principal:o.principal,resource:o.resource};return this.request({url:i,method:"POST",data:s},t)}CreateAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/create_app_meta"),s={app_type:o.app_type,client_type:o.client_type,name:o.name,description:o.description,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListAppMeta(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/list_app_meta"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}GetAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_meta"),s={appid:o.appid},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}UpdateAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/update_app_meta"),s={status:o.status,oauth2_configuration:o.oauth2_configuration,appid:o.appid,name:o.name,description:o.description,declared_permission:o.declared_permission,declared_permission_v2:o.declared_permission_v2},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}UploadPublicKey(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/upload_public_key"),s={appid:o.appid,public_key_pem:o.public_key_pem};return this.request({url:i,method:"POST",data:s},t)}DeletePublicKey(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_public_key"),s={fingerprint:o.fingerprint};return this.request({url:i,method:"POST",data:s},t)}CreateClientSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/create_client_secret"),s={appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}DeleteClientSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_client_secret"),s={appid:o.appid,client_secret_id:o.client_secret_id};return this.request({url:i,method:"POST",data:s},t)}PutOAuth2Configuration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/put_oauth2_configuration"),s={oauth2_configuration:o.oauth2_configuration,appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}AuthorizeAppWithDeclaredPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/authorize_app_with_declared_permission"),s={appid:o.appid,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListAuthorizedApps(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/list_authorized_apps"),s={page:o.page,size:o.size},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetAppAuthorizationRequestInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_authorization_request_info"),s={authorize_key:o.authorize_key},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}RevokeAppAuthorizedPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/revoke_app_authorized_permission"),s={authorization_type:o.authorization_type,appid:o.appid,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DeleteApp(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_app"),s={appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}ModifyCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/modify_collaborator"),s={principal:o.principal,resource:o.resource,collaborator_types:o.collaborator_types};return this.request({url:i,method:"POST",data:s},t)}BatchAddCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/batch_add_collaborator"),s={principal_type:o.principal_type,resource:o.resource,principal_ids:o.principal_ids,collaborator_types:o.collaborator_types};return this.request({url:i,method:"POST",data:s},t)}GetAppInstallationRequestInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_installation_request_info"),s={appid:o.appid},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}AppInstallationConsent(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/app_installation_consent"),s={appid:o.appid,installation_account_hint:o.installation_account_hint};return this.request({url:i,method:"POST",data:s},t)}ImpersonateCozeUser(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/coze_web_app/impersonate_coze_user"),s={duration_seconds:o.duration_seconds,scope:o.scope,connector_info:o.connector_info};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoConnectInfoWithInsName(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_connect_info_with_ins_name");return this.request({url:o,method:"GET"},t)}GetVolcanoMaskedMobile(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_masked_mobile");return this.request({url:o,method:"GET"},t)}BindVolcano(e,t){const o=this.genBaseURL("/api/permission_api/volcano/bind_volcano");return this.request({url:o,method:"POST"},t)}AuthorizeAppWithSpecifiedWorkspace(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/authorize_app_with_specified_permission"),s={appid:o.appid,workspace_list:o.workspace_list,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetUserProfile(e,t){const o=this.genBaseURL("/v1/users/me");return this.request({url:o,method:"GET"},t)}ListAppAuthorizations(e,t){const o=e,i=this.genBaseURL(`/v1/oauth-apps/${o.appid}/authorizations`),s={page_num:o.page_num,page_size:o.page_size},n={authorization:o.authorization};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetCertificationInfo(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/get_certification_info");return this.request({url:o,method:"GET"},t)}NeedCreateEnterprise(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/need_create_enterprise");return this.request({url:o,method:"GET"},t)}CreateEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_enterprise"),s={name:o.name,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}ListEnterprise(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/enterprise/list_enterprises"),s={contain_enterprise_of_user:o.contain_enterprise_of_user,contain_organization_of_user:o.contain_organization_of_user,contain_guest_enterprise_of_user:o.contain_guest_enterprise_of_user,is_space:o.is_space};return this.request({url:i,method:"GET",params:s},t)}GetEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_enterprise"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"GET",params:s},t)}UpdateEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise"),s={enterprise_id:o.enterprise_id,name:o.name,icon_uri:o.icon_uri,replace_logo:o.replace_logo};return this.request({url:i,method:"POST",data:s},t)}UpdateEnterpriseSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_settings"),s={enterprise_id:o.enterprise_id,enterprise_settings:o.enterprise_settings};return this.request({url:i,method:"POST",data:s},t)}BatchAddEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_add_enterprise_people"),s={enterprise_id:o.enterprise_id,enterprise_people:o.enterprise_people,need_check_people_valid:o.need_check_people_valid};return this.request({url:i,method:"POST",data:s},t)}RemoveEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/remove_enterprise_people"),s={enterprise_id:o.enterprise_id,user_id:o.user_id,receiver:o.receiver,sync_default_organization:o.sync_default_organization};return this.request({url:i,method:"POST",data:s},t)}UpdateEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_people"),s={enterprise_id:o.enterprise_id,user_id:o.user_id,enterprise_role_type_list:o.enterprise_role_type_list,sync_default_organization:o.sync_default_organization};return this.request({url:i,method:"POST",data:s},t)}CreateEnterpriseInviteLink(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_enterprise_invite_link"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}CreateJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_join_application"),s={key:o.key,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}GetInviteInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_invite_info"),s={invite_key:o.invite_key};return this.request({url:i,method:"GET",params:s},t)}UpdateJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_application"),s={application_status:o.application_status,enterprise_id:o.enterprise_id,join_application_id_list:o.join_application_id_list};return this.request({url:i,method:"POST",data:s},t)}ListPersonalAccessTokensByCreator(e,t){const o=e,i=this.genBaseURL("/api/permission_api/permission/list_personal_access_tokens_by_creator"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}ListAppInstallations(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/list_app_installations"),s={enterprise_id:o.enterprise_id,organization_id:o.organization_id},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetEnterpriseSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_enterprise_settings"),s={enterprise_id:o.enterprise_id,enterprise_setting_key_list:o.enterprise_setting_key_list};return this.request({url:i,method:"POST",data:s},t)}SearchCanAddEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_can_add_enterprise_people"),s={people_type:o.people_type,enterprise_id:o.enterprise_id,search_key:o.search_key};return this.request({url:i,method:"POST",data:s},t)}SearchEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_enterprise_people"),s={people_type:o.people_type,enterprise_id:o.enterprise_id,search_key:o.search_key,enterprise_role_type_list:o.enterprise_role_type_list,need_volcano_user_info:o.need_volcano_user_info,need_people_number:o.need_people_number,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}ListJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_application"),s={application_status:o.application_status,enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PostAdapterMpV1Code2Session(e,t){const o=e||{},i=this.genBaseURL("/adapter/mp/v1/code2session"),s={bot_id:o.bot_id,app_id:o.app_id,connector_id:o.connector_id,code:o.code,with_userinfo:o.with_userinfo,execute_mode:o.execute_mode,agent_type:o.agent_type,agent_version:o.agent_version};return this.request({url:i,method:"POST",data:s},t)}SubmitAppOboInstallationReview(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/submit_app_obo_installation_review"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}InstallAppObo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/install_app_obo"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}UninstallAppObo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/uninstall_app_obo"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetChecklistForWorkspaceMigration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_checklist_for_workspace_migration"),s={workspace_id_list:o.workspace_id_list};return this.request({url:i,method:"POST",data:s},t)}CheckEnterpriseExist(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/check_enterprise_exist");return this.request({url:o,method:"GET"},t)}GetSSOSetting(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_sso_setting"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}BatchMigrateAuthorization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/batch_migrate_authorization"),s={authorization_list:o.authorization_list,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_invitation"),s={invitation_status:o.invitation_status,enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}RevokeJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/revoke_join_invitation"),s={enterprise_id:o.enterprise_id,join_invitation_id:o.join_invitation_id};return this.request({url:i,method:"POST",data:s},t)}UpdateJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_invitation"),s={enterprise_id:o.enterprise_id,join_invitation_id:o.join_invitation_id,joined:o.joined};return this.request({url:i,method:"POST",data:s},t)}GetJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_join_invitation"),s={join_invitation_id:o.join_invitation_id};return this.request({url:i,method:"POST",data:s},t)}SearchPeopleInOtherEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_people_in_other_enterprise"),s={enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}CreateApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_application_for_enterprise_member"),s={enterprise_id:o.enterprise_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}GetApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_application_for_enterprise_member"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}AuthorizeAppsAndPersonalaccesstokenListWithPersonalAccountPermission(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/authorize_apps_and_patlist_with_personalaccountpermission"),s={crossaccount_authinfo_list:o.crossaccount_authinfo_list};return this.request({url:i,method:"POST",data:s},t)}RevokeAppAndPersonalaccesstokenPersonalAccountPermission(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/revoke_app_and_pat_personalaccountpermission"),s={crossaccount_authinfo:o.crossaccount_authinfo};return this.request({url:i,method:"POST",data:s},t)}GetAppsAndPersonalAccessTokenListForPersonalAccountPermissionAuthorization(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/get_apps_and_patlist_for_personalaccountpermission_authorization"),s={page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}create_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/create_service_identity"),s={name:o.name,organization_id:o.organization_id,expire_at:o.expire_at,duration_day:o.duration_day,permission:o.permission},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}get_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/get_service_identity"),s={id:o.id};return this.request({url:i,method:"GET",params:s},t)}update_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/update_service_identity"),s={permission:o.permission,id:o.id,name:o.name,expire_at:o.expire_at,duration_day:o.duration_day},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}delete_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/delete_service_identity"),s={id:o.id};return this.request({url:i,method:"POST",params:s},t)}list_service_identities(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/service/list_service_identities"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}ListEncryptionConfiguration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterpise/list_encryption_configuration"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}UpdateEncryptionConfiguration(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/enterpise/update_encryption_configuration"),s={encryption_configuration:o.encryption_configuration};return this.request({url:i,method:"POST",data:s},t)}SearchOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_organization"),s={enterprise_id:o.enterprise_id,search_key:o.search_key,joined:o.joined,need_people_number:o.need_people_number,need_workspace_number:o.need_workspace_number,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}CreateOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_organization"),s={enterprise_id:o.enterprise_id,name:o.name,icon_uri:o.icon_uri,description:o.description};return this.request({url:i,method:"POST",data:s},t)}GetOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization"),s={organization_id:o.organization_id,name:o.name,icon_uri:o.icon_uri,description:o.description};return this.request({url:i,method:"POST",data:s},t)}SearchCanAddOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_can_add_organization_people"),s={organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}SearchOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_organization_people"),s={organization_role_type:o.organization_role_type,people_type:o.people_type,organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size,organization_role_type_list:o.organization_role_type_list};return this.request({url:i,method:"POST",data:s},t)}CreateJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_join_organization_application"),s={organization_id:o.organization_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}ListJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_organization_application"),s={application_status:o.application_status,organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}UpdateJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_organization_application"),s={application_status:o.application_status,organization_id:o.organization_id,join_application_id_list:o.join_application_id_list};return this.request({url:i,method:"POST",data:s},t)}GetOrganizationApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization_application_for_enterprise_member"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}CanCustomEncryptionConfiguration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterpise/can_custom_encryption_configuration"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"GET",params:s},t)}BatchAddOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_add_organization_people"),s={organization_id:o.organization_id,organization_people:o.organization_people};return this.request({url:i,method:"POST",data:s},t)}RemoveOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/remove_organization_people"),s={organization_id:o.organization_id,user_id:o.user_id,receiver:o.receiver};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization_people"),s={organization_role_type:o.organization_role_type,organization_id:o.organization_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}DownloadRemoteAttestationEvidence(e,t){const o=e,i=this.genBaseURL("/api/permission_api/aicc/download_remote_attestation_evidence"),s={component_name:o.component_name};return this.request({url:i,method:"GET",params:s},t)}GetAgentAiccInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/aicc/get_agent_aicc_info"),s={agent_id:o.agent_id};return this.request({url:i,method:"GET",params:s},t)}CheckDeleteOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/check_delete_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DeleteOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/delete_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListProjectUsers(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/list_project_users"),s={project_id:o.project_id,page_size:o.page_size,page_number:o.page_number,environment:o.environment,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectUser(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user"),s={environment:o.environment,project_id:o.project_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}GetProjectAuthConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}UpdateProjectAuthConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config"),s={project_id:o.project_id,configuration:o.configuration};return this.request({url:i,method:"POST",data:s},t)}ListProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/list_project_secret"),s={env:o.env,project_id:o.project_id,with_providers:o.with_providers,deploy_id:o.deploy_id,option:o.option};return this.request({url:i,method:"POST",data:s},t)}UpdateProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/update_project_secret"),s={project_id:o.project_id,update_secrets:o.update_secrets,update_cred_provider:o.update_cred_provider};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/delete_project_secret"),s={project_id:o.project_id,keys:o.keys,cred_provider_ids:o.cred_provider_ids};return this.request({url:i,method:"POST",data:s},t)}EncryptProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/encrypt_project_secret"),s={project_id:o.project_id,project_type:o.project_type,encrypt_secrets:o.encrypt_secrets};return this.request({url:i,method:"POST",data:s},t)}InsertProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/insert_project_secret"),s={project_id:o.project_id,insert_secrets:o.insert_secrets};return this.request({url:i,method:"POST",data:s},t)}OutboundAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/outbound_auth/callback"),s={session_id:o.session_id,error:o.error};return this.request({url:i,method:"GET",params:s},t)}CreateAgentAccessToken(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:o.project_id,deployment_env:o.deployment_env};return this.request({url:i,method:"POST",data:s},t)}ListAgentAccessTokens(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}DeleteAgentAccessToken(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={token_id:o.token_id,project_id:o.project_id};return this.request({url:i,method:"DELETE",data:s},t)}GenerateInviteCode(e,t){const o=this.genBaseURL("/api/permission_api/coze_user/generate_invite_code");return this.request({url:o,method:"POST"},t)}GetInviteCodeInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/coze_user/get_invite_code_info"),s={invite_code:o.invite_code};return this.request({url:i,method:"GET",params:s},t)}AuthorizeCredProvider(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/authorize"),s={provider_id:o.provider_id};return this.request({url:i,method:"GET",params:s},t)}ProjectSecretAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/project_secret/callback"),s={code:o.code,state:o.state,error:o.error};return this.request({url:i,method:"GET",params:s},t)}ListAuthInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/list_auth_info"),s={credential_ids:o.credential_ids};return this.request({url:i,method:"POST",data:s},t)}RevokeAuthorization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/revoke"),s={credential_id:o.credential_id};return this.request({url:i,method:"POST",data:s},t)}UpdateProjectAuthConfigV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config_v2"),s={environment:o.environment,project_id:o.project_id,configuration:o.configuration};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectUserV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user_v2"),s={environment:o.environment,project_id:o.project_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}VisibilityConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/visibility_config"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoLoginMaskedMobile(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_login_masked_mobile");return this.request({url:o,method:"GET"},t)}ListProjectUsersV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/list_project_users_v2"),s={environment:o.environment,project_id:o.project_id,page_size:o.page_size,page_number:o.page_number,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}GetProjectAuthConfigV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config_v2"),s={environment:o.environment,project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}BatchGetPeopleJoinedOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_get_people_joined_organization"),s={enterprise_id:o.enterprise_id,user_ids:o.user_ids};return this.request({url:i,method:"POST",data:s},t)}BatchRemoveOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_remove_organization_people"),s={enterprise_id:o.enterprise_id,remove_user_list:o.remove_user_list};return this.request({url:i,method:"POST",data:s},t)}BatchRemoveEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_remove_enterprise_people"),s={enterprise_id:o.enterprise_id,remove_user_list:o.remove_user_list};return this.request({url:i,method:"POST",data:s},t)}GetOrganizationSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization_settings"),s={organization_id:o.organization_id,organization_setting_key_list:o.organization_setting_key_list};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganizationSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization_settings"),s={organization_id:o.organization_id,organization_settings:o.organization_settings};return this.request({url:i,method:"POST",data:s},t)}GithubAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/github_auth/callback"),s={code:o.code,state:o.state,error:o.error};return this.request({url:i,method:"GET",params:s},t)}BatchListOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_list_organization_people"),s={organization_ids:o.organization_ids,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}}const Wi=new Vi({});function Hi(e,t){return null!=e?e:t()}const Ji=1e3,Ki=Math.floor(new Date("2000-01-01T00:00:00.000Z").getTime()/Ji),Qi=e=>e instanceof Error?e.message:String(e);class Yi{constructor(e){this.ctx=e,this.config=e.config}getOAuthConfig(){return{baseURL:Hi(this.config.openApiBaseUrl,(()=>l.DEFAULT_CONFIG.openApiBaseUrl)),clientId:Hi(this.config.clientId,(()=>l.DEFAULT_CONFIG.clientId))}}async clearUserContext(){this.config.organizationId=void 0,this.config.enterpriseId=void 0,this.config.spaceId=void 0,await l.saveConfig({organizationId:void 0,enterpriseId:void 0,spaceId:void 0})}openInBrowser(e){const t="darwin"===process.platform?"open":"win32"===process.platform?"cmd":"xdg-open",o="win32"===process.platform?["/c","start",'""',e]:[e],i="Failed to open browser automatically. Please open the URL manually.";try{const e=c.spawn(t,o,{detached:!0,stdio:"ignore"});e.on("error",(()=>{this.ctx.ui.verbose(i)})),e.unref()}catch(e){this.ctx.ui.verbose(`${i} ${e instanceof Error?e.message:String(e)}`)}}async clearAuthData(){this.config.accessToken=void 0,this.config.refreshToken=void 0,this.config.tokenExpiresAt=void 0,await l.saveConfig({accessToken:void 0,refreshToken:void 0,tokenExpiresAt:void 0})}async login(t){if(this.ctx.ui.verbose("Initiating login process..."),t.token)return this.ctx.ui.info("Using Personal Access Token (PAT)..."),this.config.accessToken=t.token,await l.saveConfig({accessToken:t.token,refreshToken:void 0,tokenExpiresAt:void 0}),await this.clearUserContext(),this.ctx.ui.info("Authentication successful. Credentials saved."),void("json"===this.ctx.format&&this.ctx.response.print({success:!0,method:"PAT"}));try{this.ctx.ui.info("Starting OAuth flow...");const{baseURL:t,clientId:i}=this.getOAuthConfig();this.ctx.ui.verbose("Starting OAuth device flow...");const s=await async function(e){const t=e.workspaceId?`/api/permission/oauth2/workspace_id/${e.workspaceId}/device/code`:"/api/permission/oauth2/device/code";return(await xo.post(t,{client_id:e.clientId},{baseURL:e.baseURL})).data}({baseURL:t,clientId:i}),n=`${s.verification_uri}?user_code=${s.user_code}`;this.ctx.ui.info(`Please visit ${o.underline(n)} and authorize the application.\n\nPrivacy Policy: ${o.underline("https://docs.coze.cn/guides/privacy")}\nTerms of Service: ${o.underline("https://docs.coze.cn/guides/terms-of-service")}\n\nIf you are an agent using Coze CLI, please share the authorization link,\nPrivacy Policy, and Terms of Service with your users.\n `),this.openInBrowser(n);const r=await async function(t,o){if(!t.poll)return Lo(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 Lo(t);return o.ui.debug(`Polling for device token success: ${JSON.stringify(e)}`),e}catch(t){if(e.isHttpError(t)){const e=t;o.ui.debug(`Polling for device token error, the error is a HttpError.\n logid: ${To([e,"access",e=>e.response,"optionalAccess",e=>e.headers,"access",e=>e["x-tt-logid"]])}`),o.ui.debug(`Polling for device token error: ${JSON.stringify(ko(To([e,"access",e=>e.toJSON,"optionalCall",e=>e()]),(()=>e)))}`);const s=e.data;if(To([s,"optionalAccess",e=>e.error])===zo.AUTHORIZATION_PENDING){o.ui.debug("Polling for device token: user has not completed authorization yet."),await Ro(i);continue}if(To([s,"optionalAccess",e=>e.error])===zo.SLOW_DOWN){i<3e4&&(i+=5e3),o.ui.debug(`Polling for device token: client is polling too frequently. Increasing interval to ${i}ms`),await Ro(i);continue}}const s=t;throw o.ui.debug(`Polling for device token error, the error is: ${s.message}\n ${s.stack}\n `),t}}({baseURL:t,clientId:i,deviceCode:s.device_code,poll:!0},this.ctx);this.ctx.ui.debug(`Polling for device token success: ${JSON.stringify(r)}`),await this.saveOAuthToken(r),this.ctx.ui.debug("Saving OAuth token successfully."),await this.clearUserContext(),this.ctx.ui.info("Authentication successful. Credentials saved."),"json"===this.ctx.format&&this.ctx.response.print({success:!0,method:"OAuth"})}catch(e){throw this.ctx.ui.error(`OAuth login failed: ${Qi(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 Wi.GetUserProfile({},{baseURL:this.config.openApiBaseUrl}),s={logged_in:!0,user:i,token_expires_at:t?new Date(t).toISOString():o?void 0:"Never (PAT)"};this.ctx.response.print(s)}async getValidAccessToken(){const{accessToken:e,refreshToken:t,tokenExpiresAt:o}=this.config;if(e){if(!t)return e;if((e=>{if(!e)return!1;const t=Date.now();return!(e-t>316224e5)&&t<e-3e5})(o))return e;this.ctx.ui.verbose("Access token is expired or expiring soon, refreshing...");try{const{baseURL:e,clientId:o}=this.getOAuthConfig(),i=await async function(e){const t={};return e.clientSecret&&(t.Authorization=`Bearer ${e.clientSecret}`),(await xo.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: ${Qi(e)}`),void await this.clearAuthData()}}}async saveOAuthToken(e){const t=(o=e.expires_in)>=Ki?o*Ji:Date.now()+o*Ji;var o;this.config.accessToken=e.access_token,this.config.refreshToken=e.refresh_token,this.config.tokenExpiresAt=t,await l.saveConfig({accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:t})}}const Zi="",Xi="",es="",ts="",os="",is="",ss="",ns="",rs="[PROC]",as="[INFO]",cs="[WARN]",ls="[ERR]",ds="[DONE]",ps="[DBG]",us={debug:0,verbose:1,info:2,success:3,warn:4,error:5};function ms(e){return`${es}${Xi}${e}${Zi}`}class gs{constructor(e,t,o="info"){var i,s;this.log=e,this.silent="json"===t,this.useColor=this.detectColorSupport(),this.level=o,this.levelPriority=(s=()=>2,null!=(i=us[o])?i:s())}detectColorSupport(){return!0===function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([process,"access",e=>e.stderr,"optionalAccess",e=>e.isTTY])&&void 0===process.env.NO_COLOR}paint(e,t){return this.useColor?`${e}${t}${Zi}`:t}shouldOutput(e){return!this.silent&&us[e]>=this.levelPriority}verbose(e,...t){this.log.verbose(e,...t),this.shouldOutput("verbose")&&process.stderr.write(`${ms(rs)} ${this.paint(ss,e)}\n`)}info(e,...t){this.log.info(e,...t),this.shouldOutput("info")&&process.stderr.write(`${ms(as)} ${this.paint(Zi,e)}\n`)}warn(e,...t){this.log.warn(e,...t),this.shouldOutput("warn")&&process.stderr.write(`${ms(cs)} ${this.paint(is,e)}\n`)}error(e,...t){this.log.error(e,...t),this.shouldOutput("error")&&process.stderr.write(`${ms(ls)} ${this.paint(ts,e)}\n`)}success(e,...t){this.log.success(e,...t),this.shouldOutput("success")&&process.stderr.write(`${ms(ds)} ${this.paint(os,e)}\n`)}debug(e,...t){this.log.debug(e,...t),this.shouldOutput("debug")&&process.stderr.write(`${ms(ps)} ${this.paint(ns,e)}\n`)}}class hs{constructor(e){const{format:t}=e;this.formatter=function(e){return"text"===e?new U:new I}(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 fs(e,t){return null!=e?e:t()}async function _s(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 ys,bs,vs,ws,Cs,Es,Is,As,Ss,js,Ps,ks,Ts,zs,Rs,xs,Ls,Os,Ds,Us,Bs,qs,Ms,Ns,$s,Gs,Fs,Vs,Ws,Hs,Js,Ks,Qs,Ys,Zs,Xs,en,tn,on,sn,nn,rn,an,cn,ln,dn,pn,un,mn,gn,hn,fn,_n,yn,bn,vn,wn,Cn,En,In,An,Sn,jn,Pn,kn,Tn,zn,Rn,xn,Ln,On,Dn,Un,Bn,qn,Mn,Nn,$n,Gn,Fn,Vn,Wn,Hn,Jn,Kn,Qn,Yn,Zn,Xn,er,tr,or,ir,sr,nr,rr,ar,cr,lr,dr,pr,ur,mr,gr,hr,fr,_r,yr,br,vr,wr,Cr,Er,Ir,Ar,Sr,jr,Pr,kr,Tr,zr,Rr,xr,Lr,Or,Dr,Ur,Br,qr,Mr,Nr;function $r(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!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"}(ys||(ys={})),function(e){e[e.OldVersion=0]="OldVersion";e[e.MiddleVersion=1]="MiddleVersion";e[e.NewVersion=2]="NewVersion";e[e.MiddleVersionNotPrompt=3]="MiddleVersionNotPrompt"}(bs||(bs={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(vs||(vs={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(ws||(ws={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Cs||(Cs={})),function(e){e[e.Current=1]="Current";e[e.Previous=2]="Previous";e[e.Start=3]="Start";e[e.MostSuitable=4]="MostSuitable"}(Es||(Es={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Is||(Is={})),function(e){e[e.Default=0]="Default";e[e.Function=1]="Function"}(As||(As={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned"}(Ss||(Ss={})),function(e){e[e.LimitedReadWrite=1]="LimitedReadWrite";e[e.ReadOnly=2]="ReadOnly";e[e.UnlimitedReadWrite=3]="UnlimitedReadWrite";e[e.RWModeMax=4]="RWModeMax"}(js||(js={})),function(e){e[e.Default=0]="Default";e[e.DouyinAvatar=1]="DouyinAvatar"}(Ps||(Ps={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(ks||(ks={})),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"}(Ts||(Ts={})),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"}(zs||(zs={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Rs||(Rs={})),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"}(xs||(xs={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Ls||(Ls={})),function(e){e[e.SLM=0]="SLM";e[e.LLM=1]="LLM"}(Os||(Os={})),function(e){e[e.Pre=1]="Pre";e[e.Post=2]="Post";e[e.PreAndPost=3]="PreAndPost"}(Ds||(Ds={})),function(e){e[e.Default=0]="Default";e[e.CustomizePrompt=1]="CustomizePrompt"}(Us||(Us={})),function(e){e[e.ReplyBottom=0]="ReplyBottom";e[e.CardList=1]="CardList"}(Bs||(Bs={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(qs||(qs={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(Ms||(Ms={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(Ns||(Ns={})),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"}($s||($s={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(Gs||(Gs={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(Fs||(Fs={})),function(e){e[e.Curve=0]="Curve";e[e.Straight=1]="Straight"}(Vs||(Vs={})),function(e){e[e.Flow=1]="Flow";e[e.Host=2]="Host"}(Ws||(Ws={})),function(e){e[e.NO_NEED=1]="NO_NEED";e[e.USE_MANUAL=2]="USE_MANUAL";e[e.USE_LLM=3]="USE_LLM"}(Hs||(Hs={})),function(e){e[e.EQUAL=1]="EQUAL";e[e.NOT_EQUAL=2]="NOT_EQUAL";e[e.GREATER_THAN=3]="GREATER_THAN";e[e.LESS_THAN=4]="LESS_THAN";e[e.GREATER_EQUAL=5]="GREATER_EQUAL";e[e.LESS_EQUAL=6]="LESS_EQUAL";e[e.IN=7]="IN";e[e.NOT_IN=8]="NOT_IN";e[e.IS_NULL=9]="IS_NULL";e[e.IS_NOT_NULL=10]="IS_NOT_NULL";e[e.LIKE=11]="LIKE";e[e.NOT_LIKE=12]="NOT_LIKE"}(Js||(Js={})),function(e){e[e.Input=0]="Input";e[e.Variable=1]="Variable"}(Ks||(Ks={})),function(e){e[e.Default=0]="Default";e[e.FromSaas=1]="FromSaas"}(Qs||(Qs={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(Ys||(Ys={})),function(e){e[e.FunctionCall=1]="FunctionCall";e[e.Independent=2]="Independent"}(Zs||(Zs={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(Xs||(Xs={})),function(e){e[e.ManualUpdate=1]="ManualUpdate";e[e.AutoUpdate=2]="AutoUpdate"}(en||(en={})),function(e){e[e.SemanticSearch=0]="SemanticSearch";e[e.HybirdSearch=1]="HybirdSearch";e[e.FullTextSearch=20]="FullTextSearch"}(tn||(tn={})),function(e){e[e.Public=1]="Public";e[e.Anonymous=2]="Anonymous";e[e.Custom=3]="Custom"}(on||(on={})),function(e){e[e.Random=0]="Random";e[e.All=1]="All"}(sn||(sn={})),function(e){e[e.System=0]="System";e[e.Custom=1]="Custom";e[e.Disable=2]="Disable";e[e.OriBot=3]="OriBot"}(nn||(nn={})),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"}(rn||(rn={})),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"}(cn||(cn={})),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"}(ln||(ln={})),function(e){e[e.BotQuery=1]="BotQuery";e[e.Plugin=2]="Plugin";e[e.Workflow=3]="Workflow"}(dn||(dn={})),function(e){e[e.Unknown=0]="Unknown";e[e.Webhook=1]="Webhook"}(pn||(pn={})),function(e){e[e.Unknown=0]="Unknown";e[e.Time=1]="Time";e[e.Event=2]="Event"}(un||(un={})),function(e){e[e.NoHistory=0]="NoHistory";e[e.NeedHistory=1]="NeedHistory"}(mn||(mn={})),function(e){e[e.NoTriggered=0]="NoTriggered";e[e.Triggered=1]="Triggered";e[e.DoAction=2]="DoAction";e[e.WaitToPush=3]="WaitToPush";e[e.PushSuccess=4]="PushSuccess";e[e.PushFail=5]="PushFail"}(gn||(gn={})),function(e){e[e.Init=0]="Init";e[e.Activated=1]="Activated";e[e.Deactivated=2]="Deactivated";e[e.Suspended=3]="Suspended"}(hn||(hn={})),function(e){e[e.Preset=1]="Preset";e[e.UserTask=2]="UserTask";e[e.PluginRunTask=3]="PluginRunTask"}(fn||(fn={})),function(e){e[e.Deploying=0]="Deploying";e[e.Successful=1]="Successful";e[e.Failed=2]="Failed"}(_n||(_n={})),function(e){e[e.All=0]="All";e[e.Bind=1]="Bind";e[e.UnBind=2]="UnBind"}(yn||(yn={})),function(e){e[e.CreateTime=0]="CreateTime";e[e.UpdateTime=1]="UpdateTime"}(bn||(bn={})),function(e){e[e.EventMeta=1]="EventMeta";e[e.ProfileMeta=2]="ProfileMeta"}(vn||(vn={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(wn||(wn={})),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"}(Cn||(Cn={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(En||(En={})),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"}(In||(In={})),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"}(An||(An={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(Sn||(Sn={})),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"}(jn||(jn={})),function(e){e[e.Upgrade=1]="Upgrade";e[e.BrowseOldNoPrompt=2]="BrowseOldNoPrompt"}(Pn||(Pn={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(kn||(kn={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(Tn||(Tn={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(zn||(zn={})),function(e){e[e.Visit=1]="Visit";e[e.Edit=2]="Edit"}(Rn||(Rn={})),function(e){e[e.Online=1]="Online";e[e.Offline=2]="Offline"}(xn||(xn={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online"}(Ln||(Ln={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(On||(On={})),function(e){e[e.AutoGenBeforePublish=1]="AutoGenBeforePublish"}(Dn||(Dn={})),function(e){e[e.CozeHome=1]="CozeHome";e[e.Space=2]="Space"}(Un||(Un={})),function(e){e[e.Undefined=0]="Undefined";e[e.PersonalDraft=1]="PersonalDraft";e[e.Base=2]="Base";e[e.Publish=3]="Publish"}(Bn||(Bn={})),function(e){e[e.Undefined=0]="Undefined";e[e.Committed=1]="Committed";e[e.Behind=2]="Behind";e[e.NoDraftReplica=3]="NoDraftReplica"}(qn||(qn={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(Mn||(Mn={})),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"}(Nn||(Nn={})),function(e){e[e.Personal=1]="Personal";e[e.Organization=2]="Organization"}($n||($n={})),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"}(Gn||(Gn={})),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"}(Fn||(Fn={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned";e[e.MoveFail=3]="MoveFail"}(Vn||(Vn={})),function(e){e[e.ByteTree=1]="ByteTree";e[e.GPTAK=2]="GPTAK";e[e.MaasAK=3]="MaasAK"}(Wn||(Wn={})),function(e){e[e.Init=0]="Init";e[e.Generating=1]="Generating";e[e.Success=2]="Success";e[e.Fail=3]="Fail";e[e.Cancel=4]="Cancel"}(Hn||(Hn={})),function(e){e[e.BotStore=1]="BotStore"}(Jn||(Jn={})),function(e){e[e.shorcutIcon=1]="shorcutIcon"}(Kn||(Kn={})),function(e){e[e.Onboarding=0]="Onboarding";e[e.BackgroundImage=1]="BackgroundImage"}(Qn||(Qn={})),function(e){e[e.BasicUser=1]="BasicUser";e[e.ExternalUser=2]="ExternalUser";e[e.RootUser=3]="RootUser"}(Yn||(Yn={})),function(e){e[e.GetInfo=1]="GetInfo"}(Zn||(Zn={})),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"}(Xn||(Xn={})),function(e){e[e.Apply=1]="Apply";e[e.Invite=2]="Invite";e[e.EnterpriseApply=3]="EnterpriseApply"}(er||(er={})),function(e){e[e.GPT=1]="GPT";e[e.Claude=3]="Claude";e[e.Gemini=11]="Gemini";e[e.Moonshot=12]="Moonshot";e[e.GLM=13]="GLM";e[e.QWen=15]="QWen";e[e.DeekSeek=19]="DeekSeek";e[e.StepFun=23]="StepFun"}(tr||(tr={})),function(e){e[e.Douyin=1]="Douyin"}(or||(or={})),function(e){e[e.GPTOpenAPI=1]="GPTOpenAPI";e[e.Maas=2]="Maas";e[e.LLMFlow=3]="LLMFlow";e[e.Merlin=4]="Merlin"}(ir||(ir={})),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"}(sr||(sr={})),function(e){e[e.All=0]="All";e[e.Unread=1]="Unread"}(nr||(nr={})),function(e){e[e.Bot=1]="Bot"}(rr||(rr={})),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"}(ar||(ar={})),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"}(cr||(cr={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ShortcutCommand=3]="ShortcutCommand";e[e.Task=4]="Task"}(lr||(lr={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Knowledge=4]="Knowledge"}(dr||(dr={})),function(e){e[e.NoPublish=0]="NoPublish";e[e.HadPublished=1]="HadPublished"}(pr||(pr={})),function(e){e[e.Success=1]="Success";e[e.Failed=2]="Failed";e[e.InReview=3]="InReview"}(ur||(ur={})),function(e){e[e.Unread=1]="Unread";e[e.Read=2]="Read"}(mr||(mr={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(gr||(gr={})),function(e){e[e.UnLimit=1]="UnLimit";e[e.Forbidden=2]="Forbidden"}(hr||(hr={})),function(e){e[e.Plugin=1]="Plugin";e[e.NewBotIDEGuide=2]="NewBotIDEGuide";e[e.NewBeginnerGuide=3]="NewBeginnerGuide"}(fr||(fr={})),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"}(_r||(_r={})),function(e){e[e.All=0]="All";e[e.Self=1]="Self"}(yr||(yr={})),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"}(br||(br={})),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"}(vr||(vr={})),function(e){e[e.EnterpriseUser=1]="EnterpriseUser";e[e.ExternalUser=2]="ExternalUser"}(wr||(wr={})),function(e){e[e.Normal=0]="Normal";e[e.DevMode=1]="DevMode"}(Cr||(Cr={})),function(e){e[e.DraftBot=1]="DraftBot";e[e.Project=2]="Project";e[e.Space=3]="Space";e[e.DouyinAvatarBot=4]="DouyinAvatarBot"}(Er||(Er={})),function(e){e[e.Default=0]="Default";e[e.Owner=1]="Owner";e[e.Admin=2]="Admin";e[e.Member=3]="Member";e[e.Guest=4]="Guest"}(Ir||(Ir={})),function(e){e[e.Professional=1]="Professional"}(Ar||(Ar={})),function(e){e[e.Personal=1]="Personal";e[e.Team=2]="Team"}(Sr||(Sr={})),function(e){e[e.Dark=1]="Dark";e[e.Light=2]="Light"}(jr||(jr={})),function(e){e[e.AlwaysOn=0]="AlwaysOn";e[e.AlwaysOff=1]="AlwaysOff"}(Pr||(Pr={})),function(e){e[e.CozeAssistantGuide=1]="CozeAssistantGuide"}(kr||(kr={})),function(e){e[e.Normal=1]="Normal";e[e.Banned=2]="Banned";e[e.Canceled=3]="Canceled"}(Tr||(Tr={})),function(e){e[e.External=0]="External";e[e.Internal=1]="Internal"}(zr||(zr={})),function(e){e[e.Invisible=0]="Invisible";e[e.Visible=1]="Visible";e[e.SocietyInvisible=2]="SocietyInvisible"}(Rr||(Rr={})),function(e){e[e.SingleAgent=1]="SingleAgent";e[e.MultiAgent=2]="MultiAgent";e[e.WorkflowAsAgent=3]="WorkflowAsAgent"}(xr||(xr={})),function(e){e[e.Preset=1]="Preset";e[e.Library=2]="Library"}(Lr||(Lr={})),function(e){e[e.DatasetServiceValid=0]="DatasetServiceValid";e[e.DatasetServiceInvalid=1]="DatasetServiceInvalid"}(Or||(Or={})),function(e){e[e.DatasetValid=0]="DatasetValid";e[e.DatasetInvalid=1]="DatasetInvalid"}(Dr||(Dr={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(Ur||(Ur={})),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"}(Br||(Br={})),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"}(qr||(qr={})),function(e){e[e.SendTypeQuery=0]="SendTypeQuery";e[e.SendTypePanel=1]="SendTypePanel"}(Mr||(Mr={})),function(e){e[e.ToolTypeWorkFlow=1]="ToolTypeWorkFlow";e[e.ToolTypePlugin=2]="ToolTypePlugin"}(Nr||(Nr={}));class Gr{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Gr.prototype.__init.call(this),Gr.prototype.__init2.call(this),this.request=$r([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=$r([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}GetSpaceInfoV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/info"),s={space_id:o.space_id,join_space_type:o.join_space_type};return this.request({url:i,method:"POST",data:s},t)}DeleteSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/delete"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}SaveSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/save"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri,space_type:o.space_type,space_mode:o.space_mode,space_config:o.space_config,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetSpaceListV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/list"),s={search_word:o.search_word,enterprise_id:o.enterprise_id,organization_id:o.organization_id,scope_type:o.scope_type,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}UpdateAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_agent"),s={id:o.id,reference_id:o.reference_id,current_version:o.current_version,space_id:o.space_id,bot_id:o.bot_id,base_commit_version:o.base_commit_version,name:o.name,description:o.description,position:o.position,icon_uri:o.icon_uri,intents:o.intents,work_info:o.work_info,is_delete:o.is_delete};return this.request({url:i,method:"POST",data:s},t)}BatchCreateAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/batch_create_agent"),s={space_id:o.space_id,bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,agent_cnt:o.agent_cnt,base_commit_version:o.base_commit_version,version_compat:o.version_compat};return this.request({url:i,method:"POST",data:s},t)}GetPublishBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_publish_bot_list"),s={space_id:o.space_id,bot_mode:o.bot_mode,page_num:o.page_num,page_size:o.page_size,name:o.name,login_user_create:o.login_user_create,bot_id:o.bot_id};return this.request({url:i,method:"GET",params:s},t)}MGetBotByVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/mget_bot_by_version"),s={bot_versions:o.bot_versions,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}BotLastPublishInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_last_publish_info"),s={space_id:o.space_id,bot_id:o.bot_id,bot_mode:o.bot_mode};return this.request({url:i,method:"GET",params:s},t)}ProduceBot(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/produce/create_bot"),s={space_id:o.space_id,name:o.name,description:o.description,icon_url:o.icon_url,icon_uri:o.icon_uri,prompt:o.prompt,plugin_apis:o.plugin_apis,prologue:o.prologue,suggested_questions:o.suggested_questions,bot_source:o.bot_source};return this.request({url:i,method:"POST",data:s},t)}UpdateProducedBot(e,t){const o=e,i=this.genBaseURL("/api/playground_api/produce/update_bot"),s={bot_id:o.bot_id,name:o.name,description:o.description,icon_url:o.icon_url,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetPublishedBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_version/get_published_bot_list"),s={space_id_list:o.space_id_list,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}GetBotVersionInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_version/get_bot_version_info"),s={bot_id:o.bot_id,version:o.version,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}DuplicateBotVersionToSpace(e,t){const o=e,i=this.genBaseURL("/api/playground_api/dup_bot_version"),s={target_space_id:o.target_space_id,bot_id:o.bot_id,version:o.version,name:o.name,dup_society_host:o.dup_society_host};return this.request({url:i,method:"POST",data:s},t)}UpdateUserRiskAlertInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/update_user_risk_alert_info"),s={risk_alert_type:o.risk_alert_type,switch_info:o.switch_info};return this.request({url:i,method:"POST",data:s},t)}GetUserRiskAlertInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_user_risk_alert_info"),s={risk_alert_type_list:o.risk_alert_type_list,switch_type_list:o.switch_type_list},n={Cookie:o.Cookie};return this.request({url:i,method:"POST",data:s,headers:n},t)}DraftBotCollaboration(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/collaboration"),s={space_id:o.space_id,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}BotInfoAudit(e,t){const o=e,i=this.genBaseURL("/api/playground_api/audit/bot_info"),s={bot_id:o.bot_id,bot_audit_info:o.bot_audit_info,space_id:o.space_id,bot_mode:o.bot_mode};return this.request({url:i,method:"POST",data:s},t)}TimeCapsuleInvokeEvent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/timecapsule_invoke_event"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}InviteMemberLinkV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/invite"),s={space_id:o.space_id,team_invite_link_status:o.team_invite_link_status,func:o.func};return this.request({url:i,method:"POST",data:s},t)}SpaceMemberDetailV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/detail"),s={space_id:o.space_id,search_word:o.search_word,space_role_type:o.space_role_type,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}JoinSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/join"),s={space_id:o.space_id,join_space_type:o.join_space_type,is_reject:o.is_reject};return this.request({url:i,method:"POST",data:s},t)}UpdateSpaceMemberV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/update"),s={space_id:o.space_id,user_id:o.user_id,space_role_type:o.space_role_type};return this.request({url:i,method:"POST",data:s},t)}TransferSpaceV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/transfer"),s={space_id:o.space_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}RemoveSpaceMemberV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/remove"),s={space_id:o.space_id,remove_user_id:o.remove_user_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}SearchMemberV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/member/search"),s={search_list:o.search_list,space_id:o.space_id,search_volcano_account_list:o.search_volcano_account_list,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}AddBotSpaceMemberV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/member/add"),s={member_info_list:o.member_info_list,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}ExitSpaceV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/exit"),s={space_id:o.space_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}GetBotPopupInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/operate/get_bot_popup_info"),s={bot_popup_types:o.bot_popup_types,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}UpdateBotPopupInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/operate/update_bot_popup_info"),s={bot_popup_type:o.bot_popup_type,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}GenerateDescription(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/generate_description"),s={bot_name:o.bot_name,prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}DraftBotPublishHistoryDetail(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/publish_history_detail"),s={bot_id:o.bot_id,space_id:o.space_id,publish_id:o.publish_id,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GenerateStoreCategory(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/generate_store_category"),s={bot_name:o.bot_name,bot_description:o.bot_description,prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}UpdateMultiAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_multi_agent"),s={space_id:o.space_id,bot_id:o.bot_id,session_type:o.session_type,base_commit_version:o.base_commit_version,connector_type:o.connector_type};return this.request({url:i,method:"POST",data:s},t)}SwitchAgentVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/switch_agent_version"),s={bot_id:o.bot_id,space_id:o.space_id,operate_type:o.operate_type};return this.request({url:i,method:"POST",data:s},t)}LangDetect(e,t){const o=e,i=this.genBaseURL("/api/playground_api/audio/lang/detect"),s={detect_text_list:o.detect_text_list};return this.request({url:i,method:"POST",data:s},t)}GetImagexShortUrl(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_imagex_url"),s={uris:o.uris,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetPlatformCommonConfig(e,t){const o=this.genBaseURL("/api/playground_api/get_platform_common_config");return this.request({url:o,method:"GET"},t)}CreateShortcutCommand(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/create_shortcut_command"),s={object_id:o.object_id,shortcuts:o.shortcuts};return this.request({url:i,method:"POST",data:s},t)}MGetUserBasicInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/mget_user_info"),s={user_ids:o.user_ids,need_user_status:o.need_user_status,need_enterprise_identity:o.need_enterprise_identity,need_volcano_user_name:o.need_volcano_user_name};return this.request({url:i,method:"POST",data:s},t)}BindVolcanoTrn(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/bind_volcano_trn"),s={space_id:o.space_id,trn:o.trn,account_name:o.account_name};return this.request({url:i,method:"POST",data:s},t)}UnbindVolcanoTrn(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/unbind_volcano_trn"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}RetrieveFileOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/retrieve"),s={file_id:o.file_id};return this.request({url:i,method:"GET",params:s},t)}RetrieveFileContentOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/content/retrieve"),s={file_id:o.file_id};return this.request({url:i,method:"GET",params:s},t)}UploadFileOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/upload"),s={Data:o.Data},n={"Content-Type":o["Content-Type"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}BotInfoCheck(e,t){const o=e,i=this.genBaseURL("/api/playground_api/check/bot_info_check"),s={bot_id:o.bot_id,space_id:o.space_id,bot_audit_info:o.bot_audit_info};return this.request({url:i,method:"POST",data:s},t)}SupportVoiceCall(e,t){const o=e,i=this.genBaseURL("/api/playground_api/support_voice_call"),s={voice_id_list:o.voice_id_list};return this.request({url:i,method:"POST",data:s},t)}CreateUpdateShortcutCommand(e,t){const o=e,i=this.genBaseURL("/api/playground_api/create_update_shortcut_command"),s={object_id:o.object_id,space_id:o.space_id,shortcuts:o.shortcuts};return this.request({url:i,method:"POST",data:s},t)}MoveDraftBot(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/move_draft_bot"),s={bot_id:o.bot_id,target_spaceId:o.target_spaceId,from_spaceId:o.from_spaceId,move_action:o.move_action};return this.request({url:i,method:"POST",data:s},t)}GetShortcutAvailNodes(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_shortcut_avail_nodes"),s={bot_id:o.bot_id,space_id:o.space_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}MarkReadNotice(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/mark_read_notice"),s={bot_id:o.bot_id,pic_type:o.pic_type};return this.request({url:i,method:"POST",data:s},t)}CancelGenerateGif(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/cancel_generate_gif"),s={task_id:o.task_id};return this.request({url:i,method:"POST",data:s},t)}GetPicTask(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/get_pic_task"),s={bot_id:o.bot_id,pic_type:o.pic_type};return this.request({url:i,method:"POST",data:s},t)}GeneratePic(e,t){const o=e,i=this.genBaseURL("/api/playground_api/gen_img/generate_pic"),s={gen_prompt:o.gen_prompt,image_url:o.image_url,image_uri:o.image_uri,bot_id:o.bot_id,pic_type:o.pic_type,device_id:o.device_id,bot_name:o.bot_name,bot_desc:o.bot_desc};return this.request({url:i,method:"POST",data:s},t)}GetGenPicTimes(e,t){const o=this.genBaseURL("/api/playground_api/gen_img/get_gen_pic_times");return this.request({url:o,method:"POST"},t)}ListStyle(e,t){const o=this.genBaseURL("/api/playground_api/gen_img/list_style");return this.request({url:o,method:"POST"},t)}GetFileUrls(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_file_list"),s={scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetDraftBotInfoAgw(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/get_draft_bot_info"),s={bot_id:o.bot_id,version:o.version,commit_version:o.commit_version};return this.request({url:i,method:"POST",data:s},t)}CommitDraftBotInfoAgw(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/commit_draft_bot_info"),s={bot_id:o.bot_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}UpdateDraftBotInfoAgw(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/update_draft_bot_info"),s={bot_info:o.bot_info,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}GetUserQueryCollectOption(e,t){const o=this.genBaseURL("/api/playground_api/draftbot/get_user_query_collect_option");return this.request({url:o,method:"GET"},t)}GenerateUserQueryCollectPolicy(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/generate_user_query_collect_policy"),s={bot_id:o.bot_id,developer_name:o.developer_name,contact_information:o.contact_information};return this.request({url:i,method:"POST",data:s},t)}GetCozeProRights(e,t){const o=this.genBaseURL("/api/playground_api/get_coze_pro_rights");return this.request({url:o,method:"POST"},t)}GetPolicyContent(e,t){const o=e,i=this.genBaseURL(`/api/playground_api/private_policy/${o.secret}`);return this.request({url:i,method:"GET"},t)}UpdateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_agent_v2"),s={id:o.id,reference_id:o.reference_id,current_version:o.current_version,space_id:o.space_id,bot_id:o.bot_id,base_commit_version:o.base_commit_version,name:o.name,description:o.description,position:o.position,icon_uri:o.icon_uri,intents:o.intents,is_delete:o.is_delete,prompt_info:o.prompt_info,model_info:o.model_info,plugin_info_list:o.plugin_info_list,knowledge:o.knowledge,workflow_info_list:o.workflow_info_list,jump_config:o.jump_config,suggest_reply_info:o.suggest_reply_info,hook_info:o.hook_info};return this.request({url:i,method:"POST",data:s},t)}CopyAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/copy_agent_v2"),s={bot_id:o.bot_id,agent_id:o.agent_id,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}CreateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/create_agent_v2"),s={bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}BatchCreateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/batch_create_agent_v2"),s={bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,agent_cnt:o.agent_cnt,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyGetLinkMetaInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/get_link_meta_info"),s={auth_code:o.auth_code};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyTaskConfirm(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/copy_task_confirm"),s={auth_code:o.auth_code};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyGenerateAuthLink(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/generate_auth_link"),s={copy_user_id:o.copy_user_id,target_space_id:o.target_space_id};return this.request({url:i,method:"POST",data:s},t)}GetOpVoiceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_op_voice_list"),s={voice_ids:o.voice_ids,name:o.name,style_id:o.style_id,language_code:o.language_code,status:o.status,page_index:o.page_index,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetSupportLanguage(e,t){const o=this.genBaseURL("/api/playground_api/get_support_language");return this.request({url:o,method:"GET"},t)}SynchronizeVoiceList(e,t){const o=this.genBaseURL("/api/playground_api/synchronize_voice_list");return this.request({url:o,method:"GET"},t)}CheckBotAllModelPluginIds(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/check_bot_all_model_plugin_ids"),s={bot_id:o.bot_id,commit_version:o.commit_version};return this.request({url:i,method:"POST",data:s},t)}GetBotCollaborationQuota(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/collaboration_quota"),s={bot_id:o.bot_id,only_config_item:o.only_config_item,account_type:o.account_type};return this.request({url:i,method:"POST",data:s},t)}OpenCreateSpace(e,t){const o=e||{},i=this.genBaseURL("/v1/workspaces"),s={name:o.name,description:o.description,icon_file_id:o.icon_file_id,coze_account_id:o.coze_account_id,owner_uid:o.owner_uid};return this.request({url:i,method:"POST",data:s},t)}NoticeMarkRead(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/notice/mark_read"),s={notice_ids:o.notice_ids,mark_all:o.mark_all};return this.request({url:i,method:"POST",data:s},t)}GetNoticeList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/notice/get_list"),s={cursor:o.cursor,count:o.count,notice_rank_type:o.notice_rank_type};return this.request({url:i,method:"POST",data:s},t)}GetNoticeUnreadCount(e,t){const o=this.genBaseURL("/api/playground_api/notice/get_unread_count");return this.request({url:o,method:"POST"},t)}OpenSpaceList(e,t){const o=e||{},i=this.genBaseURL("/v1/workspaces"),s={page_num:o.page_num,page_size:o.page_size,enterprise_id:o.enterprise_id,user_id:o.user_id,coze_account_id:o.coze_account_id,scope:o.scope};return this.request({url:i,method:"GET",params:s},t)}ReportUserBehavior(e,t){const o=e,i=this.genBaseURL("/api/playground_api/report_user_behavior"),s={resource_id:o.resource_id,resource_type:o.resource_type,behavior_type:o.behavior_type,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_user_config"),s={risk_alert_type_list:o.risk_alert_type_list,switch_type_list:o.switch_type_list},n={Cookie:o.Cookie};return this.request({url:i,method:"POST",data:s,headers:n},t)}UpdateUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/update_user_config"),s={risk_alert_type:o.risk_alert_type,switch_info:o.switch_info};return this.request({url:i,method:"POST",data:s},t)}GetRecentDraftBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/get_recent_draft_bot"),s={behavior_type:o.behavior_type,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}GetPromptResourceInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_prompt_resource_info"),s={prompt_resource_id:o.prompt_resource_id};return this.request({url:i,method:"GET",params:s},t)}UpsertPromptResource(e,t){const o=e,i=this.genBaseURL("/api/playground_api/upsert_prompt_resource"),s={prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}DeletePromptResource(e,t){const o=e,i=this.genBaseURL("/api/playground_api/delete_prompt_resource"),s={prompt_resource_id:o.prompt_resource_id};return this.request({url:i,method:"POST",data:s},t)}GetPromptReferenceInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_prompt_reference_info"),s={space_id:o.space_id,reference_id:o.reference_id,reference_type:o.reference_type,api_id:o.api_id,project_id:o.project_id,avatar_bot_id:o.avatar_bot_id};return this.request({url:i,method:"POST",data:s},t)}GetOfficialPromptResourceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_official_prompt_list"),s={keyword:o.keyword};return this.request({url:i,method:"POST",data:s},t)}GetByteTreeByName(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/search_byte_tree"),s={name:o.name},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}CreatePrivateModel(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/create_private_model"),s={space_id:o.space_id,model_vendor:o.model_vendor,model_show_name:o.model_show_name,model_arch:o.model_arch,ak:o.ak,token_limit:o.token_limit,upper_limit_of_max_token:o.upper_limit_of_max_token,function_call:o.function_call,multimodal:o.multimodal,multimodal_types:o.multimodal_types,form_detail:o.form_detail,record_id:o.record_id,maas_model_name:o.maas_model_name,maas_model_version:o.maas_model_version,maas_model_customer_id:o.maas_model_customer_id,model_family:o.model_family,space_id_i18n:o.space_id_i18n,operator:o.operator,email:o.email,employee_id:o.employee_id,presence_penalty_config:o.presence_penalty_config,frequency_penalty_config:o.frequency_penalty_config,temperature_config:o.temperature_config,top_p_config:o.top_p_config},n={"x-inner-auth":o["x-inner-auth"],"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}CheckExemptFormInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/check_exempt_form_info"),s={exempt_form_type:o.exempt_form_type,space_id:o.space_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}SetByteTreeForSpace(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/set_byte_tree_for_space"),s={space_id:o.space_id,byte_tree_node_id:o.byte_tree_node_id,byte_tree_node_name:o.byte_tree_node_name,form_detail:o.form_detail,record_id:o.record_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetModelCapability(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bpm/get_model_capability"),s={vendor:o.vendor,model_arch:o.model_arch,maas_model_name:o.maas_model_name,maas_model_version:o.maas_model_version,maas_customer_id:o.maas_customer_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetSpaceDetail(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/detail"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}RevocateSpaceInvite(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/revocate_invite"),s={space_id:o.space_id,invite_user_id:o.invite_user_id};return this.request({url:i,method:"GET",params:s},t)}SaveVolcanoUserManageInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/save_volcano_user_manage_info"),s={volcano_basic_user_config:o.volcano_basic_user_config};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoUserManageInfo(e,t){const o=this.genBaseURL("/api/playground_api/coze_pro/get_volcano_user_manage_info");return this.request({url:o,method:"POST"},t)}GetSpaceInviteManageList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/invite_manage_list"),s={space_id:o.space_id,space_invite_status:o.space_invite_status,search_word:o.search_word,page:o.page,size:o.size};return this.request({url:i,method:"GET",params:s},t)}DebugDouYin(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/debug"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}GetDouYinAuthCode(e,t){const o=this.genBaseURL("/api/playground_api/douyin/get_auth_qr_code");return this.request({url:o,method:"GET"},t)}GetDouyinAvatarInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/douyin/v1/get_avatar_info"),s={is_draft:o.is_draft,body:o.body},n={"Open-Platform-App-ID":o["Open-Platform-App-ID"],"Byte-Signature":o["Byte-Signature"],"Byte-Timestamp":o["Byte-Timestamp"],"Byte-Nonce-Str":o["Byte-Nonce-Str"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}DouYinAuthUserList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/auth_user_list"),s={page_index:o.page_index,page_size:o.page_size,bind_status:o.bind_status,order_by:o.order_by};return this.request({url:i,method:"POST",data:s},t)}GetDebugDouYinStatus(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/get_debug_status"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}CanUserApplyClose(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/coze_pro/can_user_apply_close"),s={AccountId:o.AccountId,EventName:o.EventName,Action:o.Action,Version:o.Version},n={"X-Tt-Logid":o["X-Tt-Logid"],"X-Top-Service":o["X-Top-Service"],"X-Top-Region":o["X-Top-Region"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}CreateRoom(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/create_room"),s={bot_id:o.bot_id,conversation_id:o.conversation_id,scene:o.scene,voice_id:o.voice_id,video_config:o.video_config};return this.request({url:i,method:"POST",data:s},t)}GetVoiceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_list"),s={page_index:o.page_index,page_size:o.page_size,language_code:o.language_code};return this.request({url:i,method:"POST",data:s},t)}GetVoiceByIds(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_by_ids"),s={voice_id_map:o.voice_id_map,voice_type:o.voice_type,space_id:o.space_id,emotion_config:o.emotion_config,voice_biz_scene:o.voice_biz_scene};return this.request({url:i,method:"POST",data:s},t)}GrayVoice(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gray_voice"),s={bot_id:o.bot_id,language_to_voice_id:o.language_to_voice_id};return this.request({url:i,method:"POST",data:s},t)}GetSpaceApplyManageList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/apply_manage_list"),s={space_id:o.space_id,space_apply_status:o.space_apply_status,search_word:o.search_word,page:o.page,size:o.size};return this.request({url:i,method:"GET",params:s},t)}DraftBotCrossSpaceCopy(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/crossspace_copy"),s={bot_id:o.bot_id,to_space_id:o.to_space_id};return this.request({url:i,method:"POST",data:s},t)}RemovePublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/remove_publish_member"),s={space_id:o.space_id,member_list:o.member_list};return this.request({url:i,method:"POST",data:s},t)}AddPublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/add_publish_member"),s={space_id:o.space_id,member_list:o.member_list};return this.request({url:i,method:"POST",data:s},t)}SearchAddablePublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/search_addable_publish_member"),s={space_id:o.space_id,search_word:o.search_word,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}PublishMemberList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/publish_member_list"),s={space_id:o.space_id,search_word:o.search_word,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}OperateSpaceApply(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/operate_apply"),s={space_id:o.space_id,enterprise_id:o.enterprise_id,organization_id:o.organization_id,apply_id_list:o.apply_id_list,space_apply_status:o.space_apply_status};return this.request({url:i,method:"POST",data:s},t)}ImportSpaceConfirm(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/confirm"),s={space_id_list:o.space_id_list,enterprise_id:o.enterprise_id,organization_id:o.organization_id,personal_space_new_name:o.personal_space_new_name,user_id_list:o.user_id_list};return this.request({url:i,method:"POST",data:s},t)}ImportSpaceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/list"),s={enterprise_id:o.enterprise_id,organization_id:o.organization_id,search_word:o.search_word};return this.request({url:i,method:"GET",params:s},t)}ImportSpaceUserList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/user_list"),s={space_id_list:o.space_id_list,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetDouYinInfo(e,t){const o=this.genBaseURL("/api/playground_api/douyin/get_douyin_info");return this.request({url:o,method:"POST"},t)}LongTermMemoryList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/list"),s={bot_id:o.bot_id,connector_id:o.connector_id,offset:o.offset,limit:o.limit,time_capsule_item_type:o.time_capsule_item_type};return this.request({url:i,method:"GET",params:s},t)}LongTermMemoryUpdate(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/update"),s={bot_id:o.bot_id,connector_id:o.connector_id,biz_id:o.biz_id,new_content:o.new_content,event_ms:o.event_ms,ext:o.ext,tags:o.tags,time_capsule_item_type:o.time_capsule_item_type,iid:o.iid,meta_type:o.meta_type,memory_type:o.memory_type};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryClearAll(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/clear_all"),s={bot_id:o.bot_id,connector_id:o.connector_id,time_capsule_item_type:o.time_capsule_item_type};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryDelete(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/delete"),s={bot_id:o.bot_id,connector_id:o.connector_id,biz_ids:o.biz_ids,time_capsule_item_type:o.time_capsule_item_type,iids:o.iids,memory_meta_type_map:o.memory_meta_type_map};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/version"),s={bot_id:o.bot_id};return this.request({url:i,method:"GET",params:s},t)}GetVoiceListV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_list_v2"),s={language_code:o.language_code,space_id:o.space_id,voice_type:o.voice_type,page_size:o.page_size,next_cursor:o.next_cursor};return this.request({url:i,method:"POST",data:s},t)}GetUserUpdateProfileTag(e,t){const o=this.genBaseURL("/api/playground_api/get_user_update_profile_tag");return this.request({url:o,method:"GET"},t)}OpenRemoveSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={user_ids:o.user_ids};return this.request({url:i,method:"DELETE",data:s},t)}OpenSpaceMemberList(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}OpenAddSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={users:o.users};return this.request({url:i,method:"POST",data:s},t)}OpenGetBotInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}`),s={is_published:o.is_published,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}OpenApplyJoinSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members/apply`),s={user_ids:o.user_ids};return this.request({url:i,method:"POST",data:s},t)}OpenRemoveSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}`);return this.request({url:i,method:"DELETE"},t)}GetTypeList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_type_list"),s={model:o.model,voice:o.voice,raw_model:o.raw_model,space_id:o.space_id,cur_model_id:o.cur_model_id,cur_model_ids:o.cur_model_ids,model_scene:o.model_scene,tag_filters:o.tag_filters};return this.request({url:i,method:"POST",data:s},t)}GetCozeLaneInfo(e,t){const o=this.genBaseURL("/api/playground_api/get_coze_lane_info");return this.request({url:o,method:"POST"},t)}OpenUpdateSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members/${o.user_id}`),s={role_type:o.role_type};return this.request({url:i,method:"PUT",data:s},t)}OpenListBotVersions(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}/versions`),s={page_num:o.page_num,page_size:o.page_size,publish_status:o.publish_status,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}OpenSwitchBotDevelopMode(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}/collaboration_mode`),s={collaboration_mode:o.collaboration_mode};return this.request({url:i,method:"POST",data:s},t)}OpenUpdateSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}`),s={name:o.name,description:o.description};return this.request({url:i,method:"PUT",data:s},t)}}const Fr=new Gr({});function Vr(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function Wr(t,o){if(Vr([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipAuth]))return void await o();if(!t.config.accessToken)throw new e.CozeError(e.ErrorCode.E2001,"No API token found. Please authenticate first.",void 0,{fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"});if(Vr([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipOrgCheck]))return void await o();const i=await async function(t){const o=t.config.organizationId;if(!o)return!1;const{data:i}=await Wi.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0}),s=i.enterprise_info_list||[];if(!s.some((e=>Vr([e,"access",e=>e.organization_info_list,"optionalAccess",e=>e.some,"call",e=>e((e=>e.organization_id===o))]))))throw new e.CozeError(e.ErrorCode.E1000,`Organization ID ${o} is invalid or not found`,void 0,{fix:"Run `coze organization list` and select a valid organization",example:"coze organization use <organization_id>"});return!1}(t);if(Vr([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipSpaceCheck]))return i&&await Hr(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId}),void await o();const s=await async function(t){const o=t.config.organizationId,{enterpriseId:i}=t.config;let{spaceId:s}=t.config,n=!1;try{if(s){const{data:t}=await Fr.GetSpaceListV2({organization_id:o,enterprise_id:i}),n=Vr([t,"optionalAccess",e=>e.bot_space_list])||[];if(!n.some((e=>e.id===s))){const t=o?`[Context] Space ID ${s} is invalid or not found in organization ${o}.`:`[Context] Space ID ${s} is invalid or not found.`;throw new e.CozeError(e.ErrorCode.E1000,t,void 0,{fix:"Run `coze space list` and select a valid space",example:"coze space use <space_id>"})}}else{t.ui.info("[Context] Space ID not found. Attempting to auto-initialize...");const{data:r}=await Fr.GetSpaceListV2({organization_id:o,enterprise_id:i,page:1,size:1}),a=Vr([r,"optionalAccess",e=>e.bot_space_list,"optionalAccess",e=>e[0]]);if(!a){const t=o?`[Context] No spaces found in organization ${o}. Please create one.`:"[Context] No spaces found. Please create one.";throw new e.CozeError(e.ErrorCode.E3000,t,void 0,{fix:"Create a space in the current organization",example:"coze space list"})}s=a.id,t.config.spaceId=s,n=!0,t.ui.success(`[Context] Auto-selected Space: ${a.name} (${a.id})`)}}catch(t){const o=t instanceof e.CozeError?t:new e.CozeError(e.ErrorCode.E5000,t.message,t instanceof Error?t.stack:t);throw o.fix??="Switch organization or space using `coze organization use <organization_id>` or `coze space use <space_id>`",o.example??="coze organization list",o}return n}(t);await Jr(t),(i||s)&&await Hr(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId,spaceId:t.config.spaceId,billingProjectId:t.config.billingProjectId}),await o()}async function Hr(e,t){try{await l.saveConfig(t)}catch(t){e.ui.warn(`Failed to save auto-initialized context: ${t}`)}}const Jr=async o=>{const{spaceId:i}=o.config;try{const{data:s}=await t.IdeApi.GetOrCreateBillingProject({space_id:i});if(!Vr([s,"optionalAccess",e=>e.project_id]))throw new e.CozeError(e.ErrorCode.E5002,"[Context] Failed to get billing project ID from response.",s);o.config.billingProjectId=s.project_id,o.ui.success(`[Context] Billing Project: ${s.project_id} (space: ${i})`)}catch(e){const t=[`Failed to get billing project, ${e.message}. please check your space context:`," coze space list"," coze space use <space_id>"];throw e.message=`${t.join("\n")}`,e}};function Kr(e,t){return null!=e?e:t()}function Qr(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Yr=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||Qr([o,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),s=Qr([o,"optionalAccess",e=>e.config,"access",e=>e.enterpriseId]);Qr([o,"optionalAccess",e=>e.ui,"access",e=>e.verbose,"call",e=>e(`Fetching spaces for organization '${i}'...`)]);const n=await async function(e){const{data:t}=await Fr.GetSpaceListV2({organization_id:e.orgId,enterprise_id:e.enterpriseId,page:1,size:100});return Kr(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([t,"optionalAccess",e=>e.bot_space_list]),(()=>[])).map((t=>({id:Kr(t.id,(()=>"")),name:Kr(t.name,(()=>"")),org_id:Kr(e.orgId,(()=>""))})))}({orgId:i,enterpriseId:s});Qr([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Spaces:")]),Qr([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)]);const r=["Please use the following command to switch space:"," coze space use <space_id>"];Qr([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 s=i.getContext();Qr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to space '${t}'...`)]),await async function(t){try{await l.saveConfig({spaceId:t})}catch(o){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set default space to '${t}': ${o.message}`,o.stack)}}(t),Qr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default space set to '${t}' successfully.`)]),"json"===Qr([s,"optionalAccess",e=>e.format])&&Qr([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default space set to '${t}'.`})])}))};function Zr(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Xr=async t=>{Zr([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([l.loadConfig(),Wi.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 s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([t.personal_account_info,"optionalAccess",e=>e.available]))return{available:!1};const o=!!e.organizationId;return await l.saveConfig({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.");Zr([t,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switched to personal account successfully.")]),"json"===Zr([t,"optionalAccess",e=>e.format])&&Zr([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:"Switched to personal account."})])},ea=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();Zr([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching organizations...")]);const i=await async function(){const{data:e}=await Wi.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})))))}();Zr([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Organizations (Teams):")]),Zr([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(i)]);const s=["Please use the following command to switch organization:"," coze organization use <organization_id>","Please use the following command to switch space:"," coze space list"," coze space use <space_id>"];Zr([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])})),o.command("use").description("Set the default organization context").argument("[org_id]","Organization ID to set as default context (empty to switch to personal account)").config({help:{brief:"Set default organization or switch to personal account",description:"Save the specified org_id to the local configuration as the default organization for subsequent commands. The command will automatically retrieve and save the corresponding Enterprise ID. If the org_id is not found in the user's enterprise list, the command will fail without modifying the configuration. When switching to a different organization, the saved spaceId will be cleared. Omit org_id 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 s=i.getContext();if(!t)return void await Xr(s);Zr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to organization '${t}'...`)]);const{enterpriseId:n}=await async function(t){const[o,{data:i}]=await Promise.all([l.loadConfig(),Wi.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);let s="",n=!1;for(const e of i.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 r=o.organizationId!==t;return await l.saveConfig({organizationId:t,enterpriseId:s,...r?{spaceId:void 0}:{}}),{enterpriseId:s}}(t);Zr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Organization '${t}' found in enterprise '${n}'. Config saved.`)]),Zr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default organization set to '${t}' successfully.`)]),"json"===Zr([s,"optionalAccess",e=>e.format])&&Zr([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 ta(e,t){return null!=e?e:t()}const oa=async(e={})=>{const t=ta(e.stdin,(()=>process.stdin));return!0===ta(e.isTTY,(()=>t.isTTY))?null:await(async e=>{let t="";e.setEncoding("utf-8");for await(const o of e)t+=o;return t})(t)},ia=e=>{process.stdout.write(e.endsWith("\n")?e:`${e}\n`)},sa=e=>{ia(JSON.stringify(e))},na=async(e,t)=>{const o=i.resolve(e),n=i.dirname(o);if(await s.mkdir(n,{recursive:!0}),t instanceof Blob){const e=Buffer.from(await t.arrayBuffer());await s.writeFile(o,e)}else Buffer.isBuffer(t)?await s.writeFile(o,t):t instanceof ArrayBuffer?await s.writeFile(o,Buffer.from(t)):await s.writeFile(o,String(t));return o};const ra=e=>"object"==typeof e&&null!==e,aa=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},ca=e=>ra(e)&&"data"in e&&void 0!==e.data?e.data:e,la=(e,t)=>{try{const{pathname:o}=new URL(e);return i.extname(o)||t}catch(e){return t}},da=()=>{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")}`},pa=e=>{const{outputPath:t,type:o,index:s,ext:n,timestamp:r}=e,a=`${o}_${r}_${s}${n}`;return i.join(t,a)},ua=async(t,o={})=>{let i=null;o.stdin&&(i=await oa());const s=aa(t),n=aa(i),r=(c=()=>n,null!=(a=s)?a:c());var a,c;if(!r)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin with piped content");return r},ma="720p",ga="16:9",ha=!1,fa=!1;function _a(e,t){return null!=e?e:t()}function ya(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ba=(e,t)=>{if(null==e)return 5;const o=Number(e);if(!Number.isFinite(o))return ya([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?(ya([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},va=(e,t)=>{if(null==e)return;const o=Number(e);if(Number.isSafeInteger(o)&&o>=0)return o;ya([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --seed '${String(e)}', this parameter will be ignored`)])},wa=e=>{const{content:t,options:o,ctx:i}=e,s=(e=>{if("string"!=typeof e)return null;const t=e.trim(),o=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(t);if(!o)return null;const i=Number(o[1]),s=Number(o[2]);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=0)return null;const n=((e,t)=>{let o=Math.abs(e),i=Math.abs(t);for(;0!==i;){const e=o%i;o=i,i=e}return o})(i,s)||1,r=`${Math.round(i/n)}:${Math.round(s/n)}`,a=Math.max(i,s);return{ratio:r,resolution:a<=854?"480p":a<=1280?"720p":"1080p"}})(o.size),n=((e,t)=>"480p"===e||"720p"===e||"1080p"===e?e:(void 0!==e&&ya([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --resolution '${String(e)}', falling back to '${ma}'`)]),ma))(_a(o.resolution,(()=>ya([s,"optionalAccess",e=>e.resolution]))),i),r=((e,t)=>{if("string"==typeof e){const t=e.trim();if(t.length>0)return t}return void 0!==e&&ya([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --ratio '${String(e)}', falling back to '${ga}'`)]),ga})(_a(o.ratio,(()=>ya([s,"optionalAccess",e=>e.ratio]))),i);return{model:"doubao-seedance-1-5-pro-251215",content:t,callback_url:_a(aa(o.callbackUrl),(()=>{})),return_last_frame:"boolean"==typeof o.returnLastFrame?o.returnLastFrame:fa,resolution:n,ratio:r,duration:ba(o.duration,i),watermark:"boolean"!=typeof o.watermark||o.watermark,seed:va(o.seed,i),camerafixed:"boolean"==typeof o.camerafixed?o.camerafixed:ha,generate_audio:"boolean"!=typeof o.generateAudio||o.generateAudio}},Ca=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())},Ea=async e=>{const{outputPath:t,videoUrl:o,lastFrameUrl:s,shouldSaveLastFrame:n}=e,r=la(o,".mp4"),a=da(),c=pa({outputPath:t,type:"video",index:0,ext:r,timestamp:a}),l=await Ca(o),d=[await na(c,l)];if(n&&"string"==typeof s&&s.length>0){const e=(e=>{const{outputPath:t,ext:o,timestamp:s}=e,n=`last_frame_${s}_0${o}`;return i.join(t,n)})({outputPath:t,ext:la(s,".png"),timestamp:a}),o=await Ca(s),n=await na(e,o);d.push(n)}return d};var Ia,Aa,Sa,ja,Pa,ka,Ta,za,Ra,xa,La,Oa,Da,Ua,Ba,qa,Ma,Na,$a;function Ga(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInputTokens=2]="TotalInputTokens";e[e.TotalOutputTokens=3]="TotalOutputTokens"}(Ia||(Ia={})),function(e){e[e.ASC=1]="ASC";e[e.DESC=2]="DESC"}(Aa||(Aa={})),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"}(Sa||(Sa={})),function(e){e[e.Free=1]="Free";e[e.Trial=2]="Trial";e[e.Paid=3]="Paid"}(ja||(ja={})),function(e){e[e.Inactive=1]="Inactive";e[e.Active=2]="Active"}(Pa||(Pa={})),function(e){e[e.CNY=1]="CNY";e[e.ResourcePoint=2]="ResourcePoint"}(ka||(ka={})),function(e){e[e.Cancellable=0]="Cancellable";e[e.NoCancellable=1]="NoCancellable";e[e.AlwaysDefault=2]="AlwaysDefault"}(Ta||(Ta={})),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"}(za||(za={})),function(e){e[e.Internal=1]="Internal";e[e.External=2]="External";e[e.Infra=3]="Infra"}(Ra||(Ra={})),function(e){e[e.Text=1]="Text";e[e.Image=2]="Image";e[e.Video=3]="Video";e[e.Audio=4]="Audio"}(xa||(xa={})),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"}(La||(La={})),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"}(Oa||(Oa={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online";e[e.GradualRollout=2]="GradualRollout";e[e.ReadyToOffline=3]="ReadyToOffline"}(Da||(Da={})),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"}(Ua||(Ua={})),function(e){e[e.Install=1]="Install";e[e.Uninstall=2]="Uninstall"}(Ba||(Ba={})),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"}(qa||(qa={})),function(e){e[e.Scene=1]="Scene";e[e.Type=2]="Type"}(Ma||(Ma={})),function(e){e[e.Official=1]="Official";e[e.Community=2]="Community"}(Na||(Na={})),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"}($a||($a={}));class Fa{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Fa.prototype.__init.call(this),Fa.prototype.__init2.call(this),this.request=Ga([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Ga([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}ListIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/list"),s={space_id:o.space_id,project_id:o.project_id,integration_type:o.integration_type,integration_id:o.integration_id,filter_installed:o.filter_installed,org_id:o.org_id,search_words:o.search_words,page_num:o.page_num,page_size:o.page_size,project_type:o.project_type};return this.request({url:i,method:"POST",data:s},t)}SetIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/update"),s={integration_id:o.integration_id,space_id:o.space_id,auth_schema_value:o.auth_schema_value};return this.request({url:i,method:"POST",data:s},t)}DeleteIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/delete"),s={integration_id:o.integration_id,space_id:o.space_id,project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}AuthIntegrationStatus(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/auth/status"),s={integration_id:o.integration_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}ManageSpaceIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/space/manage"),s={space_ids:o.space_ids,integration_ids:o.integration_ids,op_type:o.op_type};return this.request({url:i,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}FlashASR(e,t){const o=e||{},i=this.genBaseURL("/api/v3/auc/bigmodel/recognize/flash"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}ListModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/list"),s={model_type:o.model_type,current_model_ids:o.current_model_ids,integration_ids:o.integration_ids,need_model_config_param:o.need_model_config_param,page_size:o.page_size,offset:o.offset};return this.request({url:i,method:"POST",data:s},t)}ChatCompletions(e,t){const o=e||{},i=this.genBaseURL("/api/v3/chat/completions"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CreateResponses(e,t){const o=e||{},i=this.genBaseURL("/api/v3/responses"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}GenerateImages(e,t){const o=e||{},i=this.genBaseURL("/api/v3/images/generations"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const o=e||{},i=this.genBaseURL("/api/v3/tts/unidirectional"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}GetIntegrationOauthConfig(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/auth/oauth_config"),s={integration_id:o.integration_id,space_id:o.space_id,project_id:o.project_id,session_id:o.session_id};return this.request({url:i,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks/:id"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"GET",data:s,params:n},t)}WebSearch(e,t){const o=e||{},i=this.genBaseURL("/api/search_api/web_search"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}WebSearch(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/search_api/web_search"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CreateResponses(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/responses"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks/:id"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"GET",data:s,params:n},t)}FlashASR(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/auc/bigmodel/recognize/flash"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}GenerateImages(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/images/generations"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/tts/unidirectional"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}ChatCompletions(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/chat/completions"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CancelIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/cancel"),s={integration_id:o.integration_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}Embeddings(e,t){const o=e||{},i=this.genBaseURL("/api/v3/embeddings/multimodal"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}Embeddings(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/embeddings/multimodal"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}VideoEditingUtils(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/video_editing_utils"),s={Body:o.Body},n={tool_name:o.tool_name};return this.request({url:i,method:"POST",data:s,params:n},t)}GetProjectDefaultSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/default"),s={project_type:o.project_type,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillByIDs(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/by_ids"),s={project_type:o.project_type,skill_ids:o.skill_ids,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillCategoryList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/category/list"),s={project_type:o.project_type};return this.request({url:i,method:"POST",data:s},t)}UploadSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload"),s={data:o.data},n={"Content-Type":o["Content-Type"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetUserSkillList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/user/list"),s={page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}DeleteSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/delete"),s={skill_id:o.skill_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/list"),s={project_type:o.project_type,category_type_list:o.category_type_list,space_id:o.space_id,source_list:o.source_list};return this.request({url:i,method:"POST",data:s},t)}UploadSkillConfirm(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload/confirm"),s={preview_skill_key:o.preview_skill_key};return this.request({url:i,method:"POST",data:s},t)}FetchTool(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/fetch_tool"),s={url:o.url};return this.request({url:i,method:"POST",data:s},t)}GetModelSwitchStatus(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/status"),s={model_id:o.model_id,project_ids:o.project_ids,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}StartSwitchModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/start"),s={space_id:o.space_id,project_ids:o.project_ids,current_model:o.current_model,target_model:o.target_model};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageList(e,t){const o=e||{},i=this.genBaseURL("/v1/model/usage/list"),s={space_id:o.space_id,model_id:o.model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp,order_by_field:o.order_by_field,order_by_type:o.order_by_type,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetModelDetails(e,t){const o=e||{},i=this.genBaseURL("/v1/model/details"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageDetail(e,t){const o=e||{},i=this.genBaseURL("/v1/model/usage/details"),s={space_id:o.space_id,model_id:o.model_id,project_id:o.project_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}RollbackSwitchModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/rollback"),s={space_id:o.space_id,project_ids:o.project_ids,current_model:o.current_model};return this.request({url:i,method:"POST",data:s},t)}TextEmbeddings(e,t){const o=e||{},i=this.genBaseURL("/api/v3/embeddings"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}TextEmbeddings(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/embeddings"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CheckModelReadyToOffline(e,t){const o=e||{},i=this.genBaseURL("/v1/model/ready_to_offline/check"),s={model_type:o.model_type};return this.request({url:i,method:"POST",data:s},t)}Audit(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/audit"),s={content:o.content};return this.request({url:i,method:"POST",data:s},t)}}Fa.prototype.UploadSkill=function(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload"),s=o.body;return this.request({url:i,method:"POST",data:s},t)},Fa.prototype.GenerateImages=function(e,t){const o=e||{},i=this.genBaseURL("/api/v3/images/generations"),s=o.Body;return this.request({url:i,method:"POST",data:s},t)},Fa.prototype.SubmitVideoGenerationsTasks=function(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks"),s=o;return this.request({url:i,method:"POST",data:s},t)},Fa.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 Va=new Fa({});const Wa=async e=>await new Promise((t=>setTimeout(t,e))),Ha=async e=>{const{taskId:t,baseURL:o,accessToken:i,projectId:s}=e,n=await Va.GetVideoGenerationsTasks({id:t},{baseURL:o,headers:{Authorization:`Bearer ${i}`},params:{project_id:s}});return ca(n)};function Ja(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ka=e=>`coze generate video status ${e}`,Qa=e=>{const{ctx:t,response:o}=e;"json"!==Ja([t,"optionalAccess",e=>e.format])?ia((e=>{const t=[e.status],o=Ja([e,"access",e=>e.content,"optionalAccess",e=>e.video_url]),i=Ja([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)):sa(o)},Ya=t=>{const o=t.getContext(),{outputPath:i}=t.optsWithGlobals(),s=(n=Ja([o,"optionalAccess",e=>e.config,"optionalAccess",e=>e.integrationApiBaseUrl]),r=()=>l.DEFAULT_CONFIG.integrationApiBaseUrl,null!=n?n:r());var n,r;const a=Ja([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:s,outputPath:i}},Za=async(t,o,i)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:r,outputPath:a}=Ya(i);let c=null;o.stdin&&(c=await oa());const{content:l}=(t=>{const{prompt:o,stdinPrompt:i,options:s}=t,n=_a(aa(o),(()=>aa(i))),r=aa(s.firstFrame),a=aa(s.lastFrame),c=Boolean(r)||Boolean(a);if(!n&&!c)throw new e.CozeError(e.ErrorCode.E1000,"Missing input: Please provide PROMPT/stdin text, or provide images (--first-frame/--last-frame/--reference-image)");const l=[];return n&&l.push({type:"text",text:n}),r&&l.push({type:"image_url",image_url:{url:r},role:"first_frame"}),a&&l.push({type:"image_url",image_url:{url:a},role:"last_frame"}),{content:l}})({prompt:t,stdinPrompt:c,options:o}),d=wa({content:l,options:o,ctx:n}),p=n.format,u=Ja([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!u)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const{createResp:m,taskId:g}=await(async t=>{const{requestBody:o,baseURL:i,accessToken:s,projectId:n}=t,r=await Va.SubmitVideoGenerationsTasks(o,{baseURL:i,headers:{Authorization:`Bearer ${s}`},params:{project_id:n}}),a=ca(r),c=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([a,"optionalAccess",e=>e.id]);if(!c||"string"!=typeof c)throw new e.CozeError(e.ErrorCode.E5002,"Video generation task created successfully but no valid task_id was returned",a);return{taskId:c,createResp:a}})({requestBody:d,baseURL:r,accessToken:s,projectId:u});if(!o.wait)return"json"===p?void sa({query_command:Ka(g),response:m,task_id:g}):void ia((e=>["Video generation task created successfully.",`taskId: ${e}`,`Use \`${Ka(e)}\` to query status.`].join("\n"))(g));const h=await(async t=>{const{taskId:o,baseURL:i,accessToken:s,pollIntervalMs:n,pollTimeoutMs:r,projectId:a}=t,c=Date.now();for(;;){const t=await Ha({taskId:o,baseURL:i,accessToken:s,projectId:a});if("succeeded"===t.status)return t;if("failed"===t.status||"cancelled"===t.status)throw new e.CozeError(e.ErrorCode.E5002,`Video generation failed (status=${t.status}): ${l=t.error_message,d=()=>"unknown",null!=l?l:d()}`,t);if(Date.now()-c>r)throw new e.CozeError(e.ErrorCode.E5003,[`Video generation timed out after ${r}ms.`,`taskId: ${o}`,`Use \`coze generate video status ${o}\` to query status.`].join("\n"),{task_id:o,last_status:t.status});await Wa(n)}var l,d})({taskId:g,baseURL:r,accessToken:s,pollIntervalMs:2e3,pollTimeoutMs:3e5,projectId:u}),f=Ja([h,"access",e=>e.content,"optionalAccess",e=>e.video_url]),_=Ja([h,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);if(!f||"string"!=typeof f)throw new e.CozeError(e.ErrorCode.E5002,"Video generated successfully but video_url was not returned");if(a){const e=await Ea({outputPath:a,videoUrl:f,lastFrameUrl:_,shouldSaveLastFrame:!0===o.returnLastFrame});return"json"===p?void sa({task_id:g,request:d,response:h,saved_paths:e}):void ia(e.join("\n"))}if("json"===p)return void sa({task_id:g,request:d,response:h});const y=[f];!0===o.returnLastFrame&&"string"==typeof _&&_.length>0&&y.push(_),ia(y.join("\n"))},Xa=(e,t)=>{const o=t.getContext();H(e,o)},ec=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 Za(e,t,o)}catch(e){Xa(e,o)}})),o.option("--callback-url <url>","Callback URL for task status changes").option("--return-last-frame","Return last frame URL (default: disabled)",fa).option("--resolution <res>","Resolution: 480p|720p|1080p",ma).option("--ratio <ratio>",`Aspect ratio (default: ${ga})`,ga).option("--size <size>","Derive ratio/resolution from WIDTHxHEIGHT (lower priority than explicit parameters)").option("--duration <seconds>","Duration (seconds, 4..12; out-of-bounds fallback -1), default: 5",String(5)).option("--no-watermark","Disable watermark (default: enabled)").option("--seed <seed>","Random seed (safe integer)").option("--camerafixed","Fixed camera position (default: disabled)",ha).option("--no-generate-audio","Do not generate accompanying audio (default: generate)").option("--first-frame <url>","First frame image URL").option("--last-frame <url>","Last frame image URL").option("--stdin","Read prompt from stdin (pipe input)").option("--wait","Wait for task completion by polling; by default the command returns taskId immediately")},tc=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:s,ctx:n,integrationApiBaseUrl:r}=Ya(i),a=Ja([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!a)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const c=await Ha({taskId:t,baseURL:r,accessToken:s,projectId:a});Qa({ctx:n,response:c})})(t,0,i)}catch(e){Xa(e,i)}}))};function oc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ic="2K",sc="url",nc="standard",rc="disabled",ac=3686400,cc=16777216,lc=e=>"object"==typeof e&&null!==e,dc=e=>{if("string"==typeof e){const t=e.trim();return t.length?t:nc}return nc},pc=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},uc=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)",ic).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",sc).option("--optimize-prompt-mode <mode>",`Prompt optimization mode (default: ${nc})`,nc).option("--sequential <mode>","Group image generation mode: auto|disabled",rc).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 s=i.getContext(),{outputPath:n}=i.optsWithGlobals(),r=await ua(t,{stdin:o.stdin}),a=oc([s,"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:ic};if("string"!=typeof e)return oc([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --size '${String(e)}', falling back to '${ic}'`)]),{value:ic};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:ic,warning:`Invalid --size '${o}', falling back to '${ic}'. Expected 2K/4K or WIDTHxHEIGHT`};const s=Number(i[1]),n=Number(i[2]),r=s*n,a=s/n;return Number.isFinite(s)&&Number.isFinite(n)&&s>0&&n>0&&r>=ac&&r<=cc&&a>=.0625&&a<=16?{value:`${s}x${n}`}:{value:ic,warning:`Invalid --size '${o}', falling back to '${ic}'. Total pixels must be in [3686400, 16777216], aspect ratio must be in [1:16, 16:1].`}})(o.size,s),d="url"===(p=o.responseFormat)||"b64_json"===p?{value:p}:void 0!==p?{value:sc,warning:`Invalid --response-format '${String(p)}', falling back to '${sc}'`}:{value:sc};var p;const u=(e=>"auto"===e||"disabled"===e?{value:e}:void 0!==e?{value:rc,warning:`Invalid --sequential '${String(e)}', falling back to '${rc}'`}:{value:rc})(o.sequential),m=(e=>{if(null==e)return{value:15};const t=Number(e);if(Number.isFinite(t)){const e=Math.floor(t);if(e>=1&&e<=15)return{value:e}}return{value:15,warning:`Invalid --max-images '${String(e)}', falling back to '15'`}})(o.maxImages);c.warning&&oc([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(c.warning)]),d.warning&&oc([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(d.warning)]),u.warning&&oc([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(u.warning)]),m.warning&&oc([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(m.warning)]);const g={model:"doubao-seedream-4-5-251128",prompt:r,size:c.value,watermark:"boolean"!=typeof o.watermark||o.watermark,image:pc(o.image),response_format:d.value,optimize_prompt_options:{mode:dc(o.optimizePromptMode)},sequential_image_generation:u.value,sequential_image_generation_options:{max_images:m.value}},h=(t=>{const o=lc(t)&&"data"in t?t.data:t;if(lc(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 Va.GenerateImages({Body:g},{baseURL:l.DEFAULT_CONFIG.integrationApiBaseUrl,params:{project_id:a}}));if(h.error)throw new e.CozeError(e.ErrorCode.E5002,"Image generation failed (top-level error)",h.error);const f=(y=()=>sc,null!=(_=g.response_format)?_:y());var _,y;const b=h.data.filter((e=>!e.error&&("url"===f?"string"==typeof e.url&&e.url.length>0:"string"==typeof e.b64_json&&e.b64_json.length>0)));if(0===b.length)throw new e.CozeError(e.ErrorCode.E5002,"Image generation succeeded but no valid image data was returned",h);if(n){const t=[],o=da();for(const[i,s]of b.entries()){const r="url"===f&&s.url?la(s.url,".png"):".png",a=pa({outputPath:n,type:"image",index:i,ext:r,timestamp:o});let c;if("url"===f){const t=await e.customFetch.fetch(s.url);if(!t.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download generated image: ${t.status} ${t.statusText}`);c=Buffer.from(await t.arrayBuffer())}else c=Buffer.from(s.b64_json,"base64");const l=await na(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}})(h);oc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...c,saved_paths:t})])}else oc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(h.data)])}))};function mc(e,t){return null!=e?e:t()}function gc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const hc="cli_user",fc="zh_female_xiaohe_uranus_bigtts",_c="mp3",yc=24e3,bc=(e,t)=>"pcm"===e||"mp3"===e||"ogg_opus"===e?e:(void 0!==e&&gc([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --audio-format '${String(e)}', falling back to '${_c}'`)]),_c),vc=(e,t,o,i)=>{if(null==e)return t;const s=Number(e);return Number.isFinite(s)?Math.floor(s):(gc([i,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",i=>i(`Invalid --${o} '${String(e)}', falling back to ${t}`)]),t)},wc=t=>{const o=t.trim();if(0===o.length)return null;const i=o.startsWith("data:")?o.slice(5).trim():o;if(0===i.length)return null;const s=i[0];if("{"!==s&&"["!==s)return null;const n=e.safeJsonParse(i,void 0,{onError:t=>{const i=t instanceof Error?t.message:String(t);throw new e.CozeError(e.ErrorCode.E5002,`Failed to parse response: ${i}`,{line:o})}});return void 0===n?null:ra(n)&&"number"==typeof n.code?n:null},Cc=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");uc(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: ${hc})`,hc).option("--speaker <speaker>",`Speaker (default: ${fc})`,fc).option("--audio-format <format>","Audio encoding: pcm|mp3|ogg_opus",_c).option("--sample-rate <n>","Sample rate (default: 24000)",String(yc)).option("--speech-rate <n>","Speech rate (-50..100, default: 0)",String(0)).option("--loudness-rate <n>","Loudness (-50..100, default: 0)",String(0)).option("--ssml","Treat input as SSML (defaults to plain text)",!1).option("--stdin","Read prompt from stdin (pipe input)").action((async(t,o,i)=>{const s=i.getContext();try{const{outputPath:n}=i.optsWithGlobals(),r=gc([s,"optionalAccess",e=>e.config,"access",e=>e.integrationApiBaseUrl]);if(!gc([s,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]))throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login --oauth` or `coze auth login --token <token>` first");const a=await ua(t,{stdin:o.stdin}),c=gc([s,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const l={user:{uid:mc(aa(o.uid),(()=>hc))},req_params:{speaker:mc(aa(o.speaker),(()=>fc)),audio_params:{format:bc(o.audioFormat,s),sample_rate:vc(o.sampleRate,yc,"sample-rate",s),speech_rate:vc(o.speechRate,0,"speech-rate",s),loudness_rate:vc(o.loudnessRate,0,"loudness-rate",s)}}};o.ssml?l.req_params={...l.req_params,ssml:a}:l.req_params={...l.req_params,text:a};const d=new URL("/api/v3/tts/unidirectional",r);d.searchParams.append("project_id",c);const p=await e.customFetch.fetch(d.toString(),{method:"POST",body:JSON.stringify(l)});if(!p.ok)throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis request failed: ${p.status} ${p.statusText}`,{status:p.status,statusText:p.statusText});if(!p.body)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis response is empty (no streaming body returned)");const u=new TextDecoder("utf-8"),m=p.body.getReader(),g=[];let h;const f=t=>{if(0===t.code)return n&&"string"==typeof t.data&&g.push(Buffer.from(t.data,"base64")),!1;if(2e7===t.code)return"string"==typeof t.url&&t.url.length>0&&(h=t.url),!0;throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis failed (code=${t.code}): ${mc(t.message,(()=>"unknown"))}`,t)};let _="";for(;;){const{done:e,value:t}=await m.read();if(e)break;_+=u.decode(t,{stream:!0});const o=_.split(/\r?\n/);_=mc(o.pop(),(()=>""));for(const e of o){const t=wc(e);if(t&&f(t)){await m.cancel();break}}if(h)break}if(!h){_+=u.decode();const e=_.split(/\r?\n/);_="";for(const t of e){const e=wc(t);if(e&&f(e))break}}if(n){const t=mc(gc([l,"access",e=>e.req_params,"optionalAccess",e=>e.audio_params,"optionalAccess",e=>e.format]),(()=>_c)),o="pcm"===t?".pcm":"ogg_opus"===t?".ogg":".mp3",i=da(),r=pa({outputPath:n,type:"audio",index:0,ext:o,timestamp:i});let a=null;if(g.length>0)a=await na(r,Buffer.concat(g));else if(h){const t=await e.customFetch.fetch(h);if(!t.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download synthesized speech: ${t.status} ${t.statusText}`,{status:t.status,statusText:t.statusText});const s=Buffer.from(await t.arrayBuffer()),r=la(h,o),c=pa({outputPath:n,type:"audio",index:0,ext:r,timestamp:i});a=await na(c,s)}if(!a)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis completed but no savable audio data was obtained (neither chunks nor download URL)",{url:h});return"json"===gc([s,"optionalAccess",e=>e.format])?void sa({request:l,url:h,saved_path:a}):void ia(a)}if("json"===gc([s,"optionalAccess",e=>e.format]))return void sa({request:l,url:h});if(h)return void ia(h);ia("Speech synthesis completed, but no audio download URL was returned; you can use --output json to view details.")}catch(e){H(e,s)}}))})(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);ec(t),tc(t)})(o)};function Ec(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ic=o=>{(o=>{o.command("upload <path>").description("Upload a local file").config({help:{brief:"Upload a local file",description:"Upload a local file to Coze. 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(o,i,s)=>{let n;try{n=s.getContext();try{await h.access(o)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${o}`,{filePath:o})}const i=g.basename(o),r=g.extname(o),a=r?i.slice(0,-r.length):i,c=r.slice(1),l=new _;l.append("file_name",a),l.append("file_extension",c),l.append("file_content",f.createReadStream(o)),l.append("biz_type","cli_attachment");const d=await t.IdeApi.UploadFile({data:l},{headers:{...l.getHeaders()}});"json"===Ec([n,"optionalAccess",e=>e.format])?Ec([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(d.data)]):Ec([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(Ec([d,"access",e=>e.data,"optionalAccess",e=>e.file_url]))])}catch(e){H(e,n)}}))})(o.command("file").description("General file operations").config({help:{brief:"File upload and management",description:"Manage file operations for Coze projects. Currently supports uploading local files to Coze for use as attachments or context.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf"}],seeAlso:["coze code message send"]}}))};function Ac(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Sc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function jc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Pc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const kc=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(),s=await l.listConfigs();for(const t of e){const e=s.find((e=>e.key===t));Ac(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,s)=>{const n=s.getContext();try{const e={};e[t]=o;const i="global";await l.saveConfig(e,i);const s={key:t,value:o,scope:i,status:"updated",message:`Configuration '${t}' updated successfully in ${i} scope.`};if(Sc([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.message)]),"json"===Sc([n,"optionalAccess",e=>e.format]))return void Sc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(s)])}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 s=i.getContext();for(const o of t)try{await l.deleteConfig(o);const e={key:o,status:"deleted",message:`Configuration '${o}' has been removed.`};jc([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleted ${o} from configuration file successfully.`)]),"json"===jc([s,"optionalAccess",e=>e.format])&&jc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)])}catch(t){const i=t;throw new e.CozeError(e.ErrorCode.E5000,`Failed to delete config '${o}': ${i.message}`,i.stack)}}))})(o),(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 l.listConfigs()).map((({key:e,value:t,source:o})=>({key:e,value:t,source:o})));Pc([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Configurations found:")]),Pc([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(i)])}))})(o)},Tc="__COZE_FILE_COMP__";function zc(){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 Rc(e){const t=n.homedir();switch(e){case"bash":return i.join(t,"darwin"===process.platform?".bash_profile":".bashrc");case"zsh":return i.join(t,".zshrc");case"fish":return i.join(t,".config/fish/config.fish");case"powershell":return function(){const e=["pwsh","powershell"];for(const t of e)try{const e=c.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 xc(){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]}" == "${Tc}" ]]; 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" == "${Tc}" ]]; 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 Lc(e){switch(e){case"bash":return`\n# begin coze completion\nsource ${i.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 '${Tc}') {\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 Oc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}let Dc,Uc,Bc=!1,qc=!1;function Mc(e){const t=(o=e._args,i=()=>[],null!=o?o:i());var o,i;if(0===t.length)return!1;const s=/path|file|dir|folder/i;return t.some((e=>s.test(e._name)))}function Nc(e){Uc=e,function(){const e=process.argv.indexOf("--completion");e>-1&&(Bc=!0,process.argv.splice(e,1));const t=process.argv.indexOf("--completion-fish");t>-1&&(qc=!0,process.argv.splice(t,1))}(),Dc=y("coze"),Dc.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 s="";o.line.endsWith(" ")?(s="",""===i[i.length-1]&&i.pop()):s=i.pop()||"";const n=function(e,t,o){let i=e;for(const e of t){const t=i.commands.find((t=>t.name()===e||t.alias()===e));if(t)i=t;else if(!e.startsWith("-"))return Mc(i)?[Tc]:[]}const s=[];i.commands.length>0&&i.commands.forEach((e=>{s.push(e.name())})),i.options.forEach((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))})),i!==e&&e.options.forEach((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}));const n=Array.from(new Set(s)).filter((e=>e.startsWith(o)));return 0===n.length&&Mc(i)?[Tc]:n}(e,i,s);o.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=zc();if(!e)return;const t=Rc(e);if(!t||!r.existsSync(t))return;const o=Lc(e);if(o){const e=r.readFileSync(t,"utf8").replace(new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"");r.writeFileSync(t,e)}if("bash"===e){const e=i.join(n.homedir(),".coze"),t=i.join(e,"completion.sh");r.existsSync(t)&&r.unlinkSync(t),r.existsSync(e)&&0===r.readdirSync(e).length&&r.rmdirSync(e)}}(),await l.saveConfig({completionInstalled:!1}),console.log("Shell completion removed! Please restart your terminal.");else{const e=zc();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=zc();if(!e)return!1;const t=Rc(e);if(!t)return!1;if("bash"===e){const e=i.join(n.homedir(),".coze"),t=i.join(e,"completion.sh");r.existsSync(e)||r.mkdirSync(e,{recursive:!0}),r.writeFileSync(t,xc())}const o=i.dirname(t);r.existsSync(o)||r.mkdirSync(o,{recursive:!0});const s=Lc(e);return!!s&&(r.appendFileSync(t,s),!0)}();t?(await l.saveConfig({completionInstalled:!0}),console.log(`Shell completion (${e}) setup successful! Please restart your terminal or source your config file.`)):(console.error(`Failed to setup shell completion for ${e}.`),process.exitCode=1)}}))}function $c(){return Bc?(console.log(xc()),void process.exit()):qc?(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]" = "${Tc}"`," 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(!Uc)return void process.exit();const e=process.argv.indexOf("--comppwsh"),t=process.argv.slice(e+1);let o=Uc;const i=[];for(const e of t){const t=Oc([o,"access",e=>e.commands,"optionalAccess",e=>e.find,"call",t=>t((t=>t.name()===e||t.alias()===e))]);t?o=t:i.push(e)}const s=[];Oc([o,"access",e=>e.commands,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{s.push(e.name())}))]),Oc([o,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}))]),o!==Uc&&Oc([Uc,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}))]);const n=i[i.length-1]||"",r=Array.from(new Set(s)).filter((e=>e.startsWith(n)));0===r.length&&Mc(o)?console.log(Tc):r.length>0&&console.log(r.join("\n")),process.exit()}():Dc&&Dc.init())}class Gc{static getInstance(){return Gc.INSTANCE||(Gc.INSTANCE=new Gc),Gc.INSTANCE}async getDefaultConversation(e){return(await t.BuildAgentApi.GetProjectDefaultConversation({project_id:e})).Data}async updateConversationSetting(e,o,i){await t.BuildAgentApi.UpdateConversationSetting({project_id:e,conversation_id:o,...void 0!==i.modelSetting?{model_setting:i.modelSetting}:{},...void 0!==i.skillSetting?{skill_setting:i.skillSetting}:{},...void 0!==i.mode?{mode:i.mode}:{},...void 0!==i.agentTools?{agent_tools:i.agentTools}:{}})}}const Fc=Gc.getInstance();function Vc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Wc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Hc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Jc=o=>{const i=o.command("tools").config({help:{brief:"Manage project tools",description:"Manage tools associated with a project. Tools extend project capabilities such as web search, image generation, etc.",examples:[{desc:"List project tools",cmd:"coze code tools list -p <projectId>"},{desc:"Enable a tool",cmd:"coze code tools enable enable_image_gen -p <projectId>"},{desc:"Disable a tool",cmd:"coze code tools disable enable_image_gen -p <projectId>"}],seeAlso:["coze code project","coze code model"]}}).description("Manage project tools");!function(e){e.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"}}}}}}}).action((async function(e,o){const i=o.getContext(),{projectId:s}=e,n=Vc([await t.IdeApi.GetVibeProject({project_id:s}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=Vc([await Fc.getDefaultConversation(s),"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools]),a=Vc([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===n)),"optionalAccess",e=>e.tools]);if(!a||0===a.length)return Vc([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("No tools available for this project type.")]),void Vc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e([])]);const c=a.map((e=>({tool_name:e.name,description:e.description||e.display_name,enabled:Vc([r,"optionalAccess",t=>t[e.name]])})));Vc([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${c.length} tools.`)]),Vc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(c)])}))}(i),function(o){o.command("enable <toolName>").description("Enable a conversation tool").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Enable a conversation tool",description:"Enable a specified tool in the default conversation settings.",examples:[{desc:"Enable image generation",cmd:"coze code tools enable enable_image_gen -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{toolName:{type:"string",required:!0,description:"Tool name to enable"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},enable_tool_name:{type:"string",description:"Enabled tool name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified tool is not available for this project type",fix:"Use 'coze code tools list -p <projectId>' to see available tools"}]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=Wc([await t.IdeApi.GetVibeProject({project_id:r}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=Wc([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===a)),"optionalAccess",e=>e.tools]);if(!Wc([c,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Tool '${o}' is not available for this project type`,{toolName:o,projectId:r});const l=await Fc.getDefaultConversation(r),d=Wc([l,"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools])||{};await Fc.updateConversationSetting(r,l.id,{agentTools:{...d,[o]:!0}}),Wc([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Tool '${o}' enabled.`)]),Wc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,enable_tool_name:o,message:`Tool '${o}' has been enabled successfully`})])}))}(i),function(o){o.command("disable <toolName>").description("Disable a conversation tool").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Disable a conversation tool",description:"Disable a specified tool in the default conversation settings.",examples:[{desc:"Disable image generation",cmd:"coze code tools disable enable_image_gen -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{toolName:{type:"string",required:!0,description:"Tool name to disable"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},disable_tool_name:{type:"string",description:"Disabled tool name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified tool is not available for this project type",fix:"Use 'coze code tools list -p <projectId>' to see available tools"}]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=Hc([await t.IdeApi.GetVibeProject({project_id:r}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=Hc([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===a)),"optionalAccess",e=>e.tools]);if(!Hc([c,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Tool '${o}' is not available for this project type`,{toolName:o,projectId:r});const l=await Fc.getDefaultConversation(r),d=Hc([l,"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools])||{};await Fc.updateConversationSetting(r,l.id,{agentTools:{...d,[o]:!1}}),Hc([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Tool '${o}' disabled.`)]),Hc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,disable_tool_name:o,message:`Tool '${o}' has been disabled successfully`})])}))}(i)};function Kc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Qc(e,t){return null!=e?e:t()}function Yc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Zc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Xc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function el(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const tl=o=>{const i=o.command("skill").config({help:{brief:"Manage project skills",description:"Manage skills associated with a project. Skills are important components to extend project capabilities, supporting adding, viewing, and removing project skills.",examples:[{desc:"List project skills",cmd:"coze code skill list -p <projectId>"},{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>"},{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>"}],seeAlso:["coze code project"]}}).description("Manage project skills");!function(o){o.command("list").description("List available skills for the project").requiredOption("-p, --project-id <projectId>","Project ID").option("--space-id <spaceId>","Space ID (optional, reads from config)").option("--my","List personal skills only").option("--page <page>","Page number (for personal skills)").option("--size <size>","Page size (for personal skills)").config({help:{brief:"List available skills for the project",description:"Retrieve a list of all available skills for the specified project type, with installation status indicating which skills are already added.",examples:[{desc:"List project skills",cmd:"coze code skill list --project-id <projectId>",tags:["[RECOMMENDED]"]},{desc:"List personal skills",cmd:"coze code skill list -p <projectId> --my"},{desc:"List personal skills with pagination",cmd:"coze code skill list -p <projectId> --my --page 1 --size 10"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"},my:{type:"boolean",required:!1,description:"List personal skills only"},page:{type:"number",required:!1,description:"Page number (for personal skills, default: 1)"},size:{type:"number",required:!1,description:"Page size (for personal skills, default: 20)"}},output:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{description:{type:"string",description:"Skill description"},skill_id:{type:"string",description:"Skill ID"},name:{type:"string",description:"Skill name"},icon:{type:"string",description:"Skill icon URL"},is_installed:{type:"boolean",description:"Whether the skill is installed"}}}},total:{type:"number",description:"Total number of records (only present for --my mode)"}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}]}}).action((async function(o,i){const s=i.getContext(),{projectId:n}=o;if(o.my){const e=o.page?parseInt(o.page,10):1,t=o.size?parseInt(o.size,10):20,i=await Va.GetUserSkillList({page:e,size:t});return Yc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${Yc([i,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} personal skills.`)]),void Yc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({items:Yc([i,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({skill_id:Yc([e,"optionalAccess",e=>e.skill_id]),name:Yc([e,"optionalAccess",e=>e.name]),description:Yc([e,"optionalAccess",e=>e.description]),icon:Yc([e,"optionalAccess",e=>e.icon]),is_installed:!1})))])||[],total:Qc(Yc([i,"access",e=>e.data,"optionalAccess",e=>e.total]),(()=>0))})])}const r=Qc(Qc(o.spaceId,(()=>Yc([s,"optionalAccess",e=>e.config,"access",e=>e.spaceId]))),(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing spaceId: pass --space-id <spaceId> or set config.spaceId");const a=await t.IdeApi.GetVibeProject({project_id:n}),c=Yc([await Fc.getDefaultConversation(n),"access",e=>e.conversation_setting,"optionalAccess",e=>e.skill_setting,"optionalAccess",e=>e.skills])||[],l=new Set(c.map((e=>e.skill_id)).filter(Boolean)),d=Yc([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),p=await Va.GetSkillList({project_type:d,space_id:r,category_type_list:[d]});Yc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${Yc([p,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} skills.`)]),Yc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({items:Yc([p,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({description:Yc([e,"optionalAccess",e=>e.description]),skill_id:Yc([e,"optionalAccess",e=>e.skill_id]),name:Yc([e,"optionalAccess",e=>e.name]),icon:Yc([e,"optionalAccess",e=>e.icon]),is_installed:l.has(e.skill_id||"")})))])||[]})])}))}(i),function(t){t.command("add <skillId>").description("Add skills to the conversation").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add skill to conversation",description:"Add a specified skill to the default conversation. Skills can extend capabilities, such as adding search, code execution, etc.",examples:[{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID"}},output:{project_id:{type:"string",description:"Project ID"},added_skill_ids:{type:"array",items:{type:"string"},description:"Added skill IDs"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E3002,name:"SKILL_NOT_FOUND",desc:"The specified skill does not exist",fix:"Please use `skill list` to confirm available skills"}]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t,n=[e],r=await Fc.getDefaultConversation(s);await Fc.updateConversationSetting(s,r.id,{skillSetting:{add_skills:n.map((e=>({skill_id:String(e),is_preload:!0})))}}),Zc([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skills added successfully.")]),Zc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,added_skill_ids:n,message:"added Skills successfully."})])}))}(i),function(t){t.command("remove <skillId>").description("Remove skills from the conversation").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Remove skill from conversation",description:"Remove a configured skill from the default conversation.",examples:[{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID to remove"}},output:{project_id:{type:"string",description:"Project ID"},removed_skill_ids:{type:"array",items:{type:"string"},description:"Removed skill IDs"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E3004,name:"SKILL_NOT_INSTALLED",desc:"The specified skill is not installed in the conversation",fix:"Please use `skill list` to confirm installed skills"}]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t,n=[e],r=await Fc.getDefaultConversation(s);await Fc.updateConversationSetting(s,r.id,{skillSetting:{remove_skills:n.map((e=>({skill_id:String(e),is_preload:!0})))}}),Kc([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill removed.")]),Kc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,removed_skill_ids:n,message:"removed Skills successfully."})])}))}(i),function(t){t.command("upload <filePath>").description("Upload a personal skill").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Upload a personal skill",description:"Upload a .skill file as a personal skill. If a naming conflict exists, it will be automatically confirmed to overwrite.",examples:[{desc:"Upload a skill file",cmd:'coze code skill upload "./my-skill.skill" -p <projectId>',tags:["[RECOMMENDED]"]}],schema:{input:{filePath:{type:"string",required:!0,description:"Path to the .skill file"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},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 s=i.getContext(),{projectId:n}=o,r=g.resolve(t);if(!f.existsSync(r))throw new e.CozeError(e.ErrorCode.E1000,`File not found: ${r}`,{filePath:r});const a=g.basename(r),c=f.createReadStream(r);Xc([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Uploading skill ${a}...`)]);const l=await Va.UploadSkill({body:{file_content:c,file_name:a}},{headers:{"Content-Type":"multipart/form-data"}});if(Xc([l,"access",e=>e.data,"optionalAccess",e=>e.naming_conflict])){const e=Xc([l,"access",e=>e.data,"optionalAccess",e=>e.conflict_info,"optionalAccess",e=>e.preview_skill_key]);Xc([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Naming conflict detected, auto-confirming overwrite...")]),await Va.UploadSkillConfirm({preview_skill_key:e})}Xc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill uploaded successfully.")]),Xc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,message:"Skill uploaded successfully"})])}))}(i),function(t){t.command("delete <skillId>").description("Delete a personal skill").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete a personal skill",description:"Permanently delete a personal skill. This is different from skill remove which only unlinks a skill from the project.",examples:[{desc:"Delete a skill",cmd:"coze code skill delete <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{skillId:{type:"string",required:!0,description:"Skill ID to delete"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Skill not found or invalid skill ID",fix:"Use 'coze code skill list -p <projectId> --my' to see available skills"}]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t;await Va.DeleteSkill({skill_id:e}),el([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Skill '${e}' deleted.`)]),el([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({project_id:s,message:`Skill '${e}' has been permanently deleted`})])}))}(i)};var ol,il,sl,nl,rl,al,cl,ll,dl,pl,ul,ml,gl,hl,fl,_l,yl,bl,vl,wl,Cl,El,Il,Al,Sl,jl,Pl,kl,Tl,zl,Rl,xl,Ll,Ol,Dl,Ul,Bl,ql,Ml,Nl,$l,Gl,Fl,Vl,Wl,Hl,Jl,Kl,Ql,Yl,Zl,Xl,ed,td,od,id,sd,nd,rd,ad,cd,ld,dd,pd,ud,md,gd,hd,fd,_d,yd,bd,vd,wd,Cd,Ed,Id;function Ad(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(ol||(ol={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(il||(il={})),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"}(sl||(sl={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(nl||(nl={})),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"}(rl||(rl={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(al||(al={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(cl||(cl={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(ll||(ll={})),function(e){e[e.Official=1]="Official";e[e.Public=2]="Public";e[e.Custom=3]="Custom";e[e.Others=101]="Others"}(dl||(dl={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(pl||(pl={})),function(e){e[e.App=1]="App";e[e.Resource=2]="Resource"}(ul||(ul={})),function(e){e[e.CozeModel=1]="CozeModel";e[e.VolcAccount=2]="VolcAccount";e[e.SelfAccount=3]="SelfAccount";e[e.SelfModel=4]="SelfModel"}(ml||(ml={})),function(e){e[e.Asc=1]="Asc";e[e.Desc=2]="Desc"}(gl||(gl={})),function(e){e[e.NoDetail=1]="NoDetail";e[e.Detail=2]="Detail";e[e.Operate=3]="Operate"}(hl||(hl={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(fl||(fl={})),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"}(_l||(_l={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi";e[e.MessagesApi=2]="MessagesApi"}(yl||(yl={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(bl||(bl={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(vl||(vl={})),function(e){e[e.Provider=1]="Provider";e[e.Custom=2]="Custom"}(wl||(wl={})),function(e){e[e.CozeAccountTypeUnknown=0]="CozeAccountTypeUnknown";e[e.CozeAccountTypePersonal=1]="CozeAccountTypePersonal";e[e.CozeAccountTypeOrganization=2]="CozeAccountTypeOrganization"}(Cl||(Cl={})),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"}(El||(El={})),function(e){e[e.Mobile=1]="Mobile";e[e.Web=2]="Web"}(Il||(Il={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(Al||(Al={})),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"}(Sl||(Sl={})),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"}(jl||(jl={})),function(e){e[e.DEFAULT=0]="DEFAULT";e[e.Chux=1]="Chux"}(Pl||(Pl={})),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"}(kl||(kl={})),function(e){e[e.PromptDiff=1]="PromptDiff";e[e.ModelDiff=2]="ModelDiff"}(Tl||(Tl={})),function(e){e[e.DraftBot=1]="DraftBot"}(zl||(zl={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(Rl||(Rl={})),function(e){e[e.Archive=1]="Archive";e[e.Rollback=2]="Rollback"}(xl||(xl={})),function(e){e[e.ProjectCopyCancel=1]="ProjectCopyCancel";e[e.ProjectCopyRetry=2]="ProjectCopyRetry"}(Ll||(Ll={})),function(e){e[e.ProjectCopy=1]="ProjectCopy";e[e.BotCopy=2]="BotCopy";e[e.VibeProjectCopy=3]="VibeProjectCopy"}(Ol||(Ol={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Dl||(Dl={})),function(e){e[e.Bot=1]="Bot";e[e.Workflow=2]="Workflow";e[e.Application=3]="Application"}(Ul||(Ul={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(Bl||(Bl={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(ql||(ql={})),function(e){e[e.BatchSize=1]="BatchSize";e[e.LearningRate=2]="LearningRate";e[e.Epochs=3]="Epochs"}(Ml||(Ml={})),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"}(Nl||(Nl={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}($l||($l={})),function(e){e[e.Douyin=1]="Douyin"}(Gl||(Gl={})),function(e){e[e.Terminating=1]="Terminating";e[e.Terminated=2]="Terminated"}(Fl||(Fl={})),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"}(Vl||(Vl={})),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"}(Wl||(Wl={})),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"}(Hl||(Hl={})),function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInput=2]="TotalInput";e[e.TotalOutput=3]="TotalOutput"}(Jl||(Jl={})),function(e){e[e.stop=1]="stop";e[e.resume=2]="resume",e[e.delete=3]="delete"}(Kl||(Kl={})),function(e){e[e.Recommend=1]="Recommend"}(Ql||(Ql={})),function(e){e[e.Default=0]="Default";e[e.Terminate=1]="Terminate"}(Yl||(Yl={})),function(e){e[e.All=0]="All";e[e.WithBenefit=1]="WithBenefit"}(Zl||(Zl={})),function(e){e[e.upload=1]="upload";e[e.TrainingSetSplit=2]="TrainingSetSplit"}(Xl||(Xl={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(ed||(ed={})),function(e){e[e.Using=1]="Using";e[e.Deleted=2]="Deleted"}(td||(td={})),function(e){e[e.Publish=0]="Publish";e[e.Archive=1]="Archive"}(od||(od={})),function(e){e[e.User=0]="User";e[e.NL2App=1]="NL2App"}(id||(id={})),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"}(sd||(sd={})),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"}(nd||(nd={})),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"}(rd||(rd={})),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"}(ad||(ad={})),function(e){e[e.Normal=0]="Normal";e[e.InReview=1]="InReview";e[e.Offline=2]="Offline"}(cd||(cd={})),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"}(ld||(ld={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Authorizing=3]="Authorizing"}(dd||(dd={})),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"}(pd||(pd={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(ud||(ud={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.Name=2]="Name"}(md||(md={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime"}(gd||(gd={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.PublishTime=2]="PublishTime";e[e.OpenTime=3]="OpenTime"}(hd||(hd={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(fd||(fd={})),function(e){e[e.All=0]="All";e[e.CreateByMe=1]="CreateByMe";e[e.AllWithCollaborator=2]="AllWithCollaborator";e[e.CanImportToSpace=3]="CanImportToSpace"}(_d||(_d={})),function(e){e[e.Desc=0]="Desc";e[e.Asc=1]="Asc"}(yd||(yd={})),function(e){e[e.Copy=1]="Copy";e[e.Move=2]="Move";e[e.Publish=3]="Publish";e[e.ImportExport=4]="ImportExport"}(bd||(bd={})),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"}(vd||(vd={})),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"}(wd||(wd={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(Cd||(Cd={})),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"}(Ed||(Ed={})),function(e){e[e.Packing=0]="Packing";e[e.PackSuccess=1]="PackSuccess";e[e.PackFail=2]="PackFail"}(Id||(Id={}));class Sd{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Sd.prototype.__init.call(this),Sd.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)}Ping(e,t){const o=this.genBaseURL("/api/intelligence_api/ping");return this.request({url:o,method:"POST"},t)}DraftProjectCreate(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/create"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri,monetization_conf:o.monetization_conf,create_from:o.create_from,folder_id:o.folder_id,type:o.type};return this.request({url:i,method:"POST",data:s},t)}GetDraftIntelligenceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_list"),s={space_id:o.space_id,name:o.name,has_published:o.has_published,status:o.status,types:o.types,search_scope:o.search_scope,folder_id:o.folder_id,folder_include_children:o.folder_include_children,order_type:o.order_type,project_type:o.project_type,is_fav_filter:o.is_fav_filter,is_collaborator_filter:o.is_collaborator_filter,organization_id:o.organization_id,is_fav:o.is_fav,recently_open:o.recently_open,option:o.option,order_by:o.order_by,cursor_id:o.cursor_id,size:o.size};return this.request({url:i,method:"POST",data:s},t)}DraftProjectUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/update"),s={project_id:o.project_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetDraftIntelligenceInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_info"),s={intelligence_id:o.intelligence_id,intelligence_type:o.intelligence_type,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GetUserRecentlyEditIntelligence(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/search/get_recently_edit_intelligence"),s={size:o.size,types:o.types,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DraftProjectCopy(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/copy"),s={project_id:o.project_id,to_space_id:o.to_space_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}ProcessEntityTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/entity_task/process"),s={entity_id:o.entity_id,action:o.action,task_id_list:o.task_id_list};return this.request({url:i,method:"POST",data:s},t)}DraftProjectDelete(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/delete"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}EntityTaskSearch(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/entity_task/search"),s={task_list:o.task_list};return this.request({url:i,method:"POST",data:s},t)}ListIntelligenceCollaboration(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/collaboration/list"),s={intelligence_id:o.intelligence_id,intelligence_type:o.intelligence_type};return this.request({url:i,method:"POST",data:s},t)}OceanProjectCreate(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/ocean_project/create"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}OceanProjectUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/ocean_project/update"),s={project_id:o.project_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetOceanProjectList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_list"),s={space_id:o.space_id,status:o.status,search_scope:o.search_scope,order_by:o.order_by,page_index:o.page_index,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PublishProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_project"),s={project_id:o.project_id,version_number:o.version_number,description:o.description,connectors:o.connectors,connector_publish_config:o.connector_publish_config};return this.request({url:i,method:"POST",data:s},t)}GetPublishRecordDetail(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_record_detail"),s={project_id:o.project_id,publish_record_id:o.publish_record_id};return this.request({url:i,method:"POST",data:s},t)}GetPublishRecordList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_record_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublishConnectorList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/connector_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}CheckProjectVersionNumber(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/check_version_number"),s={project_id:o.project_id,version_number:o.version_number};return this.request({url:i,method:"POST",data:s},t)}DraftProjectInnerTaskList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/inner_task_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}GetOceanProjectInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_info"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}GetModelListFilterParams(e,t){const o=this.genBaseURL("/api/intelligence_api/model/get_model_list_filter_params");return this.request({url:o,method:"POST"},t)}StartEstimatedTrainingCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/start_estimated_training_cost"),s={base_model_id:o.base_model_id,space_id:o.space_id,training_dataset_id:o.training_dataset_id,epochs:o.epochs};return this.request({url:i,method:"POST",data:s},t)}GetModelList(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_list"),s={space_id:o.space_id,name:o.name,tag_filters:o.tag_filters,context_len_min:o.context_len_min,context_len_max:o.context_len_max,model_cost_min:o.model_cost_min,model_cost_max:o.model_cost_max,model_vendor:o.model_vendor,statusList:o.statusList,model_show_family_id:o.model_show_family_id,model_source:o.model_source,order_by:o.order_by,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}GetFinetuneTemplateDataset(e,t){const o=this.genBaseURL("/api/intelligence_api/model/get_finetune_template_dataset");return this.request({url:o,method:"POST"},t)}GetModelUsageData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_usage_data"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTrainingCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_training_cost"),s={task_id:o.task_id,space_id:o.space_id,base_model_id:o.base_model_id,epochs:o.epochs};return this.request({url:i,method:"POST",data:s},t)}CreateFinetuneTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/create_finetune_task"),s={space_id:o.space_id,base_model_id:o.base_model_id,training_dataset_id:o.training_dataset_id,validating_dataset:o.validating_dataset,finetune_configuration:o.finetune_configuration,description:o.description,name:o.name};return this.request({url:i,method:"POST",data:s},t)}UploadFinetuneDataset(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/upload_finetune_dataset"),s={space_id:o.space_id,fileType:o.fileType,fileName:o.fileName,data:o.data,testing_data:o.testing_data};return this.request({url:i,method:"POST",data:s},t)}GetModelInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_info"),s={space_id:o.space_id,model_id:o.model_id,is_finetuning:o.is_finetuning};return this.request({url:i,method:"POST",data:s},t)}GetFinetuneTrainingInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_finetune_training_info"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetModelPerformanceData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_performance_data"),s={space_id:o.space_id,model_id:o.model_id,get_pct:o.get_pct};return this.request({url:i,method:"POST",data:s},t)}OperateFinetuneTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/operate_finetune_task"),s={id:o.id,action:o.action};return this.request({url:i,method:"POST",data:s},t)}DeleteFinetuneModel(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/delete_finetune_model"),s={model_id:o.model_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetUserCompleteProfileRecord(e,t){const o=this.genBaseURL("/api/intelligence_api/user_profile/get_user_complete_profile_record");return this.request({url:o,method:"POST"},t)}DownloadUserProfile(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/user_profile/download_user_profile"),s={Cookie:o.Cookie};return this.request({url:i,method:"POST",headers:s},t)}GetProjectPublishedConnector(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/get_published_connector"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublishIntelligenceUnList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_intelligence_unlist"),s={intelligence_id:o.intelligence_id,connector_ids:o.connector_ids,intelligence_type:o.intelligence_type};return this.request({url:i,method:"POST",data:s},t)}PublishIntelligenceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_publish_intelligence_list"),s={intelligence_type:o.intelligence_type,space_id:o.space_id,owner_id:o.owner_id,name:o.name,order_last_publish_time:o.order_last_publish_time,order_total_token:o.order_total_token,size:o.size,cursor_id:o.cursor_id,intelligence_ids:o.intelligence_ids};return this.request({url:i,method:"POST",data:s},t)}UpdateDiffModeInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/diff_mode/update_diff_mode_info"),s={target_type:o.target_type,target_id:o.target_id,diff_mode_info:o.diff_mode_info,exit_and_save:o.exit_and_save,exit_and_discard:o.exit_and_discard};return this.request({url:i,method:"POST",data:s},t)}GetDiffModeInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/diff_mode/get_diff_mode_info"),s={target_type:o.target_type,target_id:o.target_id};return this.request({url:i,method:"POST",data:s},t)}GetProjectPublishSummary(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_project_publish_summary"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}DraftProjectCrossSpaceCopy(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/crossspace_copy"),s={project_id:o.project_id,to_space_id:o.to_space_id};return this.request({url:i,method:"POST",data:s},t)}EntityTaskList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/entity_task/list"),s={space_id:o.space_id,task_id_list:o.task_id_list};return this.request({url:i,method:"POST",data:s},t)}ExpansionTpm(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/expansion_tpm"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,organization_id:o.organization_id,tpm_input_expansion:o.tpm_input_expansion,tpm_output_expansion:o.tpm_output_expansion,start_time:o.start_time,end_time:o.end_time};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTpmExpansionCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion_cost"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,input_tpm:o.input_tpm,output_tpm:o.output_tpm};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTpmExpansion(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,estimated_rpm:o.estimated_rpm,StartTime:o.StartTime,EndTime:o.EndTime};return this.request({url:i,method:"POST",data:s},t)}FolderUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/update"),s={folder_id:o.folder_id,name:o.name,description:o.description};return this.request({url:i,method:"POST",data:s},t)}GetFolderList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_folder_list"),s={space_id:o.space_id,type:o.type,name:o.name,search_scope:o.search_scope,parent_folder_id:o.parent_folder_id,parent_include_children:o.parent_include_children,order_by:o.order_by,order_type:o.order_type,size:o.size,page_num:o.page_num};return this.request({url:i,method:"POST",data:s},t)}FolderMove(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/move"),s={folder_id:o.folder_id,parent_folder_id:o.parent_folder_id};return this.request({url:i,method:"POST",data:s},t)}FolderDelete(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/delete"),s={folder_id:o.folder_id};return this.request({url:i,method:"POST",data:s},t)}FolderCreate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/create"),s={space_id:o.space_id,type:o.type,name:o.name,description:o.description,parent_folder_id:o.parent_folder_id};return this.request({url:i,method:"POST",data:s},t)}ArchiveProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/archive"),s={project_id:o.project_id,description:o.description,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetIntelligenceTaskInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/entity_task/task_info"),s={task_id:o.task_id};return this.request({url:i,method:"GET",params:s},t)}ProjectHistoryList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list"),s={project_id:o.project_id,history_type:o.history_type,cursor:o.cursor,size:o.size};return this.request({url:i,method:"POST",data:s},t)}RollbackProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/rollback"),s={project_id:o.project_id,rollback_version:o.rollback_version,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetModelConcurrencyPerformanceData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_concurrency_performance_data"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}UpdateModelConfigType(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/update_model_config_type"),s={space_id:o.space_id,model_id:o.model_id,config_type:o.config_type};return this.request({url:i,method:"POST",data:s},t)}GetSpaceModelUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_space_model_user_config"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}OpenGetProjectList(e,t){const o=e||{},i=this.genBaseURL("/v1/apps"),s={workspace_id:o.workspace_id,publish_status:o.publish_status,connector_id:o.connector_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}OpenGetBotList(e,t){const o=e||{},i=this.genBaseURL("/v1/bots"),s={workspace_id:o.workspace_id,publish_status:o.publish_status,connector_id:o.connector_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}GetFolderTree(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/tree"),s={space_id:o.space_id,type:o.type};return this.request({url:i,method:"POST",data:s},t)}OpenGetSpaceFolder(e,t){const o=e||{},i=this.genBaseURL("/v1/folders"),s={workspace_id:o.workspace_id,folder_type:o.folder_type,parent_folder_id:o.parent_folder_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}MoveObjectToFolder(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/move_object"),s={dest_folder_id:o.dest_folder_id,folder_space_id:o.folder_space_id,move_objects:o.move_objects};return this.request({url:i,method:"POST",data:s},t)}GetFolderInfoByIds(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/folder/get_by_ids"),s={space_id:o.space_id,folder_ids:o.folder_ids,get_path_info:o.get_path_info};return this.request({url:i,method:"POST",data:s},t)}OpenGetFolderInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/folders/${o.folder_id}`);return this.request({url:i,method:"GET"},t)}ExportPreCheck(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/export_pre_check"),s={res_type:o.res_type,id:o.id,commit_id:o.commit_id};return this.request({url:i,method:"POST",data:s},t)}ImportPreCheck(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/import_pre_check"),s={package_uri:o.package_uri};return this.request({url:i,method:"POST",data:s},t)}GetUploadAuthToken(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/upload/auth_token"),s={scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}MarkProjectHistory(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list/read"),s={project_id:o.project_id,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelDetail(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_detail"),s={model_id:o.model_id,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_list"),s={search_key:o.search_key,sort_field:o.sort_field,org_id:o.org_id,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetProjectHistoryNotice(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list/notice"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}BindCustomModelSpace(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/bind_custom_model_space"),s={model_id:o.model_id,space_id_list:o.space_id_list,status:o.status,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelSpaceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_space_list"),s={model_id:o.model_id,search_key:o.search_key,org_id:o.org_id,cursor_id:o.cursor_id,limit:o.limit,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelParameterTemplate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_parameter_template"),s={org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}OpenCopyTaskInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/entities/copy_tasks/${o.task_id}`);return this.request({url:i,method:"GET"},t)}OpenDuplicateDraftEntity(e,t){const o=e||{},i=this.genBaseURL("/v1/entities/copy_tasks"),s={entity_id:o.entity_id,entity_type:o.entity_type,to_workspace_id:o.to_workspace_id};return this.request({url:i,method:"POST",data:s},t)}ConvertCustomModelParameter(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/convert_custom_model_parameter"),s={parameters:o.parameters,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}CreateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/create_custom_model"),s={model_name:o.model_name,model_icon_uri:o.model_icon_uri,model_arch:o.model_arch,model_desc:o.model_desc,base_url:o.base_url,secret_name:o.secret_name,model_runtime_tag:o.model_runtime_tag,inputLength:o.inputLength,parameters:o.parameters,api_agreement:o.api_agreement,safety_guardrails:o.safety_guardrails,auth:o.auth,api_mode:o.api_mode,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}TerminateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/terminate_custom_model"),s={model_id:o.model_id,terminate_time:o.terminate_time,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}UpdateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/update_custom_model"),s={model_name:o.model_name,model_icon_uri:o.model_icon_uri,model_arch:o.model_arch,model_desc:o.model_desc,base_url:o.base_url,secret_name:o.secret_name,model_runtime_tag:o.model_runtime_tag,inputLength:o.inputLength,parameters:o.parameters,model_id:o.model_id,api_agreement:o.api_agreement,safety_guardrails:o.safety_guardrails,auth:o.auth,api_mode:o.api_mode,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageRecord(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_usage_record"),s={space_id:o.space_id,model_id:o.model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp,order_by_type:o.order_by_type,order_by_field:o.order_by_field,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetEntityModelUsage(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_entity_model_usage"),s={space_id:o.space_id,model_id:o.model_id,entity_id:o.entity_id,entity_type:o.entity_type,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}GetTypeList(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/get_type_list"),s={model:o.model,voice:o.voice,raw_model:o.raw_model,space_id:o.space_id,cur_model_id:o.cur_model_id,cur_model_ids:o.cur_model_ids,model_scene:o.model_scene,tag_filters:o.tag_filters,user_benefit_filter:o.user_benefit_filter};return this.request({url:i,method:"POST",data:s},t)}SaveModelReplacement(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/save_replacement"),s={space_id:o.space_id,old_model_id:o.old_model_id,new_model_id:o.new_model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}GetModelReplacement(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_replacement"),s={space_id:o.space_id,entity_type:o.entity_type,entity_id:o.entity_id};return this.request({url:i,method:"POST",data:s},t)}UpdateCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/update"),s={model_id:o.model_id,display_name:o.display_name,model_name:o.model_name,base_url:o.base_url,api_mode:o.api_mode,auth:o.auth,support_image_understanding:o.support_image_understanding,max_tokens:o.max_tokens};return this.request({url:i,method:"POST",data:s},t)}ListProviderModels(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/list_provider_models"),s={provider:o.provider,auth:o.auth,base_url:o.base_url,search_key:o.search_key};return this.request({url:i,method:"POST",data:s},t)}ListCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/list"),s={account_type:o.account_type,coze_account_id:o.coze_account_id,enterprise_id:o.enterprise_id,search_key:o.search_key,provider:o.provider,source_type:o.source_type,sort_field:o.sort_field,sort_order:o.sort_order,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}ToggleCustomModelMemberVisibility(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/toggle_member_visibility"),s={model_id:o.model_id,member_visible:o.member_visible};return this.request({url:i,method:"POST",data:s},t)}DeleteCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/delete"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}ListProviders(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/custom_model/list_providers"),s={only_enabled:o.only_enabled};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelDetailV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/detail"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}CreateCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/create"),s={source_type:o.source_type,provider:o.provider,display_name:o.display_name,model_name:o.model_name,base_url:o.base_url,api_mode:o.api_mode,auth:o.auth,support_image_understanding:o.support_image_understanding,max_tokens:o.max_tokens,account_type:o.account_type,coze_account_id:o.coze_account_id,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}}const jd=new Sd({}),Pd={agent:jl.VibeProjectAgent,workflow:jl.VibeProjectAutomation,webapp:jl.VibeProjectWebApp,app:jl.VibeProjectApp,skill:jl.VibeProjectSkill,web:jl.VibeProjectGeneralWeb,miniprogram:jl.VibeProjectWechatMiniProgram,assistant:jl.VibeProjectAssistantAgent},kd={[jl.VibeProjectAgent]:"agent",[jl.VibeProjectAutomation]:"workflow",[jl.VibeProjectWebApp]:"webapp",[jl.VibeProjectApp]:"app",[jl.VibeProjectSkill]:"skill",[jl.VibeProjectGeneralWeb]:"web",[jl.VibeProjectWechatMiniProgram]:"miniprogram",[jl.VibeProjectAssistantAgent]:"assistant"};function Td(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return Pd[o]}const zd=e=>kd[e],Rd=[jl.VibeProjectAgent,jl.VibeProjectAutomation,jl.VibeProjectWebApp,jl.VibeProjectApp,jl.VibeProjectSkill,jl.VibeProjectGeneralWeb,jl.VibeProjectWechatMiniProgram,jl.VibeProjectAssistantAgent].map(zd).filter(Boolean);function xd(e,t){return null!=e?e:t()}function Ld(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Od(e,t){return null!=e?e:t()}function Dd(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ud=["github","local"];const Bd={agent:t.VibeProjectType.Agent,workflow:t.VibeProjectType.Automation,webapp:t.VibeProjectType.WebApp,app:t.VibeProjectType.App,skill:t.VibeProjectType.Skill,web:t.VibeProjectType.GeneralWeb,miniprogram:t.VibeProjectType.WechatMiniProgram,assistant:t.VibeProjectType.AssistantAgent},qd={[t.VibeProjectType.Agent]:"agent",[t.VibeProjectType.Automation]:"workflow",[t.VibeProjectType.WebApp]:"webapp",[t.VibeProjectType.App]:"app",[t.VibeProjectType.Skill]:"skill",[t.VibeProjectType.GeneralWeb]:"web",[t.VibeProjectType.WechatMiniProgram]:"miniprogram",[t.VibeProjectType.AssistantAgent]:"assistant"};function Md(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return Bd[o]}const Nd=e=>qd[e],$d={ask:t.ProjectMode.Ask,agent:t.ProjectMode.Agent,dangerous_confirm:t.ProjectMode.DangerousConfirm,plan:t.ProjectMode.Plan};t.ProjectMode.Ask,t.ProjectMode.Agent,t.ProjectMode.DangerousConfirm,t.ProjectMode.Plan;const Gd={[t.ConversationMode.Ask]:"ask",[t.ConversationMode.Agent]:"agent",[t.ConversationMode.DangerousConfirm]:"dangerous_confirm",[t.ConversationMode.Plan]:"plan"};function Fd(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return $d[o]}function Vd(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Wd(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Hd={project_id:"7603316828982525988",icon_uri:"gen_project_icon/2026-02-06/7603316828982525988_1770308040.png",name:"OpenClaw助手(副本)",description:"OpenClaw智能代理:提供多场景AI服务,自动化处理任务,提升工作效率。"};class Jd{static getInstance(){return Jd.INSTANCE||(Jd.INSTANCE=new Jd),Jd.INSTANCE}sendMessageRunTask(e){const t=[g.resolve(__dirname,"./send-message.worker.js")],o=process.execPath;v.spawn(o,[...t,JSON.stringify(e)],{detached:!0,stdio:"ignore"}).unref()}async sendMessage(e){return await t.sendProjectChatMessage(e)}}const Kd=Jd.getInstance();function Qd(e,t){return null!=e?e:t()}function Yd(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Zd=new Set([t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.WechatMiniProgram]);function Xd(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ep=o=>{const i=o.command("project").alias("proj").config({help:{brief:"Manage Coze Coding projects",description:"Manage Coze Coding projects (Vibe Project). Supports creating, viewing, listing, and deleting projects, covering various project types like Agent, Workflow, Skill, Web apps, Mini-programs, etc.",examples:[{desc:"Create project",cmd:'coze code project create --message "Create a chatbot" --type web'},{desc:"List projects",cmd:"coze code project list"},{desc:"View project details",cmd:"coze code project get <projectId>"},{desc:"Delete project",cmd:"coze code project delete <projectId>"}],seeAlso:["coze code deploy","coze code skill"],schema:{input:{},output:{}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).description("Manage Coze Coding projects");i.command("create").description("Create a new project").requiredOption("--message <message>","Description/requirements for creating the project").requiredOption("--type <type>","Project type: agent | workflow | app | skill | web | miniprogram | assistant").option("--org-id <orgId>","Organization ID (optional, will read from context automatically)").option("--space-id <spaceId>","Space ID (optional, will read from context automatically)").option("--wait","Wait for project creation to complete").option("--chat-mode <chatMode>","Chat mode: ask | agent | dangerous_confirm | plan").option("--model-name <modelName>","Model name for the project").option("--tool-name <toolName>","Tool names to enable (can specify multiple times)",((e,t)=>t.concat(e)),[]).option("--design","Enable design wizard (auto-enabled when --chat-mode is plan)").config({help:{brief:"Create a new Coze Coding project",description:"Create a new Coze Coding project via natural language description. The system will automatically generate project structure and configuration based on the description, supporting multiple project types.",examples:[{desc:"Create an Agent project",cmd:'coze code project create --message "Create an intelligent customer service robot" --type agent',tags:["[RECOMMENDED]"]},{desc:"Create a Workflow project",cmd:'coze code project create --message "Create a data processing workflow" --type workflow'}],schema:{input:{message:{type:"string",required:!0,description:"Project description/requirements (natural language)"},type:{type:"string",required:!0,enum:Object.keys(Bd),description:"Project type"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"},chatMode:{type:"string",enum:Object.keys($d),required:!1,description:'Chat mode: ask (对话模式) | agent (Agent模式, default) | dangerous_confirm (危险操作需确认) | plan (计划模式). When set to "plan", --design is auto-enabled.'},modelName:{type:"string",required:!1,description:"Model name for the project"},toolName:{type:"array",required:!1,description:"Tool names to enable (can specify multiple times with --tool-name)"},design:{type:"boolean",required:!1,description:"Enable design wizard. Auto-enabled when --chat-mode is plan. Only supported for web/app/miniprogram project types."}},output:{project_id:{type:"string",description:"Created project ID"},type:{type:"string",description:"Project type"}}},enums:{type:Object.keys(Bd).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(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Qd(Qd(o.spaceId,(()=>Yd([s,"optionalAccess",e=>e.config,"access",e=>e.spaceId]))),(()=>"")),{message:r,type:a,wait:c,chatMode:l,modelName:d,toolName:p,design:u}=o,m=Boolean(u)||"plan"===l;Yd([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e(`Resolving project type '${a}'...`)]);const g=Md(a);if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!g)throw new e.CozeError(e.ErrorCode.E1005,`Unknown project type: ${a}`,{type:a});Yd([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching agent tools configuration...")]);const h=Yd([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===g)),"optionalAccess",e=>e.tools]);if(!h||0===h.length)throw new e.CozeError(e.ErrorCode.E5000,`No tools config for projectType: ${String(a)}`,{type:a,projectType:g});const f={};h.forEach((e=>{Yd([e,"optionalAccess",e=>e.name])&&(f[e.name]=Qd(Yd([p,"optionalAccess",e=>e.includes,"call",t=>t(e.name)]),(()=>Boolean(e.enabled))))})),Yd([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching project default skills...")]);const _={skills:Qd(Yd([await Va.GetProjectDefaultSkill({project_type:g,space_id:String(n)}),"access",e=>e.data,"optionalAccess",e=>e.skill_list]),(()=>[])).map((e=>({skill_id:e.skill_id,is_preload:e.is_preload}))),filter_types:[g]};let y;if(g===t.VibeProjectType.AssistantAgent){Yd([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating assistant project via template copy...")]);const e=await t.IdeApi.CopyVibeProject({...Hd,target_space_id:String(n)});y=Yd([e,"access",e=>e.data,"optionalAccess",e=>e.basic_info,"optionalAccess",e=>e.project_id])}else{Yd([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating project...")]);const e=Qd((await t.IdeApi.ChatCreateVibeProject({space_id:String(n),user_query:r,project_type:g,project_settings:{...Zd.has(g)?{project_symbol:t.ProjectSymbol.ProjectSymbolVersion3}:{},model_setting:{model_name:d||""},agent_tools:f,skill_setting:_,...l?{project_mode:Fd(l)}:{},...m?{wizards:{design:!0}}:{}}})).data,(()=>({})));y=e.project_id}const b=await Yd([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!b)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(s.ui.success(`Project created successfully, please use "coze code message status -p ${y}" to check the status.`),Yd([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:y,type:a})]),c){const e=await Kd.sendMessage({projectId:Qd(y,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:b,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${y}`});s.response.print(e.lastAnswerMessage)}else Kd.sendMessageRunTask({projectId:Qd(y,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:b,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${y}`})})),function(t){t.command("list").description("List all projects").config({help:{brief:"List all projects in the current space",description:"Get the list of projects in the current space. Supports filtering by type, name, publish status, and supports pagination.",examples:[{desc:"List projects",cmd:"coze code project list",tags:["[RECOMMENDED]"]},{desc:"Filter by type",cmd:"coze code project list --type agent --type workflow"},{desc:"Search by name",cmd:'coze code project list --name "customer service"'}],schema:{input:{size:{type:"number",required:!1,description:"Number of projects to return (default: 10)"},cursorId:{type:"string",required:!1,description:"Cursor for pagination"},type:{type:"array",required:!1,description:"Project type filter (can be passed multiple times)"},name:{type:"string",required:!1,description:"Filter by project name"},hasPublished:{type:"boolean",required:!1,description:"Filter by publish status"},searchScope:{type:"number",required:!1,description:"Created by (All = 0, CreateByMe = 1, AllWithCollaborator = 2)"},folderId:{type:"string",required:!1,description:"Folder ID"},orderType:{type:"number",required:!1,description:"Sort type (0 for descending, 1 for ascending)"},orderBy:{type:"number",required:!1,description:"Order by (0 for updated_at, 1 for created_at)"},isFavFilter:{type:"boolean",required:!1,description:"Filter by favorite status"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Project ID"},name:{type:"string",description:"Project name"},type:{type:"string",description:"Project type"},description:{type:"string",description:"Project description"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}],enums:{type:Rd.reduce(((e,t)=>(e[t]=`${t.toUpperCase()} project`,e)),{}),"search-scope":{0:"All",1:"CreateByMe",2:"AllWithCollaborator"},"order-type":{0:"Descending",1:"Ascending"},"order-by":{0:"updated_at",1:"created_at"}}}}).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=xd(Ld([e,"optionalAccess",e=>e.size]),(()=>10)),s=xd(Ld([e,"optionalAccess",e=>e.cursorId]),(()=>{})),n=Ld([e,"optionalAccess",e=>e.type,"optionalAccess",e=>e.map,"call",e=>e(Td),"access",e=>e.filter,"call",e=>e(Boolean)]),r=Ld([e,"optionalAccess",e=>e.name]),a=Ld([e,"optionalAccess",e=>e.hasPublished])?Boolean(Ld([e,"optionalAccess",e=>e.hasPublished])):void 0,c=Number(xd(Ld([e,"optionalAccess",e=>e.searchScope]),(()=>_d.All))),l=xd(Ld([e,"optionalAccess",e=>e.folderId]),(()=>"0")),d=Number(xd(Ld([e,"optionalAccess",e=>e.orderType]),(()=>yd.Desc))),p=Boolean(Ld([e,"optionalAccess",e=>e.isFavFilter])),u=Number(xd(Ld([e,"optionalAccess",e=>e.orderBy]),(()=>hd.UpdateTime)));let m=[];Ld([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching project list...")]);const g=await jd.GetDraftIntelligenceList({space_id:xd(Ld([o,"optionalAccess",e=>e.config,"access",e=>e.spaceId]),(()=>"")),size:i,cursor_id:s,types:n,name:r,has_published:a,search_scope:c,folder_id:l,order_type:d,order_by:u,is_fav_filter:p,status:[Sl.Using,Sl.Banned,Sl.MoveFailed]});m=Ld([g,"access",e=>e.data,"optionalAccess",e=>e.intelligences])||[],Ld([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetched ${m.length} projects.`)]),Ld([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(m.map((e=>({id:Ld([e,"access",e=>e.basic_info,"optionalAccess",e=>e.id]),name:Ld([e,"access",e=>e.basic_info,"optionalAccess",e=>e.name]),type:zd(e.type),description:Ld([e,"access",e=>e.basic_info,"optionalAccess",e=>e.description])}))))])}))}(i),function(o){o.command("get <projectId>").description("View project details").config({help:{brief:"Get project details",description:"Get the detailed configuration of the specified project, including project type, settings, skill configurations, etc.",examples:[{desc:"View project details",cmd:"coze code project get <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},project_name:{type:"string",description:"Project name"},project_type:{type:"string",description:"Project type"},type:{type:"string",description:"Human-readable project type string"},tools:{type:"object",description:"Project tool configurations (Record<string, boolean>)"},chat_mode:{type:"string",description:"Human-readable chat mode string"},model_name:{type:"string",description:"Current model name used by the project"},skills:{type:"object",description:"Project skill configurations",properties:{skills:{type:"array",items:{type:"object",properties:{skill_id:{type:"string",description:"Skill ID"},is_preload:{type:"boolean",description:"Is preloaded"}}}}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project does not exist",fix:"Please confirm if the project ID is correct, use `project list` to view available projects"}]}}).action((async function(o,i,s){const n=s.getContext();Vd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetching project details for '${o}'...`)]);try{const[i,s]=await Promise.all([t.IdeApi.GetVibeProject({project_id:o}),Fc.getDefaultConversation(o)]),r=Vd([i,"access",e=>e.data,"optionalAccess",e=>e.project_info]);if(!r)throw new e.CozeError(e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o});const a=s.conversation_setting;Vd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Project details for '${o}':`)]),Vd([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>{return e({...b.omit(r,["project_settings"]),type:Nd(Vd([r,"optionalAccess",e=>e.project_type])),tools:Vd([a,"optionalAccess",e=>e.agent_tools]),chat_mode:(t=Vd([a,"optionalAccess",e=>e.mode]),Gd[t]),model_name:Vd([a,"optionalAccess",e=>e.model_setting,"optionalAccess",e=>e.model_name]),skills:b.pick(Vd([a,"optionalAccess",e=>e.skill_setting]),["skills"])});var t}])}catch(t){W(t,e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o})}}))}(i),function(o){o.command("delete <projectId>").description("Delete a project").config({help:{brief:"Delete project",description:"Delete the specified Coze Coding project. This operation cannot be undone, please use with caution.",examples:[{desc:"Delete project",cmd:"coze code project delete <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID to delete"}},output:{project_id:{type:"string",description:"Deleted project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E3005,name:"DELETE_FAILED",desc:"Failed to delete project",fix:"Please confirm if the project ID is correct and check if you have sufficient permissions"}]}}).action((async function(o,i,s){const n=s.getContext();Wd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleting project '${o}'...`)]);try{await t.IdeApi.DeleteVibeProject({project_id:o})}catch(t){W(t,e.ErrorCode.E3005,`Failed to delete project '${o}': project not found or no permission`,{projectId:o})}Wd([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Project '${o}' deleted successfully.`)]),Wd([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:o,message:`Project '${o}' deleted successfully.`})])}))}(i),function(o){o.command("db").description("Manage project databases").command("list").description("List project database tables").requiredOption("-p, --project-id <projectId>","Project ID").option("--schema <schema>","Schema name (knowledge or public)").option("--env <env>","Environment: dev | prod (default: dev)").config({help:{brief:"List project database tables",description:"List all database tables for the specified project, grouped by schema.",examples:[{desc:"List all tables",cmd:"coze code project db list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List knowledge schema tables",cmd:"coze code project db list -p <projectId> --schema knowledge"},{desc:"List prod tables",cmd:"coze code project db list -p <projectId> --env prod"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},schema:{type:"string",required:!1,description:"Schema name filter"},env:{type:"string",required:!1,description:"Environment (dev or prod)"}},output:{type:"array",items:{type:"object",properties:{schema:{type:"string",description:"Schema name"},table_name:{type:"string",description:"Table name"}}}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid or missing project ID",fix:"Provide a valid project ID with -p <projectId>"}]}}).action((async function(e,o){const i=o.getContext(),{projectId:s,env:n}=e,r="prod"===n?t.MemoryEnv.product:t.MemoryEnv.develop,a=[];await Promise.all(["knowledge","public"].map((async e=>{((await t.IdeApi.GetSchemaTables({project_id:s,database_env:r,schema:e})).table_names||[]).forEach((t=>{a.push({schema:e,table_name:t})}))}))),Xd([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${a.length} tables.`)]),Xd([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])}))}(i),function(o){o.command("import").description("Import a project from a remote repo or local zip file").requiredOption("-s, --source <source>","Import source: github / local").option("-r, --repo <fullName>","Remote repo full name (e.g. user/repo), required for --source github").option("-f, --file <path>","Local zip file path, required for --source local").config({help:{brief:"Import a project from a remote repo or local zip file",description:"Create a new project by importing from a remote Git repository or uploading a local zip file. Remote import requires prior OAuth authorization via `coze code git auth login`. Imported remote projects will be automatically bound to the source repo. Local uploads must be zip format and no more than 500MB.",examples:[{desc:"Import from GitHub (minimal)",cmd:"coze code project import --source github --repo user/my-app"},{desc:"Import from GitHub",cmd:"coze code project import -s github -r user/my-app",tags:["[RECOMMENDED]"]},{desc:"Upload local zip file",cmd:"coze code project import --source local --file ./project.zip"},{desc:"[PIPELINE] Import and check status",cmd:"ID=$(coze code project import -s github -r user/app --format json | jq -r .project_id) && coze code project get $ID",tags:["[PIPELINE]"]},{desc:"[TEMPLATE] Import from any source",cmd:"coze code project import --source <github|local> [--repo <owner/name>] [--file <path>]",tags:["[TEMPLATE]"]}],schema:{input:{source:{type:"string",required:!0,enum:["github","local"],description:"Import source type",example:"github"},repo:{type:"string",required:!1,description:"Remote repo full name (owner/name)",example:"user/my-app"},file:{type:"string",required:!1,description:"Local zip file path",example:"./project.zip"}},output:{project_id:{type:"string",description:"Created project ID",example:"proj_abc123"},source:{type:"string",description:"Import source type",example:"github"},repo:{type:"string",description:"Remote repo full name (if applicable)",example:"user/my-app"}}},enums:{source:{github:"Import from a GitHub repository",local:"Upload a local zip file"}},errors:[{code:e.ErrorCode.E1008,name:"MISSING_IMPORT_SOURCE",desc:"Missing import source",fix:"Use --source github or --source local"},{code:e.ErrorCode.E1009,name:"MISSING_REPO",desc:"Missing --repo for github import",fix:"Add --repo <owner/name>"},{code:e.ErrorCode.E1010,name:"MISSING_FILE",desc:"Missing --file for local import",fix:"Add --file <path>"},{code:e.ErrorCode.E1011,name:"INVALID_FILE_FORMAT",desc:"File is not zip format",fix:"Only .zip files are supported"},{code:e.ErrorCode.E1012,name:"FILE_TOO_LARGE",desc:"File exceeds 500MB",fix:"Reduce file size and retry"},{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"}],seeAlso:["coze code project create","coze code repo bind","coze code git auth login"],caveats:["Remote import requires prior OAuth authorization via `coze code git auth login`","Local upload only supports .zip format, max 500MB","Remote imported projects are automatically bound to the source repo"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Od(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or run `coze space use <spaceId>` first");const{source:r,repo:a,file:c}=o;if(!r||!Ud.includes(r))throw new e.CozeError(e.ErrorCode.E1008,`Invalid or missing import source: "${r}". Use --source github or --source local`);if("github"===r){if(!a)throw new e.CozeError(e.ErrorCode.E1009,"Missing --repo: required when --source is github");s.ui.info(`Importing from GitHub: ${a}...`);const o=Od(Dd([await t.IdeApi.ImportProject({space_id:n,import_source:2,git_url:`https://github.com/${a}.git`,git_repo_name:a}),"access",e=>e.data,"optionalAccess",e=>e.vibe_project_id]),(()=>""));s.ui.success("Project imported successfully."),s.ui.info(` Project ID: ${o}`),s.ui.info(` Source: github (${a})`),s.response.print({project_id:o,source:"github",repo:a})}else if("local"===r){if(!c)throw new e.CozeError(e.ErrorCode.E1010,"Missing --file: required when --source is local");if(!c.endsWith(".zip"))throw new e.CozeError(e.ErrorCode.E1011,`Invalid file format: "${c}". Only .zip files are supported`);if(!f.existsSync(c))throw new e.CozeError(e.ErrorCode.E1011,`File not found: "${c}"`);const t=f.statSync(c);if(t.size>524288e3)throw new e.CozeError(e.ErrorCode.E1012,`File too large: ${Math.round(t.size/1024/1024)}MB. Maximum is 500MB`);s.ui.info(`Uploading local file: ${c}...`);const o=new _;o.append("space_id",n),o.append("import_source","1"),o.append("data",f.createReadStream(c),g.basename(c));const i=Od(Dd([await e.axiosInstance.post("/api/ideserver_api/project/import_project",o,{headers:{...o.getHeaders(),"agw-js-conv":"str"}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.vibe_project_id]),(()=>""));s.ui.success("Project imported successfully."),s.ui.info(` Project ID: ${i}`),s.ui.info(` Source: local (${c})`),s.response.print({project_id:i,source:"local"})}}))}(i)};function tp(e,t){return null!=e?e:t()}const op=["ecs","vefaas"],ip=e=>op.includes(tp(process.env.COZE_CLI_PLATFORM,(()=>"")).trim().toLowerCase())?"https://www.coze.cn/":tp(e,(()=>l.DEFAULT_CONFIG.apiBaseUrl)),sp=(e,t)=>`${ip(t)}p/${e}`;function np(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const rp=new Set([t.VibeProjectType.WechatMiniProgram,t.VibeProjectType.Agent,t.VibeProjectType.Automation,t.VibeProjectType.Skill,t.VibeProjectType.AssistantAgent]);function ap(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function cp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const lp=o=>{const i=o.command("model").config({help:{brief:"Manage project models",description:"Manage models for Coze Coding projects. List available models and set the active model for a project.",examples:[{desc:"List available models",cmd:"coze code model list -p <projectId>"},{desc:"Set project model",cmd:"coze code model set doubao-dev-0213 -p <projectId>"}],seeAlso:["coze code project","coze code tools"]}}).description("Manage project models");!function(o){o.command("list").description("List available models").option("-p, --project-id <projectId>","Project ID").option("--type <type>","Project type (web, app, agent, etc.)").config({help:{brief:"List available models",description:"List all available models for the specified project or project type.",examples:[{desc:"List models for a project",cmd:"coze code model list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List models by type",cmd:"coze code model list --type web"}],schema:{input:{projectId:{type:"string",required:!1,description:"Project ID"},type:{type:"string",required:!1,description:"Project type"}},output:{type:"array",items:{type:"object",properties:{model_name:{type:"string",description:"Model name"},display_name:{type:"string",description:"Display name"},enable:{type:"boolean",description:"Whether this model is currently set for the project (only available when using -p)"}}}}},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(o,i){const s=i.getContext(),{projectId:n}=o;let r,a,c;if(n){const e=await t.IdeApi.GetVibeProject({project_id:n});r=cp([e,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),a=cp([e,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.space_id]);const o=await Fc.getDefaultConversation(n);c=cp([o,"access",e=>e.conversation_setting,"optionalAccess",e=>e.model_setting,"optionalAccess",e=>e.model_name])}else{const t=o.type;if(!t)throw new e.CozeError(e.ErrorCode.E1000,"Project type is required",{projectId:n});r=Md(t)}if(!r)throw new e.CozeError(e.ErrorCode.E1000,"Project type is required",{projectId:n});const l=cp([await t.BuildAgentApi.GetModelList({project_id:n,project_type:r,space_id:a}),"access",e=>e.model_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({model_name:e.name,display_name:e.display_name,enable:n?c===e.name:void 0})))]);cp([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${cp([l,"optionalAccess",e=>e.length])||0} models.`)]),cp([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(l)])}))}(i),function(o){o.command("set <modelName>").description("Set conversation model").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Set conversation model",description:"Set the model used by the default conversation. Use model list to see available models.",examples:[{desc:"Set conversation model",cmd:"coze code model set doubao-dev-0213 -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{modelName:{type:"string",required:!0,description:"Model name"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},model_name:{type:"string",description:"Model name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified model is not available for this project",fix:"Use 'coze code model list -p <projectId>' to see available models"}]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=await t.IdeApi.GetVibeProject({project_id:r}),c=ap([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),l=ap([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.space_id]);if(!ap([await t.BuildAgentApi.GetModelList({project_id:r,project_type:c,space_id:l}),"access",e=>e.model_list,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Model '${o}' is not available. Use 'coze code model list' to see available models.`,{modelName:o,projectId:r});const d=await Fc.getDefaultConversation(r);await Fc.updateConversationSetting(r,d.id,{modelSetting:{model_name:o}}),ap([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Model set to '${o}'.`)]),ap([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,model_name:o,message:`Model has been set to '${o}' successfully`})])}))}(i)};function dp(e,t){return null!=e?e:t()}function pp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function up(e,t){return null!=e?e:t()}function mp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const gp=e=>{if(null==e)return null;return 0===e.trim().length?null:e},hp=o=>{o.command("send [message]").description("Send a prompt message to Coze Coding project chat").option("--wait","Wait for the chat response before returning").option("--stdin","Read additional context from stdin (pipe input)").config({help:{brief:"Send a message to project chat",description:"Send a prompt message to the specified Coze Coding project chat. The message can be provided as a positional argument. Use --stdin to pipe additional context. Use @<path> to mention and upload local files as context.",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug in auth module" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Send and wait for the response",cmd:'coze code message send "Fix the bug in auth module" -p 123456 --wait'},{desc:"Mention a file with @",cmd:'coze code message send "Refactor @src/utils.ts to use async/await" -p 123456'},{desc:"Mention multiple files",cmd:'coze code message send "Compare @src/old.ts and @src/new.ts, list the differences" -p 123456'},{desc:"Send message with stdin context",cmd:'cat error.log | coze code message send "Analyze this error" --stdin -p 123456'},{desc:"Use environment variable for project",cmd:'export COZE_PROJECT_ID=123456 && coze code message send "Hello"'}],errors:[{code:e.ErrorCode.E1000,name:"MISSING_MESSAGE",desc:"No message content provided",fix:"Provide MESSAGE argument or use --stdin with piped content",example:'coze code message send "Your question" -p 123456 # or: echo "context" | coze code message send --stdin "question" -p 123456'},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --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(o,i,s)=>{const n=s.getContext();try{if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const r=mp([s,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),a=up(mp([r,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!a)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");const c=await mp([n,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!c)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const{wait:l,stdin:d}=i;let p=null;d&&(p=await oa());const u=gp(o),m=gp(p);if(!u&&!m)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin");const g=u&&m?`${u}\n\n${m}`:up(up(u,(()=>m)),(()=>"")),h=new Set,f=await t.sendProjectChatMessage({projectId:a,prompt:g,apiBaseUrl:n.config.apiBaseUrl,accessToken:c,xTTEnv:n.config.xTTEnv,key:`coze-coding-cli:message:${a}`,onWarn:e=>n.ui.warn(e),waitForResponse:!!l,onMessageItem:e=>{if(l&&"json"===n.format&&e.finish){const t=(e=>{const t=up(e.msg_id,(()=>"")),o=up(e.sequence_id,(()=>""));return`${e.type}:${t}:${String(o)}`})(e);h.has(t)||(h.add(t),n.response.print({content:e.content,role:e.role,finish:e.finish,type:e.type}))}}});if(l)"text"===n.format&&n.response.print(up(mp([f,"access",e=>e.lastAnswerMessage,"optionalAccess",e=>e.content,"access",e=>e.answer]),(()=>"")));else{const e=`Message sent. Use \`coze code message status -p ${a}\` to check the result.`;"json"===n.format?n.response.print({status:"sent",project_id:a,message:e}):n.response.print(e),process.exit(0)}}catch(e){H(e,n)}}))};function fp(e,t){return null!=e?e:t()}function _p(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function yp(e,t){return null!=e?e:t()}function bp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const vp=async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError("E5000","CLI context is not initialized");const n=bp([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=yp(bp([n,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!r)throw new e.CozeError("E1001","Missing required option: --project-id (or env COZE_PROJECT_ID)");if(!await bp([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]))throw new e.CozeError("E2001","Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(o.after&&o.before)throw new e.CozeError("E1000","--after and --before cannot be used together. Use only one cursor at a time.");s.ui.verbose(`Fetching conversation history for project ${r}...`);const a=t.createChatCore({key:`coze-coding-cli:history:${r}`,apiBaseUrl:s.config.apiBaseUrl});try{const e=o.after?"loadNext":"loadPrev",t="loadNext"===e?"11":"10",i=await a.getHistoryMessage({limit:t,project_id:r,after:o.after,before:o.before}),n=[],c=new Map,l=new Map;i.histories.forEach((e=>{if(e.user){const t=e.user.msg_id;c.has(t)||n.push(t);const o=(e=>{const t=bp([e,"optionalAccess",e=>e.content]);return yp(yp(bp([t,"optionalAccess",e=>e.query,"optionalAccess",e=>e.prompt]),(()=>bp([t,"optionalAccess",e=>e.retry,"optionalAccess",e=>e.prompt]))),(()=>bp([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?`${_p([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.path])} ${fp(_p([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.from,"optionalAccess",e=>e[0]]),(()=>""))} ${fp(_p([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.to,"optionalAccess",e=>e[0]]),(()=>""))} `:"console"===e.type?_p([e,"access",e=>e.content,"access",e=>e.console,"optionalAccess",e=>e.content]):"node"===e.type?_p([e,"access",e=>e.content,"access",e=>e.node,"optionalAccess",e=>e.node_title]):"upload_file"===e.type?_p([e,"access",e=>e.content,"access",e=>e.upload_file,"optionalAccess",e=>e.file_name]):"page"===e.type?_p([e,"access",e=>e.content,"access",e=>e.page,"optionalAccess",e=>e.page_title]):"page_elements"===e.type?_p([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?_p([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 d=n[0],p=n[n.length-1],u=n.reverse().filter((e=>l.has(e))).map((e=>({userMessage:yp(c.get(e),(()=>"")),answer:yp(l.get(e),(()=>""))}))),m={histories:u,cursor:{after:d,before:p,has_more:i.has_more,loadDirection:e}};if("json"===s.format)s.response.print(m);else{if(0===u.length)return void s.response.print("No conversation history found.");u.forEach(((e,t)=>{s.response.print(`--- #${t+1} ---\nQ: ${e.userMessage}\nA: ${e.answer}\n`)})),s.response.print(`\n[cursor] after=${d}, before=${p}, has_more=${i.has_more}, loadDirection=${e}`)}}finally{a.destroy()}}catch(e){H(e,s)}};function wp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Cp=o=>{const i=o.command("message");i.description("Manage project chat messages").config({help:{brief:"Manage project chat messages",description:"Manage Coze Coding project chat messages.\n\nThis command group provides:\n- send: Send a new message to the project chat\n- status: Query the status of current chat message (auto-fetch result when completed)\n- cancel: Cancel an ongoing chat message\n- history: View conversation history",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Check message status",cmd:"coze code message status -p 123456"},{desc:"Cancel ongoing message",cmd:"coze code message cancel -p 123456"},{desc:"View conversation history",cmd:"coze code message history -p 123456"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --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)"),hp(i),(o=>{o.command("status").description("Query current project chat message status and get result when completed").config({help:{brief:"Query chat message status",description:"Get the current status of the chat message for the specified project. Returns status information such as running, completed, or error. When the chat is completed, automatically fetches and returns the result.",examples:[{desc:"Check message status (auto-fetch result when completed)",cmd:"coze code message status -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message status"},{desc:"Output as JSON",cmd:"coze code message status -p 123456 --format json"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Message status (running/completed/error)"},message:{type:"string",description:"Status message or error details"},answer:{type:"string",description:"The chat answer content (only when completed)"}}}}}}).action((async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const o=pp([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),n=dp(pp([o,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!n)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");s.ui.verbose(`Fetching chat status for project ${n}...`);const{code:r,msg:a,reply_id:c,...l}=await t.BuildAgentApi.GetChatCLIMessageStatus({project_id:n});if("done"===l.status){s.ui.verbose(`Chat completed, fetching result for project ${n}...`);const e=await t.BuildAgentApi.GetChatCLIMessageResultContent({project_id:n}),o="data"in e?e.data:e;"json"===s.format?s.response.print({...l,answer:o.answer}):s.response.print(`status: [${l.status}]\nanswer: ${dp(o.answer,(()=>""))}`)}else"json"===s.format?s.response.print(l):s.response.print(l.status)}catch(e){H(e,s)}}))})(i),function(o){o.command("cancel").description("Cancel current project chat message").config({help:{brief:"Cancel ongoing chat message",description:"Cancel the currently running chat message for the specified project. Useful for stopping long-running or stuck message generation.",examples:[{desc:"Cancel current message",cmd:"coze code message cancel -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message cancel"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Cancel operation status"},message:{type:"string",description:"Result message"}}}}}}).action((async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const o=wp([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=null!=(n=wp([o,"optionalAccess",e=>e.projectId]))?n:(()=>process.env.COZE_PROJECT_ID)();if(!r)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");const{accessToken:a}=s.config;if(!a)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");s.ui.verbose(`Canceling chat message for project ${r}...`);const{message:c}=await t.BuildAgentApi.CancelChatCLIMessage({project_id:r});"json"===s.format?s.response.print({message:c}):s.response.print(c)}catch(e){H(e,s)}var n}))}(i),(e=>{e.command("history").description("View conversation history of the project chat").option("--after <msg_id>","Cursor for fetching newer messages (smaller index)").option("--before <msg_id>","Cursor for fetching older messages (larger index)").config({help:{brief:"View conversation history",description:"Retrieve and display the conversation history for the specified Coze Coding project. Shows each round of user messages and LLM responses. By default, returns the latest 10 rounds of conversation. Use --after or --before cursors for pagination.",examples:[{desc:"View latest 10 rounds of conversation history",cmd:"coze code message history -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message history"},{desc:"Output as JSON with cursor info",cmd:"coze code message history -p 123456 --format json"},{desc:"Fetch newer messages after a cursor",cmd:"coze code message history -p 123456 --after msg_xxx"},{desc:"Fetch older messages before a cursor",cmd:"coze code message history -p 123456 --before msg_yyy"}],errors:[{code:"E1000",name:"INVALID_ARGUMENT",desc:"--after and --before cannot be used together",fix:"Use only one cursor option at a time for pagination"},{code:"E1001",name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:"E2001",name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"},after:{type:"string",description:'Cursor (message ID) for fetching newer messages. Newer messages have smaller index. Use the "after" value from previous output as this parameter.'},before:{type:"string",description:'Cursor (message ID) for fetching older messages. Older messages have larger index. Use the "before" value from previous output as this parameter.'}},output:{type:"object",properties:{histories:{type:"array",items:{type:"object",properties:{userMessage:{type:"string",description:"User's message in this round"},answer:{type:"string",description:"LLM's last answer with content"}}}},cursor:{type:"object",description:"Pagination cursor info for next/prev page requests",properties:{after:{type:"string",description:"Message ID of the newest result, use as --after to fetch newer messages (loadNext)"},before:{type:"string",description:"Message ID of the oldest result, use as --before to fetch older messages (loadPrev)"},has_more:{type:"boolean",description:"Whether there are more messages available"},loadDirection:{type:"string",enum:["loadNext","loadPrev"],description:"Load direction of current request. Defaults to 'loadPrev' (load older messages). 'loadNext' when --after is used, 'loadPrev' when --before is used or on initial request."}}}}}}}}).action(vp)})(i)};function Ep(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Ip(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Ap(o){o.command("list").description("List project environment variables").option("--env <scope>","Environment scope: dev | prod","dev").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List project environment variables",description:"Retrieve the list of environment variables for the specified project. Supports filtering by environment (dev/prod) and displays all configured sensitive information key names.",examples:[{desc:"List dev environment variables",cmd:"coze code env list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List prod environment variables",cmd:"coze code env list -p <projectId> --env prod"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},env:{type:"string",required:!1,enum:["dev","prod"],description:"Environment scope (default: dev)"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},project_type:{type:"string",description:"Project type"},env:{type:"string",description:"Environment scope"},secrets:{type:"array",description:"Environment variable list"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action((async function(e,o){const i=o.getContext(),{projectId:s}=e,n=Ip([await t.IdeApi.GetVibeProject({project_id:s}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=(a=e.env,"prod"===String(a||"dev").toLowerCase()?Bi.prod:Bi.dev);var a;const c=Ip([await Wi.ListProjectSecret({env:r,project_id:s,...n===t.VibeProjectType.Skill?{with_providers:!0}:{}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[];Ip([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secrets listed successfully.")]),Ip([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 Sp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const jp=o=>{const i=o.command("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");Ap(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(o,i,s,n){const r=n.getContext(),{projectId:a}=s,c=Ep([await t.IdeApi.GetVibeProject({project_id:a}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(c===t.VibeProjectType.Skill)throw new e.CozeError(e.ErrorCode.E3008,"Skill project secret_type logic to be supplemented",{projectId:a,projectType:c});await Wi.InsertProjectSecret({project_id:a,insert_secrets:{secrets:[{secret_key:o,secret_val:i}]}}),Ep([r,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secret set successfully")]),Ep([r,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:a,key:o,value:i})])})),function(t){t.command("delete <key>").description("Delete a project environment variable").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete project environment variable",description:"Delete a specified environment variable from the project by its key name.",examples:[{desc:"Delete an environment variable",cmd:"coze code env delete <KEY> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},key:{type:"string",required:!0,description:"Environment variable key name to delete"}},output:{message:{type:"string",description:"Result message"},key:{type:"string",description:"Deleted key"}}},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 s=i.getContext(),{projectId:n}=o,r=[t],a=Sp([await Wi.ListProjectSecret({env:Bi.dev,project_id:n}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],c=new Set(r.map((e=>String(e)))),l=a.filter((e=>c.has(String(e.secret_key||"")))).map((e=>e.secret_id)).filter(Boolean);if(0===l.length)throw new e.CozeError(e.ErrorCode.E3003,`No matched secrets by keys: ${r.join(", ")}`,{projectId:n,keys:r});await Wi.DeleteProjectSecret({project_id:n,keys:l}),Sp([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env has been delete successfully")]),Sp([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({message:"env has been delete successfully",key:t,project_id:n,keys:r,secret_ids:l})])}))}(i)};var Pp,kp,Tp,zp,Rp,xp,Lp,Op,Dp,Up,Bp,qp,Mp,Np,$p,Gp,Fp,Vp,Wp,Hp,Jp,Kp,Qp,Yp,Zp,Xp,eu,tu,ou,iu,su;function nu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e[e.Image=1]="Image";e[e.Android=2]="Android";e[e.IOS=3]="IOS";e[e.GitCode=4]="GitCode";e[e.FaasRuntimePkg=5]="FaasRuntimePkg";e[e.SkillPkg=6]="SkillPkg";e[e.H5=7]="H5"}(Pp||(Pp={})),function(e){e[e.Unknown=0]="Unknown";e[e.FreeCertificate=1]="FreeCertificate"}(kp||(kp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Normal=1]="Normal"}(Tp||(Tp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Existing=1]="Existing";e[e.Free=2]="Free"}(zp||(zp={})),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"}(Rp||(Rp={})),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"}(Lp||(Lp={})),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"}(Op||(Op={})),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"}(Dp||(Dp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Success=1]="Success";e[e.Pending=2]="Pending";e[e.Failed=3]="Failed"}(Up||(Up={})),function(e){e[e.Unknown=0]="Unknown";e[e.Default=1]="Default";e[e.Custom=2]="Custom"}(Bp||(Bp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Active=1]="Active";e[e.Disabled=2]="Disabled";e[e.Redirected=3]="Redirected";e[e.Primary=4]="Primary"}(qp||(qp={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(Mp||(Mp={})),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"}(Np||(Np={})),function(e){e[e.Created=1]="Created";e[e.Ready=3]="Ready";e[e.Stopped=4]="Stopped";e[e.Banned=5]="Banned";e[e.Paused=6]="Paused"}($p||($p={})),function(e){e[e.Unknown=0]="Unknown";e[e.VefaasFunction=1]="VefaasFunction"}(Gp||(Gp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Dev=1]="Dev";e[e.Prod=2]="Prod";e[e.Audit=3]="Audit"}(Fp||(Fp={})),function(e){e[e.A=1]="A";e[e.CNAME=2]="CNAME"}(Vp||(Vp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Single=1]="Single";e[e.Wildcard=2]="Wildcard";e[e.Multi=3]="Multi"}(Wp||(Wp={})),function(e){e[e.Unknown=0]="Unknown";e[e.DV=1]="DV";e[e.OV=2]="OV";e[e.EV=3]="EV"}(Hp||(Hp={})),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"}(Jp||(Jp={})),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"}(Kp||(Kp={})),function(e){e[e.NeedAuthorize=1]="NeedAuthorize";e[e.BindSuccess=2]="BindSuccess";e[e.BoundToOtherProject=3]="BoundToOtherProject";e[e.BoundToOtherUser=4]="BoundToOtherUser"}(Qp||(Qp={})),function(e){e[e.BoundToSelf=1]="BoundToSelf";e[e.BoundToOtherUser=2]="BoundToOtherUser";e[e.NotAuthorized=3]="NotAuthorized"}(Yp||(Yp={})),function(e){e[e.Line=1]="Line"}(Zp||(Zp={})),function(e){e[e.Default=0]="Default";e[e.WechatMini=1]="WechatMini";e[e.DouyinMini=2]="DouyinMini"}(Xp||(Xp={})),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"}(eu||(eu={})),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"}(tu||(tu={})),function(e){e[e.Recorded=1]="Recorded"}(ou||(ou={})),function(e){e[e.Sum=1]="Sum";e[e.Avg=2]="Avg"}(iu||(iu={})),function(e){e[e.Next=1]="Next";e[e.Third=3]="Third";e[e.Seventh=7]="Seventh"}(su||(su={}));class ru{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){ru.prototype.__init.call(this),ru.prototype.__init2.call(this),this.request=nu([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=nu([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}PublicCreateDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/create"),s={project_id:o.project_id,is_sync_db_to_prod:o.is_sync_db_to_prod,encrypt_env_variable:o.encrypt_env_variable,table_sync_configs:o.table_sync_configs,encrypt_deploy:o.encrypt_deploy,commit_hash:o.commit_hash,connector_configs:o.connector_configs};return this.request({url:i,method:"POST",data:s},t)}PublicRollbackDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/rollback"),s={project_id:o.project_id,target_deploy_history_id:o.target_deploy_history_id,rollback_database:o.rollback_database};return this.request({url:i,method:"POST",data:s},t)}PublicCancelDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/cancel"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_config/get"),s={project_id:o.project_id,commit_hash:o.commit_hash};return this.request({url:i,method:"GET",params:s},t)}PublicListDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/list"),s={project_id:o.project_id,page_token:o.page_token,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}PublicSearchRuntimeLog(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/runtime_log/search"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id,start_time:o.start_time,end_time:o.end_time,limit:o.limit,cursor:o.cursor,query:o.query,level:o.level};return this.request({url:i,method:"GET",params:s},t)}PublicGetDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"GET",params:s},t)}PublicBindCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/bind"),s={project_id:o.project_id,certificate_id:o.certificate_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicApplyFreeCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/apply_free"),s={project_id:o.project_id,domain:o.domain,auto_renew_free_cert:o.auto_renew_free_cert};return this.request({url:i,method:"POST",data:s},t)}PublicListDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/list"),s={project_id:o.project_id,unit_type:o.unit_type};return this.request({url:i,method:"GET",params:s},t)}PublicDeleteDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/delete"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicCreateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/create"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/get"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetCertificateDetail(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/get"),s={project_id:o.project_id,certificate_id:o.certificate_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/get"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicListVolcanoDomain(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/volcano_domain/list"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicListVolcanoCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/list_volcano"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicListProjectTraces(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/traces/list"),s={project_id:o.project_id,start_time:o.start_time,end_time:o.end_time,filter:o.filter,page_token:o.page_token,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PublicDownloadProjectTraces(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/traces/download"),s={project_id:o.project_id,start_time:o.start_time,end_time:o.end_time,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}PublicGetProjectMetrics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/metrics/get"),s={project_id:o.project_id,time_range:o.time_range,retention_days:o.retention_days};return this.request({url:i,method:"GET",params:s},t)}PublicDeleteDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/delete"),s={project_id:o.project_id,deploy_unit_id:o.deploy_unit_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetHelpCenterLink(e,t){const o=this.genBaseURL("/api/coding/deployment/help_center/link");return this.request({url:o,method:"GET"},t)}PublicCheckRollbackDatabase(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/check_rollback_database"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetMiniProgramPreview(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/mini_program/preview"),s={project_id:o.project_id,app_id:o.app_id,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}PublicSubmitAuthCode(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/submit_code"),s={project_id:o.project_id,connector_id:o.connector_id,code:o.code,verify_state:o.verify_state,auth_params:o.auth_params};return this.request({url:i,method:"POST",data:s},t)}PublicGetAuthStatus(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/status"),s={project_id:o.project_id,connector_id:o.connector_id,redirect_url:o.redirect_url};return this.request({url:i,method:"POST",data:s},t)}PublicBindAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/bind"),s={project_id:o.project_id,connector_id:o.connector_id,redirect_url:o.redirect_url,auth_params:o.auth_params,override:o.override};return this.request({url:i,method:"POST",data:s},t)}PublicUnbindAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/unbind"),s={project_id:o.project_id,connector_id:o.connector_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetBoundProject(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/get_bound_project"),s={connector_id:o.connector_id,related_id:o.related_id};return this.request({url:i,method:"GET",params:s},t)}PublicUpdateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/update"),s={project_id:o.project_id,domain:o.domain,auto_renew_free_cert:o.auto_renew_free_cert,visit_status:o.visit_status,next_primary_domain:o.next_primary_domain};return this.request({url:i,method:"POST",data:s},t)}PublicGetCertificateQuota(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/quota"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicListDomainCertificates(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/list"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicUnpublishConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/unpublish_project"),s={project_id:o.project_id,connector_ids:o.connector_ids};return this.request({url:i,method:"POST",data:s},t)}PublicListConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/list"),s={project_id:o.project_id,project_publish_status:o.project_publish_status};return this.request({url:i,method:"GET",params:s},t)}PublicPublishConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/publish_project"),s={project_id:o.project_id,connector_configs:o.connector_configs};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployCount(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get_count"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}GetRuntimeLogCount(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/runtime_log/count"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicExchangeFeishuAuthCode(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/auth/exchange_code"),s={project_id:o.project_id,code:o.code,verify_state:o.verify_state};return this.request({url:i,method:"POST",data:s},t)}PublicRevokeFeishuAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/auth/revoke"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublicUpdateDefaultDomainPrefix(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/update_default_prefix"),s={project_id:o.project_id,prefix:o.prefix};return this.request({url:i,method:"POST",data:s},t)}PublicFeishuWebhookEvent(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/webhook/event"),s={body:o.body};return this.request({url:i,method:"POST",data:s},t)}PublicCheckCreateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/check_create"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetHostedUsageMonthly(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/hosted_usage/monthly"),s={project_id:o.project_id,bill_month:o.bill_month};return this.request({url:i,method:"GET",params:s},t)}PublicGetEstimateHostedCost(e,t){const o=this.genBaseURL("/api/coding/deployment/hosted_usage/estimate_cost");return this.request({url:o,method:"GET"},t)}PublicGetDeployHistoryLog(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/log"),s={deploy_history_id:o.deploy_history_id,key:o.key};return this.request({url:i,method:"GET",params:s},t)}PublicGetMPICPStatus(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/mini_program/icp_status"),s={project_id:o.project_id,app_id:o.app_id,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetOnlineDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get_online"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetUserAnalyticsMetrics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/metrics/user_analytics/get"),s={project_id:o.project_id,time_range:o.time_range};return this.request({url:i,method:"GET",params:s},t)}PublicPauseDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/pause"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicStopDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/stop"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicResumeDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/resume"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicReportUserAnalytics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/analytics/report"),s={events:o.events},n={project_id:o.project_id,did:o.did};return this.request({url:i,method:"POST",data:s,params:n},t)}PublicCreateDefaultDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/create_default"),s={project_id:o.project_id,prefix:o.prefix};return this.request({url:i,method:"POST",data:s},t)}PublicGetProtectionConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/protection_config/get"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicUpdateProtectionConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/protection_config/update"),s={project_id:o.project_id,config:o.config};return this.request({url:i,method:"POST",data:s},t)}PublicAuthRedirect(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/redirect"),s={url:o.url};return this.request({url:i,method:"GET",params:s},t)}PublicAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/callback"),s={redirect_url:o.redirect_url};return this.request({url:i,method:"GET",params:s},t)}}const au=new ru({});function cu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function lu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function du(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const pu=t=>{const o=t.command("domain").config({help:{brief:"Manage custom domains for the project",description:"Manage custom domains for deployed projects. Supports adding, listing, and removing domains associated with a project, used to access deployed applications.",examples:[{desc:"List project domains",cmd:"coze code domain list -p <projectId>"},{desc:"Add custom domain",cmd:"coze code domain add example.com -p <projectId>"},{desc:"Delete domain",cmd:"coze code domain remove example.com -p <projectId>"}],seeAlso:["coze code deploy"]}}).description("Manage custom domains for the project");o.command("list").description("List custom domains of the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List all domains bound to the project",description:"Retrieve a list of all custom domains bound to the specified project.",examples:[{desc:"List domains",cmd:"coze code domain list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Output in JSON format",cmd:"coze code domain list -p <projectId> --format json"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Domain ID"},domain_host:{type:"string",description:"Domain host"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action((async function(e,t){const o=t.getContext(),{projectId:i}=e,s=lu([await au.PublicListDomainRelated({project_id:i}),"access",e=>e.data,"optionalAccess",e=>e.items])||[];lu([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Fetched domains List successfully")]),lu([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(s.map((e=>({id:e.id,domain_host:e.domain_host}))))])})),function(t){t.command("add <domain>").description("Add a custom domain to the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add custom domain to project",description:"Bind a custom domain to a specified project. The domain must follow standard format (e.g., example.com). Once bound, the deployed application can be accessed via this domain.",examples:[{desc:"Add domain",cmd:"coze code domain add <domain> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to add (e.g., example.com)"}},output:{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 s=i.getContext(),{projectId:n}=o;if(!/^[a-zA-Z0-9][a-zA-Z0-9-]*\.[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(t))throw new e.CozeError(e.ErrorCode.E1004,"Invalid domain",{domain:t});await au.PublicCreateDomainRelated({project_id:n,domain:t}),du([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Domain '${t}' added.`)]),du([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,domain:t})])}))}(o),function(t){t.command("remove <domain>").description("Remove a custom domain from the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete custom domain of the project",description:"Remove a bound custom domain from the specified project.",examples:[{desc:"Delete domain",cmd:"coze code domain remove example.com -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to delete"}},output:{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:s}=t;await au.PublicDeleteDomainRelated({project_id:s,domain:e}),cu([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Domain '${e}' removed.`)]),cu([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({message:`Domain '${e}' removed.`,domain:e})])}))}(o)},uu={[Dp.Pending]:"Pending",[Dp.Running]:"Running",[Dp.Succeeded]:"Succeeded",[Dp.Failed]:"Failed",[Dp.Canceled]:"Canceled",[Dp.Interrupted]:"Interrupted"},mu=[Dp.Succeeded,Dp.Failed,Dp.Canceled],gu=e=>e&&uu[e]||"Unknown";function hu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class fu{static __initStatic(){this.INSTANCE=new fu}static getInstance(){return fu.INSTANCE||(fu.INSTANCE=new fu),this.INSTANCE}async pollDeployStatus(t){const{projectId:o,deployHistoryId:i,onBeforePoll:s,onStatusChange:n}=t;let r;for(;;){hu([s,"optionalCall",e=>e()]);const t=hu([await au.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,hu([n,"optionalCall",e=>e(t)])),mu.includes(a))return t;await new Promise((e=>setTimeout(e,3e3)))}}async getLatestDeployHistoryId(e){const{projectId:t}=e;return hu([await au.PublicListDeployHistory({page_size:1,project_id:t}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list,"optionalAccess",e=>e[0],"optionalAccess",e=>e.deploy_history_id])}async getDeployHistory(t){const{projectId:o,deployHistoryId:i}=t,s=await au.PublicGetDeployHistory({project_id:o,deploy_history_id:i});if(!hu([s,"optionalAccess",e=>e.data]))throw new e.CozeError(e.ErrorCode.E5000,"Failed to get deploy history data");return s.data}canDeploy(e){return[t.VibeProjectType.AssistantAgent,t.VibeProjectType.WechatMiniProgram,t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.Skill,t.VibeProjectType.Agent,t.VibeProjectType.Automation].includes(e)}async getCommitList({projectId:o}){const i=await t.IdeApi.ProxySandboxMessage({ProjectID:o,Method:"repo_version.commit.list",Params:JSON.stringify({project_id:o})});return e.safeJsonParse(i.data,{commits:[]}).commits||[]}}fu.__initStatic();const _u=fu.getInstance();function yu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function bu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function vu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function wu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Cu(o){const i=o.command("deploy <projectId>").description("Deploy the project to production environment").option("--commit-id <commitId>","Commit ID (optional, queries latest if omitted)").option("--wait","Wait for deployment to complete").option("--table-name <tableName...>","Database table names to sync to production",((e,t)=>t.concat(e)),[]).option("--encrypt-deploy <encrypt_deploy>","Pre-encrypted environment variable string (for Skill projects)").option("--connector-id <connectorId>","Connector IDs for mini-program deployment channels (can specify multiple times, e.g. 10000127 for WeChat, 10000126 for TikTok)",((e,t)=>t.concat(e)),[]).config({help:{brief:"Deploy the project to production environment",description:"Deploy the specified project to the production environment. Supports multiple project types (Agent, Workflow, Skill, Web, Mini-program, etc.), automatically fetches the latest commit, and triggers the deployment process.",examples:[{desc:"Deploy latest project",cmd:"coze code deploy <projectId>",tags:["[RECOMMENDED]"]},{desc:"Deploy and wait for completion",cmd:"coze code deploy <projectId> --wait"},{desc:"Deploy a specific commit",cmd:"coze code deploy <projectId> --commit-id <commitId>"},{desc:"View deployment status",cmd:"coze code deploy status <projectId>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},commitId:{type:"string",required:!1,description:"Commit ID (optional, queries latest if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"},tableName:{type:"array",required:!1,description:"Database table names to sync to production (can specify multiple times)"},encryptDeploy:{type:"string",required:!1,description:"Pre-encrypted environment variable string (for Skill projects)"},connectorId:{type:"array",required:!1,description:"Connector IDs for mini-program channels (10000127=WeChat, 10000126=TikTok). If omitted, auto-detects authorized channels."}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.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(o,i,s){const n=s.getContext(),{wait:r,commitId:a,tableName:c,encryptDeploy:l,connectorId:d}=i;let p;try{p=await t.IdeApi.GetVibeProject({project_id:o})}catch(t){W(t,e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o})}const u=wu([p.data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(!_u.canDeploy(u)){const t=`Project type ${Nd(u)} is not supported for deployment`;throw new e.CozeError(e.ErrorCode.E1006,t,{projectType:u})}if(u===t.VibeProjectType.AssistantAgent)return wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying (AssistantAgent)...")]),await e.axiosInstance$1.post("api/sandbox/coze_coding/devbox/open_claw/deploy",{project_id:o}),void wu([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"ok",type:u,message:`Assistant project deployment successfully, Please access the ${sp(o,wu([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))} to view the project`})]);let m,g=a;if(!g){wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching latest commit...")]);const e=await _u.getCommitList({projectId:o});g=wu([e,"optionalAccess",e=>e[0],"optionalAccess",e=>e.id])}if(!g){const t="No commits found: commit your changes first, or pass --commit-id <commitId>";throw new e.CozeError(e.ErrorCode.E3007,t,{projectId:o})}if(u===t.VibeProjectType.WechatMiniProgram)if(d&&d.length>0)m=d.map((e=>({connector_id:e})));else{wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking Mini-program authorization...")]);const t=[{name:"WeChat",id:"10000127"},{name:"TikTok",id:"10000126"}],i=(await Promise.all(t.map((async e=>{const t=await au.PublicGetAuthStatus({project_id:o,connector_id:e.id});return{...e,authorized:Boolean(wu([t,"access",e=>e.data,"optionalAccess",e=>e.bound_related_id]))}})))).filter((e=>e.authorized));if(0===i.length){const t=`Deployment failed, no authorized Mini-program channels found. Please visit ${sp(o,wu([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))} to complete WeChat or TikTok AppID configuration.`;throw new e.CozeError(e.ErrorCode.E2002,t)}m=i.map((e=>({connector_id:e.id})))}wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking deploy config...")]),await au.PublicGetDeployConfig({project_id:o,commit_hash:g},{__disableErrorToast:!0});let h="";const f=await Wi.ListProjectSecret({env:Bi.dev,project_id:o,with_providers:!0}),_=wu([f,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],y=wu([f,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_cred_providers])||[];wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Encrypting secrets...")]);h=wu([await Wi.EncryptProjectSecret({project_id:o,project_type:u===t.VibeProjectType.Skill?Ui.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===qi.consumer?ui.consumer3:ui.user_custom2}))),cred_providers:y}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.sealed_secrets])||"",wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying...")]);const b={project_id:o,encrypt_env_variable:h,commit_hash:g,encrypt_deploy:u===t.VibeProjectType.Skill?Boolean(l):void 0,connector_configs:m};if(c&&c.length>0){const e=new Map,i=["knowledge","public"];await Promise.all(i.map((async i=>{((await t.IdeApi.GetSchemaTables({project_id:o,database_env:t.MemoryEnv.develop,schema:i})).table_names||[]).forEach((t=>{e.set(t,i)}))}))),b.table_sync_configs=c.map((t=>({table_name:t,schema:e.get(t)||"",sync_data:!0})))}const v=wu([await au.PublicCreateDeployHistory(b),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_id]);wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploy started.")]),r&&v?await _u.pollDeployStatus({projectId:o,deployHistoryId:v,onBeforePoll:()=>{wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const t=gu(e.status);wu([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",i=>i({projectId:o,status:t,domain:wu([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:v,commitHash:e.commit_hash})])}}):wu([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({projectId:o,status:gu(Dp.Pending),domain:"",deployHistoryId:v,commitHash:g})])}));!function(t){t.command("status <projectId>").description("Check deployment status").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest if omitted)").config({help:{brief:"Query project deployment status",description:"Query the deployment status of a specified project. If no deployment history ID is specified, it automatically queries the latest deployment record. Supports viewing deployment progress, results, and error messages.",examples:[{desc:"Query latest deployment status",cmd:"coze code deploy status <projectId>",tags:["[RECOMMENDED]"]},{desc:"Query specific deployment record",cmd:"coze code deploy status <projectId> --deploy-id <deployHistoryId>"},{desc:"Wait for deployment to complete",cmd:"coze code deploy status <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (optional, queries latest if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.E3006,name:"NO_DEPLOYMENT_HISTORY",desc:"No deployment history found for this project",fix:"Please deploy the project first using `coze code deploy <projectId>`"}]}}).action((async function(t,o,i){const s=i.getContext(),{deployId:n}=o,{wait:r}=yu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=n;if(!a&&(yu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("get latest deployment record...")]),a=await _u.getLatestDeployHistoryId({projectId:t}),!a))throw new e.CozeError(e.ErrorCode.E3006,"No deployment history found for this project");if(r)await _u.pollDeployStatus({projectId:t,deployHistoryId:a,onBeforePoll:()=>{yu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const o=gu(e.status);yu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",i=>i({projectId:t,status:o,domain:yu([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:a,commitHash:e.commit_hash})])}});else{yu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Querying deployment status...")]);const e=await _u.getDeployHistory({projectId:t,deployHistoryId:a}),o=gu(e.status),i=e.domain_list||[];yu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",s=>s({projectId:t,status:o,domain:i[0],deployHistoryId:a,commitHash:e.commit_hash})])}}))}(i),function(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:"object",properties:{items:{type:"array",items:{deploy_history_id:{type:"string",description:"Deployment history ID"},status:{type:"string",description:"Deployment status"},commit_hash:{type:"string",description:"Commit hash"},domain_list:{type:"array",description:"Deployed domains"},created_at:{type:"string",description:"Creation timestamp"}}},next_page_token:{type:"string",description:"Token for fetching the next page, empty if no more pages"},has_more:{type:"boolean",description:"Whether there are more records"}}}}}}).action((async function(e,t,o){const i=o.getContext(),s=Number(t.pageSize)||10,n=await au.PublicListDeployHistory({project_id:e,page_size:s,page_token:t.pageToken}),r=(bu([n,"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list])||[]).map((e=>({deploy_history_id:e.deploy_history_id,project_id:e.project_id,status:gu(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})));bu([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>{return e({items:r,next_page_token:bu([n,"optionalAccess",e=>e.data,"optionalAccess",e=>e.next_page_token])||"",has_more:(t=bu([n,"optionalAccess",e=>e.data,"optionalAccess",e=>e.has_more]),o=()=>!1,null!=t?t:o())});var t,o}])}))}(i),function(t){t.command("fix <projectId>").description("Fix a failed deployment by sending deploy logs to AI").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest failed if omitted)").option("--wait","Wait for fix message response").config({help:{brief:"Fix a failed deployment",description:"Diagnose and fix a failed deployment. Retrieves deploy logs and sends them to AI for analysis and automatic fix. Only works when the deployment status is Failed.",examples:[{desc:"Fix latest failed deployment",cmd:"coze code deploy fix <projectId>",tags:["[RECOMMENDED]"]},{desc:"Fix a specific deployment",cmd:"coze code deploy fix <projectId> --deploy-id <deployId>"},{desc:"Fix and wait for result",cmd:"coze code deploy fix <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (queries latest failed if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for fix message response"}},output:{type:"object",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 s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const{deployId:n}=o,{wait:r}=vu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=n;if(n||(a=await _u.getLatestDeployHistoryId({projectId:t})),!a)throw new e.CozeError(e.ErrorCode.E5002,`No deploy history found for project ${t}`,{project_id:t});const c=vu([await au.PublicGetDeployHistory({project_id:t,deploy_history_id:a}),"optionalAccess",e=>e.data]);if(vu([c,"optionalAccess",e=>e.status])!==Dp.Failed){const t=gu(vu([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:vu([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 d=await e.customFetch.fetch(l,{method:"GET"}),p=await d.text();if(!p)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${p}`,m=await vu([s,"access",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(r){const e=await Kd.sendMessage({projectId:t,prompt:u,apiBaseUrl:s.config.apiBaseUrl,accessToken:m,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${t}`});vu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({deploy_history_id:a,status:"fix_sent",message:e.lastAnswerMessage})])}else Kd.sendMessageRunTask({projectId:t,prompt:u,apiBaseUrl:s.config.apiBaseUrl,accessToken:m,xTTEnv:s.config.xTTEnv,key:`coze-coding-cli:message:${t}`})}))}(i)}function Eu(e,t){return null!=e?e:t()}function Iu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class Au{static getInstance(){return Au.INSTANCE||(Au.INSTANCE=new Au),Au.INSTANCE}async createSpaceDatabase(o){const i=await t.IdeApi.CreateSpaceDatabase({space_id:o},{});if(!i.database)throw new e.CozeError(e.ErrorCode.E5000,"Failed to create database");return i.database}async listSpaceDatabases(e,o){const i=await t.IdeApi.ListSpaceDatabase({space_id:e,cursor_id:Iu([o,"optionalAccess",e=>e.cursor_id]),limit:Eu(Iu([o,"optionalAccess",e=>e.limit]),(()=>20))},{});return{databases:Eu(Iu([i,"optionalAccess",e=>e.databases]),(()=>[])),next_cursor_id:i.next_cursor_id}}async getSpaceDatabase(o,i){let s;try{s=await t.IdeApi.GetSpaceDatabase({space_id:o,database_id:i},{})}catch(t){W(t,e.ErrorCode.E3010,`Database '${i}' not found or no permission`,{databaseId:i})}if(!s.database)throw new e.CozeError(e.ErrorCode.E3010,`Database '${i}' not found or no permission`,{databaseId:i});return s.database}async deleteSpaceDatabase(e,o){await t.IdeApi.DeleteSpaceDatabase({space_id:e,database_id:o},{})}async rollbackSpaceDatabase(e,o,i){return await t.IdeApi.RollbackSpaceDatabase({space_id:e,database_id:o,timestamp:i},{})}async getSpaceDatabaseStatus(e,o){return await t.IdeApi.GetSpaceDatabaseStatus({space_id:e,database_id:o},{})}}const Su=Au.getInstance(),ju={0:"active",1:"creating"},Pu={0:"dev",1:"prod"},ku={0:"restoring",1:"success",2:"failed"},Tu=e=>e&&"0"!==e?new Date(Number(e)).toLocaleString():"-";function zu(e,t){return null!=e?e:t()}function Ru(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function xu(e,t){return null!=e?e:t()}function Lu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ou=[{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 Du(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Uu(e,t){return null!=e?e:t()}function Bu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const qu=async(t,o,i,s)=>{const n=`${t}/api/platform/pg-meta/default/query`,r=Buffer.from(`${o}:${i}`).toString("base64"),a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${r}`},body:JSON.stringify({query:s})});if(!a.ok){const t=await a.text(),o=e.safeJsonParse(t,void 0),i=Uu(Uu(Bu([o,"optionalAccess",e=>e.message]),(()=>Bu([o,"optionalAccess",e=>e.error,"optionalAccess",e=>e.message]))),(()=>`pg-meta request failed: ${a.status}`));throw new Error(i)}const c=await a.json();return Array.isArray(c)?c:[]};function Mu(e,t){return null!=e?e:t()}function Nu(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,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Mu(Mu(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const n=t.sql||t.file?void 0:await async function(e,t){return null!=e?e:await t()}(await oa(),(async()=>{})),r=await(async e=>{if(Du([e,"optionalAccess",e=>e.sql]))return e.sql.trim();if(Du([e,"optionalAccess",e=>e.file])){const t=g.resolve(e.file),o=(await h.readFile(t,"utf-8")).trim();if(!o)throw new Error(`SQL file is empty: ${t}`);return o}if(Du([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}),a=(e=>{const t=[];let o="safe";const i=e.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const{pattern:e,level:s,reason:n}of Ou)e.test(i)&&(t.push(n),"critical"===s?o="critical":"safe"===o&&(o="warning"));return{isDangerous:"safe"!==o,level:o,reasons:t}})(r);if(a.isDangerous&&!t.confirm){const o="json"===i.format,s=!0===process.stdin.isTTY;if(o||!s)throw new e.CozeError(e.ErrorCode.E1007,`SQL contains dangerous operation: ${a.reasons.join(", ")}`,{sql:r.substring(0,200),analysis:a},{trigger:"Dangerous SQL detected without --confirm",fix:"Add --confirm flag to proceed, or modify the SQL to remove dangerous operations",example:`coze code db query --db-id ${t.dbId} --sql "..." --confirm`});i.ui.info(`⚠ Warning: SQL contains dangerous operation:\n ${a.reasons.join("\n ")}`);const{confirm:n}=await import("@inquirer/prompts").then((e=>({confirm:e.confirm})));if(!await n({message:"Are you sure you want to execute this SQL?",default:!1}))return void i.ui.info("Operation cancelled.")}i.ui.info("Fetching database connection info...");const c=await Su.getSpaceDatabase(s,t.dbId);if(!c.supabase_url)throw new e.CozeError(e.ErrorCode.E5005,"Database does not have supabase_url. Cannot execute SQL via pg-meta.",{databaseId:t.dbId});if(!c.super_user||!c.super_user_password)throw new e.CozeError(e.ErrorCode.E5005,"Database does not have super_user credentials. Cannot authenticate against pg-meta.",{databaseId:t.dbId});let l;i.ui.info("Executing SQL...");try{l=await qu(c.supabase_url,c.super_user,c.super_user_password,r)}catch(t){throw new e.CozeError(e.ErrorCode.E5004,`SQL execution failed: ${t.message}`,{sql:r.substring(0,200)})}const d=Mu(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([r,"access",e=>e.trim,"call",e=>e(),"access",e=>e.split,"call",e=>e(/\s+/),"access",e=>e[0],"optionalAccess",e=>e.toUpperCase,"call",e=>e()]),(()=>"UNKNOWN")),p="SELECT"===d,u=a.isDangerous?a.reasons:[],m=l.length>0,f=p||m?l.length:null;p||m?i.response.print("json"===i.format?{result:l,rows_affected:f,command:d,warnings:u}:l):(i.ui.success("SQL executed successfully (rows_affected unavailable from pg-meta)."),i.response.print("json"===i.format?{result:[],rows_affected:null,command:d,warnings:u,note:"pg-meta does not expose rows_affected for DDL/DML without RETURNING"}:{command:d,message:"SQL executed successfully."}))}))}function $u(e,t){return null!=e?e:t()}function Gu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Fu=e=>({database_id:e.database_id,name:e.name,status:$u(ju[$u(e.status,(()=>0))],(()=>String(e.status))),database_env:$u(Pu[$u(e.database_env,(()=>0))],(()=>String(e.database_env))),created_at:Tu(e.created_at)});async function Vu(t,o){const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=$u($u(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const n=$u(t.limit,(()=>20)),r="json"!==i.format;if(r||!0===t.all){const e=$u(t.maxPages,(()=>10)),o=[];let a,c=t.cursor,l=0;for(i.ui.info("Fetching databases...");l<e;){const e=await Su.listSpaceDatabases(s,{cursor_id:c,limit:n});if(o.push(...$u(e.databases,(()=>[])).map(Fu)),l+=1,i.ui.verbose(`Page ${l}: ${$u(Gu([e,"access",e=>e.databases,"optionalAccess",e=>e.length]),(()=>0))} item(s)`),a=e.next_cursor_id,!a||"0"===a){a=void 0;break}c=a}return a&&i.ui.info(`Reached --max-pages=${e}. More results available (cursor: ${a}). Pass --max-pages to fetch more.`),i.ui.info(`Fetched ${o.length} database(s).`),void(r?i.response.print(o):i.response.print({databases:o,next_cursor_id:$u(a,(()=>"0"))}))}const a=await Su.listSpaceDatabases(s,{cursor_id:t.cursor,limit:n});i.response.print({databases:$u(a.databases,(()=>[])).map(Fu),next_cursor_id:a.next_cursor_id})}function Wu(e,t){return null!=e?e:t()}function Hu(e,t){return null!=e?e:t()}async function Ju(t,o){const n=o.getContext();if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const r=Hu(Hu(t.spaceId,(()=>n.config.spaceId)),(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const a=t.includeSchema&&t.includeSchema.length>0?t.includeSchema:["public"];n.ui.info("Fetching database connection info...");const c=await Su.getSpaceDatabase(r,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});n.ui.info("Fetching OpenAPI schema from PostgREST...");const l=`${c.supabase_url}/rest/v1/`;let d,p;try{const e=await fetch(l,{headers:{apikey:c.anon_key}});if(!e.ok)throw new Error(`PostgREST returned ${e.status}`);const t=await e.json();d=await async function(e){if("string"==typeof e.openapi)return e;if("string"==typeof e.swagger){const{convertObj:t}=await import("swagger2openapi");return(await t(e,{patch:!0,warnOnly:!0})).openapi}return e}(t)}catch(o){throw new e.CozeError(e.ErrorCode.E5006,`Failed to fetch OpenAPI schema: ${o.message}`,{databaseId:t.dbId})}n.ui.info("Generating TypeScript types...");try{const e=await import("openapi-typescript"),t=await e.default(d,{exportType:!0});p="string"==typeof t?t:e.astToString(t)}catch(o){throw new e.CozeError(e.ErrorCode.E5006,`Type generation failed: ${o.message}`,{databaseId:t.dbId},{fix:"The CLI auto-converts PostgREST Swagger 2.0 to OpenAPI 3.0 before generation. If it still fails, the schema may use constructs the generator cannot map — re-run with --debug for the underlying error."})}const u=i.resolve(Hu(t.output,(()=>"types/database.ts")));await s.mkdir(i.dirname(u),{recursive:!0}),await s.writeFile(u,"// Auto-generated by coze code db gen-types\n// Do not edit manually\n\n"+p,"utf-8"),n.ui.success(`Types generated: ${u}`),n.response.print({output_path:u,schemas:a})}function Ku(e,t){return null!=e?e:t()}const Qu=/^[a-zA-Z_][a-zA-Z0-9_$]{0,62}$/,Yu=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 Zu(e,t){const[o,i,s,n]=await Promise.all([qu(e.supabaseUrl,e.username,e.password,t.tables),qu(e.supabaseUrl,e.username,e.password,t.columns),qu(e.supabaseUrl,e.username,e.password,t.constraints),qu(e.supabaseUrl,e.username,e.password,t.indexes)]),r=(e=>{const t=new Map;for(const o of e){const e=`${o.table_schema}.${o.table_name}`,i=t.get(e);i?i.push(o):t.set(e,[o])}return t})(i);let a="";for(const e of o){const t=`${e.table_schema}.${e.table_name}`,o=Ku(r.get(t),(()=>[]));a+=`CREATE TABLE IF NOT EXISTS ${e.table_schema}.${e.table_name} (\n`,a+=o.map(Yu).join(",\n"),a+="\n);\n\n"}for(const e of s){const t=e.constraint_type;("p"===t||"u"===t||"f"===t||"c"===t)&&e.definition&&(a+=`ALTER TABLE ${e.schema_name}.${e.table_name} ADD CONSTRAINT ${e.constraint_name} ${e.definition};\n`)}s.length>0&&(a+="\n");const c=new Set(s.filter((e=>"p"===e.constraint_type||"u"===e.constraint_type)).map((e=>`${e.schema_name}.${e.constraint_name}`)));for(const e of n){const t=`${e.schemaname}.${e.indexname}`;!c.has(t)&&e.indexdef&&(a+=`${e.indexdef};\n`)}return n.length>0&&(a+="\n"),a}async function Xu(t,o){const n=o.getContext();if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const r=Ku(Ku(t.spaceId,(()=>n.config.spaceId)),(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!0===t.schemaOnly&&!0===t.dataOnly)throw new e.CozeError(e.ErrorCode.E1000,"--schema-only and --data-only are mutually exclusive");const a=!t.dataOnly,c=!0===t.dataOnly,l=c?"data-only":"schema-only",d=(t=>{const o=t&&t.length>0?Array.from(new Set(t)):["public"];for(const t of o)if(!Qu.test(t))throw new e.CozeError(e.ErrorCode.E1000,`Invalid schema name '${t}'. Must be a plain PostgreSQL identifier (letters, digits, underscore, $; max 63 chars; starts with letter or underscore).`);return o})(t.includeSchema),p=(e=>{const t=e.map((e=>`'${e}'`)).join(", ");return{tables:`\n SELECT table_name, table_schema\n FROM information_schema.tables\n WHERE table_schema IN (${t})\n AND table_type = 'BASE TABLE'\n ORDER BY table_schema, table_name;\n `,columns:`\n SELECT table_name, table_schema, column_name, data_type,\n is_nullable, column_default, character_maximum_length,\n numeric_precision, numeric_scale\n FROM information_schema.columns\n WHERE table_schema IN (${t})\n ORDER BY table_schema, table_name, ordinal_position;\n `,constraints:`\n SELECT n.nspname AS schema_name,\n cl.relname AS table_name,\n c.conname AS constraint_name,\n c.contype AS constraint_type,\n pg_get_constraintdef(c.oid) AS definition\n FROM pg_catalog.pg_constraint c\n JOIN pg_catalog.pg_class cl ON c.conrelid = cl.oid\n JOIN pg_catalog.pg_namespace n ON cl.relnamespace = n.oid\n WHERE n.nspname IN (${t})\n ORDER BY n.nspname, cl.relname,\n CASE c.contype WHEN 'p' THEN 1 WHEN 'u' THEN 2 WHEN 'f' THEN 3 ELSE 4 END,\n c.conname;\n `,indexes:`\n SELECT schemaname, tablename, indexname, indexdef\n FROM pg_indexes\n WHERE schemaname IN (${t})\n ORDER BY schemaname, tablename, indexname;\n `}})(d);n.ui.info("Fetching database connection info...");const u=await Su.getSpaceDatabase(r,t.dbId);if(!u.supabase_url)throw new e.CozeError(e.ErrorCode.E5007,"Database does not have supabase_url. Cannot access pg-meta.",{databaseId:t.dbId});if(!u.super_user||!u.super_user_password)throw new e.CozeError(e.ErrorCode.E5007,"Database does not have super_user credentials. Cannot authenticate against pg-meta.",{databaseId:t.dbId});const m={supabaseUrl:u.supabase_url,username:u.super_user,password:u.super_user_password};let g="";g+="-- Dump generated by coze code db dump\n",g+=`-- Database: ${t.dbId}\n`,g+=`-- Mode: ${l}\n`,g+=`-- Schemas: ${d.join(", ")}\n`,g+=`-- Date: ${(new Date).toISOString()}\n\n`;try{a&&(n.ui.info("Exporting schema..."),g+=await Zu(m,p)),c&&(n.ui.info("Exporting data..."),g+=await async function(e,t){const o=await qu(e.supabaseUrl,e.username,e.password,t.tables);let i="";for(const t of o){const o=`SELECT * FROM ${t.table_schema}.${t.table_name};`,s=await qu(e.supabaseUrl,e.username,e.password,o);if(0===s.length)continue;const n=Object.keys(s[0]);for(const e of s){const o=n.map((t=>{return null==(o=e[t])?"NULL":"number"==typeof o?Number.isFinite(o)?String(o):"NULL":"boolean"==typeof o?o?"TRUE":"FALSE":"bigint"==typeof o?String(o):o instanceof Date?`'${o.toISOString()}'`:"object"==typeof o?`'${JSON.stringify(o).replace(/'/g,"''")}'`:`'${String(o).replace(/'/g,"''")}'`;var o}));i+=`INSERT INTO ${t.table_schema}.${t.table_name} (${n.join(", ")}) VALUES (${o.join(", ")});\n`}i+="\n"}return i}(m,p))}catch(o){throw new e.CozeError(e.ErrorCode.E5007,`Dump failed: ${o.message}`,{databaseId:t.dbId})}const h=i.resolve(Ku(t.output,(()=>"db/schema.sql")));await s.mkdir(i.dirname(h),{recursive:!0}),await s.writeFile(h,g,"utf-8"),n.ui.success(`Dump completed: ${h}`),n.response.print({output_path:h,mode:l,schemas:d})}function em(e,t){return null!=e?e:t()}function tm(e,t){return null!=e?e:t()}const om=t=>{const o=t.command("db").description("Manage Coze space databases").config({help:{brief:"Database management for Coze spaces",description:"Create, query, and manage Supabase-backed databases in your Coze space. Supports database lifecycle management, SQL execution, TypeScript type generation, and schema export.",examples:[{desc:"Create a new database",cmd:"coze code db create",tags:["[RECOMMENDED]"]},{desc:"List all databases",cmd:"coze code db list"},{desc:"Execute SQL query",cmd:'coze code db query --db-id <id> --sql "SELECT 1"'},{desc:"Generate TypeScript types",cmd:"coze code db gen-types --db-id <id>"},{desc:"Export database schema",cmd:"coze code db dump --db-id <id>"}],seeAlso:["coze code project","coze code env"],schema:{input:{},output:{}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found or no permission",fix:"Check --db-id is correct, run `coze code db list`"},{code:e.ErrorCode.E1007,name:"DB_SQL_DANGEROUS",desc:"SQL contains dangerous operation",fix:"Add --confirm flag or modify SQL"}]}});o.command("create").description("Create a new database in current space").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Create a new database",description:"Create a new Supabase database in the current space. The database name and credentials are auto-generated. Use `coze code db get` to retrieve connection info.",examples:[{desc:"Create a database",cmd:"coze code db create",tags:["[RECOMMENDED]"]}],schema:{input:{spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{database_id:{type:"string",description:"Created database ID"},status:{type:"string",description:"Database status"},database_env:{type:"string",description:"Environment"}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Use --space-id or run `coze space use <spaceId>` first"},{code:e.ErrorCode.E4002,name:"DB_QUOTA_EXCEEDED",desc:"Space database quota exceeded",fix:"Delete unused databases with `coze code db delete`"}]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=tm(tm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info("Creating database in space...");const n=await Su.createSpaceDatabase(s);i.ui.success("Database created successfully!"),i.response.print({database_id:n.database_id,database_url:n.database_url,status:tm(ju[tm(n.status,(()=>0))],(()=>n.status)),database_env:tm(Pu[tm(n.database_env,(()=>0))],(()=>n.database_env)),created_at:Tu(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(Vu)}(o),function(t){t.command("get").description("Get database details").requiredOption("--db-id <dbId>","Database ID").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Get database details",description:"Get detailed information about a specific database, including connection URLs and credentials. The console URL can be constructed from supabase_url.",examples:[{desc:"Get database details",cmd:"coze code db get --db-id <databaseId>",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"}},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,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Wu(Wu(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Fetching database '${t.dbId}'...`);const n=await Su.getSpaceDatabase(s,t.dbId);i.ui.success("Database details:"),i.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:Wu(ju[Wu(n.status,(()=>0))],(()=>n.status)),database_env:Wu(Pu[Wu(n.database_env,(()=>0))],(()=>n.database_env)),created_at:Tu(n.created_at)})}))}(o),function(t){t.command("delete").description("Delete a database").requiredOption("--db-id <dbId>","Database ID").option("--confirm","Confirm deletion (required)").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Delete a database",description:"Delete a database from the current space. This operation cannot be undone. The --confirm flag is required to proceed.",examples:[{desc:"Delete a database",cmd:"coze code db delete --db-id <databaseId> --confirm",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID to delete"},confirm:{type:"boolean",required:!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,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!t.confirm){const o="json"===i.format,s=!0===process.stdin.isTTY;if(o||!s)throw new e.CozeError(e.ErrorCode.E1007,"Deletion requires --confirm flag to proceed",{databaseId:t.dbId},{trigger:"Database deletion is a destructive operation",fix:"Add --confirm flag to confirm deletion",example:`coze code db delete --db-id ${t.dbId} --confirm`});i.ui.warn(`⚠ You are about to delete database '${t.dbId}'. This operation cannot be undone.`);const{confirm:n}=await import("@inquirer/prompts").then((e=>({confirm:e.confirm})));if(!await n({message:`Are you sure you want to delete database '${t.dbId}'?`,default:!1}))return void i.ui.info("Operation cancelled.")}const s=em(em(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Deleting database '${t.dbId}'...`),await Su.deleteSpaceDatabase(s,t.dbId),i.ui.success(`Database '${t.dbId}' deleted successfully.`),i.response.print({deleted:!0,database_id:t.dbId})}))}(o),Nu(o),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,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!t.confirm)throw new e.CozeError(e.ErrorCode.E1007,"Rollback requires --confirm flag to proceed",{databaseId:t.dbId,timestamp:t.timestamp},{trigger:"Rollback is a potentially destructive operation",fix:"Add --confirm flag to confirm rollback",example:`coze code db rollback --db-id ${t.dbId} --timestamp ${t.timestamp} --confirm`});const s=xu(xu(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Rolling back database '${t.dbId}' to ${new Date(Number(t.timestamp)).toLocaleString()}...`);const n=await Su.rollbackSpaceDatabase(s,t.dbId,t.timestamp);i.ui.success(`Rollback initiated. Use 'coze code db status --db-id ${t.dbId}' to check progress.`),i.response.print({restore_history_id:Lu([n,"optionalAccess",e=>e.restore_history_id])})}))}(o),function(t){t.command("status").description("Get database status and restore info").requiredOption("--db-id <dbId>","Database ID").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Check database status",description:"Get the status of a database including restore/rollback information. Shows whether the database can be rolled back, current restore status, and earliest restore time.",examples:[{desc:"Check database status",cmd:"coze code db status --db-id <databaseId>",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"}},output:{can_restore:{type:"boolean",description:"Whether PITR restore is available"},is_restoring:{type:"boolean",description:"Whether a restore is in progress"},latest_restore_status:{type:"string",description:"Latest restore status"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"}]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=zu(zu(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Fetching status for database '${t.dbId}'...`);const n=await Su.getSpaceDatabaseStatus(s,t.dbId);i.ui.success("Database status:"),i.response.print({can_restore:Ru([n,"optionalAccess",e=>e.can_restore]),is_restoring:Ru([n,"optionalAccess",e=>e.is_restoring]),earliest_restore_time:Tu(Ru([n,"optionalAccess",e=>e.earliest_restore_time])),latest_restore_status:zu(ku[zu(Ru([n,"optionalAccess",e=>e.latest_restore_status]),(()=>-1))],(()=>Ru([n,"optionalAccess",e=>e.latest_restore_status]))),latest_restore_error:Ru([n,"optionalAccess",e=>e.latest_restore_error]),latest_restore_start_time:Tu(Ru([n,"optionalAccess",e=>e.latest_restore_start_time])),latest_restore_end_time:Tu(Ru([n,"optionalAccess",e=>e.latest_restore_end_time]))})}))}(o),function(t){t.command("gen-types").description("Generate TypeScript types from database schema").requiredOption("--db-id <dbId>","Database ID").option("--output <path>","Output file path","types/database.ts").option("--include-schema <name>","Schema name (can be specified multiple times)",((e,t=[])=>[...t,e]),[]).option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Generate TypeScript types",description:"Generate TypeScript type definitions from database schema using PostgREST OpenAPI. The generated types follow the Supabase database type format.",examples:[{desc:"Generate types for public schema",cmd:"coze code db gen-types --db-id <id>",tags:["[RECOMMENDED]"]},{desc:"Generate types for multiple schemas",cmd:"coze code db gen-types --db-id <id> --include-schema public --include-schema auth"},{desc:"Custom output path",cmd:"coze code db gen-types --db-id <id> --output src/types/db.ts"}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},output:{type:"string",required:!1,description:"Output file path (default: types/database.ts)"},includeSchema:{type:"array",required:!1,description:"Schema names (default: public)"}},output:{output_path:{type:"string",description:"Generated file path"},schemas:{type:"array",description:"Generated schemas"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E5006,name:"DB_GEN_TYPES_FAILED",desc:"Type generation failed",fix:"Ensure the database is active. PostgREST Swagger 2.0 is auto-converted to OpenAPI 3.0; re-run with --debug to see the underlying generator error."}]}}).action(Ju)}(o),function(t){t.command("dump").description("Export database schema or data").requiredOption("--db-id <dbId>","Database ID").option("--output <path>","Output file path","db/schema.sql").option("--schema-only","Export schema only (default if neither flag set)").option("--data-only","Export data only").option("--include-schema <name>","Schema name to dump (repeatable, default: public)",((e,t=[])=>[...t,e]),[]).option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Export database schema or data",description:"Export database schema (DDL) or data as SQL. Uses pg-meta API to query information_schema. Default mode is schema-only, default schema is public. Pass --include-schema multiple times to include additional schemas (e.g. auth, storage).",examples:[{desc:"Export public schema",cmd:"coze code db dump --db-id <id>",tags:["[RECOMMENDED]"]},{desc:"Export data only",cmd:"coze code db dump --db-id <id> --data-only"},{desc:"Include multiple schemas",cmd:"coze code db dump --db-id <id> --include-schema public --include-schema auth"},{desc:"Custom output path",cmd:"coze code db dump --db-id <id> --output backups/schema.sql"}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},output:{type:"string",required:!1,description:"Output file path (default: db/schema.sql)"},schemaOnly:{type:"boolean",required:!1,description:"Export schema only (default: true)"},dataOnly:{type:"boolean",required:!1,description:"Export data only"},includeSchema:{type:"array",required:!1,description:"Schema name(s) to include (repeatable, default: public)"}},output:{output_path:{type:"string",description:"Output file path"},mode:{type:"string",description:"Export mode"},schemas:{type:"array",description:"Schemas included in the dump"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E5007,name:"DB_DUMP_FAILED",desc:"Schema export failed",fix:"Check database status and permissions"}]}}).action(Xu)}(o)};function im(e,t){return null!=e?e:t()}function sm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const nm=["github","gitlab"];function rm(e,t){return null!=e?e:t()}function am(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const cm=["github","gitlab"];function lm(e,t){return null!=e?e:t()}function dm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const pm=["github","gitlab"];const um=o=>{const i=o.command("auth").description("Git platform OAuth authorization management").config({help:{brief:"Manage Git platform OAuth authorization",description:"Manage OAuth authorization for Git platforms. Supports login, status check, and logout.",examples:[{desc:"Login",cmd:"coze code git auth login"},{desc:"Check status",cmd:"coze code git auth status"},{desc:"Logout",cmd:"coze code git auth logout"}],seeAlso:["coze code git search"]}});i.command("login").description("Authorize a Git platform via OAuth").config({help:{brief:"Authorize a Git platform via OAuth",description:"Initiate OAuth authorization flow for a Git platform. Opens a browser for the user to complete authorization. The authorization is stored at the space level and can be reused across projects. Defaults to GitHub if --provider is not specified.",examples:[{desc:"Authorize GitHub (minimal)",cmd:"coze code git auth login"},{desc:"Authorize GitHub explicitly",cmd:"coze code git auth login --provider github",tags:["[RECOMMENDED]"]},{desc:"[TEMPLATE] Authorize any provider",cmd:"coze code git auth login --provider <github|gitlab>",tags:["[TEMPLATE]"]}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",description:"Authorization status",example:"authorized"},user:{type:"string",description:"Authorized user name",example:"octocat"}}},enums:{provider:{github:"GitHub OAuth authorization",gitlab:"GitLab OAuth authorization (future)"}},errors:[{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"},{code:e.ErrorCode.E2005,name:"OAUTH_TIMEOUT",desc:"OAuth authorization timed out",fix:"Re-run `coze code git auth login`"},{code:e.ErrorCode.E2006,name:"OAUTH_CANCELLED",desc:"User cancelled the authorization",fix:"Re-run `coze code git auth login`"}],seeAlso:["coze code git auth status","coze code git auth logout"],caveats:["Authorization requires a browser. In headless environments, copy the URL from terminal output and open it manually","Authorization is stored at the space level, not per-project"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=im(im(o.provider,(()=>sm([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!nm.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${nm.join(", ")}`);const r=im(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or run `coze space use <spaceId>` first");s.ui.info("Fetching integration list...");const a=im(sm([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>sm([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=im(sm([a,"optionalAccess",e=>e.id]),(()=>""));if(!c)throw new e.CozeError(e.ErrorCode.E5000,`No integration found for provider: ${n}`);s.ui.info(`Initiating OAuth for ${n}...`);const l=im(sm([await t.IdeApi.GetOauthConfig({integration_id:c,space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.auth_url]),(()=>""));if(!l)throw new e.CozeError(e.ErrorCode.E5000,"Failed to get OAuth authorization URL");s.ui.info(`Opening browser for ${n} authorization...`),s.ui.info(`Authorization URL: ${l}`),s.ui.info("Waiting for authorization... (timeout: 120s)");const d=Date.now();let p=!1;for(;Date.now()-d<12e4;)if(await new Promise((e=>setTimeout(e,2e3))),sm([await t.IdeApi.GetOauthStatus({integration_id:c,space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.success])){p=!0;break}if(!p)throw new e.CozeError(e.ErrorCode.E2005,"OAuth authorization timed out after 120 seconds");const u=await t.IdeApi.GetUser({space_id:r,integration_id:c}),m=im(im(sm([u,"access",e=>e.data,"optionalAccess",e=>e.login]),(()=>sm([u,"access",e=>e.data,"optionalAccess",e=>e.name]))),(()=>"unknown"));s.ui.success(`${n} authorized successfully.`),s.ui.info(` User: ${m}`),s.response.print({provider:n,status:"authorized",user:m})})),function(o){o.command("status").description("Check the Git platform OAuth authorization status").config({help:{brief:"Check the Git platform OAuth authorization status",description:"Display the current OAuth authorization status and user info for the specified Git platform.",examples:[{desc:"Check GitHub auth status (minimal)",cmd:"coze code git auth status"},{desc:"[PIPELINE] Check if authorized",cmd:"coze code git auth status --format json | jq .status",tags:["[PIPELINE]"]}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",enum:["authorized","not-authorized"],description:"Authorization status",example:"authorized"},user:{type:"object",description:"Authorized user info"}}},errors:[{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"}],seeAlso:["coze code git auth login","coze code git auth logout"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=rm(rm(o.provider,(()=>am([i,"access",e=>e.parent,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!cm.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${cm.join(", ")}`);const r=rm(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");const a=rm(am([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>am([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=rm(am([a,"optionalAccess",e=>e.id]),(()=>""));if(2!==am([a,"optionalAccess",e=>e.status])||!c)return s.ui.info("Git Authorization:"),s.ui.info(` Provider: ${n}`),s.ui.info(" Status: not-authorized"),void s.response.print({provider:n,status:"not-authorized"});const l=(await t.IdeApi.GetUser({space_id:r,integration_id:c})).data;s.ui.info("Git Authorization:"),s.ui.info(` Provider: ${n}`),s.ui.info(" Status: authorized"),s.ui.info(` User: ${rm(rm(am([l,"optionalAccess",e=>e.login]),(()=>am([l,"optionalAccess",e=>e.name]))),(()=>"unknown"))}`),am([l,"optionalAccess",e=>e.avatar_url])&&s.ui.info(` Avatar: ${l.avatar_url}`),s.response.print({provider:n,status:"authorized",user:{login:rm(rm(am([l,"optionalAccess",e=>e.login]),(()=>am([l,"optionalAccess",e=>e.name]))),(()=>"unknown")),avatar_url:rm(am([l,"optionalAccess",e=>e.avatar_url]),(()=>""))}})}))}(i),function(o){o.command("logout").description("Revoke OAuth authorization for a Git platform").option("--force","Skip confirmation and revoke directly",!1).config({help:{brief:"Revoke OAuth authorization for a Git platform",description:"Cancel the OAuth authorization for the specified Git platform in the current space. This will revoke access for all projects in the space that use this provider. Use --force to skip the confirmation prompt.",examples:[{desc:"Logout GitHub (minimal)",cmd:"coze code git auth logout"},{desc:"Force logout without confirmation",cmd:"coze code git auth logout --force",tags:["[RECOMMENDED]"]},{desc:"Logout a specific provider",cmd:"coze code git auth logout --provider gitlab"}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"},force:{type:"boolean",required:!1,description:"Skip confirmation",example:!1}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",description:"Result status",example:"deauthorized"}}},errors:[{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"},{code:e.ErrorCode.E2007,name:"NOT_AUTHORIZED",desc:"Git service is not authorized",fix:"Use `coze code git auth status` to check status"}],seeAlso:["coze code git auth login","coze code git auth status"],caveats:["Revoking authorization affects ALL projects in the current space that use this provider","Projects bound to repos via this provider will lose sync capability until re-authorized"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=lm(lm(o.provider,(()=>dm([i,"access",e=>e.parent,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!pm.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${pm.join(", ")}`);const r=lm(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");const a=lm(dm([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>dm([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=lm(dm([a,"optionalAccess",e=>e.id]),(()=>""));if(2!==dm([a,"optionalAccess",e=>e.status])||!c)throw new e.CozeError(e.ErrorCode.E2007,`${n} is not currently authorized`);await t.IdeApi.CancelOauth({integration_id:c,space_id:r}),s.ui.success(`${n} authorization revoked successfully.`),s.response.print({provider:n,status:"deauthorized"})}))}(i)};function mm(e,t){return null!=e?e:t()}function gm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const hm=["github","gitlab"];const fm=o=>{const i=o.command("git").description("Git platform integration management").option("--provider <provider>","Git service provider: github / gitlab","github").config({help:{brief:"Manage Git platform integrations (OAuth authorization and repository search)",description:"Manage Git platform integrations including OAuth authorization and repository search. Use --provider to specify the Git service provider (default: github).",examples:[{desc:"Authorize GitHub",cmd:"coze code git auth login"},{desc:"Search repos",cmd:"coze code git search --keyword react"}],seeAlso:["coze code repo"]}});um(i),i.command("search").description("Search repositories on the authorized Git platform").option("-k, --keyword <keyword>","Search keyword").option("--page <page>","Page number",parseInt).option("--page-size <size>","Results per page",parseInt).config({help:{brief:"Search repositories on the authorized Git platform",description:"Search through repositories accessible to the authorized Git user. Supports keyword filtering and pagination. Requires prior OAuth authorization.",examples:[{desc:"List all repos (minimal)",cmd:"coze code git search"},{desc:"Search by keyword",cmd:"coze code git search --keyword react",tags:["[RECOMMENDED]"]},{desc:"Paginated search",cmd:"coze code git search -k react --page 2 --page-size 10"},{desc:"[PIPELINE] Find empty repos for binding",cmd:'coze code git search -k my-repo --format json | jq ".items[] | select(.size == 0)"',tags:["[PIPELINE]"]}],schema:{input:{keyword:{type:"string",required:!1,description:"Search keyword",example:"react"},page:{type:"number",required:!1,description:"Page number",example:1},pageSize:{type:"number",required:!1,description:"Results per page",example:20}},output:{items:{type:"array",description:"Matching repositories"},total_count:{type:"number",description:"Total matching count",example:15}}},errors:[{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"}],seeAlso:["coze code repo bind","coze code repo create"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=mm(mm(o.provider,(()=>gm([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!hm.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}`);const r=mm(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");s.ui.info("Searching repositories...");const a=await t.IdeApi.SearchRepo({space_id:r,name_search:mm(o.keyword,(()=>"")),per_page:mm(o.pageSize,(()=>20)),page:mm(o.page,(()=>1))}),c=mm(gm([a,"access",e=>e.data,"optionalAccess",e=>e.items]),(()=>[])),l=mm(gm([a,"access",e=>e.data,"optionalAccess",e=>e.total_count]),(()=>0));if(0===c.length)s.ui.info("No repositories found.");else{s.ui.info(`Found ${l} repositories:`);for(const e of c){const t=e.private?"private":"public";s.ui.info(` ${e.full_name} (${t})`)}}s.response.print({items:c.map((e=>({full_name:e.full_name,private:mm(e.private,(()=>!1)),size:mm(e.size,(()=>0)),updated_at:mm(e.updated_at,(()=>""))}))),total_count:l})}))};function _m(e,t){return null!=e?e:t()}function ym(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function bm(e,t){return null!=e?e:t()}function vm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function wm(e,t){return null!=e?e:t()}function Cm(e,t){return null!=e?e:t()}function Em(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Im=o=>{const i=o.command("repo").description("Manage remote repositories for projects").option("--provider <provider>","Git service provider: github / gitlab","github").config({help:{brief:"Manage remote repository bindings for Coze Coding projects",description:"Manage remote repository bindings and sync operations for Coze Coding projects. Supports creating, binding, unbinding, pushing, pulling, and checking status of remote repositories.",examples:[{desc:"Bind repo",cmd:"coze code repo bind -p proj_abc -r user/my-repo"},{desc:"Push changes",cmd:"coze code repo push -p proj_abc"},{desc:"Check status",cmd:"coze code repo status -p proj_abc"}],seeAlso:["coze code git"]}});i.command("create").description("Create a new repository on the remote Git platform").option("-n, --name <name>","Repository name").option("--private","Create as private repository",!1).config({help:{brief:"Create a new repository on the remote Git platform",description:"Create a new empty repository under the authorized user account on the Git platform. The created repo can then be bound to a project using `coze code repo bind`.",examples:[{desc:"Create a public repo (minimal)",cmd:"coze code repo create --name my-app"},{desc:"Create a private repo",cmd:"coze code repo create -n my-app --private",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Create and bind",cmd:"coze code repo create -n my-repo --private && coze code repo bind -p proj_abc -r user/my-repo",tags:["[PIPELINE]"]}],schema:{input:{name:{type:"string",required:!0,description:"Repository name",example:"my-new-repo"},private:{type:"boolean",required:!1,description:"Create as private [RECOMMENDED]",example:!0}},output:{full_name:{type:"string",description:"Created repo full name",example:"user/my-new-repo"},html_url:{type:"string",description:"Repository URL",example:"https://github.com/user/my-new-repo"},private:{type:"boolean",description:"Visibility",example:!0}}},errors:[{code:e.ErrorCode.E1014,name:"MISSING_REPO_CREATION_NAME",desc:"Missing repo name",fix:"Use --name <name>"},{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"},{code:e.ErrorCode.E3009,name:"CONFLICT",desc:"Repository name already exists",fix:"Use a different name"}],seeAlso:["coze code repo bind","coze code git search"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=_m(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");if(!o.name)throw new e.CozeError(e.ErrorCode.E1014,"Missing repository name: use --name <name>");s.ui.info(`Creating repository "${o.name}"...`);const r=(await t.IdeApi.CreateRepo({space_id:n,name:o.name,private:_m(o.private,(()=>!1))})).data;s.ui.success("Repository created successfully."),s.ui.info(` Name: ${_m(ym([r,"optionalAccess",e=>e.full_name]),(()=>o.name))}`),s.ui.info(` URL: ${_m(ym([r,"optionalAccess",e=>e.html_url]),(()=>""))}`),s.ui.info(" Visibility: "+(o.private?"private":"public")),s.response.print({full_name:_m(ym([r,"optionalAccess",e=>e.full_name]),(()=>o.name)),html_url:_m(ym([r,"optionalAccess",e=>e.html_url]),(()=>"")),private:_m(o.private,(()=>!1))})})),function(o){o.command("bind").description("Bind a remote repository to a project").requiredOption("-p, --project-id <projectId>","Project ID").option("-r, --repo <fullName>","Remote repo full name (e.g. user/repo)").config({help:{brief:"Bind a remote repository to a project",description:"Bind an empty remote repository to the specified project. The repository must be empty (non-empty repo binding is not supported in this version). Requires prior Git OAuth authorization.",examples:[{desc:"Bind a repo (minimal)",cmd:"coze code repo bind -p proj_abc -r user/my-repo"},{desc:"Bind after creating a new repo",cmd:"coze code repo create --name my-repo && coze code repo bind -p proj_abc -r user/my-repo",tags:["[RECOMMENDED]"]},{desc:"[ERROR RECOVERY] E3015: Repo not empty",cmd:"coze code repo create --name my-new-repo --private && coze code repo bind -p proj_abc -r user/my-new-repo",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},repo:{type:"string",required:!0,description:"Remote repo full name (must be empty)",example:"user/my-repo"}},output:{project_id:{type:"string",description:"Project ID",example:"proj_abc123"},repo_full_name:{type:"string",description:"Bound repo full name",example:"user/my-repo"},status:{type:"string",description:"Binding result",example:"bound"}}},errors:[{code:e.ErrorCode.E1013,name:"MISSING_REPO_NAME",desc:"Missing repo name",fix:"Use --repo <owner/name>"},{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"},{code:e.ErrorCode.E3015,name:"REPO_NOT_EMPTY",desc:"Repo not empty",fix:"Use `coze code repo create` to create an empty repo"},{code:e.ErrorCode.E3016,name:"REPO_ALREADY_BOUND",desc:"Project already bound",fix:"Run `coze code repo unbind -p <id>` first"}],seeAlso:["coze code repo unbind","coze code repo create","coze code repo status"],caveats:["Only empty repositories are supported for binding in this version","A project can only be bound to one repository at a time"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=bm(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");if(!o.repo)throw new e.CozeError(e.ErrorCode.E1013,"Missing repository full name: use --repo <owner/name>");const r=bm(vm([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]),(()=>1));if(3===r)throw new e.CozeError(e.ErrorCode.E3016,"Project is already bound to a remote repository. Run `coze code repo unbind -p <projectId>` first.");if(1===r)throw new e.CozeError(e.ErrorCode.E2004,"Git service is not authorized. Run `coze code git auth login` first.");const a=bm(vm([await t.IdeApi.ListIntegration({space_id:n}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])),c=bm(bm(o.provider,(()=>vm([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github")),l=a.find((e=>vm([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===c)),d=bm(vm([l,"optionalAccess",e=>e.id]),(()=>""));s.ui.info(`Binding repository "${o.repo}" to project "${o.projectId}"...`),await t.IdeApi.AddRemote({project_id:o.projectId,repo_full_name:o.repo,integration_id:d}),s.ui.success("Repository bound successfully."),s.ui.info(` Project: ${o.projectId}`),s.ui.info(` Repository: ${o.repo}`),s.response.print({project_id:o.projectId,repo_full_name:o.repo,status:"bound"})}))}(i),function(o){o.command("unbind").description("Unbind the remote repository from a project").requiredOption("-p, --project-id <projectId>","Project ID").option("--force","Skip confirmation and unbind directly",!1).config({help:{brief:"Unbind the remote repository from a project",description:"Remove the remote repository binding from the specified project. This operation does not delete the remote repository itself. Use --force to skip confirmation.",examples:[{desc:"Unbind repo (minimal)",cmd:"coze code repo unbind -p proj_abc"},{desc:"Force unbind",cmd:"coze code repo unbind -p proj_abc --force",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},force:{type:"boolean",required:!1,description:"Skip confirmation",example:!1}},output:{project_id:{type:"string",description:"Project ID",example:"proj_abc123"},status:{type:"string",description:"Result status",example:"unbound"}}},errors:[{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Use `coze code repo status -p <id>` to check status"}],seeAlso:["coze code repo bind","coze code repo status"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");var n;if(3!==(null!=(n=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]))?n:(()=>1)()))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Use `coze code repo status -p <projectId>` to check status.");s.ui.info(`Unbinding remote repository from project "${o.projectId}"...`),await t.IdeApi.RemoveRemote({project_id:o.projectId}),s.ui.success("Repository unbound successfully."),s.ui.info(` Project: ${o.projectId}`),s.response.print({project_id:o.projectId,status:"unbound"})}))}(i),function(o){o.command("push").description("Push local commits to the bound remote repository").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Push local commits to the bound remote repository",description:"Push local commits to the bound remote repository. Requires the project to be bound to a remote repository. If the remote has new commits, you must pull first before pushing.",examples:[{desc:"Push changes (minimal)",cmd:"coze code repo push -p proj_abc"},{desc:"[PIPELINE] Push and check status",cmd:"coze code repo push -p proj_abc && coze code repo status -p proj_abc",tags:["[PIPELINE]"]},{desc:"[ERROR RECOVERY] E3018: Pull first",cmd:"coze code repo pull -p proj_abc && coze code repo push -p proj_abc",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"}},output:{status:{type:"string",enum:["success","failed"],description:"Push result",example:"success"},pushed_commits:{type:"number",description:"Number of commits pushed",example:2}}},errors:[{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Bind a repo first"},{code:e.ErrorCode.E3017,name:"NOTHING_TO_PUSH",desc:"Nothing to push",fix:"Already in sync with remote"},{code:e.ErrorCode.E3018,name:"REMOTE_HAS_UPDATES",desc:"Remote has updates",fix:"Run `coze code repo pull -p <id>` first"}],seeAlso:["coze code repo pull","coze code repo status"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");var n;if(3!==(null!=(n=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]))?n:(()=>1)()))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Run `coze code repo bind` first.");s.ui.info("Pushing to remote..."),s.ui.success("Push completed successfully."),s.response.print({status:"success",pushed_commits:0})}))}(i),function(o){o.command("pull").description("Pull remote changes from the bound repository").requiredOption("-p, --project-id <projectId>","Project ID").option("--conflict-strategy <strategy>","Auto conflict resolution strategy: ours / theirs").config({help:{brief:"Pull remote changes from the bound repository",description:"Pull the latest changes from the bound remote repository. If conflicts occur and --conflict-strategy is provided, conflicts will be auto-resolved. Without --conflict-strategy, the command will fail on conflict with exit code 1.",examples:[{desc:"Pull changes (minimal)",cmd:"coze code repo pull -p proj_abc"},{desc:"Auto-resolve keeping local",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours",tags:["[RECOMMENDED]"]},{desc:"Auto-resolve using remote",cmd:"coze code repo pull -p proj_abc --conflict-strategy theirs"},{desc:"[PIPELINE] Pull then push",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours && coze code repo push -p proj_abc",tags:["[PIPELINE]"]},{desc:"[ERROR RECOVERY] E3019: Resolve conflict",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},conflictStrategy:{type:"string",required:!1,enum:["ours","theirs"],description:"Auto conflict resolution strategy",example:"ours"}},output:{status:{type:"string",enum:["success","conflict_resolved","failed"],description:"Pull result",example:"success"},conflict_resolved:{type:"boolean",description:"Whether conflicts were resolved",example:!1},conflict_strategy:{type:"string",description:"Strategy used",example:"ours"},conflict_files:{type:"array",items:{type:"string"},description:"Conflicting files",example:["src/index.ts"]}}},enums:{"conflict-strategy":{ours:"Keep local version for all conflicting files",theirs:"Use remote version for all conflicting files"}},errors:[{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Bind a repo first"},{code:e.ErrorCode.E3019,name:"MERGE_CONFLICT",desc:"Merge conflict without strategy",fix:"Use --conflict-strategy ours or theirs"},{code:e.ErrorCode.E3020,name:"WOULD_OVERWRITE",desc:"Local changes would be overwritten",fix:"Commit local changes first"}],seeAlso:["coze code repo push","coze code repo status"],caveats:["Without --conflict-strategy, conflicts will cause the command to fail","Conflict resolution applies to ALL conflicting files (no per-file selection in CLI)"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(3!==wm(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]),(()=>1)))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Run `coze code repo bind` first.");s.ui.info("Pulling from remote..."),s.ui.success("Pull completed successfully."),s.response.print({status:"success",conflict_resolved:!1,conflict_strategy:wm(o.conflictStrategy,(()=>null)),conflict_files:[]})}))}(i),function(o){o.command("status").description("Show remote repository binding and sync status for a project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Show remote repository binding and sync status for a project",description:"Display the current remote repository binding status of a project, including the bind status and (when bound) the repository full name and URL.",examples:[{desc:"Check repo status (minimal)",cmd:"coze code repo status -p proj_abc"},{desc:"JSON output for scripting",cmd:"coze code repo status -p proj_abc --format json",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Check binding status",cmd:"coze code repo status -p proj_abc --format json | jq .bind_status",tags:["[PIPELINE]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"}},output:{bind_status:{type:"string",enum:["unauth","not-bound","bound"],description:"Binding status",example:"bound"},repo_full_name:{type:"string",description:"Remote repo full name",example:"user/my-app"},html_url:{type:"string",description:"Repository URL",example:"https://github.com/user/my-app"}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Confirm the project ID is correct"}],seeAlso:["coze code repo bind","coze code repo push","coze code repo pull"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");s.ui.info("Fetching remote repository status...");const n=await t.IdeApi.GetRemote({project_id:o.projectId}),{data:r}=n,a=Cm(Em([r,"optionalAccess",e=>e.status]),(()=>1)),c=Cm({1:"unauth",2:"not-bound",3:"bound"}[a],(()=>"unauth"));if(3!==a)return s.ui.info("Remote Repository:"),s.ui.info(` Status: ${c}`),void s.response.print({bind_status:c});const l=Em([r,"optionalAccess",e=>e.basic_info]),d=Cm(Em([l,"optionalAccess",e=>e.full_name]),(()=>"")),p=Cm(Em([l,"optionalAccess",e=>e.html_url]),(()=>""));s.ui.info("Remote Repository:"),s.ui.info(` Status: ${c}`),s.ui.info(` Repository: ${d}`),s.ui.info(` URL: ${p}`),s.response.print({bind_status:c,repo_full_name:d,html_url:p})}))}(i)};function Am(o){const i=o.command("code").description("Coze Coding CLI utilities").config({help:{brief:"Coze Coding project management",description:"Manage Coze Coding projects, including project creation, messaging, deployment, environment variables, domains, skills, and previews.",examples:[{desc:"Create a new project",cmd:'coze code project create --message "Create a chatbot" --type web'},{desc:"Send a message",cmd:'coze code message send "Fix the bug" -p <projectId>'},{desc:"Deploy project",cmd:"coze code deploy <projectId>"},{desc:"Preview project",cmd:"coze code preview <projectId>"}],seeAlso:["coze auth","coze space","coze organization"]}});Cp(i),Cu(i),ep(i),jp(i),pu(i),tl(i),function(o){o.command("preview <projectId>").description("Get deployment preview info for the project").config({help:{brief:"Get project preview URL",description:"Get the sandbox preview URL for the project. Supported for general Web/App project types, returning an accessible preview URL. Sandbox initialization takes 1-3 minutes. WechatMiniProgram, Agent, Automation, Skill, and AssistantAgent projects are not previewable from the CLI.",examples:[{desc:"Get preview URL",cmd:"coze code preview <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:{type:"string",description:"Project type"},preview_url:{type:"string",description:"Preview URL"}}},errors:[{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Unsupported project type for CLI preview",fix:`Preview is not available for MiniProgram, Agent, Automation, Skill, or AssistantAgent projects. Use the Web dashboard: ${ip().replace(/\/$/,"")}`},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Missing required argument: projectId",fix:"Pass <projectId> as the first argument: `coze code preview <projectId>`",example:"coze code preview 123456"}]}}).action((async function(o,i,s){const n=s.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E1000,"Missing projectId: pass <projectId> as argument");const r=np([await t.IdeApi.GetVibeProject({project_id:o}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),a={type:Nd(r)};if(rp.has(r))return void np([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({type:a.type,message:`Project type '${a.type}' does not support CLI preview. Please visit the Web dashboard: ${sp(o,np([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))}`})]);const c=await t.IdeApi.InitSandbox({project_id:o});a.preview_url=c.token?`https://${c.project_host}?token=${c.token}`:`https://${c.project_host}`,np([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Sandbox initialization started. Please access the preview URL in 1-3 minutes,preview_url: ${a.preview_url}`)]),np([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])}))}(i),om(i),Jc(i),lp(i),fm(i),Im(i)}const Sm=async e=>await new Promise((t=>setTimeout(t,e)));function jm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Pm=e=>{if(!e)return;const t=e.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);if(jm([t,"optionalAccess",e=>e[1]]))return(e=>{try{return decodeURIComponent(e)}catch(t){return URIError,e}})(t[1]);const o=e.match(/filename\s*=\s*"([^"]+)"/i);if(jm([o,"optionalAccess",e=>e[1]]))return o[1];const i=e.match(/filename\s*=\s*([^;]+)/i);return jm([i,"optionalAccess",e=>e[1]])?i[1].trim():void 0},km=async({url:t,outputPath:o,fetchImpl:s=t=>e.customFetch.fetch(t)})=>{const{buffer:n,response:r}=await(async(t,o)=>{const i=await o(t);if(!i.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download session file: ${i.status} ${i.statusText}`);return{buffer:Buffer.from(await i.arrayBuffer()),response:i}})(t,s),a=o||(e=>{const t=Pm((o=e.contentDisposition,s=()=>null,null!=o?o:s()));var o,s;if(t)return t;for(const t of[e.responseUrl,e.requestUrl]){if(!t||!URL.canParse(t))continue;const e=new URL(t),o=i.basename(decodeURIComponent(e.pathname));if(o&&"/"!==o&&"."!==o)return o}return"session-file.bin"})({requestUrl:t,responseUrl:r.url,contentDisposition:r.headers.get("content-disposition")}),c=await na(a,n);return{path:c,filename:i.basename(c),size:n.byteLength,url:t,logid:r.headers.get("x-tt-logid")||void 0}},Tm="1008033";function zm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Rm=async({baseUrl:t,headers:o,xTTEnv:i})=>{const s=new URL("/api/coze_claw/resource/get_frontier_key",l.normalizeBaseUrl(t));l.appendSearchParams(s,{aid:Tm});const n={...o,...l.getPpeHeaders(i)},r=await e.customFetch.fetch(s.toString(),{method:"GET",headers:n}),a=await l.parseServiceResponseBody(r,{}),c=l.getServiceResponseLogId(r);if(!r.ok)throw new Error(l.formatServiceErrorWithLogId({fallback:`Failed to get frontier key: ${r.status} ${r.statusText}`,logId:c,message:a.msg}));const d=zm([a,"access",e=>e.data,"optionalAccess",e=>e.access_key]),p=zm([a,"access",e=>e.data,"optionalAccess",e=>e.device_id]);if(!d||!p)throw new Error(l.formatServiceErrorWithLogId({fallback:"Frontier key response is incomplete",logId:c,message:a.msg}));return{accessKey:d,deviceId:p}};function xm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Lm=async({filePaths:t,clawId:o,sessionId:n,accessFile:a=s.access,createFileReadStream:c=r.openAsBlob,uploadFile:l})=>{const d=[];for(const s of t){try{await a(s)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${s}${t instanceof Error?` (${t.message})`:""}`)}const t=i.basename(s),r=await l({fileName:t,fileContent:await c(s),clawId:o,sessionId:n}),p=xm([r,"access",e=>e.data,"optionalAccess",e=>e.file]);if(!xm([p,"optionalAccess",e=>e.file_uri])||!xm([p,"optionalAccess",e=>e.file_url]))throw new e.CozeError(e.ErrorCode.E5002,r.msg||`Failed to upload session file: ${s}`);d.push({file_name:p.file_name||t,file_uri:p.file_uri,file_url:p.file_url})}return d},Om=async({filePaths:e,sessionId:t,apiBaseUrl:o,sessionApiBaseUrl:i,sessionSpaceWebId:s,xTTEnv:n,service:r,deps:a})=>{if(!e||0===e.length)return[];const c=xm([a,"optionalAccess",e=>e.store])||l.createSessionConfigStore(),{sessionClawId:d}=await c.get(),p=d||(await r.getStatus()).clawId;if(!p)throw new l.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const u=i||o,m=await(async({sessionSpaceWebId:e,baseUrl:t,xTTEnv:o})=>{if(e)return e;try{return(await Rm({baseUrl:t,headers:{},xTTEnv:o})).deviceId}catch(e){return}})({sessionSpaceWebId:s,baseUrl:u,xTTEnv:n}),g=(xm([a,"optionalAccess",e=>e.createApi])||l.createSessionApiClient)({baseUrl:u,webOrigin:u,xSpaceWebId:m,xTTEnv:n}),h=xm([a,"optionalAccess",e=>e.uploadFiles])||Lm;return await h({filePaths:e,clawId:p,sessionId:t,uploadFile:({fileName:e,fileContent:t,clawId:o,sessionId:i})=>g.uploadFile({fileName:e,fileContent:t,clawId:o,sessionId:i})})};function Dm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Um=1048576,Bm=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,qm=({absolutePath:e,root:t})=>{const o=i.relative(t,e);return Boolean(o)&&!o.startsWith("..")&&!i.isAbsolute(o)},Mm=async({onWarn:e,shouldWarnInvalidMention:t=()=>!0,statFile:o=s.stat,userInput:n,workTree:r})=>{(e=>{if(e.length>Um)throw new Error("Message input is too long: max 1048576 characters")})(n);const a=[...n.matchAll(Bm)];if(0===a.length)return[{type:"text",text:n}];const c=[],l=i.resolve(r);let d=0;for(const s of a){const r=s.index,a=s[0],p=s[1];r>d&&c.push({type:"text",text:n.slice(d,r)});const u=i.resolve(l,p);let m=!1;if(qm({absolutePath:u,root:l}))try{(await o(u)).isFile()?m=!0:t(p)&&Dm([e,"optionalCall",e=>e(`Uploading directories is not supported: ${p}`)])}catch(o){t(p)&&Dm([e,"optionalCall",e=>e(`File not found: ${p}`)])}m?c.push({type:"file",absolutePath:u,rawMention:a,relativePath:p}):c.push({type:"text",text:a}),d=r+a.length}return d<n.length&&c.push({type:"text",text:n.slice(d)}),c};const Nm=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},$m=e=>e.includes("/")||e.includes("\\")||e.includes(".")||e.startsWith("."),Gm=async(e,t={})=>{const o=await(async e=>{const t=await oa(),o=Nm(e),i=Nm(t);return o||i?o&&i?`${o}\n\n${i}`:(n=()=>i,null!=(s=o)?s:n()):null;var s,n})(e);if(!o)return{content:o,filePaths:[]};const i=await Mm({onWarn:t.onWarn,shouldWarnInvalidMention:$m,userInput:o,workTree:t.cwd||process.cwd()}),s=[];return{content:Nm(i.map((e=>"text"===e.type?e.text:(s.push(e.absolutePath),""))).join("")),filePaths:s}};const Fm=e=>function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([e,"optionalAccess",e=>e.trim,"call",e=>e(),"access",e=>e.toLowerCase,"call",e=>e()])||"",Vm=async({baseUrl:t,xTTEnv:o,fetchImpl:i=e.customFetch.fetch.bind(e.customFetch)})=>{const s={"content-type":"application/json"};o&&(s["x-use-ppe"]="1",s["x-tt-env"]=o);const n=await i(`${(e=>new URL(e).origin)(t)}/api/coze_space/get_podcast_config`,{method:"POST",headers:s,body:"{}"});if(!n.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to fetch podcast config: ${String(n.status||"")} ${String(n.statusText||"")}`.trim());const r=await n.json();if(0!==r.code&&void 0!==r.code)throw new e.CozeError(e.ErrorCode.E5002,r.msg||"Failed to fetch podcast config");return r.data||{}},Wm=({config:t,mode:o,keyword:i})=>{const s=(({config:t,mode:o})=>{if(!o)return;const i=Fm(o),s=(t.mode_options||[]).find((e=>Fm(e.value)===i||Fm(e.label)===i));if(!s)throw new e.CozeError(e.ErrorCode.E1000,`Podcast mode not found: ${o}`);return s})({config:t,mode:o}),n=Fm(i);return(s?[s]:t.mode_options||[]).flatMap((e=>(e.voice_options||[]).map((t=>({mode_label:e.label,mode_value:e.value,label:t.label,value:t.value,sample:t.sample,color_code:t.color_code}))).filter((e=>!n||(Fm(e.label).includes(n)||Fm(e.value).includes(n))))))};
16
+ ***************************************************************************** */var Le=function(){return Le=Object.assign||function(e){for(var t,o=1,i=arguments.length;o<i;o++)for(var s in t=arguments[o])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},Le.apply(this,arguments)};function Oe(e,t){var o="function"==typeof Symbol&&e[Symbol.iterator];if(!o)return e;var i,s,n=o.call(e),r=[];try{for(;(void 0===t||t-- >0)&&!(i=n.next()).done;)r.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(o=n.return)&&o.call(n)}finally{if(s)throw s.error}}return r}function De(e,t,o){if(2===arguments.length)for(var i,s=0,n=t.length;s<n;s++)!i&&s in t||(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return e.concat(i||Array.prototype.slice.call(t))}var Ue=function(){return{}};function Be(e){return e}function qe(e){return"object"==typeof e&&null!==e}var Me=Object.prototype;function Ne(e){return"[object Array]"===Me.toString.call(e)}function $e(e){return"number"==typeof e}function Ge(e){return"string"==typeof e}function Fe(e,t){if(!Ne(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 Ve=function(e,t){if(!Ne(e))return e;var o=e.indexOf(t);if(o>=0){var i=e.slice();return i.splice(o,1),i}return e};function We(e){try{return Ge(e)?e:JSON.stringify(e)}catch(e){return"[FAILED_TO_STRINGIFY]:"+String(e)}}var He="".padStart?function(e,t){return void 0===t&&(t=8),e.padStart(t," ")}:function(e){return e},Je=0,Ke=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,De(["[SDK]",Date.now(),He(""+Je++)],Oe(e),!1))},Qe=0,Ye=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,De(["[SDK]",Date.now(),He(""+Qe++)],Oe(e),!1))},Ze=function(e){return Math.random()<Number(e)},Xe=function(e,t){return e<Number(t)},et=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 ot(){var e=function(){for(var e=new Array(16),t=0,o=0;o<16;o++)3&o||(t=4294967296*Math.random()),e[o]=t>>>((3&o)<<3)&255;return e}();return e[6]=15&e[6]|64,e[8]=63&e[8]|128,function(e){for(var t=[],o=0;o<256;++o)t[o]=(o+256).toString(16).substr(1);var i=0,s=t;return[s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]]].join("")}(e)}var it=["init","start","config","beforeDestroy","provide","beforeReport","report","beforeBuild","build","beforeSend","send","beforeConfig"];function st(e){var t,o,i=e.builder,s=e.createSender,n=e.createDefaultConfig,r=e.createConfigManager,a=e.userConfigNormalizer,c=e.initConfigNormalizer,l=e.validateInitConfig,d={};it.forEach((function(e){return d[e]=[]}));var p=!1,u=!1,m=!1,g=[],h=[],f=function(){var e=!1,t={},o=function(e){e.length&&e.forEach((function(e){try{e()}catch(e){}})),e.length=0},i=function(e){t[e]&&t[e].forEach((function(e){o(e[1])})),t[e]=void 0};return{set:function(i,s,n){t[i]?t[i].push([s,n]):t[i]=[[s,n]],e&&o(n)},has:function(e){return!!t[e]},remove:i,removeByEvType:function(e){Object.keys(t).forEach((function(i){t[i]&&t[i].forEach((function(t){t[0]===e&&o(t[1])}))}))},clear:function(){e=!0,Object.keys(t).forEach((function(e){i(e)}))}}}(),_={getBuilder:function(){return i},getSender:function(){return t},getPreStartQueue:function(){return g},init:function(e){if(p)Ye("already inited");else{if(!(e&&qe(e)&&l(e)))throw new Error("invalid InitConfig, init failed");var i=n(e);if(!i)throw new Error("defaultConfig missing");var a=c(e);if((o=r(i)).setConfig(a),o.onChange((function(){y("config")})),!(t=s(o.getConfig())))throw new Error("sender missing");p=!0,y("init",!0)}},set:function(e){p&&e&&qe(e)&&(y("beforeConfig",!1,e),null==o||o.setConfig(e))},config:function(e){if(p)return e&&qe(e)&&(y("beforeConfig",!1,e),null==o||o.setConfig(a(e))),null==o?void 0:o.getConfig()},provide:function(e,t){Fe(h,e)?Ye("cannot provide "+e+", reserved"):(_[e]=t,y("provide",!1,e))},start:function(){p&&(u||null==o||o.onReady((function(){u=!0,y("start",!0),function(e){var t=e.getPreStartQueue();t.forEach((function(t){return e.build(t)})),t.length=0}(_)})))},report:function(e){if(e){var t=et(d.beforeReport)(e);if(t){var o=et(d.report)(t);o&&(u?this.build(o):function(e,t,o){if(t.push(o),!(t.length<500)){var i=t.splice(0,50);e.savePreStartDataToDb&&e.savePreStartDataToDb(i)}}(_,g,o))}}},build:function(e){if(u){var t=et(d.beforeBuild)(e);if(t){var o=i.build(t);if(o){var s=et(d.build)(o);s&&this.send(s)}}}},send:function(e){if(u){var o=et(d.beforeSend)(e);o&&(t.send(o),y("send",!1,o))}},destroy:function(){f.clear(),m=!0,g.length=0,y("beforeDestroy",!0)},on:function(e,t){if("init"===e&&p||"start"===e&&u||"beforeDestroy"===e&&m)try{t()}catch(e){}else d[e]&&d[e].push(t)},off:function(e,t){d[e]&&(d[e]=Ve(d[e],t))},destroyAgent:f};return h=Object.keys(_),_;function y(e,t){void 0===t&&(t=!1);for(var o=[],i=2;i<arguments.length;i++)o[i-2]=arguments[i];d[e].forEach((function(e){try{e.apply(void 0,De([],Oe(o),!1))}catch(e){}})),t&&(d[e].length=0)}}var nt=function(e){var t=function(){var e={},t={},o={set:function(i,s){return e[i]=s,t[i]=We(s),o},merge:function(i){return e=Le(Le({},e),i),Object.keys(i).forEach((function(e){t[e]=We(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 Le({},t)}};return o}();e.provide("context",t),e.on("report",(function(e){return e.extra||(e.extra={}),e.extra.context=t.toString(),e}))};var rt=function(){return Date.now()};var at=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&&qe(window))return window}());o&&(o.errors||(o.errors=[]),o.errors.push(e))},ct="custom",lt=function(e){var t=function(o){var i=function(e){if(e&&qe(e)&&e.name&&Ge(e.name)){var t={name:e.name,type:"event"};if("metrics"in e&&qe(e.metrics)){var o=e.metrics,i={};for(var s in o)$e(o[s])&&(i[s]=o[s]);t.metrics=i}if("categories"in e&&qe(e.categories)){var n=e.categories,r={};for(var s in n)r[s]=We(n[s]);t.categories=r}return"attached_log"in e&&Ge(e.attached_log)&&(t.attached_log=e.attached_log),t}}(o);if(i){var s=function(e){var t;if("object"==typeof window&&window.__perfsee__){var o={};return null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,o,e),o.stack}}(t);s&&(i.stacks=s),e.report({ev_type:ct,payload:i,extra:{timestamp:rt()}})}};e.provide("sendEvent",t),e.provide("sendLog",(function(t){var o=function(e){if(e&&qe(e)&&e.content&&Ge(e.content)){var t={content:We(e.content),type:"log",level:"info"};if("level"in e&&(t.level=e.level),"extra"in e&&qe(e.extra)){var o=e.extra,i={},s={};for(var n in o)$e(o[n])?i[n]=o[n]:s[n]=We(o[n]);t.metrics=i,t.categories=s}return"attached_log"in e&&Ge(e.attached_log)&&(t.attached_log=e.attached_log),t}}(t);o&&e.report({ev_type:ct,payload:o,extra:{timestamp:rt()}})}))},dt=function(e,t){var o=e.common||{};return o.sample_rate=t,e.common=o,e},pt=function(e,t,o,i,s){return e?(n=s(i,t),function(){return n}):function(){return o(t)};var n},ut=function(e,t,o,i){var s=function(e,t,o){for(var i,s=Oe(t.split(".")),n=s[0],r=s.slice(1);e&&r.length>0;)e=e[n],n=(i=Oe(r))[0],r=i.slice(1);if(e)return o(e,n)}(e,t,(function(e,t){return e[t]}));return void 0!==s&&function(e,t,o){switch(o){case"eq":return 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)}}))}(i,"boolean"==typeof s?"bool":$e(s)?"number":"string"),o)},mt=function(e,t){try{return"rule"===t.type?ut(e,t.field,t.op,t.values):"and"===t.type?t.children.every((function(t){return mt(e,t)})):t.children.some((function(t){return mt(e,t)}))}catch(e){return at(e),!1}},gt=function(e,t,o,i,s){if(!t)return Be;var n=t.sample_rate,r=t.include_users,a=t.sample_granularity,c=t.rules,l=t.r,d=void 0===l?Math.random():l;if(Fe(r,e))return function(e){return dt(e,1)};var p="session"===a,u=pt(p,n,o,d,i),m=function(e,t,o,i,s,n){var r={};return Object.keys(e).forEach((function(a){var c=e[a],l=c.enable,d=c.sample_rate,p=c.conditional_sample_rules;l?(r[a]={enable:l,sample_rate:d,effectiveSampleRate:d*o,hit:pt(t,d,i,s,n)},p&&(r[a].conditional_hit_rules=p.map((function(e){var r=e.sample_rate,a=e.filter;return{sample_rate:r,hit:pt(t,r,i,s,n),effectiveSampleRate:r*o,filter:a}})))):r[a]={enable:l,hit:function(){return!1},sample_rate:0,effectiveSampleRate:0}})),r}(c,p,n,o,d,i);return function(e){var t;if(!u())return p&&s[0](),!1;if(!(e.ev_type in m))return dt(e,n);if(!m[e.ev_type].enable)return p&&s[1](e.ev_type),!1;if(null===(t=e.common)||void 0===t?void 0:t.sample_rate)return e;var o=m[e.ev_type],i=o.conditional_hit_rules;if(i)for(var r=0;r<i.length;r++)if(mt(e,i[r].filter))return!!i[r].hit()&&dt(e,i[r].effectiveSampleRate);return o.hit()?dt(e,o.effectiveSampleRate):((!i||!i.length)&&p&&s[1](e.ev_type),!1)}},ht={build:function(e){return{ev_type:e.ev_type,payload:e.payload,common:Le(Le({},e.extra||{}),e.overrides||{})}}},ft={sample_rate:1,include_users:[],sample_granularity:"session",rules:{}};function _t(e){var t,o;try{for(var i=function(e){var t="function"==typeof Symbol&&Symbol.iterator,o=t&&e[t],i=0;if(o)return o.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(["userId","deviceId","sessionId","env"]),s=i.next();!s.done;s=i.next()){var n=s.value;e[n]||delete e[n]}}catch(e){t={error:e}}finally{try{s&&!s.done&&(o=i.return)&&o.call(i)}finally{if(t)throw t.error}}return e}function yt(e){return _t(Le({},e))}function bt(e){return qe(e)&&"bid"in e&&"transport"in e}function vt(e){return _t(Le({},e))}var wt=function(e,t){return void 0===t&&(t="/monitor_browser/collect/batch/"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Ct=function(e,t){return void 0===t&&(t="/monitor_web/settings/browser-settings"),(e&&e.indexOf("//")>=0?"":"https://")+e+t},Et=function(e){var t,o,i=e,s={},n=Ue,r=Ue;return{getConfig:function(){return i},setConfig:function(e){return s=Le(Le({},s),e||{}),a(),t||(t=e,i.useLocalConfig||!i.bid?(o={},n()):function(e,t,o,i){if(!e.get)return i({});e.get({withCredentials:!0,url:Ct(t)+"?bid="+o+"&store=1",success:function(e){i(e.data||{})},fail:function(){i({sample:{sample_rate:.001}})}})}(i.transport,i.domain,i.bid,(function(e){o=function(e){if(!e)return{};var t=e.sample,o=e.timestamp,i=e.quota_rate,s=void 0===i?1:i;if(!t)return{};var n=t.sample_rate,r=t.sample_granularity,a=void 0===r?"session":r,c=t.include_users,l=t.rules;return{sample:{include_users:c,sample_rate:n*s,sample_granularity:a,rules:(void 0===l?[]:l).reduce((function(e,t){var o=t.name,i=t.enable,s=t.sample_rate,n=t.conditional_sample_rules;return e[o]={enable:i,sample_rate:s,conditional_sample_rules:n},e}),{})},serverTimestamp:o}}(e),a(),n()}))),i},onChange:function(e){r=e},onReady:function(e){n=e,o&&n()}};function a(){var t=Le(Le(Le({},e),o||{}),s);t.sample=It(It(e.sample,null==o?void 0:o.sample),s.sample),i=t,r()}};function It(e,t){if(!e||!t)return e||t;var o=Le(Le({},e),t);return o.include_users=De(De([],Oe(e.include_users||[]),!1),Oe(t.include_users||[]),!1),o.rules=De(De([],Oe(Object.keys(e.rules||{})),!1),Oe(Object.keys(t.rules||{})),!1).reduce((function(o,i){var s,n;return i in o||(i in(e.rules||{})&&i in(t.rules||{})?(o[i]=Le(Le({},e.rules[i]),t.rules[i]),o[i].conditional_sample_rules=De(De([],Oe(e.rules[i].conditional_sample_rules||[]),!1),Oe(t.rules[i].conditional_sample_rules||[]),!1)):o[i]=(null===(s=e.rules)||void 0===s?void 0:s[i])||(null===(n=t.rules)||void 0===n?void 0:n[i])),o}),{}),o}var At=function(e){e.on("report",(function(t){return function(e,t){var o=t||{},i=o.version,s=o.name,n={url:"",protocol:"",domain:"",path:"",query:"",timestamp:Date.now(),sdk_version:i||"2.1.8",sdk_name:s||"SDK_BASE"};return Le(Le({},e),{extra:Le(Le({},n),e.extra||{})})}(t,e.config())}))},St=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,Le(Le({},e),{extra:Le(Le({},o),e.extra||{})})}(t,e.config())}))};var jt=function(e){return{bid:"",pid:"",viewId:(t="_",t+"_"+Date.now()),userId:ot(),deviceId:ot(),sessionId:ot(),domain:"mon.zijieapi.com",release:"",env:"production",sample:ft,plugins:{},transport:{get:Ue,post:Ue},useLocalConfig:!1};var t},Pt=function(e){var t=void 0===e?{}:e,o=t.createSender,i=void 0===o?function(e){return function(e){return xe(e)}({size:20,endpoint:wt(e.domain),transport:e.transport})}:o,s=t.builder,n=void 0===s?ht:s,r=t.createDefaultConfig,a=st({validateInitConfig:bt,initConfigNormalizer:yt,userConfigNormalizer:vt,createSender:i,builder:n,createDefaultConfig:void 0===r?jt:r,createConfigManager:Et});return nt(a),St(a),At(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=Ve(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&&qe(window)&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__.push(e)}catch(e){}}(a),a},kt=function(e){void 0===e&&(e={});var t=Pt(e);return function(e){e.on("start",(function(){var t=e.config(),o=t.userId,i=t.sample,s=gt(o,i,Ze,Xe,[function(){e.destroy()},function(t){e.destroyAgent.removeByEvType(t)}]);e.on("build",s)}))}(t),lt(t),t}();const Tt=Re("slardar:transport"),zt=()=>{};function Rt(e){const{url:t,method:o,data:i,success:s=zt,fail:n=zt,getResponseText:r=zt}=e;if(Tt("Making %s request to %s",o,t),i&&Tt("Request data: %s",i.slice(0,200)),!t||"string"!=typeof t){const e=new Error(`Invalid URL: ${t}`);return Tt("Invalid URL provided: %o",t),void n(e)}try{const e=new URL(t);Tt("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:d.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=>{Tt("Response callback triggered: status=%s",e.statusCode);let t="";e.on("data",(e=>{Tt("Response data chunk received: %s bytes",e.length),t+=e.toString()})),e.on("end",(()=>{Tt("Response end event fired"),Tt("Response received: status=%s, body=%s",e.statusCode,t.slice(0,200)),r(t);try{if(e.statusCode&&e.statusCode>=400)Tt("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);Tt("Request succeeded"),s(e)}else Tt("Request succeeded with empty response"),s({})}catch(e){Tt("Failed to parse response: %s",e.message),n(e)}}))}));c.on("error",(e=>{Tt("Request error: %s",e.message),n(e)})),c.on("timeout",(()=>{Tt("Request timeout"),c.destroy(),n(new Error("Request timeout"))})),i&&c.write(i),c.end()}catch(e){Tt("Exception during request: %s",e.message),n(e)}}function xt(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Lt=Re("slardar:reporter");class Ot{constructor(){Ot.prototype.__init.call(this),Ot.prototype.__init2.call(this)}__init(){this.initialized=!1}__init2(){this.client=kt}setup(e){var t,o;if(this.initialized)Lt("Already initialized, skipping setup");else try{Lt("Initializing Slardar with config:",{bid:e.bid,release:e.release,env:e.env,userId:e.userId,projectId:e.projectId});const i={get(e){Tt("Transport GET called: %s",e.url),Rt({method:"GET",...e})},post({url:e,data:t}){Tt("Transport POST called: %s",e),Rt({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=>{Lt("send hook called for event: %s",xt([e,"optionalAccess",e=>e.ev_type])||"unknown")})),this.client.start(),this.initialized=!0,Lt("Slardar initialized successfully")}catch(e){Lt("Failed to initialize:",e)}}ensureInitialized(){return!!this.initialized||(Lt("Not initialized, call setup() first"),!1)}sendEvent(e,t,o){if(this.ensureInitialized())try{Lt("Sending event:",{name:e,metrics:t,categories:o});const i=t?Object.fromEntries(Object.entries(t).filter((([,e])=>void 0!==e))):void 0,s=o?Object.fromEntries(Object.entries(o).filter((([,e])=>void 0!==e))):void 0;xt([this,"access",e=>e.client,"access",e=>e.sendEvent,"optionalCall",t=>t({name:e,metrics:i,categories:s})])}catch(e){Lt("Failed to send event:",e)}}sendLog(e,t,o){if(this.ensureInitialized())try{Lt("Sending log:",{level:e,message:t,extra:o}),this.sendEvent("cli_log",void 0,{level:e,message:t,...o})}catch(e){Lt("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"}}};Lt("Reporting JS error:",{name:e.name,message:e.message.slice(0,100),stack:xt([e,"access",e=>e.stack,"optionalAccess",e=>e.slice,"call",e=>e(0,200)]),extra:t,source:o}),this.client.report(i),Lt("JS error reported successfully")}catch(e){Lt("Failed to report error:",e)}}setContext(e,t){this.ensureInitialized()&&xt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.set,"call",o=>o(e,t)])}mergeContext(e){this.ensureInitialized()&&(Lt("Merging context:",e),xt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.merge,"call",t=>t(e)]))}deleteContext(e){this.ensureInitialized()&&xt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.delete,"call",t=>t(e)])}clearContext(){this.ensureInitialized()&&xt([this,"access",e=>e.client,"access",e=>e.context,"optionalAccess",e=>e.clear,"call",e=>e()])}updateConfig(e){if(this.ensureInitialized())try{Lt("Updating config:",e),this.client.config({userId:e.userId,release:e.release,sessionId:e.sessionId,env:e.env})}catch(e){Lt("Failed to update config:",e)}}async flush(e=1500){this.ensureInitialized()&&(Lt("Flushing Slardar data..."),xt([this,"access",e=>e.client,"access",e=>e.getSender,"optionalCall",e=>e(),"optionalAccess",e=>e.flush,"call",e=>e()]),Lt("Waiting %dms for events to be sent...",e),await new Promise((t=>setTimeout(t,e))),Lt("Slardar data flushed"))}getRawClient(){return this.client}}const Dt=new Ot;function Ut(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Bt="cli_start",qt="cli_command",Mt="cli_command_complete",Nt="cli_error",$t="network_request",Gt="file_operation",Ft={cliStart:e=>({name:Bt,metrics:{duration:0,...e}}),cliCommand:(e,t)=>({name:qt,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:Mt,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:$t,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:Gt,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:Nt,categories:{errorName:e.name,errorMessage:e.message,stack:e.stack||"",...t},metrics:{errorCode:1}})};function Vt(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Wt(e){return(...t)=>{try{const o=e(...t);return o instanceof Promise?o.catch((()=>{})):o}catch(e){}}}const Ht=Wt((()=>{var e,t;Dt.setup({bid:"coze_cli",release:Ae,env:"production",userId:process.env.USER||"",useLocalConfig:!1,domain:"mon.zijieapi.com"}),Dt.mergeContext({platform:process.platform,callerPlatform:(e=process.env.COZE_CLI_PLATFORM,t=()=>"unknown",null!=e?e:t()),nodeVersion:process.version,cliVersion:Ae})})),Jt=Wt((e=>{const t=Ft.cliCommand(e);Dt.sendEvent(t.name,t.metrics,t.categories)})),Kt=Wt(((e,t,o,i)=>{const s=Ft.cliCommandComplete(e,t,o,{errorCode:Vt([i,"optionalAccess",e=>e.errorCode])});Dt.sendEvent(s.name,s.metrics,s.categories)})),Qt=Wt(((e,t)=>{Dt.reportError(e,t,{type:"cli",data:t})})),Yt=Wt((async()=>{await Dt.flush()}));async function Zt(e,t){if(e.config.disableTelemetry)return void await t();Ht();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);Jt(o);const i=Date.now();let s,n=!0;try{await t()}catch(e){throw n=!1,s=e instanceof Error?e:new Error(String(e)),e}finally{const e=Date.now()-i;try{n?Kt(o,!0,e):(s&&Qt(s,{command:o}),Kt(o,!1,e)),await Yt()}catch(e){}}}function Xt(e,t){return null!=e?e:t()}const eo=i.join(n.homedir(),".coze","logs");class to{__init(){this.fileStream=null}__init2(){this.writeError=!1}constructor(e={}){to.prototype.__init.call(this),to.prototype.__init2.call(this),this.format=Xt(e.format,(()=>"text")),this.printToStderr=Xt(e.printToStderr,(()=>!1)),this.tags=Xt(e.tags,(()=>({}))),this.startTime=Date.now();const t=Xt(e.logFile,(()=>this.getDefaultLogPath()));this.logFile=t;try{this.ensureLogDir(),this.rotateLogFiles(),this.fileStream=r.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 i.join(eo,`${e}-${t}.log`)}ensureLogDir(){r.existsSync(eo)||r.mkdirSync(eo,{recursive:!0})}rotateLogFiles(){try{const e=r.readdirSync(eo).filter((e=>e.endsWith(".log"))).map((e=>({name:e,path:i.join(eo,e),mtime:r.statSync(i.join(eo,e)).mtime.getTime()}))).sort(((e,t)=>t.mtime-e.mtime));e.length>=10&&e.slice(9).forEach((e=>{try{r.unlinkSync(e.path)}catch(e){}}))}catch(e){}}verbose(e,...t){this.log("verbose",e,t)}info(e,...t){this.log("info",e,t)}warn(e,...t){this.log("warn",e,t)}error(e,...t){this.log("error",e,t)}success(e,...t){this.log("success",e,t)}debug(e,...t){this.log("debug",e,t)}debugFileOnly(e,...t){this.log("debug",e,t,!1)}log(e,t,o,i=this.printToStderr){const s=this.formatEntry(e,t,o);if(this.fileStream)try{this.fileStream.write(`${s}\n`)}catch(e){!this.writeError&&i&&(process.stderr.write("Warning: Log write failed\n"),this.writeError=!0)}i&&process.stderr.write(`${s}\n`)}formatEntry(e,t,o){const i=(new Date).toISOString(),s=Date.now()-this.startTime;if("json"===this.format){const n={level:e,timestamp:i,delta:s,...this.tags,message:t};return o.length>0&&(n.args=o),JSON.stringify(n)}const n=Object.entries(this.tags).map((([e,t])=>`${e}=${t}`)).join(" "),r=o.length>0?` ${o.map(String).join(" ")}`:"";return`${e.toUpperCase().padEnd(7)} [${i}] +${s}ms ${n} ${t}${r}`}close(){if(this.fileStream)try{this.fileStream.end()}catch(e){}}}function oo(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const io=new Set(["authorization","cookie","set-cookie"]),so=/(^|_|-)(token|secret|password|authorization|cookie)(_|-|$)/i,no=Symbol("request-debug-json-parse-fallback");let ro=null,ao=!1,co=!1;const lo=e.customFetch.fetch.bind(e.customFetch),po=e=>"[object Object]"===Object.prototype.toString.call(e),uo=e=>{try{return JSON.stringify(e)}catch(t){return JSON.stringify(String(e))}},mo=e=>{if("string"!=typeof e)return"***";const t=e.trim(),o=oo([/^bearer\s+/i,"access",e=>e.exec,"call",e=>e(t),"optionalAccess",e=>e[0]]);return o?`${o}***`:"***"},go=(e,t)=>t&&so.test(t)?mo(e):Array.isArray(e)?e.map((e=>go(e))):po(e)?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,go(t,e)]))):e,ho=e=>{if(!e)return{};if(e instanceof Headers)return Object.fromEntries(Array.from(e.entries()).map((([e,t])=>[e.toLowerCase(),t])));if(Array.isArray(e))return Object.fromEntries(e.map((([e,t])=>[e.toLowerCase(),String(t)])));const t=e;return"function"==typeof t.toJSON?ho(t.toJSON()):"function"==typeof t.entries?Object.fromEntries(Array.from(t.entries()).map((([e,t])=>[e.toLowerCase(),t]))):Object.fromEntries(Object.entries(e).map((([e,t])=>[e.toLowerCase(),Array.isArray(t)?t.map((e=>String(e))).join(", "):String(t)])))},fo=(e,t)=>e[t.toLowerCase()],_o=(e,t,o="binary")=>{const i=(e=>"string"==typeof e?u.Buffer.byteLength(e):u.Buffer.isBuffer(e)?e.length:e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:"undefined"!=typeof Blob&&e instanceof Blob?e.size:void 0)(e),s=[o];return t&&s.push(t),"number"==typeof i&&s.push(`${i} bytes`),`[${s.join("; ")}]`},yo=(t,o)=>{if(null==t||""===t)return"<empty>";const i=oo([fo,"call",e=>e(o,"content-type"),"optionalAccess",e=>e.toLowerCase,"call",e=>e()]);if(oo([i,"optionalAccess",e=>e.includes,"call",e=>e("multipart/form-data")]))return _o(t,i,"multipart");if(t instanceof URLSearchParams)return uo(go(Object.fromEntries(Array.from(t.entries()))));if(u.Buffer.isBuffer(t)||t instanceof Uint8Array||t instanceof ArrayBuffer||"undefined"!=typeof Blob&&t instanceof Blob)return _o(t,i);if("string"==typeof t){const o=(t=>{const o=e.safeJsonParse(t,no);if(o!==no)return o})(t);return void 0!==o?uo(go(o)):JSON.stringify(t)}return Array.isArray(t)||po(t)?uo(go(t)):_o(t,i,typeof t)},bo=(e,t)=>{try{return new URL(e,t).toString()}catch(o){return t?`${t}${e}`:e}},vo=e=>{const t=ho(e);return t["x-tt-logid"]||t["x-tt-log-id"]||t.logid||""},wo=e=>(e||"GET").toUpperCase(),Co=e=>{ao&&ro&&(ro instanceof to?ro.debugFileOnly(e):ro.debug(e))},Eo=({method:e,url:t,headers:o,body:i})=>{const s=ho(o);Co(`[DBG][HTTP][REQ] ${e} ${t}\nheaders: ${uo((e=>Object.fromEntries(Object.entries(e).map((([e,t])=>[e,io.has(e)?mo(t):t]))))(s))}\nbody: ${yo(i,s)}`)},Io=({method:e,url:t,status:o,logId:i})=>{Co(`[DBG][HTTP][RES] ${e} ${t} status=${o} logid=${i||"-"}`)},Ao=({method:e,url:t,status:o,logId:i,message:s})=>{const n=(a=()=>"ERR",null!=(r=o)?r:a());var r,a;const c=s?` error=${JSON.stringify(s)}`:"";Co(`[DBG][HTTP][ERR] ${e} ${t} status=${n} logid=${i||"-"}${c}`)},So=(e,t)=>t&&"body"in t?t.body:"object"==typeof e&&e&&"body"in e&&null!==e.body?"[request body stream]":void 0,jo=()=>{e.axiosInstance.interceptors.request.use((e=>((e=>{const t=wo(e.method),o=bo(e.url||"",e.baseURL),i=ho(e.headers);Eo({method:t,url:o,headers:i,body:e.data})})(e),e))),e.axiosInstance.interceptors.response.use((e=>((e=>{const t=wo(oo([e,"access",e=>e.config,"optionalAccess",e=>e.method])),o=bo(oo([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",oo([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Io({method:t,url:o,status:e.status,logId:vo(e.headers)})})(e),e)),(e=>((e=>{const t=wo(oo([e,"access",e=>e.config,"optionalAccess",e=>e.method])),o=bo(oo([e,"access",e=>e.config,"optionalAccess",e=>e.url])||"",oo([e,"access",e=>e.config,"optionalAccess",e=>e.baseURL]));Ao({method:t,url:o,status:oo([e,"access",e=>e.response,"optionalAccess",e=>e.status]),logId:vo(oo([e,"access",e=>e.response,"optionalAccess",e=>e.headers])),message:e.message})})(e),Promise.reject(e))))},Po=()=>{e.customFetch.fetch=async(t,o)=>{const i=((e,t)=>oo([t,"optionalAccess",e=>e.method])?wo(t.method):"object"==typeof e&&e&&"method"in e&&"string"==typeof e.method?wo(e.method):"GET")(t,o),s=(e=>"string"==typeof e?e:e instanceof URL?e.toString():"object"==typeof e&&e&&"url"in e&&"string"==typeof e.url?e.url:String(e))(t),n=e.customFetch.getRequestHeaders(t,o);Eo({method:i,url:s,headers:n,body:So(t,o)});try{const e=await lo(t,o);return Io({method:i,url:s,status:e.status,logId:vo(e.headers)}),e}catch(e){throw Ao({method:i,url:s,message:e instanceof Error?e.message:String(e)}),e}}};function ko(e,t){return null!=e?e:t()}function To(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}var zo;!function(e){e.AUTHORIZATION_PENDING="authorization_pending";e.SLOW_DOWN="slow_down";e.ACCESS_DENIED="access_denied";e.EXPIRED_TOKEN="expired_token"}(zo||(zo={}));const Ro=e=>new Promise((t=>setTimeout(t,e))),xo=e.createRequestClient({baseURL:"https://api.coze.com",useDefaultPlugins:!0,plugins:[{name:"oauth-error-handler",onError:t=>{if(e.isHttpError(t))throw t;const o=t,i=ko(To([o,"access",e=>e.response,"optionalAccess",e=>e.data]),(()=>({}))),s=i.error_description||i.error||o.message,n={status:To([o,"access",e=>e.response,"optionalAccess",e=>e.status]),code:i.error,config:o.config,response:o.response,data:i};throw new e.HttpError(ko(s,(()=>"OAuth request failed")),n)}}]});async function Lo(e){return(await xo.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 Oo=async(t,o)=>{const i=process.env.HTTP_PROXY||process.env.http_proxy,s=process.env.HTTPS_PROXY||process.env.https_proxy;if(s||i){const o=new m.EnvHttpProxyAgent;e.customFetch.setDispatcher(o);const[{HttpProxyAgent:n},{HttpsProxyAgent:r}]=await Promise.all([import("http-proxy-agent"),import("https-proxy-agent")]);e.axiosInstance$1.defaults.proxy=!1,xo.defaults.proxy=!1,s&&(e.axiosInstance$1.defaults.httpsAgent=new r(s),xo.defaults.httpsAgent=new r(s),t.ui.debug(`HTTPS proxy enabled: ${s}`)),i&&(e.axiosInstance$1.defaults.httpAgent=new n(i),xo.defaults.httpAgent=new n(i),t.ui.debug(`HTTP proxy enabled: ${i}`))}await o()};let Do=()=>{},Uo=null;const Bo=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),qo=(e,t)=>{return Bo(o=e)&&"function"==typeof o.set?(Object.entries(t).forEach((([t,o])=>{e.set(t,o)})),e):{...Bo(e)?e:{},...t};var o},Mo=t=>{Do=t,null===Uo&&(Uo=e.axiosInstance$1.interceptors.request.use((t=>{const o=l.getCozeAccountHeaders(Do());return 0!==Object.keys(o).length&&l.shouldInjectCozeAccountHeader((t=>{const o=t.url;if(!o)return"";try{return new URL(o,t.baseURL||e.axiosInstance$1.defaults.baseURL).toString()}catch(e){return""}})(t))?(t.headers=qo(t.headers,o),t):t})))};async function No(t,o){Mo((()=>t.config.organizationId)),l.installScopedCozeAccountFetchHeader({getOrganizationId:()=>t.config.organizationId});const i=await t.auth.getValidAccessToken();e.axiosInstance$1.defaults.baseURL=t.config.apiBaseUrl;const s=`Bearer ${i}`;e.axiosInstance$1.defaults.headers.Authorization=s,e.axiosInstance$1.defaults.headers["x-request-from-coze-cli"]="1",e.customFetch.setHeaders({Authorization:s,"x-request-from-coze-cli":"1"}),t.config.xTTEnv&&(e.axiosInstance$1.defaults.headers["x-use-ppe"]="1",e.axiosInstance$1.defaults.headers["x-tt-env"]=t.config.xTTEnv,e.customFetch.setHeaders({"x-use-ppe":"1","x-tt-env":t.config.xTTEnv})),await o()}function $o(e){if(!Array.isArray(e))throw new TypeError("Middleware stack must be an array!");for(const t of e)if("function"!=typeof t)throw new TypeError("Middleware must be composed of functions!");return function(t,o){let i=-1;return function s(n){if(n<=i)return Promise.reject(new Error("next() called multiple times"));i=n;let r=e[n];n===e.length&&(r=o);if(!r)return Promise.resolve();try{return Promise.resolve(r(t,s.bind(null,n+1)))}catch(e){return Promise.reject(e)}}(0)}}var Go,Fo,Vo,Wo,Ho,Jo,Ko,Qo,Yo,Zo,Xo,ei,ti,oi,ii,si,ni,ri,ai,ci,li,di,pi,ui,mi,gi,hi,fi,_i,yi,bi,vi,wi,Ci,Ei,Ii,Ai,Si,ji,Pi,ki,Ti,zi,Ri,xi,Li,Oi,Di,Ui,Bi,qi,Mi,Ni,$i,Gi;function Fi(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e.app="app";e.pat="pat"}(Go||(Go={})),function(e){e.can_apply2="CanApply";e.already_applied2="AlreadyApplied";e.joined4="Joined";e.deny3="Deny"}(Fo||(Fo={})),function(e){e.processing="Processing";e.approved="Approved";e.rejected="Rejected";e.auto_approved="AutoApproved"}(Vo||(Vo={})),function(e){e.normal="Normal";e.connector="Connector";e.privilege="Privilege"}(Wo||(Wo={})),function(e){e.auth_app="AuthApp";e.on_behalf_of_user="OnBehalfOfUser"}(Ho||(Ho={})),function(e){e.password="Password";e.sms="Sms";e.email="Email";e.unknown3="Unknown"}(Jo||(Jo={})),function(e){e.email2="Email";e.phone="Phone";e.unknown4="Unknown"}(Ko||(Ko={})),function(e){e.authorized="authorized";e.unauthorized="unauthorized";e.expired4="expired"}(Qo||(Qo={})),function(e){e.api_key="api_key";e.wechat_official="wechat_official";e.oauth_2="oauth2"}(Yo||(Yo={})),function(e){e.noncertificated="Noncertificated";e.certificated="Certificated"}(Zo||(Zo={})),function(e){e.uncertified="Uncertified";e.personal_certification="PersonalCertification";e.enterprise_certification="EnterpriseCertification"}(Xo||(Xo={})),function(e){e.obo="Obo";e.app_auth="AppAuth";e.personal_access_token="PersonalAccessToken"}(ei||(ei={})),function(e){e.legacy="Legacy";e.web_backend="WebBackend";e.single_page_or_native="SinglePageOrNative";e.terminal="Terminal";e.service="Service"}(ti||(ti={})),function(e){e.bot_editor="BotEditor";e.bot_developer="BotDeveloper";e.bot_operator="BotOperator"}(oi||(oi={})),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"}(ii||(ii={})),function(e){e.visitors_prohibited="VisitorsProhibited";e.guest_prohibited_by_invited_user_enterprise2="GuestProhibitedByInvitedUserEnterprise";e.prohibited_by_custom_people_management="ProhibitedByCustomPeopleManagement"}(si||(si={})),function(e){e.dev2="DEV";e.prod2="PROD"}(ni||(ni={})),function(e){e._1="1";e._30="30";e._90="90";e._180="180";e._365="365";e.customize="customize";e.permanent="permanent"}(ri||(ri={})),function(e){e._12="1";e._302="30";e._902="90";e._1802="180";e._3652="365";e.customize2="customize";e.permanent2="permanent"}(ai||(ai={})),function(e){e.aes_256_gcm="AES-256-GCM"}(ci||(ci={})),function(e){e.conversation="Conversation";e.unknown="Unknown"}(li||(li={})),function(e){e.active3="Active";e.inactive="Inactive"}(di||(di={})),function(e){e.cloud_kms="CloudKMS",e.default="Default";e.unknown2="Unknown"}(pi||(pi={})),function(e){e.user_custom2="user_custom";e.consumer3="consumer"}(ui||(ui={})),function(e){e.super_admin="SuperAdmin";e.admin="Admin";e.member="Member";e.guest="Guest"}(mi||(mi={})),function(e){e.join_enterprise_share_link_expiration_time="JoinEnterpriseShareLinkExpirationTime";e.sso="SSO";e.forbid_guest_join_enterprise="ForbidGuestJoinEnterprise";e.forbid_member_join_other_enterprise="ForbidMemberJoinOtherEnterprise";e.replace_enterprise_logo="ReplaceEnterpriseLogo";e.forbid_custom_people_management="ForbidCustomPeopleManagement";e.forbid_coze_store_plugin_access="ForbidCozeStorePluginAccess";e.enterprise_member_listing_skill_coze_store="EnterpriseMemberListingSkillCozeStore";e.listing_skill_enterprise_store_audit="ListingSkillEnterpriseStoreAudit"}(gi||(gi={})),function(e){e.string="String";e.boolean="Boolean";e.integer="Integer";e.string_list="StringList"}(hi||(hi={})),function(e){e.must_handle="MustHandle";e.no_need_handle="NoNeedHandle"}(fi||(fi={})),function(e){e.pending_review_app_auth="pending_review_app_auth";e.pending_review_app_obo="pending_review_app_obo";e.approved_app_auth="approved_app_auth";e.approved_app_obo="approved_app_obo"}(_i||(_i={})),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"}(yi||(yi={})),function(e){e.confirming2="Confirming";e.joined3="Joined";e.rejected3="Rejected";e.revoked2="Revoked";e.expired3="Expired";e.deny2="Deny"}(bi||(bi={})),function(e){e.confirming="Confirming";e.joined2="Joined";e.rejected2="Rejected";e.revoked="Revoked";e.expired2="Expired"}(vi||(vi={})),function(e){e.can_join="CanJoin";e.guest_prohibited_by_enterprise="GuestProhibitedByEnterprise";e.guest_prohibited_by_invited_user_enterprise="GuestProhibitedByInvitedUserEnterprise"}(wi||(wi={})),function(e){e.can_apply="CanApply";e.already_applied="AlreadyApplied";e.joined="Joined";e.expired="Expired";e.deny="Deny"}(Ci||(Ci={})),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"}(Ei||(Ei={})),function(e){e.user_custom_only="user_custom_only";e.all2="all"}(Ii||(Ii={})),function(e){e.system="system";e.custom="custom"}(Ai||(Ai={})),function(e){e.not_in_enterprise="NotInEnterprise";e.prohibited_by_custom_people_management2="ProhibitedByCustomPeopleManagement"}(Si||(Si={})),function(e){e.can_apply3="CanApply";e.already_applied3="AlreadyApplied";e.joined5="Joined";e.deny4="Deny"}(ji||(ji={})),function(e){e.super_admin2="SuperAdmin";e.admin2="Admin";e.member2="Member";e.guest2="Guest"}(Pi||(Pi={})),function(e){e.member_joining_auto_approved="MemberJoiningAutoApproved"}(ki||(ki={})),function(e){e.string2="String";e.boolean2="Boolean";e.integer2="Integer";e.string_list2="StringList"}(Ti||(Ti={})),function(e){e.developer="developer";e.consumer2="consumer"}(zi||(zi={})),function(e){e.all="all";e.owned="owned";e.others="others"}(Ri||(Ri={})),function(e){e.enterprise_member="EnterpriseMember";e.enterprise_guest="EnterpriseGuest"}(xi||(xi={})),function(e){e.not_created="NotCreated";e.enabled="Enabled";e.disabled="Disabled"}(Li||(Li={})),function(e){e.not_created2="NotCreated";e.not_support_not_supabase="NotSupportNotSupabase";e.enabled2="Enabled";e.disabled2="Disabled";e.not_support_project_type="NotSupportProjectType"}(Oi||(Oi={})),function(e){e.production="Production";e.development="Development"}(Di||(Di={})),(Ui||(Ui={})).skill="skill",function(e){e.dev="dev";e.prod="prod"}(Bi||(Bi={})),function(e){e.user_custom="user_custom";e.coze_default="coze_default";e.consumer="consumer"}(qi||(qi={})),function(e){e.active2="Active";e.deactive="Deactive"}(Mi||(Mi={})),function(e){e.active="active";e.deactivated="deactivated";e.offboarded="offboarded"}(Ni||(Ni={})),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"}($i||($i={})),function(e){e.root_user="RootUser";e.basic_user="BasicUser"}(Gi||(Gi={}));class Vi{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Vi.prototype.__init.call(this),Vi.prototype.__init2.call(this),this.request=Fi([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Fi([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}CreatePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/create_personal_access_token_and_permission"),s={name:o.name,expire_at:o.expire_at,duration_day:o.duration_day,organization_id:o.organization_id,workspace_permission:o.workspace_permission,account_permission:o.account_permission,workspace_permission_v2:o.workspace_permission_v2,enterprise_permission:o.enterprise_permission},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}UpdatePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/update_personal_access_token_and_permission"),s={workspace_permission:o.workspace_permission,account_permission:o.account_permission,workspace_permission_v2:o.workspace_permission_v2,enterprise_permission:o.enterprise_permission,id:o.id,name:o.name},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}DeletePersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/delete_personal_access_token_and_permission"),s={id:o.id};return this.request({url:i,method:"POST",data:s},t)}ListPersonalAccessTokens(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/pat/list_personal_access_tokens"),s={organization_id:o.organization_id,page:o.page,size:o.size,search_option:o.search_option};return this.request({url:i,method:"GET",params:s},t)}GetPersonalAccessTokenAndPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/get_personal_access_token_and_permission"),s={id:o.id};return this.request({url:i,method:"GET",params:s},t)}ListPersonalAccessTokenSupportPermissions(e,t){const o=this.genBaseURL("/api/permission_api/pat/list_personal_access_token_support_permissions");return this.request({url:o,method:"GET"},t)}CheckPersonalAccessTokenInWorkspace(e,t){const o=e,i=this.genBaseURL("/api/permission_api/pat/check_personal_access_token_in_workspace"),s={workspace_id:o.workspace_id};return this.request({url:i,method:"GET",params:s},t)}AddCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/add_collaborator"),s={collaborator_types:o.collaborator_types,principal:o.principal,resource:o.resource};return this.request({url:i,method:"POST",data:s},t)}RemoveCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/remove_collaborator"),s={principal:o.principal,resource:o.resource};return this.request({url:i,method:"POST",data:s},t)}CreateAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/create_app_meta"),s={app_type:o.app_type,client_type:o.client_type,name:o.name,description:o.description,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListAppMeta(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/list_app_meta"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}GetAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_meta"),s={appid:o.appid},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}UpdateAppMeta(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/update_app_meta"),s={status:o.status,oauth2_configuration:o.oauth2_configuration,appid:o.appid,name:o.name,description:o.description,declared_permission:o.declared_permission,declared_permission_v2:o.declared_permission_v2},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}UploadPublicKey(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/upload_public_key"),s={appid:o.appid,public_key_pem:o.public_key_pem};return this.request({url:i,method:"POST",data:s},t)}DeletePublicKey(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_public_key"),s={fingerprint:o.fingerprint};return this.request({url:i,method:"POST",data:s},t)}CreateClientSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/create_client_secret"),s={appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}DeleteClientSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_client_secret"),s={appid:o.appid,client_secret_id:o.client_secret_id};return this.request({url:i,method:"POST",data:s},t)}PutOAuth2Configuration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/put_oauth2_configuration"),s={oauth2_configuration:o.oauth2_configuration,appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}AuthorizeAppWithDeclaredPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/authorize_app_with_declared_permission"),s={appid:o.appid,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListAuthorizedApps(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/list_authorized_apps"),s={page:o.page,size:o.size},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetAppAuthorizationRequestInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_authorization_request_info"),s={authorize_key:o.authorize_key},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}RevokeAppAuthorizedPermission(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/revoke_app_authorized_permission"),s={authorization_type:o.authorization_type,appid:o.appid,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DeleteApp(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/delete_app"),s={appid:o.appid};return this.request({url:i,method:"POST",data:s},t)}ModifyCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/modify_collaborator"),s={principal:o.principal,resource:o.resource,collaborator_types:o.collaborator_types};return this.request({url:i,method:"POST",data:s},t)}BatchAddCollaborator(e,t){const o=e,i=this.genBaseURL("/api/permission/authz/batch_add_collaborator"),s={principal_type:o.principal_type,resource:o.resource,principal_ids:o.principal_ids,collaborator_types:o.collaborator_types};return this.request({url:i,method:"POST",data:s},t)}GetAppInstallationRequestInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_app_installation_request_info"),s={appid:o.appid},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}AppInstallationConsent(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/app_installation_consent"),s={appid:o.appid,installation_account_hint:o.installation_account_hint};return this.request({url:i,method:"POST",data:s},t)}ImpersonateCozeUser(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/coze_web_app/impersonate_coze_user"),s={duration_seconds:o.duration_seconds,scope:o.scope,connector_info:o.connector_info};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoConnectInfoWithInsName(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_connect_info_with_ins_name");return this.request({url:o,method:"GET"},t)}GetVolcanoMaskedMobile(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_masked_mobile");return this.request({url:o,method:"GET"},t)}BindVolcano(e,t){const o=this.genBaseURL("/api/permission_api/volcano/bind_volcano");return this.request({url:o,method:"POST"},t)}AuthorizeAppWithSpecifiedWorkspace(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/authorize_app_with_specified_permission"),s={appid:o.appid,workspace_list:o.workspace_list,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetUserProfile(e,t){const o=this.genBaseURL("/v1/users/me");return this.request({url:o,method:"GET"},t)}ListAppAuthorizations(e,t){const o=e,i=this.genBaseURL(`/v1/oauth-apps/${o.appid}/authorizations`),s={page_num:o.page_num,page_size:o.page_size},n={authorization:o.authorization};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetCertificationInfo(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/get_certification_info");return this.request({url:o,method:"GET"},t)}NeedCreateEnterprise(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/need_create_enterprise");return this.request({url:o,method:"GET"},t)}CreateEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_enterprise"),s={name:o.name,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}ListEnterprise(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/enterprise/list_enterprises"),s={contain_enterprise_of_user:o.contain_enterprise_of_user,contain_organization_of_user:o.contain_organization_of_user,contain_guest_enterprise_of_user:o.contain_guest_enterprise_of_user,is_space:o.is_space};return this.request({url:i,method:"GET",params:s},t)}GetEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_enterprise"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"GET",params:s},t)}UpdateEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise"),s={enterprise_id:o.enterprise_id,name:o.name,icon_uri:o.icon_uri,replace_logo:o.replace_logo};return this.request({url:i,method:"POST",data:s},t)}UpdateEnterpriseSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_settings"),s={enterprise_id:o.enterprise_id,enterprise_settings:o.enterprise_settings};return this.request({url:i,method:"POST",data:s},t)}BatchAddEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_add_enterprise_people"),s={enterprise_id:o.enterprise_id,enterprise_people:o.enterprise_people,need_check_people_valid:o.need_check_people_valid};return this.request({url:i,method:"POST",data:s},t)}RemoveEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/remove_enterprise_people"),s={enterprise_id:o.enterprise_id,user_id:o.user_id,receiver:o.receiver,sync_default_organization:o.sync_default_organization};return this.request({url:i,method:"POST",data:s},t)}UpdateEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_enterprise_people"),s={enterprise_id:o.enterprise_id,user_id:o.user_id,enterprise_role_type_list:o.enterprise_role_type_list,sync_default_organization:o.sync_default_organization};return this.request({url:i,method:"POST",data:s},t)}CreateEnterpriseInviteLink(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_enterprise_invite_link"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}CreateJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_join_application"),s={key:o.key,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}GetInviteInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_invite_info"),s={invite_key:o.invite_key};return this.request({url:i,method:"GET",params:s},t)}UpdateJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_application"),s={application_status:o.application_status,enterprise_id:o.enterprise_id,join_application_id_list:o.join_application_id_list};return this.request({url:i,method:"POST",data:s},t)}ListPersonalAccessTokensByCreator(e,t){const o=e,i=this.genBaseURL("/api/permission_api/permission/list_personal_access_tokens_by_creator"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}ListAppInstallations(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/list_app_installations"),s={enterprise_id:o.enterprise_id,organization_id:o.organization_id},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}GetEnterpriseSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_enterprise_settings"),s={enterprise_id:o.enterprise_id,enterprise_setting_key_list:o.enterprise_setting_key_list};return this.request({url:i,method:"POST",data:s},t)}SearchCanAddEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_can_add_enterprise_people"),s={people_type:o.people_type,enterprise_id:o.enterprise_id,search_key:o.search_key};return this.request({url:i,method:"POST",data:s},t)}SearchEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_enterprise_people"),s={people_type:o.people_type,enterprise_id:o.enterprise_id,search_key:o.search_key,enterprise_role_type_list:o.enterprise_role_type_list,need_volcano_user_info:o.need_volcano_user_info,need_people_number:o.need_people_number,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}ListJoinApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_application"),s={application_status:o.application_status,enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PostAdapterMpV1Code2Session(e,t){const o=e||{},i=this.genBaseURL("/adapter/mp/v1/code2session"),s={bot_id:o.bot_id,app_id:o.app_id,connector_id:o.connector_id,code:o.code,with_userinfo:o.with_userinfo,execute_mode:o.execute_mode,agent_type:o.agent_type,agent_version:o.agent_version};return this.request({url:i,method:"POST",data:s},t)}SubmitAppOboInstallationReview(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/submit_app_obo_installation_review"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}InstallAppObo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/install_app_obo"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}UninstallAppObo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/uninstall_app_obo"),s={appid:o.appid,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetChecklistForWorkspaceMigration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/get_checklist_for_workspace_migration"),s={workspace_id_list:o.workspace_id_list};return this.request({url:i,method:"POST",data:s},t)}CheckEnterpriseExist(e,t){const o=this.genBaseURL("/api/permission_api/enterprise/check_enterprise_exist");return this.request({url:o,method:"GET"},t)}GetSSOSetting(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_sso_setting"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}BatchMigrateAuthorization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/app/batch_migrate_authorization"),s={authorization_list:o.authorization_list,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_invitation"),s={invitation_status:o.invitation_status,enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}RevokeJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/revoke_join_invitation"),s={enterprise_id:o.enterprise_id,join_invitation_id:o.join_invitation_id};return this.request({url:i,method:"POST",data:s},t)}UpdateJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_invitation"),s={enterprise_id:o.enterprise_id,join_invitation_id:o.join_invitation_id,joined:o.joined};return this.request({url:i,method:"POST",data:s},t)}GetJoinInvitation(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_join_invitation"),s={join_invitation_id:o.join_invitation_id};return this.request({url:i,method:"POST",data:s},t)}SearchPeopleInOtherEnterprise(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_people_in_other_enterprise"),s={enterprise_id:o.enterprise_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}CreateApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_application_for_enterprise_member"),s={enterprise_id:o.enterprise_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}GetApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_application_for_enterprise_member"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}AuthorizeAppsAndPersonalaccesstokenListWithPersonalAccountPermission(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/authorize_apps_and_patlist_with_personalaccountpermission"),s={crossaccount_authinfo_list:o.crossaccount_authinfo_list};return this.request({url:i,method:"POST",data:s},t)}RevokeAppAndPersonalaccesstokenPersonalAccountPermission(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/revoke_app_and_pat_personalaccountpermission"),s={crossaccount_authinfo:o.crossaccount_authinfo};return this.request({url:i,method:"POST",data:s},t)}GetAppsAndPersonalAccessTokenListForPersonalAccountPermissionAuthorization(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/app/get_apps_and_patlist_for_personalaccountpermission_authorization"),s={page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}create_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/create_service_identity"),s={name:o.name,organization_id:o.organization_id,expire_at:o.expire_at,duration_day:o.duration_day,permission:o.permission},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}get_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/get_service_identity"),s={id:o.id};return this.request({url:i,method:"GET",params:s},t)}update_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/update_service_identity"),s={permission:o.permission,id:o.id,name:o.name,expire_at:o.expire_at,duration_day:o.duration_day},n={"x-tt-env":o["x-tt-env"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}delete_service_identity(e,t){const o=e,i=this.genBaseURL("/api/permission_api/service/delete_service_identity"),s={id:o.id};return this.request({url:i,method:"POST",params:s},t)}list_service_identities(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/service/list_service_identities"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}ListEncryptionConfiguration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterpise/list_encryption_configuration"),s={organization_id:o.organization_id};return this.request({url:i,method:"GET",params:s},t)}UpdateEncryptionConfiguration(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/enterpise/update_encryption_configuration"),s={encryption_configuration:o.encryption_configuration};return this.request({url:i,method:"POST",data:s},t)}SearchOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_organization"),s={enterprise_id:o.enterprise_id,search_key:o.search_key,joined:o.joined,need_people_number:o.need_people_number,need_workspace_number:o.need_workspace_number,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}CreateOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_organization"),s={enterprise_id:o.enterprise_id,name:o.name,icon_uri:o.icon_uri,description:o.description};return this.request({url:i,method:"POST",data:s},t)}GetOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization"),s={organization_id:o.organization_id,name:o.name,icon_uri:o.icon_uri,description:o.description};return this.request({url:i,method:"POST",data:s},t)}SearchCanAddOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_can_add_organization_people"),s={organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}SearchOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/search_organization_people"),s={organization_role_type:o.organization_role_type,people_type:o.people_type,organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size,organization_role_type_list:o.organization_role_type_list};return this.request({url:i,method:"POST",data:s},t)}CreateJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/create_join_organization_application"),s={organization_id:o.organization_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}ListJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/list_join_organization_application"),s={application_status:o.application_status,organization_id:o.organization_id,search_key:o.search_key,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}UpdateJoinOrganizationApplication(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_join_organization_application"),s={application_status:o.application_status,organization_id:o.organization_id,join_application_id_list:o.join_application_id_list};return this.request({url:i,method:"POST",data:s},t)}GetOrganizationApplicationForEnterpriseMember(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization_application_for_enterprise_member"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}CanCustomEncryptionConfiguration(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterpise/can_custom_encryption_configuration"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"GET",params:s},t)}BatchAddOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_add_organization_people"),s={organization_id:o.organization_id,organization_people:o.organization_people};return this.request({url:i,method:"POST",data:s},t)}RemoveOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/remove_organization_people"),s={organization_id:o.organization_id,user_id:o.user_id,receiver:o.receiver};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization_people"),s={organization_role_type:o.organization_role_type,organization_id:o.organization_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}DownloadRemoteAttestationEvidence(e,t){const o=e,i=this.genBaseURL("/api/permission_api/aicc/download_remote_attestation_evidence"),s={component_name:o.component_name};return this.request({url:i,method:"GET",params:s},t)}GetAgentAiccInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/aicc/get_agent_aicc_info"),s={agent_id:o.agent_id};return this.request({url:i,method:"GET",params:s},t)}CheckDeleteOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/check_delete_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DeleteOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/delete_organization"),s={organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}ListProjectUsers(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/list_project_users"),s={project_id:o.project_id,page_size:o.page_size,page_number:o.page_number,environment:o.environment,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectUser(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user"),s={environment:o.environment,project_id:o.project_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}GetProjectAuthConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}UpdateProjectAuthConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config"),s={project_id:o.project_id,configuration:o.configuration};return this.request({url:i,method:"POST",data:s},t)}ListProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/list_project_secret"),s={env:o.env,project_id:o.project_id,with_providers:o.with_providers,deploy_id:o.deploy_id,option:o.option};return this.request({url:i,method:"POST",data:s},t)}UpdateProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/update_project_secret"),s={project_id:o.project_id,update_secrets:o.update_secrets,update_cred_provider:o.update_cred_provider};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/delete_project_secret"),s={project_id:o.project_id,keys:o.keys,cred_provider_ids:o.cred_provider_ids};return this.request({url:i,method:"POST",data:s},t)}EncryptProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/encrypt_project_secret"),s={project_id:o.project_id,project_type:o.project_type,encrypt_secrets:o.encrypt_secrets};return this.request({url:i,method:"POST",data:s},t)}InsertProjectSecret(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/insert_project_secret"),s={project_id:o.project_id,insert_secrets:o.insert_secrets};return this.request({url:i,method:"POST",data:s},t)}OutboundAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/outbound_auth/callback"),s={session_id:o.session_id,error:o.error};return this.request({url:i,method:"GET",params:s},t)}CreateAgentAccessToken(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:o.project_id,deployment_env:o.deployment_env};return this.request({url:i,method:"POST",data:s},t)}ListAgentAccessTokens(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}DeleteAgentAccessToken(e,t){const o=e,i=this.genBaseURL("/api/permission_api/inbound_auth/agent_access_token"),s={token_id:o.token_id,project_id:o.project_id};return this.request({url:i,method:"DELETE",data:s},t)}GenerateInviteCode(e,t){const o=this.genBaseURL("/api/permission_api/coze_user/generate_invite_code");return this.request({url:o,method:"POST"},t)}GetInviteCodeInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/coze_user/get_invite_code_info"),s={invite_code:o.invite_code};return this.request({url:i,method:"GET",params:s},t)}AuthorizeCredProvider(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/authorize"),s={provider_id:o.provider_id};return this.request({url:i,method:"GET",params:s},t)}ProjectSecretAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/project_secret/callback"),s={code:o.code,state:o.state,error:o.error};return this.request({url:i,method:"GET",params:s},t)}ListAuthInfo(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/list_auth_info"),s={credential_ids:o.credential_ids};return this.request({url:i,method:"POST",data:s},t)}RevokeAuthorization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/project_secret/revoke"),s={credential_id:o.credential_id};return this.request({url:i,method:"POST",data:s},t)}UpdateProjectAuthConfigV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/update_project_auth_config_v2"),s={environment:o.environment,project_id:o.project_id,configuration:o.configuration};return this.request({url:i,method:"POST",data:s},t)}DeleteProjectUserV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/delete_project_user_v2"),s={environment:o.environment,project_id:o.project_id,user_id:o.user_id};return this.request({url:i,method:"POST",data:s},t)}VisibilityConfig(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/visibility_config"),s={enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoLoginMaskedMobile(e,t){const o=this.genBaseURL("/api/permission_api/volcano/get_volcano_login_masked_mobile");return this.request({url:o,method:"GET"},t)}ListProjectUsersV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/list_project_users_v2"),s={environment:o.environment,project_id:o.project_id,page_size:o.page_size,page_number:o.page_number,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}GetProjectAuthConfigV2(e,t){const o=e,i=this.genBaseURL("/api/permission_api/auth_integration/get_project_auth_config_v2"),s={environment:o.environment,project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}BatchGetPeopleJoinedOrganization(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_get_people_joined_organization"),s={enterprise_id:o.enterprise_id,user_ids:o.user_ids};return this.request({url:i,method:"POST",data:s},t)}BatchRemoveOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_remove_organization_people"),s={enterprise_id:o.enterprise_id,remove_user_list:o.remove_user_list};return this.request({url:i,method:"POST",data:s},t)}BatchRemoveEnterprisePeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_remove_enterprise_people"),s={enterprise_id:o.enterprise_id,remove_user_list:o.remove_user_list};return this.request({url:i,method:"POST",data:s},t)}GetOrganizationSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/get_organization_settings"),s={organization_id:o.organization_id,organization_setting_key_list:o.organization_setting_key_list};return this.request({url:i,method:"POST",data:s},t)}UpdateOrganizationSettings(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/update_organization_settings"),s={organization_id:o.organization_id,organization_settings:o.organization_settings};return this.request({url:i,method:"POST",data:s},t)}GithubAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/permission_api/github_auth/callback"),s={code:o.code,state:o.state,error:o.error};return this.request({url:i,method:"GET",params:s},t)}BatchListOrganizationPeople(e,t){const o=e,i=this.genBaseURL("/api/permission_api/enterprise/batch_list_organization_people"),s={organization_ids:o.organization_ids,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}}const Wi=new Vi({});function Hi(e,t){return null!=e?e:t()}const Ji=1e3,Ki=Math.floor(new Date("2000-01-01T00:00:00.000Z").getTime()/Ji),Qi=e=>e instanceof Error?e.message:String(e);class Yi{constructor(e){this.ctx=e,this.config=e.config}getOAuthConfig(){return{baseURL:Hi(this.config.openApiBaseUrl,(()=>l.DEFAULT_CONFIG.openApiBaseUrl)),clientId:Hi(this.config.clientId,(()=>l.DEFAULT_CONFIG.clientId))}}async clearUserContext(){this.config.organizationId=void 0,this.config.enterpriseId=void 0,this.config.spaceId=void 0,await l.saveConfig({organizationId:void 0,enterpriseId:void 0,spaceId:void 0})}openInBrowser(e){const t="darwin"===process.platform?"open":"win32"===process.platform?"cmd":"xdg-open",o="win32"===process.platform?["/c","start",'""',e]:[e],i="Failed to open browser automatically. Please open the URL manually.";try{const e=c.spawn(t,o,{detached:!0,stdio:"ignore"});e.on("error",(()=>{this.ctx.ui.verbose(i)})),e.unref()}catch(e){this.ctx.ui.verbose(`${i} ${e instanceof Error?e.message:String(e)}`)}}async clearAuthData(){this.config.accessToken=void 0,this.config.refreshToken=void 0,this.config.tokenExpiresAt=void 0,await l.saveConfig({accessToken:void 0,refreshToken:void 0,tokenExpiresAt:void 0})}async login(t){if(this.ctx.ui.verbose("Initiating login process..."),t.token)return this.ctx.ui.info("Using Personal Access Token (PAT)..."),this.config.accessToken=t.token,await l.saveConfig({accessToken:t.token,refreshToken:void 0,tokenExpiresAt:void 0}),await this.clearUserContext(),this.ctx.ui.info("Authentication successful. Credentials saved."),void("json"===this.ctx.format&&this.ctx.response.print({success:!0,method:"PAT"}));try{this.ctx.ui.info("Starting OAuth flow...");const{baseURL:t,clientId:i}=this.getOAuthConfig();this.ctx.ui.verbose("Starting OAuth device flow...");const s=await async function(e){const t=e.workspaceId?`/api/permission/oauth2/workspace_id/${e.workspaceId}/device/code`:"/api/permission/oauth2/device/code";return(await xo.post(t,{client_id:e.clientId},{baseURL:e.baseURL})).data}({baseURL:t,clientId:i}),n=`${s.verification_uri}?user_code=${s.user_code}`;this.ctx.ui.info(`Please visit ${o.underline(n)} and authorize the application.\n\nPrivacy Policy: ${o.underline("https://docs.coze.cn/guides/privacy")}\nTerms of Service: ${o.underline("https://docs.coze.cn/guides/terms-of-service")}\n\nIf you are an agent using Coze CLI, please share the authorization link,\nPrivacy Policy, and Terms of Service with your users.\n `),this.openInBrowser(n);const r=await async function(t,o){if(!t.poll)return Lo(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 Lo(t);return o.ui.debug(`Polling for device token success: ${JSON.stringify(e)}`),e}catch(t){if(e.isHttpError(t)){const e=t;o.ui.debug(`Polling for device token error, the error is a HttpError.\n logid: ${To([e,"access",e=>e.response,"optionalAccess",e=>e.headers,"access",e=>e["x-tt-logid"]])}`),o.ui.debug(`Polling for device token error: ${JSON.stringify(ko(To([e,"access",e=>e.toJSON,"optionalCall",e=>e()]),(()=>e)))}`);const s=e.data;if(To([s,"optionalAccess",e=>e.error])===zo.AUTHORIZATION_PENDING){o.ui.debug("Polling for device token: user has not completed authorization yet."),await Ro(i);continue}if(To([s,"optionalAccess",e=>e.error])===zo.SLOW_DOWN){i<3e4&&(i+=5e3),o.ui.debug(`Polling for device token: client is polling too frequently. Increasing interval to ${i}ms`),await Ro(i);continue}}const s=t;throw o.ui.debug(`Polling for device token error, the error is: ${s.message}\n ${s.stack}\n `),t}}({baseURL:t,clientId:i,deviceCode:s.device_code,poll:!0},this.ctx);this.ctx.ui.debug(`Polling for device token success: ${JSON.stringify(r)}`),await this.saveOAuthToken(r),this.ctx.ui.debug("Saving OAuth token successfully."),await this.clearUserContext(),this.ctx.ui.info("Authentication successful. Credentials saved."),"json"===this.ctx.format&&this.ctx.response.print({success:!0,method:"OAuth"})}catch(e){throw this.ctx.ui.error(`OAuth login failed: ${Qi(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 Wi.GetUserProfile({},{baseURL:this.config.openApiBaseUrl}),s={logged_in:!0,user:i,token_expires_at:t?new Date(t).toISOString():o?void 0:"Never (PAT)"};this.ctx.response.print(s)}async getValidAccessToken(){const{accessToken:e,refreshToken:t,tokenExpiresAt:o}=this.config;if(e){if(!t)return e;if((e=>{if(!e)return!1;const t=Date.now();return!(e-t>316224e5)&&t<e-3e5})(o))return e;this.ctx.ui.verbose("Access token is expired or expiring soon, refreshing...");try{const{baseURL:e,clientId:o}=this.getOAuthConfig(),i=await async function(e){const t={};return e.clientSecret&&(t.Authorization=`Bearer ${e.clientSecret}`),(await xo.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: ${Qi(e)}`),void await this.clearAuthData()}}}async saveOAuthToken(e){const t=(o=e.expires_in)>=Ki?o*Ji:Date.now()+o*Ji;var o;this.config.accessToken=e.access_token,this.config.refreshToken=e.refresh_token,this.config.tokenExpiresAt=t,await l.saveConfig({accessToken:e.access_token,refreshToken:e.refresh_token,tokenExpiresAt:t})}}const Zi="",Xi="",es="",ts="",os="",is="",ss="",ns="",rs="[PROC]",as="[INFO]",cs="[WARN]",ls="[ERR]",ds="[DONE]",ps="[DBG]",us={debug:0,verbose:1,info:2,success:3,warn:4,error:5};function ms(e){return`${es}${Xi}${e}${Zi}`}class gs{constructor(e,t,o="info"){var i,s;this.log=e,this.silent="json"===t,this.useColor=this.detectColorSupport(),this.level=o,this.levelPriority=(s=()=>2,null!=(i=us[o])?i:s())}detectColorSupport(){return!0===function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([process,"access",e=>e.stderr,"optionalAccess",e=>e.isTTY])&&void 0===process.env.NO_COLOR}paint(e,t){return this.useColor?`${e}${t}${Zi}`:t}shouldOutput(e){return!this.silent&&us[e]>=this.levelPriority}verbose(e,...t){this.log.verbose(e,...t),this.shouldOutput("verbose")&&process.stderr.write(`${ms(rs)} ${this.paint(ss,e)}\n`)}info(e,...t){this.log.info(e,...t),this.shouldOutput("info")&&process.stderr.write(`${ms(as)} ${this.paint(Zi,e)}\n`)}warn(e,...t){this.log.warn(e,...t),this.shouldOutput("warn")&&process.stderr.write(`${ms(cs)} ${this.paint(is,e)}\n`)}error(e,...t){this.log.error(e,...t),this.shouldOutput("error")&&process.stderr.write(`${ms(ls)} ${this.paint(ts,e)}\n`)}success(e,...t){this.log.success(e,...t),this.shouldOutput("success")&&process.stderr.write(`${ms(ds)} ${this.paint(os,e)}\n`)}debug(e,...t){this.log.debug(e,...t),this.shouldOutput("debug")&&process.stderr.write(`${ms(ps)} ${this.paint(ns,e)}\n`)}}class hs{constructor(e){const{format:t}=e;this.formatter=function(e){return"text"===e?new U:new I}(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 fs(e,t){return null!=e?e:t()}async function _s(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 ys,bs,vs,ws,Cs,Es,Is,As,Ss,js,Ps,ks,Ts,zs,Rs,xs,Ls,Os,Ds,Us,Bs,qs,Ms,Ns,$s,Gs,Fs,Vs,Ws,Hs,Js,Ks,Qs,Ys,Zs,Xs,en,tn,on,sn,nn,rn,an,cn,ln,dn,pn,un,mn,gn,hn,fn,_n,yn,bn,vn,wn,Cn,En,In,An,Sn,jn,Pn,kn,Tn,zn,Rn,xn,Ln,On,Dn,Un,Bn,qn,Mn,Nn,$n,Gn,Fn,Vn,Wn,Hn,Jn,Kn,Qn,Yn,Zn,Xn,er,tr,or,ir,sr,nr,rr,ar,cr,lr,dr,pr,ur,mr,gr,hr,fr,_r,yr,br,vr,wr,Cr,Er,Ir,Ar,Sr,jr,Pr,kr,Tr,zr,Rr,xr,Lr,Or,Dr,Ur,Br,qr,Mr,Nr;function $r(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!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"}(ys||(ys={})),function(e){e[e.OldVersion=0]="OldVersion";e[e.MiddleVersion=1]="MiddleVersion";e[e.NewVersion=2]="NewVersion";e[e.MiddleVersionNotPrompt=3]="MiddleVersionNotPrompt"}(bs||(bs={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(vs||(vs={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(ws||(ws={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Cs||(Cs={})),function(e){e[e.Current=1]="Current";e[e.Previous=2]="Previous";e[e.Start=3]="Start";e[e.MostSuitable=4]="MostSuitable"}(Es||(Es={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(Is||(Is={})),function(e){e[e.Default=0]="Default";e[e.Function=1]="Function"}(As||(As={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned"}(Ss||(Ss={})),function(e){e[e.LimitedReadWrite=1]="LimitedReadWrite";e[e.ReadOnly=2]="ReadOnly";e[e.UnlimitedReadWrite=3]="UnlimitedReadWrite";e[e.RWModeMax=4]="RWModeMax"}(js||(js={})),function(e){e[e.Default=0]="Default";e[e.DouyinAvatar=1]="DouyinAvatar"}(Ps||(Ps={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(ks||(ks={})),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"}(Ts||(Ts={})),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"}(zs||(zs={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Rs||(Rs={})),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"}(xs||(xs={})),function(e){e[e.Off=0]="Off";e[e.On=1]="On"}(Ls||(Ls={})),function(e){e[e.SLM=0]="SLM";e[e.LLM=1]="LLM"}(Os||(Os={})),function(e){e[e.Pre=1]="Pre";e[e.Post=2]="Post";e[e.PreAndPost=3]="PreAndPost"}(Ds||(Ds={})),function(e){e[e.Default=0]="Default";e[e.CustomizePrompt=1]="CustomizePrompt"}(Us||(Us={})),function(e){e[e.ReplyBottom=0]="ReplyBottom";e[e.CardList=1]="CardList"}(Bs||(Bs={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(qs||(qs={})),function(e){e[e.Coze=0]="Coze";e[e.Volcano=1]="Volcano";e[e.ThirdParty=2]="ThirdParty"}(Ms||(Ms={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(Ns||(Ns={})),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"}($s||($s={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(Gs||(Gs={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(Fs||(Fs={})),function(e){e[e.Curve=0]="Curve";e[e.Straight=1]="Straight"}(Vs||(Vs={})),function(e){e[e.Flow=1]="Flow";e[e.Host=2]="Host"}(Ws||(Ws={})),function(e){e[e.NO_NEED=1]="NO_NEED";e[e.USE_MANUAL=2]="USE_MANUAL";e[e.USE_LLM=3]="USE_LLM"}(Hs||(Hs={})),function(e){e[e.EQUAL=1]="EQUAL";e[e.NOT_EQUAL=2]="NOT_EQUAL";e[e.GREATER_THAN=3]="GREATER_THAN";e[e.LESS_THAN=4]="LESS_THAN";e[e.GREATER_EQUAL=5]="GREATER_EQUAL";e[e.LESS_EQUAL=6]="LESS_EQUAL";e[e.IN=7]="IN";e[e.NOT_IN=8]="NOT_IN";e[e.IS_NULL=9]="IS_NULL";e[e.IS_NOT_NULL=10]="IS_NOT_NULL";e[e.LIKE=11]="LIKE";e[e.NOT_LIKE=12]="NOT_LIKE"}(Js||(Js={})),function(e){e[e.Input=0]="Input";e[e.Variable=1]="Variable"}(Ks||(Ks={})),function(e){e[e.Default=0]="Default";e[e.FromSaas=1]="FromSaas"}(Qs||(Qs={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(Ys||(Ys={})),function(e){e[e.FunctionCall=1]="FunctionCall";e[e.Independent=2]="Independent"}(Zs||(Zs={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(Xs||(Xs={})),function(e){e[e.ManualUpdate=1]="ManualUpdate";e[e.AutoUpdate=2]="AutoUpdate"}(en||(en={})),function(e){e[e.SemanticSearch=0]="SemanticSearch";e[e.HybirdSearch=1]="HybirdSearch";e[e.FullTextSearch=20]="FullTextSearch"}(tn||(tn={})),function(e){e[e.Public=1]="Public";e[e.Anonymous=2]="Anonymous";e[e.Custom=3]="Custom"}(on||(on={})),function(e){e[e.Random=0]="Random";e[e.All=1]="All"}(sn||(sn={})),function(e){e[e.System=0]="System";e[e.Custom=1]="Custom";e[e.Disable=2]="Disable";e[e.OriBot=3]="OriBot"}(nn||(nn={})),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"}(rn||(rn={})),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"}(cn||(cn={})),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"}(ln||(ln={})),function(e){e[e.BotQuery=1]="BotQuery";e[e.Plugin=2]="Plugin";e[e.Workflow=3]="Workflow"}(dn||(dn={})),function(e){e[e.Unknown=0]="Unknown";e[e.Webhook=1]="Webhook"}(pn||(pn={})),function(e){e[e.Unknown=0]="Unknown";e[e.Time=1]="Time";e[e.Event=2]="Event"}(un||(un={})),function(e){e[e.NoHistory=0]="NoHistory";e[e.NeedHistory=1]="NeedHistory"}(mn||(mn={})),function(e){e[e.NoTriggered=0]="NoTriggered";e[e.Triggered=1]="Triggered";e[e.DoAction=2]="DoAction";e[e.WaitToPush=3]="WaitToPush";e[e.PushSuccess=4]="PushSuccess";e[e.PushFail=5]="PushFail"}(gn||(gn={})),function(e){e[e.Init=0]="Init";e[e.Activated=1]="Activated";e[e.Deactivated=2]="Deactivated";e[e.Suspended=3]="Suspended"}(hn||(hn={})),function(e){e[e.Preset=1]="Preset";e[e.UserTask=2]="UserTask";e[e.PluginRunTask=3]="PluginRunTask"}(fn||(fn={})),function(e){e[e.Deploying=0]="Deploying";e[e.Successful=1]="Successful";e[e.Failed=2]="Failed"}(_n||(_n={})),function(e){e[e.All=0]="All";e[e.Bind=1]="Bind";e[e.UnBind=2]="UnBind"}(yn||(yn={})),function(e){e[e.CreateTime=0]="CreateTime";e[e.UpdateTime=1]="UpdateTime"}(bn||(bn={})),function(e){e[e.EventMeta=1]="EventMeta";e[e.ProfileMeta=2]="ProfileMeta"}(vn||(vn={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(wn||(wn={})),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"}(Cn||(Cn={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}(En||(En={})),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"}(In||(In={})),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"}(An||(An={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(Sn||(Sn={})),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"}(jn||(jn={})),function(e){e[e.Upgrade=1]="Upgrade";e[e.BrowseOldNoPrompt=2]="BrowseOldNoPrompt"}(Pn||(Pn={})),function(e){e[e.Default=1]="Default";e[e.Customize=2]="Customize"}(kn||(kn={})),function(e){e[e.Direct=1]="Direct";e[e.WebView=2]="WebView";e[e.SendMessage=3]="SendMessage"}(Tn||(Tn={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(zn||(zn={})),function(e){e[e.Visit=1]="Visit";e[e.Edit=2]="Edit"}(Rn||(Rn={})),function(e){e[e.Online=1]="Online";e[e.Offline=2]="Offline"}(xn||(xn={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online"}(Ln||(Ln={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(On||(On={})),function(e){e[e.AutoGenBeforePublish=1]="AutoGenBeforePublish"}(Dn||(Dn={})),function(e){e[e.CozeHome=1]="CozeHome";e[e.Space=2]="Space"}(Un||(Un={})),function(e){e[e.Undefined=0]="Undefined";e[e.PersonalDraft=1]="PersonalDraft";e[e.Base=2]="Base";e[e.Publish=3]="Publish"}(Bn||(Bn={})),function(e){e[e.Undefined=0]="Undefined";e[e.Committed=1]="Committed";e[e.Behind=2]="Behind";e[e.NoDraftReplica=3]="NoDraftReplica"}(qn||(qn={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(Mn||(Mn={})),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"}(Nn||(Nn={})),function(e){e[e.Personal=1]="Personal";e[e.Organization=2]="Organization"}($n||($n={})),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"}(Gn||(Gn={})),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"}(Fn||(Fn={})),function(e){e[e.Deleted=0]="Deleted";e[e.Using=1]="Using";e[e.Banned=2]="Banned";e[e.MoveFail=3]="MoveFail"}(Vn||(Vn={})),function(e){e[e.ByteTree=1]="ByteTree";e[e.GPTAK=2]="GPTAK";e[e.MaasAK=3]="MaasAK"}(Wn||(Wn={})),function(e){e[e.Init=0]="Init";e[e.Generating=1]="Generating";e[e.Success=2]="Success";e[e.Fail=3]="Fail";e[e.Cancel=4]="Cancel"}(Hn||(Hn={})),function(e){e[e.BotStore=1]="BotStore"}(Jn||(Jn={})),function(e){e[e.shorcutIcon=1]="shorcutIcon"}(Kn||(Kn={})),function(e){e[e.Onboarding=0]="Onboarding";e[e.BackgroundImage=1]="BackgroundImage"}(Qn||(Qn={})),function(e){e[e.BasicUser=1]="BasicUser";e[e.ExternalUser=2]="ExternalUser";e[e.RootUser=3]="RootUser"}(Yn||(Yn={})),function(e){e[e.GetInfo=1]="GetInfo"}(Zn||(Zn={})),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"}(Xn||(Xn={})),function(e){e[e.Apply=1]="Apply";e[e.Invite=2]="Invite";e[e.EnterpriseApply=3]="EnterpriseApply"}(er||(er={})),function(e){e[e.GPT=1]="GPT";e[e.Claude=3]="Claude";e[e.Gemini=11]="Gemini";e[e.Moonshot=12]="Moonshot";e[e.GLM=13]="GLM";e[e.QWen=15]="QWen";e[e.DeekSeek=19]="DeekSeek";e[e.StepFun=23]="StepFun"}(tr||(tr={})),function(e){e[e.Douyin=1]="Douyin"}(or||(or={})),function(e){e[e.GPTOpenAPI=1]="GPTOpenAPI";e[e.Maas=2]="Maas";e[e.LLMFlow=3]="LLMFlow";e[e.Merlin=4]="Merlin"}(ir||(ir={})),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"}(sr||(sr={})),function(e){e[e.All=0]="All";e[e.Unread=1]="Unread"}(nr||(nr={})),function(e){e[e.Bot=1]="Bot"}(rr||(rr={})),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"}(ar||(ar={})),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"}(cr||(cr={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ShortcutCommand=3]="ShortcutCommand";e[e.Task=4]="Task"}(lr||(lr={})),function(e){e[e.Plugin=1]="Plugin";e[e.Workflow=2]="Workflow";e[e.ImageFlow=3]="ImageFlow";e[e.Knowledge=4]="Knowledge"}(dr||(dr={})),function(e){e[e.NoPublish=0]="NoPublish";e[e.HadPublished=1]="HadPublished"}(pr||(pr={})),function(e){e[e.Success=1]="Success";e[e.Failed=2]="Failed";e[e.InReview=3]="InReview"}(ur||(ur={})),function(e){e[e.Unread=1]="Unread";e[e.Read=2]="Read"}(mr||(mr={})),function(e){e[e.HasUpdates=1]="HasUpdates";e[e.IsDelete=2]="IsDelete"}(gr||(gr={})),function(e){e[e.UnLimit=1]="UnLimit";e[e.Forbidden=2]="Forbidden"}(hr||(hr={})),function(e){e[e.Plugin=1]="Plugin";e[e.NewBotIDEGuide=2]="NewBotIDEGuide";e[e.NewBeginnerGuide=3]="NewBeginnerGuide"}(fr||(fr={})),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"}(_r||(_r={})),function(e){e[e.All=0]="All";e[e.Self=1]="Self"}(yr||(yr={})),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"}(br||(br={})),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"}(vr||(vr={})),function(e){e[e.EnterpriseUser=1]="EnterpriseUser";e[e.ExternalUser=2]="ExternalUser"}(wr||(wr={})),function(e){e[e.Normal=0]="Normal";e[e.DevMode=1]="DevMode"}(Cr||(Cr={})),function(e){e[e.DraftBot=1]="DraftBot";e[e.Project=2]="Project";e[e.Space=3]="Space";e[e.DouyinAvatarBot=4]="DouyinAvatarBot"}(Er||(Er={})),function(e){e[e.Default=0]="Default";e[e.Owner=1]="Owner";e[e.Admin=2]="Admin";e[e.Member=3]="Member";e[e.Guest=4]="Guest"}(Ir||(Ir={})),function(e){e[e.Professional=1]="Professional"}(Ar||(Ar={})),function(e){e[e.Personal=1]="Personal";e[e.Team=2]="Team"}(Sr||(Sr={})),function(e){e[e.Dark=1]="Dark";e[e.Light=2]="Light"}(jr||(jr={})),function(e){e[e.AlwaysOn=0]="AlwaysOn";e[e.AlwaysOff=1]="AlwaysOff"}(Pr||(Pr={})),function(e){e[e.CozeAssistantGuide=1]="CozeAssistantGuide"}(kr||(kr={})),function(e){e[e.Normal=1]="Normal";e[e.Banned=2]="Banned";e[e.Canceled=3]="Canceled"}(Tr||(Tr={})),function(e){e[e.External=0]="External";e[e.Internal=1]="Internal"}(zr||(zr={})),function(e){e[e.Invisible=0]="Invisible";e[e.Visible=1]="Visible";e[e.SocietyInvisible=2]="SocietyInvisible"}(Rr||(Rr={})),function(e){e[e.SingleAgent=1]="SingleAgent";e[e.MultiAgent=2]="MultiAgent";e[e.WorkflowAsAgent=3]="WorkflowAsAgent"}(xr||(xr={})),function(e){e[e.Preset=1]="Preset";e[e.Library=2]="Library"}(Lr||(Lr={})),function(e){e[e.DatasetServiceValid=0]="DatasetServiceValid";e[e.DatasetServiceInvalid=1]="DatasetServiceInvalid"}(Or||(Or={})),function(e){e[e.DatasetValid=0]="DatasetValid";e[e.DatasetInvalid=1]="DatasetInvalid"}(Dr||(Dr={})),function(e){e[e.RootUser=1]="RootUser";e[e.BasicUser=2]="BasicUser"}(Ur||(Ur={})),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"}(Br||(Br={})),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"}(qr||(qr={})),function(e){e[e.SendTypeQuery=0]="SendTypeQuery";e[e.SendTypePanel=1]="SendTypePanel"}(Mr||(Mr={})),function(e){e[e.ToolTypeWorkFlow=1]="ToolTypeWorkFlow";e[e.ToolTypePlugin=2]="ToolTypePlugin"}(Nr||(Nr={}));class Gr{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Gr.prototype.__init.call(this),Gr.prototype.__init2.call(this),this.request=$r([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=$r([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}GetSpaceInfoV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/info"),s={space_id:o.space_id,join_space_type:o.join_space_type};return this.request({url:i,method:"POST",data:s},t)}DeleteSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/delete"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}SaveSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/save"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri,space_type:o.space_type,space_mode:o.space_mode,space_config:o.space_config,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetSpaceListV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/list"),s={search_word:o.search_word,enterprise_id:o.enterprise_id,organization_id:o.organization_id,scope_type:o.scope_type,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}UpdateAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_agent"),s={id:o.id,reference_id:o.reference_id,current_version:o.current_version,space_id:o.space_id,bot_id:o.bot_id,base_commit_version:o.base_commit_version,name:o.name,description:o.description,position:o.position,icon_uri:o.icon_uri,intents:o.intents,work_info:o.work_info,is_delete:o.is_delete};return this.request({url:i,method:"POST",data:s},t)}BatchCreateAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/batch_create_agent"),s={space_id:o.space_id,bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,agent_cnt:o.agent_cnt,base_commit_version:o.base_commit_version,version_compat:o.version_compat};return this.request({url:i,method:"POST",data:s},t)}GetPublishBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_publish_bot_list"),s={space_id:o.space_id,bot_mode:o.bot_mode,page_num:o.page_num,page_size:o.page_size,name:o.name,login_user_create:o.login_user_create,bot_id:o.bot_id};return this.request({url:i,method:"GET",params:s},t)}MGetBotByVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/mget_bot_by_version"),s={bot_versions:o.bot_versions,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}BotLastPublishInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_last_publish_info"),s={space_id:o.space_id,bot_id:o.bot_id,bot_mode:o.bot_mode};return this.request({url:i,method:"GET",params:s},t)}ProduceBot(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/produce/create_bot"),s={space_id:o.space_id,name:o.name,description:o.description,icon_url:o.icon_url,icon_uri:o.icon_uri,prompt:o.prompt,plugin_apis:o.plugin_apis,prologue:o.prologue,suggested_questions:o.suggested_questions,bot_source:o.bot_source};return this.request({url:i,method:"POST",data:s},t)}UpdateProducedBot(e,t){const o=e,i=this.genBaseURL("/api/playground_api/produce/update_bot"),s={bot_id:o.bot_id,name:o.name,description:o.description,icon_url:o.icon_url,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetPublishedBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_version/get_published_bot_list"),s={space_id_list:o.space_id_list,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}GetBotVersionInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bot_version/get_bot_version_info"),s={bot_id:o.bot_id,version:o.version,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}DuplicateBotVersionToSpace(e,t){const o=e,i=this.genBaseURL("/api/playground_api/dup_bot_version"),s={target_space_id:o.target_space_id,bot_id:o.bot_id,version:o.version,name:o.name,dup_society_host:o.dup_society_host};return this.request({url:i,method:"POST",data:s},t)}UpdateUserRiskAlertInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/update_user_risk_alert_info"),s={risk_alert_type:o.risk_alert_type,switch_info:o.switch_info};return this.request({url:i,method:"POST",data:s},t)}GetUserRiskAlertInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_user_risk_alert_info"),s={risk_alert_type_list:o.risk_alert_type_list,switch_type_list:o.switch_type_list},n={Cookie:o.Cookie};return this.request({url:i,method:"POST",data:s,headers:n},t)}DraftBotCollaboration(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/collaboration"),s={space_id:o.space_id,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}BotInfoAudit(e,t){const o=e,i=this.genBaseURL("/api/playground_api/audit/bot_info"),s={bot_id:o.bot_id,bot_audit_info:o.bot_audit_info,space_id:o.space_id,bot_mode:o.bot_mode};return this.request({url:i,method:"POST",data:s},t)}TimeCapsuleInvokeEvent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/timecapsule_invoke_event"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}InviteMemberLinkV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/invite"),s={space_id:o.space_id,team_invite_link_status:o.team_invite_link_status,func:o.func};return this.request({url:i,method:"POST",data:s},t)}SpaceMemberDetailV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/detail"),s={space_id:o.space_id,search_word:o.search_word,space_role_type:o.space_role_type,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}JoinSpaceV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/join"),s={space_id:o.space_id,join_space_type:o.join_space_type,is_reject:o.is_reject};return this.request({url:i,method:"POST",data:s},t)}UpdateSpaceMemberV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/update"),s={space_id:o.space_id,user_id:o.user_id,space_role_type:o.space_role_type};return this.request({url:i,method:"POST",data:s},t)}TransferSpaceV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/transfer"),s={space_id:o.space_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}RemoveSpaceMemberV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/remove"),s={space_id:o.space_id,remove_user_id:o.remove_user_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}SearchMemberV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/member/search"),s={search_list:o.search_list,space_id:o.space_id,search_volcano_account_list:o.search_volcano_account_list,page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}AddBotSpaceMemberV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/member/add"),s={member_info_list:o.member_info_list,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}ExitSpaceV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/member/exit"),s={space_id:o.space_id,transfer_user_id:o.transfer_user_id};return this.request({url:i,method:"POST",data:s},t)}GetBotPopupInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/operate/get_bot_popup_info"),s={bot_popup_types:o.bot_popup_types,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}UpdateBotPopupInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/operate/update_bot_popup_info"),s={bot_popup_type:o.bot_popup_type,bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}GenerateDescription(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/generate_description"),s={bot_name:o.bot_name,prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}DraftBotPublishHistoryDetail(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/publish_history_detail"),s={bot_id:o.bot_id,space_id:o.space_id,publish_id:o.publish_id,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GenerateStoreCategory(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/generate_store_category"),s={bot_name:o.bot_name,bot_description:o.bot_description,prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}UpdateMultiAgent(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_multi_agent"),s={space_id:o.space_id,bot_id:o.bot_id,session_type:o.session_type,base_commit_version:o.base_commit_version,connector_type:o.connector_type};return this.request({url:i,method:"POST",data:s},t)}SwitchAgentVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/switch_agent_version"),s={bot_id:o.bot_id,space_id:o.space_id,operate_type:o.operate_type};return this.request({url:i,method:"POST",data:s},t)}LangDetect(e,t){const o=e,i=this.genBaseURL("/api/playground_api/audio/lang/detect"),s={detect_text_list:o.detect_text_list};return this.request({url:i,method:"POST",data:s},t)}GetImagexShortUrl(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_imagex_url"),s={uris:o.uris,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetPlatformCommonConfig(e,t){const o=this.genBaseURL("/api/playground_api/get_platform_common_config");return this.request({url:o,method:"GET"},t)}CreateShortcutCommand(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/create_shortcut_command"),s={object_id:o.object_id,shortcuts:o.shortcuts};return this.request({url:i,method:"POST",data:s},t)}MGetUserBasicInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/mget_user_info"),s={user_ids:o.user_ids,need_user_status:o.need_user_status,need_enterprise_identity:o.need_enterprise_identity,need_volcano_user_name:o.need_volcano_user_name};return this.request({url:i,method:"POST",data:s},t)}BindVolcanoTrn(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/bind_volcano_trn"),s={space_id:o.space_id,trn:o.trn,account_name:o.account_name};return this.request({url:i,method:"POST",data:s},t)}UnbindVolcanoTrn(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/unbind_volcano_trn"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}RetrieveFileOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/retrieve"),s={file_id:o.file_id};return this.request({url:i,method:"GET",params:s},t)}RetrieveFileContentOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/content/retrieve"),s={file_id:o.file_id};return this.request({url:i,method:"GET",params:s},t)}UploadFileOpen(e,t){const o=e,i=this.genBaseURL("/v1/files/upload"),s={Data:o.Data},n={"Content-Type":o["Content-Type"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}BotInfoCheck(e,t){const o=e,i=this.genBaseURL("/api/playground_api/check/bot_info_check"),s={bot_id:o.bot_id,space_id:o.space_id,bot_audit_info:o.bot_audit_info};return this.request({url:i,method:"POST",data:s},t)}SupportVoiceCall(e,t){const o=e,i=this.genBaseURL("/api/playground_api/support_voice_call"),s={voice_id_list:o.voice_id_list};return this.request({url:i,method:"POST",data:s},t)}CreateUpdateShortcutCommand(e,t){const o=e,i=this.genBaseURL("/api/playground_api/create_update_shortcut_command"),s={object_id:o.object_id,space_id:o.space_id,shortcuts:o.shortcuts};return this.request({url:i,method:"POST",data:s},t)}MoveDraftBot(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/move_draft_bot"),s={bot_id:o.bot_id,target_spaceId:o.target_spaceId,from_spaceId:o.from_spaceId,move_action:o.move_action};return this.request({url:i,method:"POST",data:s},t)}GetShortcutAvailNodes(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_shortcut_avail_nodes"),s={bot_id:o.bot_id,space_id:o.space_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}MarkReadNotice(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/mark_read_notice"),s={bot_id:o.bot_id,pic_type:o.pic_type};return this.request({url:i,method:"POST",data:s},t)}CancelGenerateGif(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/cancel_generate_gif"),s={task_id:o.task_id};return this.request({url:i,method:"POST",data:s},t)}GetPicTask(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gen_img/get_pic_task"),s={bot_id:o.bot_id,pic_type:o.pic_type};return this.request({url:i,method:"POST",data:s},t)}GeneratePic(e,t){const o=e,i=this.genBaseURL("/api/playground_api/gen_img/generate_pic"),s={gen_prompt:o.gen_prompt,image_url:o.image_url,image_uri:o.image_uri,bot_id:o.bot_id,pic_type:o.pic_type,device_id:o.device_id,bot_name:o.bot_name,bot_desc:o.bot_desc};return this.request({url:i,method:"POST",data:s},t)}GetGenPicTimes(e,t){const o=this.genBaseURL("/api/playground_api/gen_img/get_gen_pic_times");return this.request({url:o,method:"POST"},t)}ListStyle(e,t){const o=this.genBaseURL("/api/playground_api/gen_img/list_style");return this.request({url:o,method:"POST"},t)}GetFileUrls(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_file_list"),s={scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetDraftBotInfoAgw(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/get_draft_bot_info"),s={bot_id:o.bot_id,version:o.version,commit_version:o.commit_version};return this.request({url:i,method:"POST",data:s},t)}CommitDraftBotInfoAgw(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/commit_draft_bot_info"),s={bot_id:o.bot_id,remark:o.remark};return this.request({url:i,method:"POST",data:s},t)}UpdateDraftBotInfoAgw(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/update_draft_bot_info"),s={bot_info:o.bot_info,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}GetUserQueryCollectOption(e,t){const o=this.genBaseURL("/api/playground_api/draftbot/get_user_query_collect_option");return this.request({url:o,method:"GET"},t)}GenerateUserQueryCollectPolicy(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/generate_user_query_collect_policy"),s={bot_id:o.bot_id,developer_name:o.developer_name,contact_information:o.contact_information};return this.request({url:i,method:"POST",data:s},t)}GetCozeProRights(e,t){const o=this.genBaseURL("/api/playground_api/get_coze_pro_rights");return this.request({url:o,method:"POST"},t)}GetPolicyContent(e,t){const o=e,i=this.genBaseURL(`/api/playground_api/private_policy/${o.secret}`);return this.request({url:i,method:"GET"},t)}UpdateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/update_agent_v2"),s={id:o.id,reference_id:o.reference_id,current_version:o.current_version,space_id:o.space_id,bot_id:o.bot_id,base_commit_version:o.base_commit_version,name:o.name,description:o.description,position:o.position,icon_uri:o.icon_uri,intents:o.intents,is_delete:o.is_delete,prompt_info:o.prompt_info,model_info:o.model_info,plugin_info_list:o.plugin_info_list,knowledge:o.knowledge,workflow_info_list:o.workflow_info_list,jump_config:o.jump_config,suggest_reply_info:o.suggest_reply_info,hook_info:o.hook_info};return this.request({url:i,method:"POST",data:s},t)}CopyAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/copy_agent_v2"),s={bot_id:o.bot_id,agent_id:o.agent_id,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}CreateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/create_agent_v2"),s={bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}BatchCreateAgentV2(e,t){const o=e,i=this.genBaseURL("/api/playground_api/batch_create_agent_v2"),s={bot_id:o.bot_id,agent_type:o.agent_type,position:o.position,references:o.references,agent_cnt:o.agent_cnt,base_commit_version:o.base_commit_version};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyGetLinkMetaInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/get_link_meta_info"),s={auth_code:o.auth_code};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyTaskConfirm(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/copy_task_confirm"),s={auth_code:o.auth_code};return this.request({url:i,method:"POST",data:s},t)}CozeProCopyGenerateAuthLink(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/generate_auth_link"),s={copy_user_id:o.copy_user_id,target_space_id:o.target_space_id};return this.request({url:i,method:"POST",data:s},t)}GetOpVoiceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_op_voice_list"),s={voice_ids:o.voice_ids,name:o.name,style_id:o.style_id,language_code:o.language_code,status:o.status,page_index:o.page_index,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetSupportLanguage(e,t){const o=this.genBaseURL("/api/playground_api/get_support_language");return this.request({url:o,method:"GET"},t)}SynchronizeVoiceList(e,t){const o=this.genBaseURL("/api/playground_api/synchronize_voice_list");return this.request({url:o,method:"GET"},t)}CheckBotAllModelPluginIds(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/check_bot_all_model_plugin_ids"),s={bot_id:o.bot_id,commit_version:o.commit_version};return this.request({url:i,method:"POST",data:s},t)}GetBotCollaborationQuota(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/collaboration_quota"),s={bot_id:o.bot_id,only_config_item:o.only_config_item,account_type:o.account_type};return this.request({url:i,method:"POST",data:s},t)}OpenCreateSpace(e,t){const o=e||{},i=this.genBaseURL("/v1/workspaces"),s={name:o.name,description:o.description,icon_file_id:o.icon_file_id,coze_account_id:o.coze_account_id,owner_uid:o.owner_uid};return this.request({url:i,method:"POST",data:s},t)}NoticeMarkRead(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/notice/mark_read"),s={notice_ids:o.notice_ids,mark_all:o.mark_all};return this.request({url:i,method:"POST",data:s},t)}GetNoticeList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/notice/get_list"),s={cursor:o.cursor,count:o.count,notice_rank_type:o.notice_rank_type};return this.request({url:i,method:"POST",data:s},t)}GetNoticeUnreadCount(e,t){const o=this.genBaseURL("/api/playground_api/notice/get_unread_count");return this.request({url:o,method:"POST"},t)}OpenSpaceList(e,t){const o=e||{},i=this.genBaseURL("/v1/workspaces"),s={page_num:o.page_num,page_size:o.page_size,enterprise_id:o.enterprise_id,user_id:o.user_id,coze_account_id:o.coze_account_id,scope:o.scope};return this.request({url:i,method:"GET",params:s},t)}ReportUserBehavior(e,t){const o=e,i=this.genBaseURL("/api/playground_api/report_user_behavior"),s={resource_id:o.resource_id,resource_type:o.resource_type,behavior_type:o.behavior_type,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_user_config"),s={risk_alert_type_list:o.risk_alert_type_list,switch_type_list:o.switch_type_list},n={Cookie:o.Cookie};return this.request({url:i,method:"POST",data:s,headers:n},t)}UpdateUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/update_user_config"),s={risk_alert_type:o.risk_alert_type,switch_info:o.switch_info};return this.request({url:i,method:"POST",data:s},t)}GetRecentDraftBotList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/draftbot/get_recent_draft_bot"),s={behavior_type:o.behavior_type,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}GetPromptResourceInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_prompt_resource_info"),s={prompt_resource_id:o.prompt_resource_id};return this.request({url:i,method:"GET",params:s},t)}UpsertPromptResource(e,t){const o=e,i=this.genBaseURL("/api/playground_api/upsert_prompt_resource"),s={prompt:o.prompt};return this.request({url:i,method:"POST",data:s},t)}DeletePromptResource(e,t){const o=e,i=this.genBaseURL("/api/playground_api/delete_prompt_resource"),s={prompt_resource_id:o.prompt_resource_id};return this.request({url:i,method:"POST",data:s},t)}GetPromptReferenceInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/get_prompt_reference_info"),s={space_id:o.space_id,reference_id:o.reference_id,reference_type:o.reference_type,api_id:o.api_id,project_id:o.project_id,avatar_bot_id:o.avatar_bot_id};return this.request({url:i,method:"POST",data:s},t)}GetOfficialPromptResourceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_official_prompt_list"),s={keyword:o.keyword};return this.request({url:i,method:"POST",data:s},t)}GetByteTreeByName(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/search_byte_tree"),s={name:o.name},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}CreatePrivateModel(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/create_private_model"),s={space_id:o.space_id,model_vendor:o.model_vendor,model_show_name:o.model_show_name,model_arch:o.model_arch,ak:o.ak,token_limit:o.token_limit,upper_limit_of_max_token:o.upper_limit_of_max_token,function_call:o.function_call,multimodal:o.multimodal,multimodal_types:o.multimodal_types,form_detail:o.form_detail,record_id:o.record_id,maas_model_name:o.maas_model_name,maas_model_version:o.maas_model_version,maas_model_customer_id:o.maas_model_customer_id,model_family:o.model_family,space_id_i18n:o.space_id_i18n,operator:o.operator,email:o.email,employee_id:o.employee_id,presence_penalty_config:o.presence_penalty_config,frequency_penalty_config:o.frequency_penalty_config,temperature_config:o.temperature_config,top_p_config:o.top_p_config},n={"x-inner-auth":o["x-inner-auth"],"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}CheckExemptFormInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/check_exempt_form_info"),s={exempt_form_type:o.exempt_form_type,space_id:o.space_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}SetByteTreeForSpace(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/bpm/set_byte_tree_for_space"),s={space_id:o.space_id,byte_tree_node_id:o.byte_tree_node_id,byte_tree_node_name:o.byte_tree_node_name,form_detail:o.form_detail,record_id:o.record_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetModelCapability(e,t){const o=e,i=this.genBaseURL("/api/playground_api/bpm/get_model_capability"),s={vendor:o.vendor,model_arch:o.model_arch,maas_model_name:o.maas_model_name,maas_model_version:o.maas_model_version,maas_customer_id:o.maas_customer_id},n={"x-jwt-token":o["x-jwt-token"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetSpaceDetail(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/detail"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}RevocateSpaceInvite(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/revocate_invite"),s={space_id:o.space_id,invite_user_id:o.invite_user_id};return this.request({url:i,method:"GET",params:s},t)}SaveVolcanoUserManageInfo(e,t){const o=e,i=this.genBaseURL("/api/playground_api/coze_pro/save_volcano_user_manage_info"),s={volcano_basic_user_config:o.volcano_basic_user_config};return this.request({url:i,method:"POST",data:s},t)}GetVolcanoUserManageInfo(e,t){const o=this.genBaseURL("/api/playground_api/coze_pro/get_volcano_user_manage_info");return this.request({url:o,method:"POST"},t)}GetSpaceInviteManageList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/invite_manage_list"),s={space_id:o.space_id,space_invite_status:o.space_invite_status,search_word:o.search_word,page:o.page,size:o.size};return this.request({url:i,method:"GET",params:s},t)}DebugDouYin(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/debug"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}GetDouYinAuthCode(e,t){const o=this.genBaseURL("/api/playground_api/douyin/get_auth_qr_code");return this.request({url:o,method:"GET"},t)}GetDouyinAvatarInfo(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/douyin/v1/get_avatar_info"),s={is_draft:o.is_draft,body:o.body},n={"Open-Platform-App-ID":o["Open-Platform-App-ID"],"Byte-Signature":o["Byte-Signature"],"Byte-Timestamp":o["Byte-Timestamp"],"Byte-Nonce-Str":o["Byte-Nonce-Str"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}DouYinAuthUserList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/auth_user_list"),s={page_index:o.page_index,page_size:o.page_size,bind_status:o.bind_status,order_by:o.order_by};return this.request({url:i,method:"POST",data:s},t)}GetDebugDouYinStatus(e,t){const o=e,i=this.genBaseURL("/api/playground_api/douyin/get_debug_status"),s={bot_id:o.bot_id};return this.request({url:i,method:"POST",data:s},t)}CanUserApplyClose(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/coze_pro/can_user_apply_close"),s={AccountId:o.AccountId,EventName:o.EventName,Action:o.Action,Version:o.Version},n={"X-Tt-Logid":o["X-Tt-Logid"],"X-Top-Service":o["X-Top-Service"],"X-Top-Region":o["X-Top-Region"]};return this.request({url:i,method:"GET",params:s,headers:n},t)}CreateRoom(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/create_room"),s={bot_id:o.bot_id,conversation_id:o.conversation_id,scene:o.scene,voice_id:o.voice_id,video_config:o.video_config};return this.request({url:i,method:"POST",data:s},t)}GetVoiceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_list"),s={page_index:o.page_index,page_size:o.page_size,language_code:o.language_code};return this.request({url:i,method:"POST",data:s},t)}GetVoiceByIds(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_by_ids"),s={voice_id_map:o.voice_id_map,voice_type:o.voice_type,space_id:o.space_id,emotion_config:o.emotion_config,voice_biz_scene:o.voice_biz_scene};return this.request({url:i,method:"POST",data:s},t)}GrayVoice(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/gray_voice"),s={bot_id:o.bot_id,language_to_voice_id:o.language_to_voice_id};return this.request({url:i,method:"POST",data:s},t)}GetSpaceApplyManageList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/apply_manage_list"),s={space_id:o.space_id,space_apply_status:o.space_apply_status,search_word:o.search_word,page:o.page,size:o.size};return this.request({url:i,method:"GET",params:s},t)}DraftBotCrossSpaceCopy(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/draftbot/crossspace_copy"),s={bot_id:o.bot_id,to_space_id:o.to_space_id};return this.request({url:i,method:"POST",data:s},t)}RemovePublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/remove_publish_member"),s={space_id:o.space_id,member_list:o.member_list};return this.request({url:i,method:"POST",data:s},t)}AddPublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/add_publish_member"),s={space_id:o.space_id,member_list:o.member_list};return this.request({url:i,method:"POST",data:s},t)}SearchAddablePublishMember(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/search_addable_publish_member"),s={space_id:o.space_id,search_word:o.search_word,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}PublishMemberList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/space/publish_member_list"),s={space_id:o.space_id,search_word:o.search_word,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}OperateSpaceApply(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/operate_apply"),s={space_id:o.space_id,enterprise_id:o.enterprise_id,organization_id:o.organization_id,apply_id_list:o.apply_id_list,space_apply_status:o.space_apply_status};return this.request({url:i,method:"POST",data:s},t)}ImportSpaceConfirm(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/confirm"),s={space_id_list:o.space_id_list,enterprise_id:o.enterprise_id,organization_id:o.organization_id,personal_space_new_name:o.personal_space_new_name,user_id_list:o.user_id_list};return this.request({url:i,method:"POST",data:s},t)}ImportSpaceList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/list"),s={enterprise_id:o.enterprise_id,organization_id:o.organization_id,search_word:o.search_word};return this.request({url:i,method:"GET",params:s},t)}ImportSpaceUserList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/space/import/user_list"),s={space_id_list:o.space_id_list,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}GetDouYinInfo(e,t){const o=this.genBaseURL("/api/playground_api/douyin/get_douyin_info");return this.request({url:o,method:"POST"},t)}LongTermMemoryList(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/list"),s={bot_id:o.bot_id,connector_id:o.connector_id,offset:o.offset,limit:o.limit,time_capsule_item_type:o.time_capsule_item_type};return this.request({url:i,method:"GET",params:s},t)}LongTermMemoryUpdate(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/update"),s={bot_id:o.bot_id,connector_id:o.connector_id,biz_id:o.biz_id,new_content:o.new_content,event_ms:o.event_ms,ext:o.ext,tags:o.tags,time_capsule_item_type:o.time_capsule_item_type,iid:o.iid,meta_type:o.meta_type,memory_type:o.memory_type};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryClearAll(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/clear_all"),s={bot_id:o.bot_id,connector_id:o.connector_id,time_capsule_item_type:o.time_capsule_item_type};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryDelete(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/delete"),s={bot_id:o.bot_id,connector_id:o.connector_id,biz_ids:o.biz_ids,time_capsule_item_type:o.time_capsule_item_type,iids:o.iids,memory_meta_type_map:o.memory_meta_type_map};return this.request({url:i,method:"POST",data:s},t)}LongTermMemoryVersion(e,t){const o=e,i=this.genBaseURL("/api/playground_api/long_term_memory/version"),s={bot_id:o.bot_id};return this.request({url:i,method:"GET",params:s},t)}GetVoiceListV2(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_voice_list_v2"),s={language_code:o.language_code,space_id:o.space_id,voice_type:o.voice_type,page_size:o.page_size,next_cursor:o.next_cursor};return this.request({url:i,method:"POST",data:s},t)}GetUserUpdateProfileTag(e,t){const o=this.genBaseURL("/api/playground_api/get_user_update_profile_tag");return this.request({url:o,method:"GET"},t)}OpenRemoveSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={user_ids:o.user_ids};return this.request({url:i,method:"DELETE",data:s},t)}OpenSpaceMemberList(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}OpenAddSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members`),s={users:o.users};return this.request({url:i,method:"POST",data:s},t)}OpenGetBotInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}`),s={is_published:o.is_published,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}OpenApplyJoinSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members/apply`),s={user_ids:o.user_ids};return this.request({url:i,method:"POST",data:s},t)}OpenRemoveSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}`);return this.request({url:i,method:"DELETE"},t)}GetTypeList(e,t){const o=e||{},i=this.genBaseURL("/api/playground_api/get_type_list"),s={model:o.model,voice:o.voice,raw_model:o.raw_model,space_id:o.space_id,cur_model_id:o.cur_model_id,cur_model_ids:o.cur_model_ids,model_scene:o.model_scene,tag_filters:o.tag_filters};return this.request({url:i,method:"POST",data:s},t)}GetCozeLaneInfo(e,t){const o=this.genBaseURL("/api/playground_api/get_coze_lane_info");return this.request({url:o,method:"POST"},t)}OpenUpdateSpaceMember(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}/members/${o.user_id}`),s={role_type:o.role_type};return this.request({url:i,method:"PUT",data:s},t)}OpenListBotVersions(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}/versions`),s={page_num:o.page_num,page_size:o.page_size,publish_status:o.publish_status,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}OpenSwitchBotDevelopMode(e,t){const o=e||{},i=this.genBaseURL(`/v1/bots/${o.bot_id}/collaboration_mode`),s={collaboration_mode:o.collaboration_mode};return this.request({url:i,method:"POST",data:s},t)}OpenUpdateSpace(e,t){const o=e||{},i=this.genBaseURL(`/v1/workspaces/${o.workspace_id}`),s={name:o.name,description:o.description};return this.request({url:i,method:"PUT",data:s},t)}}const Fr=new Gr({});function Vr(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}async function Wr(t,o){if(Vr([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipAuth]))return void await o();if(!t.config.accessToken)throw new e.CozeError(e.ErrorCode.E2001,"No API token found. Please authenticate first.",void 0,{fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --oauth"});if(Vr([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipOrgCheck]))return void await o();const i=await async function(t){const o=t.config.organizationId;if(!o)return!1;const{data:i}=await Wi.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0}),s=i.enterprise_info_list||[];if(!s.some((e=>Vr([e,"access",e=>e.organization_info_list,"optionalAccess",e=>e.some,"call",e=>e((e=>e.organization_id===o))]))))throw new e.CozeError(e.ErrorCode.E1000,`Organization ID ${o} is invalid or not found`,void 0,{fix:"Run `coze organization list` and select a valid organization",example:"coze organization use <organization_id>"});return!1}(t);if(Vr([t,"access",e=>e.commandConfig,"optionalAccess",e=>e.skipSpaceCheck]))return i&&await Hr(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId}),void await o();const s=await async function(t){const o=t.config.organizationId,{enterpriseId:i}=t.config;let{spaceId:s}=t.config,n=!1;try{if(s){const{data:t}=await Fr.GetSpaceListV2({organization_id:o,enterprise_id:i}),n=Vr([t,"optionalAccess",e=>e.bot_space_list])||[];if(!n.some((e=>e.id===s))){const t=o?`[Context] Space ID ${s} is invalid or not found in organization ${o}.`:`[Context] Space ID ${s} is invalid or not found.`;throw new e.CozeError(e.ErrorCode.E1000,t,void 0,{fix:"Run `coze space list` and select a valid space",example:"coze space use <space_id>"})}}else{t.ui.info("[Context] Space ID not found. Attempting to auto-initialize...");const{data:r}=await Fr.GetSpaceListV2({organization_id:o,enterprise_id:i,page:1,size:1}),a=Vr([r,"optionalAccess",e=>e.bot_space_list,"optionalAccess",e=>e[0]]);if(!a){const t=o?`[Context] No spaces found in organization ${o}. Please create one.`:"[Context] No spaces found. Please create one.";throw new e.CozeError(e.ErrorCode.E3000,t,void 0,{fix:"Create a space in the current organization",example:"coze space list"})}s=a.id,t.config.spaceId=s,n=!0,t.ui.success(`[Context] Auto-selected Space: ${a.name} (${a.id})`)}}catch(t){const o=t instanceof e.CozeError?t:new e.CozeError(e.ErrorCode.E5000,t.message,t instanceof Error?t.stack:t);throw o.fix??="Switch organization or space using `coze organization use <organization_id>` or `coze space use <space_id>`",o.example??="coze organization list",o}return n}(t);await Jr(t),(i||s)&&await Hr(t,{organizationId:t.config.organizationId,enterpriseId:t.config.enterpriseId,spaceId:t.config.spaceId,billingProjectId:t.config.billingProjectId}),await o()}async function Hr(e,t){try{await l.saveConfig(t)}catch(t){e.ui.warn(`Failed to save auto-initialized context: ${t}`)}}const Jr=async o=>{const{spaceId:i}=o.config;try{const{data:s}=await t.IdeApi.GetOrCreateBillingProject({space_id:i});if(!Vr([s,"optionalAccess",e=>e.project_id]))throw new e.CozeError(e.ErrorCode.E5002,"[Context] Failed to get billing project ID from response.",s);o.config.billingProjectId=s.project_id,o.ui.success(`[Context] Billing Project: ${s.project_id} (space: ${i})`)}catch(e){const t=[`Failed to get billing project, ${e.message}. please check your space context:`," coze space list"," coze space use <space_id>"];throw e.message=`${t.join("\n")}`,e}};function Kr(e,t){return null!=e?e:t()}function Qr(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Yr=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||Qr([o,"optionalAccess",e=>e.config,"access",e=>e.organizationId]),s=Qr([o,"optionalAccess",e=>e.config,"access",e=>e.enterpriseId]);Qr([o,"optionalAccess",e=>e.ui,"access",e=>e.verbose,"call",e=>e(`Fetching spaces for organization '${i}'...`)]);const n=await async function(e){const{data:t}=await Fr.GetSpaceListV2({organization_id:e.orgId,enterprise_id:e.enterpriseId,page:1,size:100});return Kr(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([t,"optionalAccess",e=>e.bot_space_list]),(()=>[])).map((t=>({id:Kr(t.id,(()=>"")),name:Kr(t.name,(()=>"")),org_id:Kr(e.orgId,(()=>""))})))}({orgId:i,enterpriseId:s});Qr([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Spaces:")]),Qr([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(n)]);const r=["Please use the following command to switch space:"," coze space use <space_id>"];Qr([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 s=i.getContext();Qr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to space '${t}'...`)]),await async function(t){try{await l.saveConfig({spaceId:t})}catch(o){throw new e.CozeError(e.ErrorCode.E5000,`Failed to set default space to '${t}': ${o.message}`,o.stack)}}(t),Qr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default space set to '${t}' successfully.`)]),"json"===Qr([s,"optionalAccess",e=>e.format])&&Qr([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:`Default space set to '${t}'.`})])}))};function Zr(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Xr=async t=>{Zr([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([l.loadConfig(),Wi.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 s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([t.personal_account_info,"optionalAccess",e=>e.available]))return{available:!1};const o=!!e.organizationId;return await l.saveConfig({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.");Zr([t,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Switched to personal account successfully.")]),"json"===Zr([t,"optionalAccess",e=>e.format])&&Zr([t,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"success",message:"Switched to personal account."})])},ea=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();Zr([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching organizations...")]);const i=await async function(){const{data:e}=await Wi.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})))))}();Zr([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Available Organizations (Teams):")]),Zr([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(i)]);const s=["Please use the following command to switch organization:"," coze organization use <organization_id>","Please use the following command to switch space:"," coze space list"," coze space use <space_id>"];Zr([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.join("\n"))])})),o.command("use").description("Set the default organization context").argument("[org_id]","Organization ID to set as default context (empty to switch to personal account)").config({help:{brief:"Set default organization or switch to personal account",description:"Save the specified org_id to the local configuration as the default organization for subsequent commands. The command will automatically retrieve and save the corresponding Enterprise ID. If the org_id is not found in the user's enterprise list, the command will fail without modifying the configuration. When switching to a different organization, the saved spaceId will be cleared. Omit org_id 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 s=i.getContext();if(!t)return void await Xr(s);Zr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Switching to organization '${t}'...`)]);const{enterpriseId:n}=await async function(t){const[o,{data:i}]=await Promise.all([l.loadConfig(),Wi.ListEnterprise({contain_enterprise_of_user:!0,contain_organization_of_user:!0})]);let s="",n=!1;for(const e of i.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 r=o.organizationId!==t;return await l.saveConfig({organizationId:t,enterpriseId:s,...r?{spaceId:void 0}:{}}),{enterpriseId:s}}(t);Zr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Organization '${t}' found in enterprise '${n}'. Config saved.`)]),Zr([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Default organization set to '${t}' successfully.`)]),"json"===Zr([s,"optionalAccess",e=>e.format])&&Zr([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 ta(e,t){return null!=e?e:t()}const oa=async(e={})=>{const t=ta(e.stdin,(()=>process.stdin));return!0===ta(e.isTTY,(()=>t.isTTY))?null:await(async e=>{let t="";e.setEncoding("utf-8");for await(const o of e)t+=o;return t})(t)},ia=e=>{process.stdout.write(e.endsWith("\n")?e:`${e}\n`)},sa=e=>{ia(JSON.stringify(e))},na=async(e,t)=>{const o=i.resolve(e),n=i.dirname(o);if(await s.mkdir(n,{recursive:!0}),t instanceof Blob){const e=Buffer.from(await t.arrayBuffer());await s.writeFile(o,e)}else Buffer.isBuffer(t)?await s.writeFile(o,t):t instanceof ArrayBuffer?await s.writeFile(o,Buffer.from(t)):await s.writeFile(o,String(t));return o};const ra=e=>"object"==typeof e&&null!==e,aa=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},ca=e=>ra(e)&&"data"in e&&void 0!==e.data?e.data:e,la=(e,t)=>{try{const{pathname:o}=new URL(e);return i.extname(o)||t}catch(e){return t}},da=()=>{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")}`},pa=e=>{const{outputPath:t,type:o,index:s,ext:n,timestamp:r}=e,a=`${o}_${r}_${s}${n}`;return i.join(t,a)},ua=async(t,o={})=>{let i=null;o.stdin&&(i=await oa());const s=aa(t),n=aa(i),r=(c=()=>n,null!=(a=s)?a:c());var a,c;if(!r)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin with piped content");return r},ma="720p",ga="16:9",ha=!1,fa=!1;function _a(e,t){return null!=e?e:t()}function ya(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ba=(e,t)=>{if(null==e)return 5;const o=Number(e);if(!Number.isFinite(o))return ya([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?(ya([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},va=(e,t)=>{if(null==e)return;const o=Number(e);if(Number.isSafeInteger(o)&&o>=0)return o;ya([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --seed '${String(e)}', this parameter will be ignored`)])},wa=e=>{const{content:t,options:o,ctx:i}=e,s=(e=>{if("string"!=typeof e)return null;const t=e.trim(),o=/^([0-9]{1,5})x([0-9]{1,5})$/i.exec(t);if(!o)return null;const i=Number(o[1]),s=Number(o[2]);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=0)return null;const n=((e,t)=>{let o=Math.abs(e),i=Math.abs(t);for(;0!==i;){const e=o%i;o=i,i=e}return o})(i,s)||1,r=`${Math.round(i/n)}:${Math.round(s/n)}`,a=Math.max(i,s);return{ratio:r,resolution:a<=854?"480p":a<=1280?"720p":"1080p"}})(o.size),n=((e,t)=>"480p"===e||"720p"===e||"1080p"===e?e:(void 0!==e&&ya([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --resolution '${String(e)}', falling back to '${ma}'`)]),ma))(_a(o.resolution,(()=>ya([s,"optionalAccess",e=>e.resolution]))),i),r=((e,t)=>{if("string"==typeof e){const t=e.trim();if(t.length>0)return t}return void 0!==e&&ya([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --ratio '${String(e)}', falling back to '${ga}'`)]),ga})(_a(o.ratio,(()=>ya([s,"optionalAccess",e=>e.ratio]))),i);return{model:"doubao-seedance-1-5-pro-251215",content:t,callback_url:_a(aa(o.callbackUrl),(()=>{})),return_last_frame:"boolean"==typeof o.returnLastFrame?o.returnLastFrame:fa,resolution:n,ratio:r,duration:ba(o.duration,i),watermark:"boolean"!=typeof o.watermark||o.watermark,seed:va(o.seed,i),camerafixed:"boolean"==typeof o.camerafixed?o.camerafixed:ha,generate_audio:"boolean"!=typeof o.generateAudio||o.generateAudio}},Ca=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())},Ea=async e=>{const{outputPath:t,videoUrl:o,lastFrameUrl:s,shouldSaveLastFrame:n}=e,r=la(o,".mp4"),a=da(),c=pa({outputPath:t,type:"video",index:0,ext:r,timestamp:a}),l=await Ca(o),d=[await na(c,l)];if(n&&"string"==typeof s&&s.length>0){const e=(e=>{const{outputPath:t,ext:o,timestamp:s}=e,n=`last_frame_${s}_0${o}`;return i.join(t,n)})({outputPath:t,ext:la(s,".png"),timestamp:a}),o=await Ca(s),n=await na(e,o);d.push(n)}return d};var Ia,Aa,Sa,ja,Pa,ka,Ta,za,Ra,xa,La,Oa,Da,Ua,Ba,qa,Ma,Na,$a;function Ga(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInputTokens=2]="TotalInputTokens";e[e.TotalOutputTokens=3]="TotalOutputTokens"}(Ia||(Ia={})),function(e){e[e.ASC=1]="ASC";e[e.DESC=2]="DESC"}(Aa||(Aa={})),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"}(Sa||(Sa={})),function(e){e[e.Free=1]="Free";e[e.Trial=2]="Trial";e[e.Paid=3]="Paid"}(ja||(ja={})),function(e){e[e.Inactive=1]="Inactive";e[e.Active=2]="Active"}(Pa||(Pa={})),function(e){e[e.CNY=1]="CNY";e[e.ResourcePoint=2]="ResourcePoint"}(ka||(ka={})),function(e){e[e.Cancellable=0]="Cancellable";e[e.NoCancellable=1]="NoCancellable";e[e.AlwaysDefault=2]="AlwaysDefault"}(Ta||(Ta={})),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"}(za||(za={})),function(e){e[e.Internal=1]="Internal";e[e.External=2]="External";e[e.Infra=3]="Infra"}(Ra||(Ra={})),function(e){e[e.Text=1]="Text";e[e.Image=2]="Image";e[e.Video=3]="Video";e[e.Audio=4]="Audio"}(xa||(xa={})),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"}(La||(La={})),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"}(Oa||(Oa={})),function(e){e[e.Offline=0]="Offline";e[e.Online=1]="Online";e[e.GradualRollout=2]="GradualRollout";e[e.ReadyToOffline=3]="ReadyToOffline"}(Da||(Da={})),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"}(Ua||(Ua={})),function(e){e[e.Install=1]="Install";e[e.Uninstall=2]="Uninstall"}(Ba||(Ba={})),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"}(qa||(qa={})),function(e){e[e.Scene=1]="Scene";e[e.Type=2]="Type"}(Ma||(Ma={})),function(e){e[e.Official=1]="Official";e[e.Community=2]="Community"}(Na||(Na={})),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"}($a||($a={}));class Fa{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Fa.prototype.__init.call(this),Fa.prototype.__init2.call(this),this.request=Ga([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=Ga([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}ListIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/list"),s={space_id:o.space_id,project_id:o.project_id,integration_type:o.integration_type,integration_id:o.integration_id,filter_installed:o.filter_installed,org_id:o.org_id,search_words:o.search_words,page_num:o.page_num,page_size:o.page_size,project_type:o.project_type};return this.request({url:i,method:"POST",data:s},t)}SetIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/update"),s={integration_id:o.integration_id,space_id:o.space_id,auth_schema_value:o.auth_schema_value};return this.request({url:i,method:"POST",data:s},t)}DeleteIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/delete"),s={integration_id:o.integration_id,space_id:o.space_id,project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}AuthIntegrationStatus(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/auth/status"),s={integration_id:o.integration_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}ManageSpaceIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/space/manage"),s={space_ids:o.space_ids,integration_ids:o.integration_ids,op_type:o.op_type};return this.request({url:i,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}FlashASR(e,t){const o=e||{},i=this.genBaseURL("/api/v3/auc/bigmodel/recognize/flash"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}ListModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/list"),s={model_type:o.model_type,current_model_ids:o.current_model_ids,integration_ids:o.integration_ids,need_model_config_param:o.need_model_config_param,page_size:o.page_size,offset:o.offset};return this.request({url:i,method:"POST",data:s},t)}ChatCompletions(e,t){const o=e||{},i=this.genBaseURL("/api/v3/chat/completions"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CreateResponses(e,t){const o=e||{},i=this.genBaseURL("/api/v3/responses"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}GenerateImages(e,t){const o=e||{},i=this.genBaseURL("/api/v3/images/generations"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const o=e||{},i=this.genBaseURL("/api/v3/tts/unidirectional"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}GetIntegrationOauthConfig(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/auth/oauth_config"),s={integration_id:o.integration_id,space_id:o.space_id,project_id:o.project_id,session_id:o.session_id};return this.request({url:i,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks/:id"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"GET",data:s,params:n},t)}WebSearch(e,t){const o=e||{},i=this.genBaseURL("/api/search_api/web_search"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}WebSearch(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/search_api/web_search"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CreateResponses(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/responses"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}GetVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks/:id"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"GET",data:s,params:n},t)}FlashASR(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/auc/bigmodel/recognize/flash"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}SubmitVideoGenerationsTasks(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/contents/generations/tasks"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}GenerateImages(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/images/generations"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}UnidirectionalTTS(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/tts/unidirectional"),s={Body:o.Body},n={project_id:o.project_id};return this.request({url:i,method:"POST",data:s,params:n},t)}ChatCompletions(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/chat/completions"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CancelIntegration(e,t){const o=e||{},i=this.genBaseURL("/v1/integration/cancel"),s={integration_id:o.integration_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}Embeddings(e,t){const o=e||{},i=this.genBaseURL("/api/v3/embeddings/multimodal"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}Embeddings(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/embeddings/multimodal"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}VideoEditingUtils(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/video_editing_utils"),s={Body:o.Body},n={tool_name:o.tool_name};return this.request({url:i,method:"POST",data:s,params:n},t)}GetProjectDefaultSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/default"),s={project_type:o.project_type,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillByIDs(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/by_ids"),s={project_type:o.project_type,skill_ids:o.skill_ids,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillCategoryList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/category/list"),s={project_type:o.project_type};return this.request({url:i,method:"POST",data:s},t)}UploadSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload"),s={data:o.data},n={"Content-Type":o["Content-Type"]};return this.request({url:i,method:"POST",data:s,headers:n},t)}GetUserSkillList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/user/list"),s={page:o.page,size:o.size};return this.request({url:i,method:"POST",data:s},t)}DeleteSkill(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/delete"),s={skill_id:o.skill_id};return this.request({url:i,method:"POST",data:s},t)}GetSkillList(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/list"),s={project_type:o.project_type,category_type_list:o.category_type_list,space_id:o.space_id,source_list:o.source_list};return this.request({url:i,method:"POST",data:s},t)}UploadSkillConfirm(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload/confirm"),s={preview_skill_key:o.preview_skill_key};return this.request({url:i,method:"POST",data:s},t)}FetchTool(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/fetch_tool"),s={url:o.url};return this.request({url:i,method:"POST",data:s},t)}GetModelSwitchStatus(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/status"),s={model_id:o.model_id,project_ids:o.project_ids,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}StartSwitchModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/start"),s={space_id:o.space_id,project_ids:o.project_ids,current_model:o.current_model,target_model:o.target_model};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageList(e,t){const o=e||{},i=this.genBaseURL("/v1/model/usage/list"),s={space_id:o.space_id,model_id:o.model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp,order_by_field:o.order_by_field,order_by_type:o.order_by_type,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetModelDetails(e,t){const o=e||{},i=this.genBaseURL("/v1/model/details"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageDetail(e,t){const o=e||{},i=this.genBaseURL("/v1/model/usage/details"),s={space_id:o.space_id,model_id:o.model_id,project_id:o.project_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}RollbackSwitchModel(e,t){const o=e||{},i=this.genBaseURL("/v1/model/switch/rollback"),s={space_id:o.space_id,project_ids:o.project_ids,current_model:o.current_model};return this.request({url:i,method:"POST",data:s},t)}TextEmbeddings(e,t){const o=e||{},i=this.genBaseURL("/api/v3/embeddings"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}TextEmbeddings(e,t){const o=e||{},i=this.genBaseURL("/coze-coding/api/v3/embeddings"),s={Body:o.Body};return this.request({url:i,method:"POST",data:s},t)}CheckModelReadyToOffline(e,t){const o=e||{},i=this.genBaseURL("/v1/model/ready_to_offline/check"),s={model_type:o.model_type};return this.request({url:i,method:"POST",data:s},t)}Audit(e,t){const o=e||{},i=this.genBaseURL("/api/v1/integration/audit"),s={content:o.content};return this.request({url:i,method:"POST",data:s},t)}}Fa.prototype.UploadSkill=function(e,t){const o=e||{},i=this.genBaseURL("/v1/skill/upload"),s=o.body;return this.request({url:i,method:"POST",data:s},t)},Fa.prototype.GenerateImages=function(e,t){const o=e||{},i=this.genBaseURL("/api/v3/images/generations"),s=o.Body;return this.request({url:i,method:"POST",data:s},t)},Fa.prototype.SubmitVideoGenerationsTasks=function(e,t){const o=e||{},i=this.genBaseURL("/api/v3/contents/generations/tasks"),s=o;return this.request({url:i,method:"POST",data:s},t)},Fa.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 Va=new Fa({});const Wa=async e=>await new Promise((t=>setTimeout(t,e))),Ha=async e=>{const{taskId:t,baseURL:o,accessToken:i,projectId:s}=e,n=await Va.GetVideoGenerationsTasks({id:t},{baseURL:o,headers:{Authorization:`Bearer ${i}`},params:{project_id:s}});return ca(n)};function Ja(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ka=e=>`coze generate video status ${e}`,Qa=e=>{const{ctx:t,response:o}=e;"json"!==Ja([t,"optionalAccess",e=>e.format])?ia((e=>{const t=[e.status],o=Ja([e,"access",e=>e.content,"optionalAccess",e=>e.video_url]),i=Ja([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)):sa(o)},Ya=t=>{const o=t.getContext(),{outputPath:i}=t.optsWithGlobals(),s=(n=Ja([o,"optionalAccess",e=>e.config,"optionalAccess",e=>e.integrationApiBaseUrl]),r=()=>l.DEFAULT_CONFIG.integrationApiBaseUrl,null!=n?n:r());var n,r;const a=Ja([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:s,outputPath:i}},Za=async(t,o,i)=>{const{accessToken:s,ctx:n,integrationApiBaseUrl:r,outputPath:a}=Ya(i);let c=null;o.stdin&&(c=await oa());const{content:l}=(t=>{const{prompt:o,stdinPrompt:i,options:s}=t,n=_a(aa(o),(()=>aa(i))),r=aa(s.firstFrame),a=aa(s.lastFrame),c=Boolean(r)||Boolean(a);if(!n&&!c)throw new e.CozeError(e.ErrorCode.E1000,"Missing input: Please provide PROMPT/stdin text, or provide images (--first-frame/--last-frame/--reference-image)");const l=[];return n&&l.push({type:"text",text:n}),r&&l.push({type:"image_url",image_url:{url:r},role:"first_frame"}),a&&l.push({type:"image_url",image_url:{url:a},role:"last_frame"}),{content:l}})({prompt:t,stdinPrompt:c,options:o}),d=wa({content:l,options:o,ctx:n}),p=n.format,u=Ja([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!u)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const{createResp:m,taskId:g}=await(async t=>{const{requestBody:o,baseURL:i,accessToken:s,projectId:n}=t,r=await Va.SubmitVideoGenerationsTasks(o,{baseURL:i,headers:{Authorization:`Bearer ${s}`},params:{project_id:n}}),a=ca(r),c=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([a,"optionalAccess",e=>e.id]);if(!c||"string"!=typeof c)throw new e.CozeError(e.ErrorCode.E5002,"Video generation task created successfully but no valid task_id was returned",a);return{taskId:c,createResp:a}})({requestBody:d,baseURL:r,accessToken:s,projectId:u});if(!o.wait)return"json"===p?void sa({query_command:Ka(g),response:m,task_id:g}):void ia((e=>["Video generation task created successfully.",`taskId: ${e}`,`Use \`${Ka(e)}\` to query status.`].join("\n"))(g));const h=await(async t=>{const{taskId:o,baseURL:i,accessToken:s,pollIntervalMs:n,pollTimeoutMs:r,projectId:a}=t,c=Date.now();for(;;){const t=await Ha({taskId:o,baseURL:i,accessToken:s,projectId:a});if("succeeded"===t.status)return t;if("failed"===t.status||"cancelled"===t.status)throw new e.CozeError(e.ErrorCode.E5002,`Video generation failed (status=${t.status}): ${l=t.error_message,d=()=>"unknown",null!=l?l:d()}`,t);if(Date.now()-c>r)throw new e.CozeError(e.ErrorCode.E5003,[`Video generation timed out after ${r}ms.`,`taskId: ${o}`,`Use \`coze generate video status ${o}\` to query status.`].join("\n"),{task_id:o,last_status:t.status});await Wa(n)}var l,d})({taskId:g,baseURL:r,accessToken:s,pollIntervalMs:2e3,pollTimeoutMs:3e5,projectId:u}),f=Ja([h,"access",e=>e.content,"optionalAccess",e=>e.video_url]),_=Ja([h,"access",e=>e.content,"optionalAccess",e=>e.last_frame_url]);if(!f||"string"!=typeof f)throw new e.CozeError(e.ErrorCode.E5002,"Video generated successfully but video_url was not returned");if(a){const e=await Ea({outputPath:a,videoUrl:f,lastFrameUrl:_,shouldSaveLastFrame:!0===o.returnLastFrame});return"json"===p?void sa({task_id:g,request:d,response:h,saved_paths:e}):void ia(e.join("\n"))}if("json"===p)return void sa({task_id:g,request:d,response:h});const y=[f];!0===o.returnLastFrame&&"string"==typeof _&&_.length>0&&y.push(_),ia(y.join("\n"))},Xa=(e,t)=>{const o=t.getContext();H(e,o)},ec=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 Za(e,t,o)}catch(e){Xa(e,o)}})),o.option("--callback-url <url>","Callback URL for task status changes").option("--return-last-frame","Return last frame URL (default: disabled)",fa).option("--resolution <res>","Resolution: 480p|720p|1080p",ma).option("--ratio <ratio>",`Aspect ratio (default: ${ga})`,ga).option("--size <size>","Derive ratio/resolution from WIDTHxHEIGHT (lower priority than explicit parameters)").option("--duration <seconds>","Duration (seconds, 4..12; out-of-bounds fallback -1), default: 5",String(5)).option("--no-watermark","Disable watermark (default: enabled)").option("--seed <seed>","Random seed (safe integer)").option("--camerafixed","Fixed camera position (default: disabled)",ha).option("--no-generate-audio","Do not generate accompanying audio (default: generate)").option("--first-frame <url>","First frame image URL").option("--last-frame <url>","Last frame image URL").option("--stdin","Read prompt from stdin (pipe input)").option("--wait","Wait for task completion by polling; by default the command returns taskId immediately")},tc=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:s,ctx:n,integrationApiBaseUrl:r}=Ya(i),a=Ja([n,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!a)throw new e.CozeError(e.ErrorCode.E1000,"Missing billing project ID");const c=await Ha({taskId:t,baseURL:r,accessToken:s,projectId:a});Qa({ctx:n,response:c})})(t,0,i)}catch(e){Xa(e,i)}}))};function oc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ic="2K",sc="url",nc="standard",rc="disabled",ac=3686400,cc=16777216,lc=e=>"object"==typeof e&&null!==e,dc=e=>{if("string"==typeof e){const t=e.trim();return t.length?t:nc}return nc},pc=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},uc=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)",ic).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",sc).option("--optimize-prompt-mode <mode>",`Prompt optimization mode (default: ${nc})`,nc).option("--sequential <mode>","Group image generation mode: auto|disabled",rc).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 s=i.getContext(),{outputPath:n}=i.optsWithGlobals(),r=await ua(t,{stdin:o.stdin}),a=oc([s,"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:ic};if("string"!=typeof e)return oc([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --size '${String(e)}', falling back to '${ic}'`)]),{value:ic};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:ic,warning:`Invalid --size '${o}', falling back to '${ic}'. Expected 2K/4K or WIDTHxHEIGHT`};const s=Number(i[1]),n=Number(i[2]),r=s*n,a=s/n;return Number.isFinite(s)&&Number.isFinite(n)&&s>0&&n>0&&r>=ac&&r<=cc&&a>=.0625&&a<=16?{value:`${s}x${n}`}:{value:ic,warning:`Invalid --size '${o}', falling back to '${ic}'. Total pixels must be in [3686400, 16777216], aspect ratio must be in [1:16, 16:1].`}})(o.size,s),d="url"===(p=o.responseFormat)||"b64_json"===p?{value:p}:void 0!==p?{value:sc,warning:`Invalid --response-format '${String(p)}', falling back to '${sc}'`}:{value:sc};var p;const u=(e=>"auto"===e||"disabled"===e?{value:e}:void 0!==e?{value:rc,warning:`Invalid --sequential '${String(e)}', falling back to '${rc}'`}:{value:rc})(o.sequential),m=(e=>{if(null==e)return{value:15};const t=Number(e);if(Number.isFinite(t)){const e=Math.floor(t);if(e>=1&&e<=15)return{value:e}}return{value:15,warning:`Invalid --max-images '${String(e)}', falling back to '15'`}})(o.maxImages);c.warning&&oc([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(c.warning)]),d.warning&&oc([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(d.warning)]),u.warning&&oc([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(u.warning)]),m.warning&&oc([s,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",e=>e(m.warning)]);const g={model:"doubao-seedream-4-5-251128",prompt:r,size:c.value,watermark:"boolean"!=typeof o.watermark||o.watermark,image:pc(o.image),response_format:d.value,optimize_prompt_options:{mode:dc(o.optimizePromptMode)},sequential_image_generation:u.value,sequential_image_generation_options:{max_images:m.value}},h=(t=>{const o=lc(t)&&"data"in t?t.data:t;if(lc(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 Va.GenerateImages({Body:g},{baseURL:l.DEFAULT_CONFIG.integrationApiBaseUrl,params:{project_id:a}}));if(h.error)throw new e.CozeError(e.ErrorCode.E5002,"Image generation failed (top-level error)",h.error);const f=(y=()=>sc,null!=(_=g.response_format)?_:y());var _,y;const b=h.data.filter((e=>!e.error&&("url"===f?"string"==typeof e.url&&e.url.length>0:"string"==typeof e.b64_json&&e.b64_json.length>0)));if(0===b.length)throw new e.CozeError(e.ErrorCode.E5002,"Image generation succeeded but no valid image data was returned",h);if(n){const t=[],o=da();for(const[i,s]of b.entries()){const r="url"===f&&s.url?la(s.url,".png"):".png",a=pa({outputPath:n,type:"image",index:i,ext:r,timestamp:o});let c;if("url"===f){const t=await e.customFetch.fetch(s.url);if(!t.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download generated image: ${t.status} ${t.statusText}`);c=Buffer.from(await t.arrayBuffer())}else c=Buffer.from(s.b64_json,"base64");const l=await na(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}})(h);oc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({...c,saved_paths:t})])}else oc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(h.data)])}))};function mc(e,t){return null!=e?e:t()}function gc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const hc="cli_user",fc="zh_female_xiaohe_uranus_bigtts",_c="mp3",yc=24e3,bc=(e,t)=>"pcm"===e||"mp3"===e||"ogg_opus"===e?e:(void 0!==e&&gc([t,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",t=>t(`Invalid --audio-format '${String(e)}', falling back to '${_c}'`)]),_c),vc=(e,t,o,i)=>{if(null==e)return t;const s=Number(e);return Number.isFinite(s)?Math.floor(s):(gc([i,"optionalAccess",e=>e.ui,"access",e=>e.warn,"call",i=>i(`Invalid --${o} '${String(e)}', falling back to ${t}`)]),t)},wc=t=>{const o=t.trim();if(0===o.length)return null;const i=o.startsWith("data:")?o.slice(5).trim():o;if(0===i.length)return null;const s=i[0];if("{"!==s&&"["!==s)return null;const n=e.safeJsonParse(i,void 0,{onError:t=>{const i=t instanceof Error?t.message:String(t);throw new e.CozeError(e.ErrorCode.E5002,`Failed to parse response: ${i}`,{line:o})}});return void 0===n?null:ra(n)&&"number"==typeof n.code?n:null},Cc=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");uc(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: ${hc})`,hc).option("--speaker <speaker>",`Speaker (default: ${fc})`,fc).option("--audio-format <format>","Audio encoding: pcm|mp3|ogg_opus",_c).option("--sample-rate <n>","Sample rate (default: 24000)",String(yc)).option("--speech-rate <n>","Speech rate (-50..100, default: 0)",String(0)).option("--loudness-rate <n>","Loudness (-50..100, default: 0)",String(0)).option("--ssml","Treat input as SSML (defaults to plain text)",!1).option("--stdin","Read prompt from stdin (pipe input)").action((async(t,o,i)=>{const s=i.getContext();try{const{outputPath:n}=i.optsWithGlobals(),r=gc([s,"optionalAccess",e=>e.config,"access",e=>e.integrationApiBaseUrl]);if(!gc([s,"optionalAccess",e=>e.config,"optionalAccess",e=>e.accessToken]))throw new e.CozeError(e.ErrorCode.E2001,"Missing access_token: Please run `coze auth login --oauth` or `coze auth login --token <token>` first");const a=await ua(t,{stdin:o.stdin}),c=gc([s,"optionalAccess",e=>e.config,"access",e=>e.billingProjectId]);if(!c)throw new e.CozeError(e.ErrorCode.E1001,"Missing billing project ID");const l={user:{uid:mc(aa(o.uid),(()=>hc))},req_params:{speaker:mc(aa(o.speaker),(()=>fc)),audio_params:{format:bc(o.audioFormat,s),sample_rate:vc(o.sampleRate,yc,"sample-rate",s),speech_rate:vc(o.speechRate,0,"speech-rate",s),loudness_rate:vc(o.loudnessRate,0,"loudness-rate",s)}}};o.ssml?l.req_params={...l.req_params,ssml:a}:l.req_params={...l.req_params,text:a};const d=new URL("/api/v3/tts/unidirectional",r);d.searchParams.append("project_id",c);const p=await e.customFetch.fetch(d.toString(),{method:"POST",body:JSON.stringify(l)});if(!p.ok)throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis request failed: ${p.status} ${p.statusText}`,{status:p.status,statusText:p.statusText});if(!p.body)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis response is empty (no streaming body returned)");const u=new TextDecoder("utf-8"),m=p.body.getReader(),g=[];let h;const f=t=>{if(0===t.code)return n&&"string"==typeof t.data&&g.push(Buffer.from(t.data,"base64")),!1;if(2e7===t.code)return"string"==typeof t.url&&t.url.length>0&&(h=t.url),!0;throw new e.CozeError(e.ErrorCode.E5002,`Speech synthesis failed (code=${t.code}): ${mc(t.message,(()=>"unknown"))}`,t)};let _="";for(;;){const{done:e,value:t}=await m.read();if(e)break;_+=u.decode(t,{stream:!0});const o=_.split(/\r?\n/);_=mc(o.pop(),(()=>""));for(const e of o){const t=wc(e);if(t&&f(t)){await m.cancel();break}}if(h)break}if(!h){_+=u.decode();const e=_.split(/\r?\n/);_="";for(const t of e){const e=wc(t);if(e&&f(e))break}}if(n){const t=mc(gc([l,"access",e=>e.req_params,"optionalAccess",e=>e.audio_params,"optionalAccess",e=>e.format]),(()=>_c)),o="pcm"===t?".pcm":"ogg_opus"===t?".ogg":".mp3",i=da(),r=pa({outputPath:n,type:"audio",index:0,ext:o,timestamp:i});let a=null;if(g.length>0)a=await na(r,Buffer.concat(g));else if(h){const t=await e.customFetch.fetch(h);if(!t.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download synthesized speech: ${t.status} ${t.statusText}`,{status:t.status,statusText:t.statusText});const s=Buffer.from(await t.arrayBuffer()),r=la(h,o),c=pa({outputPath:n,type:"audio",index:0,ext:r,timestamp:i});a=await na(c,s)}if(!a)throw new e.CozeError(e.ErrorCode.E5002,"Speech synthesis completed but no savable audio data was obtained (neither chunks nor download URL)",{url:h});return"json"===gc([s,"optionalAccess",e=>e.format])?void sa({request:l,url:h,saved_path:a}):void ia(a)}if("json"===gc([s,"optionalAccess",e=>e.format]))return void sa({request:l,url:h});if(h)return void ia(h);ia("Speech synthesis completed, but no audio download URL was returned; you can use --output json to view details.")}catch(e){H(e,s)}}))})(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);ec(t),tc(t)})(o)};function Ec(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ic=o=>{(o=>{o.command("upload <path>").description("Upload a local file").config({help:{brief:"Upload a local file",description:"Upload a local file to Coze. 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(o,i,s)=>{let n;try{n=s.getContext();try{await h.access(o)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${o}`,{filePath:o})}const i=g.basename(o),r=g.extname(o),a=r?i.slice(0,-r.length):i,c=r.slice(1),l=new _;l.append("file_name",a),l.append("file_extension",c),l.append("file_content",f.createReadStream(o)),l.append("biz_type","cli_attachment");const d=await t.IdeApi.UploadFile({data:l},{headers:{...l.getHeaders()}});"json"===Ec([n,"optionalAccess",e=>e.format])?Ec([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(d.data)]):Ec([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(Ec([d,"access",e=>e.data,"optionalAccess",e=>e.file_url]))])}catch(e){H(e,n)}}))})(o.command("file").description("General file operations").config({help:{brief:"File upload and management",description:"Manage file operations for Coze projects. Currently supports uploading local files to Coze for use as attachments or context.",examples:[{desc:"Upload a file",cmd:"coze file upload ./document.pdf"}],seeAlso:["coze code message send"]}}))};function Ac(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Sc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function jc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Pc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const kc=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(),s=await l.listConfigs();for(const t of e){const e=s.find((e=>e.key===t));Ac(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,s)=>{const n=s.getContext();try{const e={};e[t]=o;const i="global";await l.saveConfig(e,i);const s={key:t,value:o,scope:i,status:"updated",message:`Configuration '${t}' updated successfully in ${i} scope.`};if(Sc([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(s.message)]),"json"===Sc([n,"optionalAccess",e=>e.format]))return void Sc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(s)])}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 s=i.getContext();for(const o of t)try{await l.deleteConfig(o);const e={key:o,status:"deleted",message:`Configuration '${o}' has been removed.`};jc([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleted ${o} from configuration file successfully.`)]),"json"===jc([s,"optionalAccess",e=>e.format])&&jc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t(e)])}catch(t){const i=t;throw new e.CozeError(e.ErrorCode.E5000,`Failed to delete config '${o}': ${i.message}`,i.stack)}}))})(o),(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 l.listConfigs()).map((({key:e,value:t,source:o})=>({key:e,value:t,source:o})));Pc([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Configurations found:")]),Pc([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(i)])}))})(o)},Tc="__COZE_FILE_COMP__";function zc(){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 Rc(e){const t=n.homedir();switch(e){case"bash":return i.join(t,"darwin"===process.platform?".bash_profile":".bashrc");case"zsh":return i.join(t,".zshrc");case"fish":return i.join(t,".config/fish/config.fish");case"powershell":return function(){const e=["pwsh","powershell"];for(const t of e)try{const e=c.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 xc(){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]}" == "${Tc}" ]]; 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" == "${Tc}" ]]; 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 Lc(e){switch(e){case"bash":return`\n# begin coze completion\nsource ${i.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 '${Tc}') {\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 Oc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}let Dc,Uc,Bc=!1,qc=!1;function Mc(e){const t=(o=e._args,i=()=>[],null!=o?o:i());var o,i;if(0===t.length)return!1;const s=/path|file|dir|folder/i;return t.some((e=>s.test(e._name)))}function Nc(e){Uc=e,function(){const e=process.argv.indexOf("--completion");e>-1&&(Bc=!0,process.argv.splice(e,1));const t=process.argv.indexOf("--completion-fish");t>-1&&(qc=!0,process.argv.splice(t,1))}(),Dc=y("coze"),Dc.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 s="";o.line.endsWith(" ")?(s="",""===i[i.length-1]&&i.pop()):s=i.pop()||"";const n=function(e,t,o){let i=e;for(const e of t){const t=i.commands.find((t=>t.name()===e||t.alias()===e));if(t)i=t;else if(!e.startsWith("-"))return Mc(i)?[Tc]:[]}const s=[];i.commands.length>0&&i.commands.forEach((e=>{s.push(e.name())})),i.options.forEach((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))})),i!==e&&e.options.forEach((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}));const n=Array.from(new Set(s)).filter((e=>e.startsWith(o)));return 0===n.length&&Mc(i)?[Tc]:n}(e,i,s);o.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=zc();if(!e)return;const t=Rc(e);if(!t||!r.existsSync(t))return;const o=Lc(e);if(o){const e=r.readFileSync(t,"utf8").replace(new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"");r.writeFileSync(t,e)}if("bash"===e){const e=i.join(n.homedir(),".coze"),t=i.join(e,"completion.sh");r.existsSync(t)&&r.unlinkSync(t),r.existsSync(e)&&0===r.readdirSync(e).length&&r.rmdirSync(e)}}(),await l.saveConfig({completionInstalled:!1}),console.log("Shell completion removed! Please restart your terminal.");else{const e=zc();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=zc();if(!e)return!1;const t=Rc(e);if(!t)return!1;if("bash"===e){const e=i.join(n.homedir(),".coze"),t=i.join(e,"completion.sh");r.existsSync(e)||r.mkdirSync(e,{recursive:!0}),r.writeFileSync(t,xc())}const o=i.dirname(t);r.existsSync(o)||r.mkdirSync(o,{recursive:!0});const s=Lc(e);return!!s&&(r.appendFileSync(t,s),!0)}();t?(await l.saveConfig({completionInstalled:!0}),console.log(`Shell completion (${e}) setup successful! Please restart your terminal or source your config file.`)):(console.error(`Failed to setup shell completion for ${e}.`),process.exitCode=1)}}))}function $c(){return Bc?(console.log(xc()),void process.exit()):qc?(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]" = "${Tc}"`," 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(!Uc)return void process.exit();const e=process.argv.indexOf("--comppwsh"),t=process.argv.slice(e+1);let o=Uc;const i=[];for(const e of t){const t=Oc([o,"access",e=>e.commands,"optionalAccess",e=>e.find,"call",t=>t((t=>t.name()===e||t.alias()===e))]);t?o=t:i.push(e)}const s=[];Oc([o,"access",e=>e.commands,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{s.push(e.name())}))]),Oc([o,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}))]),o!==Uc&&Oc([Uc,"access",e=>e.options,"optionalAccess",e=>e.forEach,"call",e=>e((e=>{e.flags.split(/[ ,|]+/).forEach((e=>{e.startsWith("<")||e.startsWith("[")||s.push(e)}))}))]);const n=i[i.length-1]||"",r=Array.from(new Set(s)).filter((e=>e.startsWith(n)));0===r.length&&Mc(o)?console.log(Tc):r.length>0&&console.log(r.join("\n")),process.exit()}():Dc&&Dc.init())}class Gc{static getInstance(){return Gc.INSTANCE||(Gc.INSTANCE=new Gc),Gc.INSTANCE}async getDefaultConversation(e){return(await t.BuildAgentApi.GetProjectDefaultConversation({project_id:e})).Data}async updateConversationSetting(e,o,i){await t.BuildAgentApi.UpdateConversationSetting({project_id:e,conversation_id:o,...void 0!==i.modelSetting?{model_setting:i.modelSetting}:{},...void 0!==i.skillSetting?{skill_setting:i.skillSetting}:{},...void 0!==i.mode?{mode:i.mode}:{},...void 0!==i.agentTools?{agent_tools:i.agentTools}:{}})}}const Fc=Gc.getInstance();function Vc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Wc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Hc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Jc=o=>{const i=o.command("tools").config({help:{brief:"Manage project tools",description:"Manage tools associated with a project. Tools extend project capabilities such as web search, image generation, etc.",examples:[{desc:"List project tools",cmd:"coze code tools list -p <projectId>"},{desc:"Enable a tool",cmd:"coze code tools enable enable_image_gen -p <projectId>"},{desc:"Disable a tool",cmd:"coze code tools disable enable_image_gen -p <projectId>"}],seeAlso:["coze code project","coze code model"]}}).description("Manage project tools");!function(e){e.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"}}}}}}}).action((async function(e,o){const i=o.getContext(),{projectId:s}=e,n=Vc([await t.IdeApi.GetVibeProject({project_id:s}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=Vc([await Fc.getDefaultConversation(s),"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools]),a=Vc([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===n)),"optionalAccess",e=>e.tools]);if(!a||0===a.length)return Vc([i,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("No tools available for this project type.")]),void Vc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e([])]);const c=a.map((e=>({tool_name:e.name,description:e.description||e.display_name,enabled:Vc([r,"optionalAccess",t=>t[e.name]])})));Vc([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${c.length} tools.`)]),Vc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(c)])}))}(i),function(o){o.command("enable <toolName>").description("Enable a conversation tool").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Enable a conversation tool",description:"Enable a specified tool in the default conversation settings.",examples:[{desc:"Enable image generation",cmd:"coze code tools enable enable_image_gen -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{toolName:{type:"string",required:!0,description:"Tool name to enable"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},enable_tool_name:{type:"string",description:"Enabled tool name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified tool is not available for this project type",fix:"Use 'coze code tools list -p <projectId>' to see available tools"}]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=Wc([await t.IdeApi.GetVibeProject({project_id:r}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=Wc([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===a)),"optionalAccess",e=>e.tools]);if(!Wc([c,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Tool '${o}' is not available for this project type`,{toolName:o,projectId:r});const l=await Fc.getDefaultConversation(r),d=Wc([l,"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools])||{};await Fc.updateConversationSetting(r,l.id,{agentTools:{...d,[o]:!0}}),Wc([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Tool '${o}' enabled.`)]),Wc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,enable_tool_name:o,message:`Tool '${o}' has been enabled successfully`})])}))}(i),function(o){o.command("disable <toolName>").description("Disable a conversation tool").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Disable a conversation tool",description:"Disable a specified tool in the default conversation settings.",examples:[{desc:"Disable image generation",cmd:"coze code tools disable enable_image_gen -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{toolName:{type:"string",required:!0,description:"Tool name to disable"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},disable_tool_name:{type:"string",description:"Disabled tool name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified tool is not available for this project type",fix:"Use 'coze code tools list -p <projectId>' to see available tools"}]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=Hc([await t.IdeApi.GetVibeProject({project_id:r}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),c=Hc([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===a)),"optionalAccess",e=>e.tools]);if(!Hc([c,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Tool '${o}' is not available for this project type`,{toolName:o,projectId:r});const l=await Fc.getDefaultConversation(r),d=Hc([l,"access",e=>e.conversation_setting,"optionalAccess",e=>e.agent_tools])||{};await Fc.updateConversationSetting(r,l.id,{agentTools:{...d,[o]:!1}}),Hc([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Tool '${o}' disabled.`)]),Hc([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,disable_tool_name:o,message:`Tool '${o}' has been disabled successfully`})])}))}(i)};function Kc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Qc(e,t){return null!=e?e:t()}function Yc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Zc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Xc(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function el(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const tl=o=>{const i=o.command("skill").config({help:{brief:"Manage project skills",description:"Manage skills associated with a project. Skills are important components to extend project capabilities, supporting adding, viewing, and removing project skills.",examples:[{desc:"List project skills",cmd:"coze code skill list -p <projectId>"},{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>"},{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>"}],seeAlso:["coze code project"]}}).description("Manage project skills");!function(o){o.command("list").description("List available skills for the project").requiredOption("-p, --project-id <projectId>","Project ID").option("--space-id <spaceId>","Space ID (optional, reads from config)").option("--my","List personal skills only").option("--page <page>","Page number (for personal skills)").option("--size <size>","Page size (for personal skills)").config({help:{brief:"List available skills for the project",description:"Retrieve a list of all available skills for the specified project type, with installation status indicating which skills are already added.",examples:[{desc:"List project skills",cmd:"coze code skill list --project-id <projectId>",tags:["[RECOMMENDED]"]},{desc:"List personal skills",cmd:"coze code skill list -p <projectId> --my"},{desc:"List personal skills with pagination",cmd:"coze code skill list -p <projectId> --my --page 1 --size 10"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"},my:{type:"boolean",required:!1,description:"List personal skills only"},page:{type:"number",required:!1,description:"Page number (for personal skills, default: 1)"},size:{type:"number",required:!1,description:"Page size (for personal skills, default: 20)"}},output:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{description:{type:"string",description:"Skill description"},skill_id:{type:"string",description:"Skill ID"},name:{type:"string",description:"Skill name"},icon:{type:"string",description:"Skill icon URL"},is_installed:{type:"boolean",description:"Whether the skill is installed"}}}},total:{type:"number",description:"Total number of records (only present for --my mode)"}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}]}}).action((async function(o,i){const s=i.getContext(),{projectId:n}=o;if(o.my){const e=o.page?parseInt(o.page,10):1,t=o.size?parseInt(o.size,10):20,i=await Va.GetUserSkillList({page:e,size:t});return Yc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${Yc([i,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} personal skills.`)]),void Yc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({items:Yc([i,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({skill_id:Yc([e,"optionalAccess",e=>e.skill_id]),name:Yc([e,"optionalAccess",e=>e.name]),description:Yc([e,"optionalAccess",e=>e.description]),icon:Yc([e,"optionalAccess",e=>e.icon]),is_installed:!1})))])||[],total:Qc(Yc([i,"access",e=>e.data,"optionalAccess",e=>e.total]),(()=>0))})])}const r=Qc(Qc(o.spaceId,(()=>Yc([s,"optionalAccess",e=>e.config,"access",e=>e.spaceId]))),(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing spaceId: pass --space-id <spaceId> or set config.spaceId");const a=await t.IdeApi.GetVibeProject({project_id:n}),c=Yc([await Fc.getDefaultConversation(n),"access",e=>e.conversation_setting,"optionalAccess",e=>e.skill_setting,"optionalAccess",e=>e.skills])||[],l=new Set(c.map((e=>e.skill_id)).filter(Boolean)),d=Yc([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),p=await Va.GetSkillList({project_type:d,space_id:r,category_type_list:[d]});Yc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${Yc([p,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.length])||0} skills.`)]),Yc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({items:Yc([p,"access",e=>e.data,"optionalAccess",e=>e.skill_meta_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({description:Yc([e,"optionalAccess",e=>e.description]),skill_id:Yc([e,"optionalAccess",e=>e.skill_id]),name:Yc([e,"optionalAccess",e=>e.name]),icon:Yc([e,"optionalAccess",e=>e.icon]),is_installed:l.has(e.skill_id||"")})))])||[]})])}))}(i),function(t){t.command("add <skillId>").description("Add skills to the conversation").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add skill to conversation",description:"Add a specified skill to the default conversation. Skills can extend capabilities, such as adding search, code execution, etc.",examples:[{desc:"Add skill",cmd:"coze code skill add <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID"}},output:{project_id:{type:"string",description:"Project ID"},added_skill_ids:{type:"array",items:{type:"string"},description:"Added skill IDs"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E3002,name:"SKILL_NOT_FOUND",desc:"The specified skill does not exist",fix:"Please use `skill list` to confirm available skills"}]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t,n=[e],r=await Fc.getDefaultConversation(s);await Fc.updateConversationSetting(s,r.id,{skillSetting:{add_skills:n.map((e=>({skill_id:String(e),is_preload:!0})))}}),Zc([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skills added successfully.")]),Zc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,added_skill_ids:n,message:"added Skills successfully."})])}))}(i),function(t){t.command("remove <skillId>").description("Remove skills from the conversation").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Remove skill from conversation",description:"Remove a configured skill from the default conversation.",examples:[{desc:"Remove skill",cmd:"coze code skill remove <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},skillId:{type:"string",required:!0,description:"Skill ID to remove"}},output:{project_id:{type:"string",description:"Project ID"},removed_skill_ids:{type:"array",items:{type:"string"},description:"Removed skill IDs"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E3004,name:"SKILL_NOT_INSTALLED",desc:"The specified skill is not installed in the conversation",fix:"Please use `skill list` to confirm installed skills"}]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t,n=[e],r=await Fc.getDefaultConversation(s);await Fc.updateConversationSetting(s,r.id,{skillSetting:{remove_skills:n.map((e=>({skill_id:String(e),is_preload:!0})))}}),Kc([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill removed.")]),Kc([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:s,removed_skill_ids:n,message:"removed Skills successfully."})])}))}(i),function(t){t.command("upload <filePath>").description("Upload a personal skill").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Upload a personal skill",description:"Upload a .skill file as a personal skill. If a naming conflict exists, it will be automatically confirmed to overwrite.",examples:[{desc:"Upload a skill file",cmd:'coze code skill upload "./my-skill.skill" -p <projectId>',tags:["[RECOMMENDED]"]}],schema:{input:{filePath:{type:"string",required:!0,description:"Path to the .skill file"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},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 s=i.getContext(),{projectId:n}=o,r=g.resolve(t);if(!f.existsSync(r))throw new e.CozeError(e.ErrorCode.E1000,`File not found: ${r}`,{filePath:r});const a=g.basename(r),c=f.createReadStream(r);Xc([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Uploading skill ${a}...`)]);const l=await Va.UploadSkill({body:{file_content:c,file_name:a}},{headers:{"Content-Type":"multipart/form-data"}});if(Xc([l,"access",e=>e.data,"optionalAccess",e=>e.naming_conflict])){const e=Xc([l,"access",e=>e.data,"optionalAccess",e=>e.conflict_info,"optionalAccess",e=>e.preview_skill_key]);Xc([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Naming conflict detected, auto-confirming overwrite...")]),await Va.UploadSkillConfirm({preview_skill_key:e})}Xc([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Skill uploaded successfully.")]),Xc([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,message:"Skill uploaded successfully"})])}))}(i),function(t){t.command("delete <skillId>").description("Delete a personal skill").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete a personal skill",description:"Permanently delete a personal skill. This is different from skill remove which only unlinks a skill from the project.",examples:[{desc:"Delete a skill",cmd:"coze code skill delete <skillId> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{skillId:{type:"string",required:!0,description:"Skill ID to delete"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Skill not found or invalid skill ID",fix:"Use 'coze code skill list -p <projectId> --my' to see available skills"}]}}).action((async function(e,t,o){const i=o.getContext(),{projectId:s}=t;await Va.DeleteSkill({skill_id:e}),el([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Skill '${e}' deleted.`)]),el([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({project_id:s,message:`Skill '${e}' has been permanently deleted`})])}))}(i)};var ol,il,sl,nl,rl,al,cl,ll,dl,pl,ul,ml,gl,hl,fl,_l,yl,bl,vl,wl,Cl,El,Il,Al,Sl,jl,Pl,kl,Tl,zl,Rl,xl,Ll,Ol,Dl,Ul,Bl,ql,Ml,Nl,$l,Gl,Fl,Vl,Wl,Hl,Jl,Kl,Ql,Yl,Zl,Xl,ed,td,od,id,sd,nd,rd,ad,cd,ld,dd,pd,ud,md,gd,hd,fd,_d,yd,bd,vd,wd,Cd,Ed,Id;function Ad(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(ol||(ol={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(il||(il={})),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"}(sl||(sl={})),function(e){e[e.FullSupport=0]="FullSupport";e[e.PoorSupport=1]="PoorSupport";e[e.NotSupport=2]="NotSupport"}(nl||(nl={})),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"}(rl||(rl={})),function(e){e[e.Text=0]="Text";e[e.Markdown=1]="Markdown";e[e.JSON=2]="JSON"}(al||(al={})),function(e){e[e.Custom=0]="Custom";e[e.Creative=1]="Creative";e[e.Balance=2]="Balance";e[e.Precise=3]="Precise"}(cl||(cl={})),function(e){e[e.Auditing=0]="Auditing";e[e.Success=1]="Success";e[e.Failed=2]="Failed"}(ll||(ll={})),function(e){e[e.Official=1]="Official";e[e.Public=2]="Public";e[e.Custom=3]="Custom";e[e.Others=101]="Others"}(dl||(dl={})),function(e){e[e.Normal=0]="Normal";e[e.Offline=1]="Offline";e[e.TokenDisconnect=2]="TokenDisconnect"}(pl||(pl={})),function(e){e[e.App=1]="App";e[e.Resource=2]="Resource"}(ul||(ul={})),function(e){e[e.CozeModel=1]="CozeModel";e[e.VolcAccount=2]="VolcAccount";e[e.SelfAccount=3]="SelfAccount";e[e.SelfModel=4]="SelfModel"}(ml||(ml={})),function(e){e[e.Asc=1]="Asc";e[e.Desc=2]="Desc"}(gl||(gl={})),function(e){e[e.NoDetail=1]="NoDetail";e[e.Detail=2]="Detail";e[e.Operate=3]="Operate"}(hl||(hl={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(fl||(fl={})),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"}(_l||(_l={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi";e[e.MessagesApi=2]="MessagesApi"}(yl||(yl={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(bl||(bl={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(vl||(vl={})),function(e){e[e.Provider=1]="Provider";e[e.Custom=2]="Custom"}(wl||(wl={})),function(e){e[e.CozeAccountTypeUnknown=0]="CozeAccountTypeUnknown";e[e.CozeAccountTypePersonal=1]="CozeAccountTypePersonal";e[e.CozeAccountTypeOrganization=2]="CozeAccountTypeOrganization"}(Cl||(Cl={})),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"}(El||(El={})),function(e){e[e.Mobile=1]="Mobile";e[e.Web=2]="Web"}(Il||(Il={})),function(e){e[e.CacheClosed=0]="CacheClosed";e[e.PrefixCache=1]="PrefixCache"}(Al||(Al={})),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"}(Sl||(Sl={})),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"}(jl||(jl={})),function(e){e[e.DEFAULT=0]="DEFAULT";e[e.Chux=1]="Chux"}(Pl||(Pl={})),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"}(kl||(kl={})),function(e){e[e.PromptDiff=1]="PromptDiff";e[e.ModelDiff=2]="ModelDiff"}(Tl||(Tl={})),function(e){e[e.DraftBot=1]="DraftBot"}(zl||(zl={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(Rl||(Rl={})),function(e){e[e.Archive=1]="Archive";e[e.Rollback=2]="Rollback"}(xl||(xl={})),function(e){e[e.ProjectCopyCancel=1]="ProjectCopyCancel";e[e.ProjectCopyRetry=2]="ProjectCopyRetry"}(Ll||(Ll={})),function(e){e[e.ProjectCopy=1]="ProjectCopy";e[e.BotCopy=2]="BotCopy";e[e.VibeProjectCopy=3]="VibeProjectCopy"}(Ol||(Ol={})),function(e){e[e.ChatApi=0]="ChatApi";e[e.ResponsesApi=1]="ResponsesApi"}(Dl||(Dl={})),function(e){e[e.Bot=1]="Bot";e[e.Workflow=2]="Workflow";e[e.Application=3]="Application"}(Ul||(Ul={})),function(e){e[e.DefaultHeader=1]="DefaultHeader";e[e.SpecifiedHeader=2]="SpecifiedHeader"}(Bl||(Bl={})),function(e){e[e.VolcKms=1]="VolcKms";e[e.PlainText=2]="PlainText"}(ql||(ql={})),function(e){e[e.BatchSize=1]="BatchSize";e[e.LearningRate=2]="LearningRate";e[e.Epochs=3]="Epochs"}(Ml||(Ml={})),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"}(Nl||(Nl={})),function(e){e[e.Float=1]="Float";e[e.Int=2]="Int";e[e.Boolean=3]="Boolean";e[e.String=4]="String"}($l||($l={})),function(e){e[e.Douyin=1]="Douyin"}(Gl||(Gl={})),function(e){e[e.Terminating=1]="Terminating";e[e.Terminated=2]="Terminated"}(Fl||(Fl={})),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"}(Vl||(Vl={})),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"}(Wl||(Wl={})),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"}(Hl||(Hl={})),function(e){e[e.TotalTokens=1]="TotalTokens";e[e.TotalInput=2]="TotalInput";e[e.TotalOutput=3]="TotalOutput"}(Jl||(Jl={})),function(e){e[e.stop=1]="stop";e[e.resume=2]="resume",e[e.delete=3]="delete"}(Kl||(Kl={})),function(e){e[e.Recommend=1]="Recommend"}(Ql||(Ql={})),function(e){e[e.Default=0]="Default";e[e.Terminate=1]="Terminate"}(Yl||(Yl={})),function(e){e[e.All=0]="All";e[e.WithBenefit=1]="WithBenefit"}(Zl||(Zl={})),function(e){e[e.upload=1]="upload";e[e.TrainingSetSplit=2]="TrainingSetSplit"}(Xl||(Xl={})),function(e){e[e.Text=1]="Text";e[e.ImageFirstFrame=2]="ImageFirstFrame";e[e.ImageFirstLastFrame=3]="ImageFirstLastFrame";e[e.ReferencePicture=4]="ReferencePicture"}(ed||(ed={})),function(e){e[e.Using=1]="Using";e[e.Deleted=2]="Deleted"}(td||(td={})),function(e){e[e.Publish=0]="Publish";e[e.Archive=1]="Archive"}(od||(od={})),function(e){e[e.User=0]="User";e[e.NL2App=1]="NL2App"}(id||(id={})),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"}(sd||(sd={})),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"}(nd||(nd={})),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"}(rd||(rd={})),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"}(ad||(ad={})),function(e){e[e.Normal=0]="Normal";e[e.InReview=1]="InReview";e[e.Offline=2]="Offline"}(cd||(cd={})),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"}(ld||(ld={})),function(e){e[e.Authorized=1]="Authorized";e[e.UnAuthorized=2]="UnAuthorized";e[e.Authorizing=3]="Authorizing"}(dd||(dd={})),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"}(pd||(pd={})),function(e){e[e.SingleMode=0]="SingleMode";e[e.MultiMode=1]="MultiMode";e[e.WorkflowMode=2]="WorkflowMode"}(ud||(ud={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.Name=2]="Name"}(md||(md={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime"}(gd||(gd={})),function(e){e[e.UpdateTime=0]="UpdateTime";e[e.CreateTime=1]="CreateTime";e[e.PublishTime=2]="PublishTime";e[e.OpenTime=3]="OpenTime"}(hd||(hd={})),function(e){e[e.Standard=0]="Standard";e[e.PrefixPrompt=1]="PrefixPrompt"}(fd||(fd={})),function(e){e[e.All=0]="All";e[e.CreateByMe=1]="CreateByMe";e[e.AllWithCollaborator=2]="AllWithCollaborator";e[e.CanImportToSpace=3]="CanImportToSpace"}(_d||(_d={})),function(e){e[e.Desc=0]="Desc";e[e.Asc=1]="Asc"}(yd||(yd={})),function(e){e[e.Copy=1]="Copy";e[e.Move=2]="Move";e[e.Publish=3]="Publish";e[e.ImportExport=4]="ImportExport"}(bd||(bd={})),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"}(vd||(vd={})),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"}(wd||(wd={})),function(e){e[e.Success=1]="Success";e[e.Processing=2]="Processing";e[e.Failed=3]="Failed";e[e.Canceled=4]="Canceled"}(Cd||(Cd={})),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"}(Ed||(Ed={})),function(e){e[e.Packing=0]="Packing";e[e.PackSuccess=1]="PackSuccess";e[e.PackFail=2]="PackFail"}(Id||(Id={}));class Sd{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){Sd.prototype.__init.call(this),Sd.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)}Ping(e,t){const o=this.genBaseURL("/api/intelligence_api/ping");return this.request({url:o,method:"POST"},t)}DraftProjectCreate(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/create"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri,monetization_conf:o.monetization_conf,create_from:o.create_from,folder_id:o.folder_id,type:o.type};return this.request({url:i,method:"POST",data:s},t)}GetDraftIntelligenceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_list"),s={space_id:o.space_id,name:o.name,has_published:o.has_published,status:o.status,types:o.types,search_scope:o.search_scope,folder_id:o.folder_id,folder_include_children:o.folder_include_children,order_type:o.order_type,project_type:o.project_type,is_fav_filter:o.is_fav_filter,is_collaborator_filter:o.is_collaborator_filter,organization_id:o.organization_id,is_fav:o.is_fav,recently_open:o.recently_open,option:o.option,order_by:o.order_by,cursor_id:o.cursor_id,size:o.size};return this.request({url:i,method:"POST",data:s},t)}DraftProjectUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/update"),s={project_id:o.project_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetDraftIntelligenceInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/search/get_draft_intelligence_info"),s={intelligence_id:o.intelligence_id,intelligence_type:o.intelligence_type,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GetUserRecentlyEditIntelligence(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/search/get_recently_edit_intelligence"),s={size:o.size,types:o.types,enterprise_id:o.enterprise_id,organization_id:o.organization_id};return this.request({url:i,method:"POST",data:s},t)}DraftProjectCopy(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/copy"),s={project_id:o.project_id,to_space_id:o.to_space_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}ProcessEntityTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/entity_task/process"),s={entity_id:o.entity_id,action:o.action,task_id_list:o.task_id_list};return this.request({url:i,method:"POST",data:s},t)}DraftProjectDelete(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/delete"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}EntityTaskSearch(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/entity_task/search"),s={task_list:o.task_list};return this.request({url:i,method:"POST",data:s},t)}ListIntelligenceCollaboration(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/collaboration/list"),s={intelligence_id:o.intelligence_id,intelligence_type:o.intelligence_type};return this.request({url:i,method:"POST",data:s},t)}OceanProjectCreate(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/ocean_project/create"),s={space_id:o.space_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}OceanProjectUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/ocean_project/update"),s={project_id:o.project_id,name:o.name,description:o.description,icon_uri:o.icon_uri};return this.request({url:i,method:"POST",data:s},t)}GetOceanProjectList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_list"),s={space_id:o.space_id,status:o.status,search_scope:o.search_scope,order_by:o.order_by,page_index:o.page_index,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PublishProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_project"),s={project_id:o.project_id,version_number:o.version_number,description:o.description,connectors:o.connectors,connector_publish_config:o.connector_publish_config};return this.request({url:i,method:"POST",data:s},t)}GetPublishRecordDetail(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_record_detail"),s={project_id:o.project_id,publish_record_id:o.publish_record_id};return this.request({url:i,method:"POST",data:s},t)}GetPublishRecordList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_record_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublishConnectorList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/connector_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}CheckProjectVersionNumber(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/check_version_number"),s={project_id:o.project_id,version_number:o.version_number};return this.request({url:i,method:"POST",data:s},t)}DraftProjectInnerTaskList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/inner_task_list"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}GetOceanProjectInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_ocean_project_info"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}GetModelListFilterParams(e,t){const o=this.genBaseURL("/api/intelligence_api/model/get_model_list_filter_params");return this.request({url:o,method:"POST"},t)}StartEstimatedTrainingCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/start_estimated_training_cost"),s={base_model_id:o.base_model_id,space_id:o.space_id,training_dataset_id:o.training_dataset_id,epochs:o.epochs};return this.request({url:i,method:"POST",data:s},t)}GetModelList(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_list"),s={space_id:o.space_id,name:o.name,tag_filters:o.tag_filters,context_len_min:o.context_len_min,context_len_max:o.context_len_max,model_cost_min:o.model_cost_min,model_cost_max:o.model_cost_max,model_vendor:o.model_vendor,statusList:o.statusList,model_show_family_id:o.model_show_family_id,model_source:o.model_source,order_by:o.order_by,cursor_id:o.cursor_id,limit:o.limit};return this.request({url:i,method:"POST",data:s},t)}GetFinetuneTemplateDataset(e,t){const o=this.genBaseURL("/api/intelligence_api/model/get_finetune_template_dataset");return this.request({url:o,method:"POST"},t)}GetModelUsageData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_usage_data"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTrainingCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_training_cost"),s={task_id:o.task_id,space_id:o.space_id,base_model_id:o.base_model_id,epochs:o.epochs};return this.request({url:i,method:"POST",data:s},t)}CreateFinetuneTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/create_finetune_task"),s={space_id:o.space_id,base_model_id:o.base_model_id,training_dataset_id:o.training_dataset_id,validating_dataset:o.validating_dataset,finetune_configuration:o.finetune_configuration,description:o.description,name:o.name};return this.request({url:i,method:"POST",data:s},t)}UploadFinetuneDataset(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/upload_finetune_dataset"),s={space_id:o.space_id,fileType:o.fileType,fileName:o.fileName,data:o.data,testing_data:o.testing_data};return this.request({url:i,method:"POST",data:s},t)}GetModelInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_info"),s={space_id:o.space_id,model_id:o.model_id,is_finetuning:o.is_finetuning};return this.request({url:i,method:"POST",data:s},t)}GetFinetuneTrainingInfo(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_finetune_training_info"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}GetModelPerformanceData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_performance_data"),s={space_id:o.space_id,model_id:o.model_id,get_pct:o.get_pct};return this.request({url:i,method:"POST",data:s},t)}OperateFinetuneTask(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/operate_finetune_task"),s={id:o.id,action:o.action};return this.request({url:i,method:"POST",data:s},t)}DeleteFinetuneModel(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/delete_finetune_model"),s={model_id:o.model_id,space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}GetUserCompleteProfileRecord(e,t){const o=this.genBaseURL("/api/intelligence_api/user_profile/get_user_complete_profile_record");return this.request({url:o,method:"POST"},t)}DownloadUserProfile(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/user_profile/download_user_profile"),s={Cookie:o.Cookie};return this.request({url:i,method:"POST",headers:s},t)}GetProjectPublishedConnector(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/get_published_connector"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublishIntelligenceUnList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/publish/publish_intelligence_unlist"),s={intelligence_id:o.intelligence_id,connector_ids:o.connector_ids,intelligence_type:o.intelligence_type};return this.request({url:i,method:"POST",data:s},t)}PublishIntelligenceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_publish_intelligence_list"),s={intelligence_type:o.intelligence_type,space_id:o.space_id,owner_id:o.owner_id,name:o.name,order_last_publish_time:o.order_last_publish_time,order_total_token:o.order_total_token,size:o.size,cursor_id:o.cursor_id,intelligence_ids:o.intelligence_ids};return this.request({url:i,method:"POST",data:s},t)}UpdateDiffModeInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/diff_mode/update_diff_mode_info"),s={target_type:o.target_type,target_id:o.target_id,diff_mode_info:o.diff_mode_info,exit_and_save:o.exit_and_save,exit_and_discard:o.exit_and_discard};return this.request({url:i,method:"POST",data:s},t)}GetDiffModeInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/diff_mode/get_diff_mode_info"),s={target_type:o.target_type,target_id:o.target_id};return this.request({url:i,method:"POST",data:s},t)}GetProjectPublishSummary(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_project_publish_summary"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}DraftProjectCrossSpaceCopy(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/draft_project/crossspace_copy"),s={project_id:o.project_id,to_space_id:o.to_space_id};return this.request({url:i,method:"POST",data:s},t)}EntityTaskList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/entity_task/list"),s={space_id:o.space_id,task_id_list:o.task_id_list};return this.request({url:i,method:"POST",data:s},t)}ExpansionTpm(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/expansion_tpm"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,organization_id:o.organization_id,tpm_input_expansion:o.tpm_input_expansion,tpm_output_expansion:o.tpm_output_expansion,start_time:o.start_time,end_time:o.end_time};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTpmExpansionCost(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion_cost"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,input_tpm:o.input_tpm,output_tpm:o.output_tpm};return this.request({url:i,method:"POST",data:s},t)}GetEstimatedTpmExpansion(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_estimated_tpm_expansion"),s={model_id:o.model_id,enterprise_id:o.enterprise_id,estimated_rpm:o.estimated_rpm,StartTime:o.StartTime,EndTime:o.EndTime};return this.request({url:i,method:"POST",data:s},t)}FolderUpdate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/update"),s={folder_id:o.folder_id,name:o.name,description:o.description};return this.request({url:i,method:"POST",data:s},t)}GetFolderList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/search/get_folder_list"),s={space_id:o.space_id,type:o.type,name:o.name,search_scope:o.search_scope,parent_folder_id:o.parent_folder_id,parent_include_children:o.parent_include_children,order_by:o.order_by,order_type:o.order_type,size:o.size,page_num:o.page_num};return this.request({url:i,method:"POST",data:s},t)}FolderMove(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/move"),s={folder_id:o.folder_id,parent_folder_id:o.parent_folder_id};return this.request({url:i,method:"POST",data:s},t)}FolderDelete(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/delete"),s={folder_id:o.folder_id};return this.request({url:i,method:"POST",data:s},t)}FolderCreate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/create"),s={space_id:o.space_id,type:o.type,name:o.name,description:o.description,parent_folder_id:o.parent_folder_id};return this.request({url:i,method:"POST",data:s},t)}ArchiveProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/archive"),s={project_id:o.project_id,description:o.description,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetIntelligenceTaskInfo(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/entity_task/task_info"),s={task_id:o.task_id};return this.request({url:i,method:"GET",params:s},t)}ProjectHistoryList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list"),s={project_id:o.project_id,history_type:o.history_type,cursor:o.cursor,size:o.size};return this.request({url:i,method:"POST",data:s},t)}RollbackProject(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/rollback"),s={project_id:o.project_id,rollback_version:o.rollback_version,scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}GetModelConcurrencyPerformanceData(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_concurrency_performance_data"),s={space_id:o.space_id,model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}UpdateModelConfigType(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/update_model_config_type"),s={space_id:o.space_id,model_id:o.model_id,config_type:o.config_type};return this.request({url:i,method:"POST",data:s},t)}GetSpaceModelUserConfig(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_space_model_user_config"),s={space_id:o.space_id};return this.request({url:i,method:"POST",data:s},t)}OpenGetProjectList(e,t){const o=e||{},i=this.genBaseURL("/v1/apps"),s={workspace_id:o.workspace_id,publish_status:o.publish_status,connector_id:o.connector_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}OpenGetBotList(e,t){const o=e||{},i=this.genBaseURL("/v1/bots"),s={workspace_id:o.workspace_id,publish_status:o.publish_status,connector_id:o.connector_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}GetFolderTree(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/tree"),s={space_id:o.space_id,type:o.type};return this.request({url:i,method:"POST",data:s},t)}OpenGetSpaceFolder(e,t){const o=e||{},i=this.genBaseURL("/v1/folders"),s={workspace_id:o.workspace_id,folder_type:o.folder_type,parent_folder_id:o.parent_folder_id,page_num:o.page_num,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}MoveObjectToFolder(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/folder/move_object"),s={dest_folder_id:o.dest_folder_id,folder_space_id:o.folder_space_id,move_objects:o.move_objects};return this.request({url:i,method:"POST",data:s},t)}GetFolderInfoByIds(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/folder/get_by_ids"),s={space_id:o.space_id,folder_ids:o.folder_ids,get_path_info:o.get_path_info};return this.request({url:i,method:"POST",data:s},t)}OpenGetFolderInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/folders/${o.folder_id}`);return this.request({url:i,method:"GET"},t)}ExportPreCheck(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/export_pre_check"),s={res_type:o.res_type,id:o.id,commit_id:o.commit_id};return this.request({url:i,method:"POST",data:s},t)}ImportPreCheck(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/import_pre_check"),s={package_uri:o.package_uri};return this.request({url:i,method:"POST",data:s},t)}GetUploadAuthToken(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/upload/auth_token"),s={scene:o.scene};return this.request({url:i,method:"POST",data:s},t)}MarkProjectHistory(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list/read"),s={project_id:o.project_id,version:o.version};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelDetail(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_detail"),s={model_id:o.model_id,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_list"),s={search_key:o.search_key,sort_field:o.sort_field,org_id:o.org_id,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetProjectHistoryNotice(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/draft_project/history_list/notice"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}BindCustomModelSpace(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/bind_custom_model_space"),s={model_id:o.model_id,space_id_list:o.space_id_list,status:o.status,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelSpaceList(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_space_list"),s={model_id:o.model_id,search_key:o.search_key,org_id:o.org_id,cursor_id:o.cursor_id,limit:o.limit,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelParameterTemplate(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/get_custom_model_parameter_template"),s={org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}OpenCopyTaskInfo(e,t){const o=e||{},i=this.genBaseURL(`/v1/entities/copy_tasks/${o.task_id}`);return this.request({url:i,method:"GET"},t)}OpenDuplicateDraftEntity(e,t){const o=e||{},i=this.genBaseURL("/v1/entities/copy_tasks"),s={entity_id:o.entity_id,entity_type:o.entity_type,to_workspace_id:o.to_workspace_id};return this.request({url:i,method:"POST",data:s},t)}ConvertCustomModelParameter(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/convert_custom_model_parameter"),s={parameters:o.parameters,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}CreateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/create_custom_model"),s={model_name:o.model_name,model_icon_uri:o.model_icon_uri,model_arch:o.model_arch,model_desc:o.model_desc,base_url:o.base_url,secret_name:o.secret_name,model_runtime_tag:o.model_runtime_tag,inputLength:o.inputLength,parameters:o.parameters,api_agreement:o.api_agreement,safety_guardrails:o.safety_guardrails,auth:o.auth,api_mode:o.api_mode,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}TerminateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/terminate_custom_model"),s={model_id:o.model_id,terminate_time:o.terminate_time,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}UpdateCustomModel(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/model/update_custom_model"),s={model_name:o.model_name,model_icon_uri:o.model_icon_uri,model_arch:o.model_arch,model_desc:o.model_desc,base_url:o.base_url,secret_name:o.secret_name,model_runtime_tag:o.model_runtime_tag,inputLength:o.inputLength,parameters:o.parameters,model_id:o.model_id,api_agreement:o.api_agreement,safety_guardrails:o.safety_guardrails,auth:o.auth,api_mode:o.api_mode,org_id:o.org_id};return this.request({url:i,method:"POST",data:s},t)}GetModelUsageRecord(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_model_usage_record"),s={space_id:o.space_id,model_id:o.model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp,order_by_type:o.order_by_type,order_by_field:o.order_by_field,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}GetEntityModelUsage(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_entity_model_usage"),s={space_id:o.space_id,model_id:o.model_id,entity_id:o.entity_id,entity_type:o.entity_type,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}GetTypeList(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/get_type_list"),s={model:o.model,voice:o.voice,raw_model:o.raw_model,space_id:o.space_id,cur_model_id:o.cur_model_id,cur_model_ids:o.cur_model_ids,model_scene:o.model_scene,tag_filters:o.tag_filters,user_benefit_filter:o.user_benefit_filter};return this.request({url:i,method:"POST",data:s},t)}SaveModelReplacement(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/save_replacement"),s={space_id:o.space_id,old_model_id:o.old_model_id,new_model_id:o.new_model_id,start_timestamp:o.start_timestamp,end_timestamp:o.end_timestamp};return this.request({url:i,method:"POST",data:s},t)}GetModelReplacement(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/model/get_replacement"),s={space_id:o.space_id,entity_type:o.entity_type,entity_id:o.entity_id};return this.request({url:i,method:"POST",data:s},t)}UpdateCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/update"),s={model_id:o.model_id,display_name:o.display_name,model_name:o.model_name,base_url:o.base_url,api_mode:o.api_mode,auth:o.auth,support_image_understanding:o.support_image_understanding,max_tokens:o.max_tokens};return this.request({url:i,method:"POST",data:s},t)}ListProviderModels(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/list_provider_models"),s={provider:o.provider,auth:o.auth,base_url:o.base_url,search_key:o.search_key};return this.request({url:i,method:"POST",data:s},t)}ListCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/list"),s={account_type:o.account_type,coze_account_id:o.coze_account_id,enterprise_id:o.enterprise_id,search_key:o.search_key,provider:o.provider,source_type:o.source_type,sort_field:o.sort_field,sort_order:o.sort_order,page:o.page,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}ToggleCustomModelMemberVisibility(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/toggle_member_visibility"),s={model_id:o.model_id,member_visible:o.member_visible};return this.request({url:i,method:"POST",data:s},t)}DeleteCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/delete"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}ListProviders(e,t){const o=e||{},i=this.genBaseURL("/api/intelligence_api/custom_model/list_providers"),s={only_enabled:o.only_enabled};return this.request({url:i,method:"POST",data:s},t)}GetCustomModelDetailV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/detail"),s={model_id:o.model_id};return this.request({url:i,method:"POST",data:s},t)}CreateCustomModelV2(e,t){const o=e,i=this.genBaseURL("/api/intelligence_api/custom_model/create"),s={source_type:o.source_type,provider:o.provider,display_name:o.display_name,model_name:o.model_name,base_url:o.base_url,api_mode:o.api_mode,auth:o.auth,support_image_understanding:o.support_image_understanding,max_tokens:o.max_tokens,account_type:o.account_type,coze_account_id:o.coze_account_id,enterprise_id:o.enterprise_id};return this.request({url:i,method:"POST",data:s},t)}}const jd=new Sd({}),Pd={agent:jl.VibeProjectAgent,workflow:jl.VibeProjectAutomation,webapp:jl.VibeProjectWebApp,app:jl.VibeProjectApp,skill:jl.VibeProjectSkill,web:jl.VibeProjectGeneralWeb,miniprogram:jl.VibeProjectWechatMiniProgram,assistant:jl.VibeProjectAssistantAgent},kd={[jl.VibeProjectAgent]:"agent",[jl.VibeProjectAutomation]:"workflow",[jl.VibeProjectWebApp]:"webapp",[jl.VibeProjectApp]:"app",[jl.VibeProjectSkill]:"skill",[jl.VibeProjectGeneralWeb]:"web",[jl.VibeProjectWechatMiniProgram]:"miniprogram",[jl.VibeProjectAssistantAgent]:"assistant"};function Td(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return Pd[o]}const zd=e=>kd[e],Rd=[jl.VibeProjectAgent,jl.VibeProjectAutomation,jl.VibeProjectWebApp,jl.VibeProjectApp,jl.VibeProjectSkill,jl.VibeProjectGeneralWeb,jl.VibeProjectWechatMiniProgram,jl.VibeProjectAssistantAgent].map(zd).filter(Boolean);function xd(e,t){return null!=e?e:t()}function Ld(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Od(e,t){return null!=e?e:t()}function Dd(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ud=["github","local"];const Bd={agent:t.VibeProjectType.Agent,workflow:t.VibeProjectType.Automation,webapp:t.VibeProjectType.WebApp,app:t.VibeProjectType.App,skill:t.VibeProjectType.Skill,web:t.VibeProjectType.GeneralWeb,miniprogram:t.VibeProjectType.WechatMiniProgram,assistant:t.VibeProjectType.AssistantAgent},qd={[t.VibeProjectType.Agent]:"agent",[t.VibeProjectType.Automation]:"workflow",[t.VibeProjectType.WebApp]:"webapp",[t.VibeProjectType.App]:"app",[t.VibeProjectType.Skill]:"skill",[t.VibeProjectType.GeneralWeb]:"web",[t.VibeProjectType.WechatMiniProgram]:"miniprogram",[t.VibeProjectType.AssistantAgent]:"assistant"};function Md(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return Bd[o]}const Nd=e=>qd[e],$d={ask:t.ProjectMode.Ask,agent:t.ProjectMode.Agent,dangerous_confirm:t.ProjectMode.DangerousConfirm,plan:t.ProjectMode.Plan};t.ProjectMode.Ask,t.ProjectMode.Agent,t.ProjectMode.DangerousConfirm,t.ProjectMode.Plan;const Gd={[t.ConversationMode.Ask]:"ask",[t.ConversationMode.Agent]:"agent",[t.ConversationMode.DangerousConfirm]:"dangerous_confirm",[t.ConversationMode.Plan]:"plan"};function Fd(e){if(!e)return;const t=String(e).trim();if(!t)return;const o=t.toLowerCase();return $d[o]}function Vd(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Wd(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Hd={project_id:"7603316828982525988",icon_uri:"gen_project_icon/2026-02-06/7603316828982525988_1770308040.png",name:"OpenClaw助手(副本)",description:"OpenClaw智能代理:提供多场景AI服务,自动化处理任务,提升工作效率。"};class Jd{static getInstance(){return Jd.INSTANCE||(Jd.INSTANCE=new Jd),Jd.INSTANCE}sendMessageRunTask(e){const t=[g.resolve(__dirname,"./send-message.worker.js")],o=process.execPath;v.spawn(o,[...t,JSON.stringify(e)],{detached:!0,stdio:"ignore"}).unref()}async sendMessage(e){return await t.sendProjectChatMessage(e)}}const Kd=Jd.getInstance();function Qd(e,t){return null!=e?e:t()}function Yd(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Zd=new Set([t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.WechatMiniProgram]);function Xd(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const ep=o=>{const i=o.command("project").alias("proj").config({help:{brief:"Manage Coze Coding projects",description:"Manage Coze Coding projects (Vibe Project). Supports creating, viewing, listing, and deleting projects, covering various project types like Agent, Workflow, Skill, Web apps, Mini-programs, etc.",examples:[{desc:"Create project",cmd:'coze code project create --message "Create a chatbot" --type web'},{desc:"List projects",cmd:"coze code project list"},{desc:"View project details",cmd:"coze code project get <projectId>"},{desc:"Delete project",cmd:"coze code project delete <projectId>"}],seeAlso:["coze code deploy","coze code skill"],schema:{input:{},output:{}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).description("Manage Coze Coding projects");i.command("create").description("Create a new project").requiredOption("--message <message>","Description/requirements for creating the project").requiredOption("--type <type>","Project type: agent | workflow | app | skill | web | miniprogram | assistant").option("--org-id <orgId>","Organization ID (optional, will read from context automatically)").option("--space-id <spaceId>","Space ID (optional, will read from context automatically)").option("--wait","Wait for project creation to complete").option("--chat-mode <chatMode>","Chat mode: ask | agent | dangerous_confirm | plan").option("--model-name <modelName>","Model name for the project").option("--tool-name <toolName>","Tool names to enable (can specify multiple times)",((e,t)=>t.concat(e)),[]).option("--design","Enable design wizard (auto-enabled when --chat-mode is plan)").config({help:{brief:"Create a new Coze Coding project",description:"Create a new Coze Coding project via natural language description. The system will automatically generate project structure and configuration based on the description, supporting multiple project types.",examples:[{desc:"Create an Agent project",cmd:'coze code project create --message "Create an intelligent customer service robot" --type agent',tags:["[RECOMMENDED]"]},{desc:"Create a Workflow project",cmd:'coze code project create --message "Create a data processing workflow" --type workflow'}],schema:{input:{message:{type:"string",required:!0,description:"Project description/requirements (natural language)"},type:{type:"string",required:!0,enum:Object.keys(Bd),description:"Project type"},spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"},chatMode:{type:"string",enum:Object.keys($d),required:!1,description:'Chat mode: ask (对话模式) | agent (Agent模式, default) | dangerous_confirm (危险操作需确认) | plan (计划模式). When set to "plan", --design is auto-enabled.'},modelName:{type:"string",required:!1,description:"Model name for the project"},toolName:{type:"array",required:!1,description:"Tool names to enable (can specify multiple times with --tool-name)"},design:{type:"boolean",required:!1,description:"Enable design wizard. Auto-enabled when --chat-mode is plan. Only supported for web/app/miniprogram project types."}},output:{project_id:{type:"string",description:"Created project ID"},type:{type:"string",description:"Project type"}}},enums:{type:Object.keys(Bd).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(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Qd(Qd(o.spaceId,(()=>Yd([s,"optionalAccess",e=>e.config,"access",e=>e.spaceId]))),(()=>"")),{message:r,type:a,wait:c,chatMode:l,modelName:d,toolName:p,design:u}=o,m=Boolean(u)||"plan"===l;Yd([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e(`Resolving project type '${a}'...`)]);const g=Md(a);if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!g)throw new e.CozeError(e.ErrorCode.E1005,`Unknown project type: ${a}`,{type:a});Yd([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching agent tools configuration...")]);const h=Yd([await t.BuildAgentApi.GetTools(),"access",e=>e.project_types,"optionalAccess",e=>e.find,"call",e=>e((e=>e.project_type===g)),"optionalAccess",e=>e.tools]);if(!h||0===h.length)throw new e.CozeError(e.ErrorCode.E5000,`No tools config for projectType: ${String(a)}`,{type:a,projectType:g});const f={};h.forEach((e=>{Yd([e,"optionalAccess",e=>e.name])&&(f[e.name]=Qd(Yd([p,"optionalAccess",e=>e.includes,"call",t=>t(e.name)]),(()=>Boolean(e.enabled))))})),Yd([s,"optionalAccess",e=>e.log,"access",e=>e.debug,"call",e=>e("Fetching project default skills...")]);const _={skills:Qd(Yd([await Va.GetProjectDefaultSkill({project_type:g,space_id:String(n)}),"access",e=>e.data,"optionalAccess",e=>e.skill_list]),(()=>[])).map((e=>({skill_id:e.skill_id,is_preload:e.is_preload}))),filter_types:[g]};let y;if(g===t.VibeProjectType.AssistantAgent){Yd([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating assistant project via template copy...")]);const e=await t.IdeApi.CopyVibeProject({...Hd,target_space_id:String(n)});y=Yd([e,"access",e=>e.data,"optionalAccess",e=>e.basic_info,"optionalAccess",e=>e.project_id])}else{Yd([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Creating project...")]);const e=Qd((await t.IdeApi.ChatCreateVibeProject({space_id:String(n),user_query:r,project_type:g,project_settings:{...Zd.has(g)?{project_symbol:t.ProjectSymbol.ProjectSymbolVersion3}:{},model_setting:{model_name:d||""},agent_tools:f,skill_setting:_,...l?{project_mode:Fd(l)}:{},...m?{wizards:{design:!0}}:{}}})).data,(()=>({})));y=e.project_id}const b=await Yd([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!b)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");s.ui.success(`Project created successfully, please use "coze code message status -p ${y}" to check the status.`),Yd([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:y,type:a})]);const v=await Fc.getDefaultConversation(Qd(y,(()=>"")));if(c){const e=await Kd.sendMessage({projectId:Qd(y,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:b,xTTEnv:s.config.xTTEnv,conversationId:v.id,key:`coze-coding-cli:message:${y}`});s.response.print(e.lastAnswerMessage)}else Kd.sendMessageRunTask({projectId:Qd(y,(()=>"")),prompt:r,apiBaseUrl:s.config.apiBaseUrl,accessToken:b,xTTEnv:s.config.xTTEnv,conversationId:v.id,key:`coze-coding-cli:message:${y}`})})),function(t){t.command("list").description("List all projects").config({help:{brief:"List all projects in the current space",description:"Get the list of projects in the current space. Supports filtering by type, name, publish status, and supports pagination.",examples:[{desc:"List projects",cmd:"coze code project list",tags:["[RECOMMENDED]"]},{desc:"Filter by type",cmd:"coze code project list --type agent --type workflow"},{desc:"Search by name",cmd:'coze code project list --name "customer service"'}],schema:{input:{size:{type:"number",required:!1,description:"Number of projects to return (default: 10)"},cursorId:{type:"string",required:!1,description:"Cursor for pagination"},type:{type:"array",required:!1,description:"Project type filter (can be passed multiple times)"},name:{type:"string",required:!1,description:"Filter by project name"},hasPublished:{type:"boolean",required:!1,description:"Filter by publish status"},searchScope:{type:"number",required:!1,description:"Created by (All = 0, CreateByMe = 1, AllWithCollaborator = 2)"},folderId:{type:"string",required:!1,description:"Folder ID"},orderType:{type:"number",required:!1,description:"Sort type (0 for descending, 1 for ascending)"},orderBy:{type:"number",required:!1,description:"Order by (0 for updated_at, 1 for created_at)"},isFavFilter:{type:"boolean",required:!1,description:"Filter by favorite status"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Project ID"},name:{type:"string",description:"Project name"},type:{type:"string",description:"Project type"},description:{type:"string",description:"Project description"}}}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Please use --space-id <spaceId> or run `coze space use <spaceId>` first"}],enums:{type:Rd.reduce(((e,t)=>(e[t]=`${t.toUpperCase()} project`,e)),{}),"search-scope":{0:"All",1:"CreateByMe",2:"AllWithCollaborator"},"order-type":{0:"Descending",1:"Ascending"},"order-by":{0:"updated_at",1:"created_at"}}}}).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=xd(Ld([e,"optionalAccess",e=>e.size]),(()=>10)),s=xd(Ld([e,"optionalAccess",e=>e.cursorId]),(()=>{})),n=Ld([e,"optionalAccess",e=>e.type,"optionalAccess",e=>e.map,"call",e=>e(Td),"access",e=>e.filter,"call",e=>e(Boolean)]),r=Ld([e,"optionalAccess",e=>e.name]),a=Ld([e,"optionalAccess",e=>e.hasPublished])?Boolean(Ld([e,"optionalAccess",e=>e.hasPublished])):void 0,c=Number(xd(Ld([e,"optionalAccess",e=>e.searchScope]),(()=>_d.All))),l=xd(Ld([e,"optionalAccess",e=>e.folderId]),(()=>"0")),d=Number(xd(Ld([e,"optionalAccess",e=>e.orderType]),(()=>yd.Desc))),p=Boolean(Ld([e,"optionalAccess",e=>e.isFavFilter])),u=Number(xd(Ld([e,"optionalAccess",e=>e.orderBy]),(()=>hd.UpdateTime)));let m=[];Ld([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching project list...")]);const g=await jd.GetDraftIntelligenceList({space_id:xd(Ld([o,"optionalAccess",e=>e.config,"access",e=>e.spaceId]),(()=>"")),size:i,cursor_id:s,types:n,name:r,has_published:a,search_scope:c,folder_id:l,order_type:d,order_by:u,is_fav_filter:p,status:[Sl.Using,Sl.Banned,Sl.MoveFailed]});m=Ld([g,"access",e=>e.data,"optionalAccess",e=>e.intelligences])||[],Ld([o,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetched ${m.length} projects.`)]),Ld([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(m.map((e=>({id:Ld([e,"access",e=>e.basic_info,"optionalAccess",e=>e.id]),name:Ld([e,"access",e=>e.basic_info,"optionalAccess",e=>e.name]),type:zd(e.type),description:Ld([e,"access",e=>e.basic_info,"optionalAccess",e=>e.description])}))))])}))}(i),function(o){o.command("get <projectId>").description("View project details").config({help:{brief:"Get project details",description:"Get the detailed configuration of the specified project, including project type, settings, skill configurations, etc.",examples:[{desc:"View project details",cmd:"coze code project get <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},project_name:{type:"string",description:"Project name"},project_type:{type:"string",description:"Project type"},type:{type:"string",description:"Human-readable project type string"},tools:{type:"object",description:"Project tool configurations (Record<string, boolean>)"},chat_mode:{type:"string",description:"Human-readable chat mode string"},model_name:{type:"string",description:"Current model name used by the project"},skills:{type:"object",description:"Project skill configurations",properties:{skills:{type:"array",items:{type:"object",properties:{skill_id:{type:"string",description:"Skill ID"},is_preload:{type:"boolean",description:"Is preloaded"}}}}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project does not exist",fix:"Please confirm if the project ID is correct, use `project list` to view available projects"}]}}).action((async function(o,i,s){const n=s.getContext();Vd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Fetching project details for '${o}'...`)]);try{const[i,s]=await Promise.all([t.IdeApi.GetVibeProject({project_id:o}),Fc.getDefaultConversation(o)]),r=Vd([i,"access",e=>e.data,"optionalAccess",e=>e.project_info]);if(!r)throw new e.CozeError(e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o});const a=s.conversation_setting;Vd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Project details for '${o}':`)]),Vd([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>{return e({...b.omit(r,["project_settings"]),type:Nd(Vd([r,"optionalAccess",e=>e.project_type])),tools:Vd([a,"optionalAccess",e=>e.agent_tools]),chat_mode:(t=Vd([a,"optionalAccess",e=>e.mode]),Gd[t]),model_name:Vd([a,"optionalAccess",e=>e.model_setting,"optionalAccess",e=>e.model_name]),skills:b.pick(Vd([a,"optionalAccess",e=>e.skill_setting]),["skills"])});var t}])}catch(t){W(t,e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o})}}))}(i),function(o){o.command("delete <projectId>").description("Delete a project").config({help:{brief:"Delete project",description:"Delete the specified Coze Coding project. This operation cannot be undone, please use with caution.",examples:[{desc:"Delete project",cmd:"coze code project delete <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID to delete"}},output:{project_id:{type:"string",description:"Deleted project ID"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E3005,name:"DELETE_FAILED",desc:"Failed to delete project",fix:"Please confirm if the project ID is correct and check if you have sufficient permissions"}]}}).action((async function(o,i,s){const n=s.getContext();Wd([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Deleting project '${o}'...`)]);try{await t.IdeApi.DeleteVibeProject({project_id:o})}catch(t){W(t,e.ErrorCode.E3005,`Failed to delete project '${o}': project not found or no permission`,{projectId:o})}Wd([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Project '${o}' deleted successfully.`)]),Wd([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:o,message:`Project '${o}' deleted successfully.`})])}))}(i),function(o){o.command("db").description("Manage project databases").command("list").description("List project database tables").requiredOption("-p, --project-id <projectId>","Project ID").option("--schema <schema>","Schema name (knowledge or public)").option("--env <env>","Environment: dev | prod (default: dev)").config({help:{brief:"List project database tables",description:"List all database tables for the specified project, grouped by schema.",examples:[{desc:"List all tables",cmd:"coze code project db list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List knowledge schema tables",cmd:"coze code project db list -p <projectId> --schema knowledge"},{desc:"List prod tables",cmd:"coze code project db list -p <projectId> --env prod"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},schema:{type:"string",required:!1,description:"Schema name filter"},env:{type:"string",required:!1,description:"Environment (dev or prod)"}},output:{type:"array",items:{type:"object",properties:{schema:{type:"string",description:"Schema name"},table_name:{type:"string",description:"Table name"}}}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Invalid or missing project ID",fix:"Provide a valid project ID with -p <projectId>"}]}}).action((async function(e,o){const i=o.getContext(),{projectId:s,env:n}=e,r="prod"===n?t.MemoryEnv.product:t.MemoryEnv.develop,a=[];await Promise.all(["knowledge","public"].map((async e=>{((await t.IdeApi.GetSchemaTables({project_id:s,database_env:r,schema:e})).table_names||[]).forEach((t=>{a.push({schema:e,table_name:t})}))}))),Xd([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${a.length} tables.`)]),Xd([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])}))}(i),function(o){o.command("import").description("Import a project from a remote repo or local zip file").requiredOption("-s, --source <source>","Import source: github / local").option("-r, --repo <fullName>","Remote repo full name (e.g. user/repo), required for --source github").option("-f, --file <path>","Local zip file path, required for --source local").config({help:{brief:"Import a project from a remote repo or local zip file",description:"Create a new project by importing from a remote Git repository or uploading a local zip file. Remote import requires prior OAuth authorization via `coze code git auth login`. Imported remote projects will be automatically bound to the source repo. Local uploads must be zip format and no more than 500MB.",examples:[{desc:"Import from GitHub (minimal)",cmd:"coze code project import --source github --repo user/my-app"},{desc:"Import from GitHub",cmd:"coze code project import -s github -r user/my-app",tags:["[RECOMMENDED]"]},{desc:"Upload local zip file",cmd:"coze code project import --source local --file ./project.zip"},{desc:"[PIPELINE] Import and check status",cmd:"ID=$(coze code project import -s github -r user/app --format json | jq -r .project_id) && coze code project get $ID",tags:["[PIPELINE]"]},{desc:"[TEMPLATE] Import from any source",cmd:"coze code project import --source <github|local> [--repo <owner/name>] [--file <path>]",tags:["[TEMPLATE]"]}],schema:{input:{source:{type:"string",required:!0,enum:["github","local"],description:"Import source type",example:"github"},repo:{type:"string",required:!1,description:"Remote repo full name (owner/name)",example:"user/my-app"},file:{type:"string",required:!1,description:"Local zip file path",example:"./project.zip"}},output:{project_id:{type:"string",description:"Created project ID",example:"proj_abc123"},source:{type:"string",description:"Import source type",example:"github"},repo:{type:"string",description:"Remote repo full name (if applicable)",example:"user/my-app"}}},enums:{source:{github:"Import from a GitHub repository",local:"Upload a local zip file"}},errors:[{code:e.ErrorCode.E1008,name:"MISSING_IMPORT_SOURCE",desc:"Missing import source",fix:"Use --source github or --source local"},{code:e.ErrorCode.E1009,name:"MISSING_REPO",desc:"Missing --repo for github import",fix:"Add --repo <owner/name>"},{code:e.ErrorCode.E1010,name:"MISSING_FILE",desc:"Missing --file for local import",fix:"Add --file <path>"},{code:e.ErrorCode.E1011,name:"INVALID_FILE_FORMAT",desc:"File is not zip format",fix:"Only .zip files are supported"},{code:e.ErrorCode.E1012,name:"FILE_TOO_LARGE",desc:"File exceeds 500MB",fix:"Reduce file size and retry"},{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"}],seeAlso:["coze code project create","coze code repo bind","coze code git auth login"],caveats:["Remote import requires prior OAuth authorization via `coze code git auth login`","Local upload only supports .zip format, max 500MB","Remote imported projects are automatically bound to the source repo"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=Od(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or run `coze space use <spaceId>` first");const{source:r,repo:a,file:c}=o;if(!r||!Ud.includes(r))throw new e.CozeError(e.ErrorCode.E1008,`Invalid or missing import source: "${r}". Use --source github or --source local`);if("github"===r){if(!a)throw new e.CozeError(e.ErrorCode.E1009,"Missing --repo: required when --source is github");s.ui.info(`Importing from GitHub: ${a}...`);const o=Od(Dd([await t.IdeApi.ImportProject({space_id:n,import_source:2,git_url:`https://github.com/${a}.git`,git_repo_name:a}),"access",e=>e.data,"optionalAccess",e=>e.vibe_project_id]),(()=>""));s.ui.success("Project imported successfully."),s.ui.info(` Project ID: ${o}`),s.ui.info(` Source: github (${a})`),s.response.print({project_id:o,source:"github",repo:a})}else if("local"===r){if(!c)throw new e.CozeError(e.ErrorCode.E1010,"Missing --file: required when --source is local");if(!c.endsWith(".zip"))throw new e.CozeError(e.ErrorCode.E1011,`Invalid file format: "${c}". Only .zip files are supported`);if(!f.existsSync(c))throw new e.CozeError(e.ErrorCode.E1011,`File not found: "${c}"`);const t=f.statSync(c);if(t.size>524288e3)throw new e.CozeError(e.ErrorCode.E1012,`File too large: ${Math.round(t.size/1024/1024)}MB. Maximum is 500MB`);s.ui.info(`Uploading local file: ${c}...`);const o=new _;o.append("space_id",n),o.append("import_source","1"),o.append("data",f.createReadStream(c),g.basename(c));const i=Od(Dd([await e.axiosInstance.post("/api/ideserver_api/project/import_project",o,{headers:{...o.getHeaders(),"agw-js-conv":"str"}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.vibe_project_id]),(()=>""));s.ui.success("Project imported successfully."),s.ui.info(` Project ID: ${i}`),s.ui.info(` Source: local (${c})`),s.response.print({project_id:i,source:"local"})}}))}(i)};function tp(e,t){return null!=e?e:t()}const op=["ecs","vefaas"],ip=e=>op.includes(tp(process.env.COZE_CLI_PLATFORM,(()=>"")).trim().toLowerCase())?"https://www.coze.cn/":tp(e,(()=>l.DEFAULT_CONFIG.apiBaseUrl)),sp=(e,t)=>`${ip(t)}p/${e}`;function np(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const rp=new Set([t.VibeProjectType.WechatMiniProgram,t.VibeProjectType.Agent,t.VibeProjectType.Automation,t.VibeProjectType.Skill,t.VibeProjectType.AssistantAgent]);function ap(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function cp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const lp=o=>{const i=o.command("model").config({help:{brief:"Manage project models",description:"Manage models for Coze Coding projects. List available models and set the active model for a project.",examples:[{desc:"List available models",cmd:"coze code model list -p <projectId>"},{desc:"Set project model",cmd:"coze code model set doubao-dev-0213 -p <projectId>"}],seeAlso:["coze code project","coze code tools"]}}).description("Manage project models");!function(o){o.command("list").description("List available models").option("-p, --project-id <projectId>","Project ID").option("--type <type>","Project type (web, app, agent, etc.)").config({help:{brief:"List available models",description:"List all available models for the specified project or project type.",examples:[{desc:"List models for a project",cmd:"coze code model list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List models by type",cmd:"coze code model list --type web"}],schema:{input:{projectId:{type:"string",required:!1,description:"Project ID"},type:{type:"string",required:!1,description:"Project type"}},output:{type:"array",items:{type:"object",properties:{model_name:{type:"string",description:"Model name"},display_name:{type:"string",description:"Display name"},enable:{type:"boolean",description:"Whether this model is currently set for the project (only available when using -p)"}}}}},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(o,i){const s=i.getContext(),{projectId:n}=o;let r,a,c;if(n){const e=await t.IdeApi.GetVibeProject({project_id:n});r=cp([e,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),a=cp([e,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.space_id]);const o=await Fc.getDefaultConversation(n);c=cp([o,"access",e=>e.conversation_setting,"optionalAccess",e=>e.model_setting,"optionalAccess",e=>e.model_name])}else{const t=o.type;if(!t)throw new e.CozeError(e.ErrorCode.E1000,"Project type is required",{projectId:n});r=Md(t)}if(!r)throw new e.CozeError(e.ErrorCode.E1000,"Project type is required",{projectId:n});const l=cp([await t.BuildAgentApi.GetModelList({project_id:n,project_type:r,space_id:a}),"access",e=>e.model_list,"optionalAccess",e=>e.map,"call",e=>e((e=>({model_name:e.name,display_name:e.display_name,enable:n?c===e.name:void 0})))]);cp([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Fetched ${cp([l,"optionalAccess",e=>e.length])||0} models.`)]),cp([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(l)])}))}(i),function(o){o.command("set <modelName>").description("Set conversation model").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Set conversation model",description:"Set the model used by the default conversation. Use model list to see available models.",examples:[{desc:"Set conversation model",cmd:"coze code model set doubao-dev-0213 -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{modelName:{type:"string",required:!0,description:"Model name"},projectId:{type:"string",required:!0,description:"Project ID"}},output:{project_id:{type:"string",description:"Project ID"},model_name:{type:"string",description:"Model name"},message:{type:"string",description:"Result message"}}},errors:[{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"The specified model is not available for this project",fix:"Use 'coze code model list -p <projectId>' to see available models"}]}}).action((async function(o,i,s){const n=s.getContext(),{projectId:r}=i,a=await t.IdeApi.GetVibeProject({project_id:r}),c=ap([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),l=ap([a,"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.space_id]);if(!ap([await t.BuildAgentApi.GetModelList({project_id:r,project_type:c,space_id:l}),"access",e=>e.model_list,"optionalAccess",e=>e.find,"call",e=>e((e=>e.name===o))]))throw new e.CozeError(e.ErrorCode.E1000,`Model '${o}' is not available. Use 'coze code model list' to see available models.`,{modelName:o,projectId:r});const d=await Fc.getDefaultConversation(r);await Fc.updateConversationSetting(r,d.id,{modelSetting:{model_name:o}}),ap([n,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Model set to '${o}'.`)]),ap([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:r,model_name:o,message:`Model has been set to '${o}' successfully`})])}))}(i)};function dp(e,t){return null!=e?e:t()}function pp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function up(e,t){return null!=e?e:t()}function mp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const gp=e=>{if(null==e)return null;return 0===e.trim().length?null:e},hp=o=>{o.command("send [message]").description("Send a prompt message to Coze Coding project chat").option("--wait","Wait for the chat response before returning").option("--stdin","Read additional context from stdin (pipe input)").config({help:{brief:"Send a message to project chat",description:"Send a prompt message to the specified Coze Coding project chat. The message can be provided as a positional argument. Use --stdin to pipe additional context. Use @<path> to mention and upload local files as context.",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug in auth module" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Send and wait for the response",cmd:'coze code message send "Fix the bug in auth module" -p 123456 --wait'},{desc:"Mention a file with @",cmd:'coze code message send "Refactor @src/utils.ts to use async/await" -p 123456'},{desc:"Mention multiple files",cmd:'coze code message send "Compare @src/old.ts and @src/new.ts, list the differences" -p 123456'},{desc:"Send message with stdin context",cmd:'cat error.log | coze code message send "Analyze this error" --stdin -p 123456'},{desc:"Use environment variable for project",cmd:'export COZE_PROJECT_ID=123456 && coze code message send "Hello"'}],errors:[{code:e.ErrorCode.E1000,name:"MISSING_MESSAGE",desc:"No message content provided",fix:"Provide MESSAGE argument or use --stdin with piped content",example:'coze code message send "Your question" -p 123456 # or: echo "context" | coze code message send --stdin "question" -p 123456'},{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --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(o,i,s)=>{const n=s.getContext();try{if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const r=mp([s,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),a=up(mp([r,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!a)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");const c=await mp([n,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]);if(!c)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");const{wait:l,stdin:d}=i;let p=null;d&&(p=await oa());const u=gp(o),m=gp(p);if(!u&&!m)throw new e.CozeError(e.ErrorCode.E1000,"Missing prompt: provide PROMPT argument or use --stdin");const g=u&&m?`${u}\n\n${m}`:up(up(u,(()=>m)),(()=>"")),h=await Fc.getDefaultConversation(a),f=new Set,_=await t.sendProjectChatMessage({projectId:a,conversationId:h.id,prompt:g,apiBaseUrl:n.config.apiBaseUrl,accessToken:c,xTTEnv:n.config.xTTEnv,key:`coze-coding-cli:message:${a}`,onWarn:e=>n.ui.warn(e),waitForResponse:!!l,onMessageItem:e=>{if(l&&"json"===n.format&&e.finish){const t=(e=>{const t=up(e.msg_id,(()=>"")),o=up(e.sequence_id,(()=>""));return`${e.type}:${t}:${String(o)}`})(e);f.has(t)||(f.add(t),n.response.print({content:e.content,role:e.role,finish:e.finish,type:e.type}))}}});if(l)"text"===n.format&&n.response.print(up(mp([_,"access",e=>e.lastAnswerMessage,"optionalAccess",e=>e.content,"access",e=>e.answer]),(()=>"")));else{const e=`Message sent. Use \`coze code message status -p ${a}\` to check the result.`;"json"===n.format?n.response.print({status:"sent",project_id:a,message:e}):n.response.print(e),process.exit(0)}}catch(e){H(e,n)}}))};function fp(e,t){return null!=e?e:t()}function _p(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function yp(e,t){return null!=e?e:t()}function bp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const vp=async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError("E5000","CLI context is not initialized");const n=bp([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=yp(bp([n,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!r)throw new e.CozeError("E1001","Missing required option: --project-id (or env COZE_PROJECT_ID)");if(!await bp([s,"optionalAccess",e=>e.auth,"optionalAccess",e=>e.getValidAccessToken,"call",e=>e()]))throw new e.CozeError("E2001","Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");if(o.after&&o.before)throw new e.CozeError("E1000","--after and --before cannot be used together. Use only one cursor at a time.");s.ui.verbose(`Fetching conversation history for project ${r}...`);const a=await Fc.getDefaultConversation(r),c=t.createChatCore({key:`coze-coding-cli:history:${r}`,apiBaseUrl:s.config.apiBaseUrl});try{const e=o.after?"loadNext":"loadPrev",t="loadNext"===e?"11":"10",i=await c.getHistoryMessage({limit:t,project_id:r,conversation_id:a.id,after:o.after,before:o.before}),n=[],l=new Map,d=new Map;i.histories.forEach((e=>{if(e.user){const t=e.user.msg_id;l.has(t)||n.push(t);const o=(e=>{const t=bp([e,"optionalAccess",e=>e.content]);return yp(yp(bp([t,"optionalAccess",e=>e.query,"optionalAccess",e=>e.prompt]),(()=>bp([t,"optionalAccess",e=>e.retry,"optionalAccess",e=>e.prompt]))),(()=>bp([t,"optionalAccess",e=>e.edit,"optionalAccess",e=>e.prompt])))})(e.user.message);l.set(t,o?(e=>e.map((e=>"text"===e.type?e.content.text:"file"===e.type?`${_p([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.path])} ${fp(_p([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.from,"optionalAccess",e=>e[0]]),(()=>""))} ${fp(_p([e,"access",e=>e.content,"access",e=>e.file,"optionalAccess",e=>e.to,"optionalAccess",e=>e[0]]),(()=>""))} `:"console"===e.type?_p([e,"access",e=>e.content,"access",e=>e.console,"optionalAccess",e=>e.content]):"node"===e.type?_p([e,"access",e=>e.content,"access",e=>e.node,"optionalAccess",e=>e.node_title]):"upload_file"===e.type?_p([e,"access",e=>e.content,"access",e=>e.upload_file,"optionalAccess",e=>e.file_name]):"page"===e.type?_p([e,"access",e=>e.content,"access",e=>e.page,"optionalAccess",e=>e.page_title]):"page_elements"===e.type?_p([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?_p([e,"access",e=>e.content,"access",e=>e.wf_canvas_change,"optionalAccess",e=>e.query]):"")).join(" "))(o):"")}if(e.assistant){const t=e.assistant.messages.find((e=>"answer"===e.type&&e.content.answer));if(!t)return;const o=t.query_msg_id,i=t.content.answer;"string"==typeof o&&"string"==typeof i&&d.set(o,i)}}));const p=n[0],u=n[n.length-1],m=n.reverse().filter((e=>d.has(e))).map((e=>({userMessage:yp(l.get(e),(()=>"")),answer:yp(d.get(e),(()=>""))}))),g={histories:m,cursor:{after:p,before:u,has_more:i.has_more,loadDirection:e}};if("json"===s.format)s.response.print(g);else{if(0===m.length)return void s.response.print("No conversation history found.");m.forEach(((e,t)=>{s.response.print(`--- #${t+1} ---\nQ: ${e.userMessage}\nA: ${e.answer}\n`)})),s.response.print(`\n[cursor] after=${p}, before=${u}, has_more=${i.has_more}, loadDirection=${e}`)}}finally{c.destroy()}}catch(e){H(e,s)}};function wp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Cp=o=>{const i=o.command("message");i.description("Manage project chat messages").config({help:{brief:"Manage project chat messages",description:"Manage Coze Coding project chat messages.\n\nThis command group provides:\n- send: Send a new message to the project chat\n- status: Query the status of current chat message (auto-fetch result when completed)\n- cancel: Cancel an ongoing chat message\n- history: View conversation history",examples:[{desc:"Send a message to project",cmd:'coze code message send "Fix the bug" -p 123456',tags:["[RECOMMENDED]"]},{desc:"Check message status",cmd:"coze code message status -p 123456"},{desc:"Cancel ongoing message",cmd:"coze code message cancel -p 123456"},{desc:"View conversation history",cmd:"coze code message history -p 123456"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided via -p/--project-id or COZE_PROJECT_ID env",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable",example:'coze code message send "Hello" -p 123456'},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable",example:"coze auth login --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)"),hp(i),(o=>{o.command("status").description("Query current project chat message status and get result when completed").config({help:{brief:"Query chat message status",description:"Get the current status of the chat message for the specified project. Returns status information such as running, completed, or error. When the chat is completed, automatically fetches and returns the result.",examples:[{desc:"Check message status (auto-fetch result when completed)",cmd:"coze code message status -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message status"},{desc:"Output as JSON",cmd:"coze code message status -p 123456 --format json"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Message status (running/completed/error)"},message:{type:"string",description:"Status message or error details"},answer:{type:"string",description:"The chat answer content (only when completed)"}}}}}}).action((async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const o=pp([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),n=dp(pp([o,"optionalAccess",e=>e.projectId]),(()=>process.env.COZE_PROJECT_ID));if(!n)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");s.ui.verbose(`Fetching chat status for project ${n}...`);const r=await Fc.getDefaultConversation(n),{code:a,msg:c,reply_id:l,...d}=await t.BuildAgentApi.GetChatCLIMessageStatus({project_id:n,conversation_id:r.id});if("done"===d.status){s.ui.verbose(`Chat completed, fetching result for project ${n}...`);const e=await t.BuildAgentApi.GetChatCLIMessageResultContent({project_id:n,conversation_id:r.id}),o="data"in e?e.data:e;"json"===s.format?s.response.print({...d,answer:o.answer}):s.response.print(`status: [${d.status}]\nanswer: ${dp(o.answer,(()=>""))}`)}else"json"===s.format?s.response.print(d):s.response.print(d.status)}catch(e){H(e,s)}}))})(i),function(o){o.command("cancel").description("Cancel current project chat message").config({help:{brief:"Cancel ongoing chat message",description:"Cancel the currently running chat message for the specified project. Useful for stopping long-running or stuck message generation.",examples:[{desc:"Cancel current message",cmd:"coze code message cancel -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message cancel"}],errors:[{code:e.ErrorCode.E1001,name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:e.ErrorCode.E2001,name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"},{code:e.ErrorCode.E5000,name:"UNEXPECTED_ERROR",desc:"CLI context is not initialized",fix:"Please retry and make sure the CLI is initialized correctly"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"}},output:{type:"object",properties:{status:{type:"string",description:"Cancel operation status"},message:{type:"string",description:"Result message"}}}}}}).action((async(o,i)=>{const s=i.getContext();try{if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const o=wp([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()]),r=null!=(n=wp([o,"optionalAccess",e=>e.projectId]))?n:(()=>process.env.COZE_PROJECT_ID)();if(!r)throw new e.CozeError(e.ErrorCode.E1001,"Missing required option: --project-id (or env COZE_PROJECT_ID)");const{accessToken:a}=s.config;if(!a)throw new e.CozeError(e.ErrorCode.E2001,"Missing API token: set env COZE_API_TOKEN or run `coze auth login` first");s.ui.verbose(`Canceling chat message for project ${r}...`);const c=await Fc.getDefaultConversation(r),{message:l}=await t.BuildAgentApi.CancelChatCLIMessage({project_id:r,conversation_id:c.id});"json"===s.format?s.response.print({message:l}):s.response.print(l)}catch(e){H(e,s)}var n}))}(i),(e=>{e.command("history").description("View conversation history of the project chat").option("--after <msg_id>","Cursor for fetching newer messages (smaller index)").option("--before <msg_id>","Cursor for fetching older messages (larger index)").config({help:{brief:"View conversation history",description:"Retrieve and display the conversation history for the specified Coze Coding project. Shows each round of user messages and LLM responses. By default, returns the latest 10 rounds of conversation. Use --after or --before cursors for pagination.",examples:[{desc:"View latest 10 rounds of conversation history",cmd:"coze code message history -p 123456",tags:["[RECOMMENDED]"]},{desc:"With environment variable",cmd:"coze code message history"},{desc:"Output as JSON with cursor info",cmd:"coze code message history -p 123456 --format json"},{desc:"Fetch newer messages after a cursor",cmd:"coze code message history -p 123456 --after msg_xxx"},{desc:"Fetch older messages before a cursor",cmd:"coze code message history -p 123456 --before msg_yyy"}],errors:[{code:"E1000",name:"INVALID_ARGUMENT",desc:"--after and --before cannot be used together",fix:"Use only one cursor option at a time for pagination"},{code:"E1001",name:"MISSING_PROJECT_ID",desc:"No project ID provided",fix:"Provide -p/--project-id option or set COZE_PROJECT_ID environment variable"},{code:"E2001",name:"AUTH_FAILED",desc:"Missing or invalid API token",fix:"Run `coze auth login` or set COZE_API_TOKEN environment variable"}],schema:{input:{projectId:{type:"string",required:!0,description:"Coze project ID"},after:{type:"string",description:'Cursor (message ID) for fetching newer messages. Newer messages have smaller index. Use the "after" value from previous output as this parameter.'},before:{type:"string",description:'Cursor (message ID) for fetching older messages. Older messages have larger index. Use the "before" value from previous output as this parameter.'}},output:{type:"object",properties:{histories:{type:"array",items:{type:"object",properties:{userMessage:{type:"string",description:"User's message in this round"},answer:{type:"string",description:"LLM's last answer with content"}}}},cursor:{type:"object",description:"Pagination cursor info for next/prev page requests",properties:{after:{type:"string",description:"Message ID of the newest result, use as --after to fetch newer messages (loadNext)"},before:{type:"string",description:"Message ID of the oldest result, use as --before to fetch older messages (loadPrev)"},has_more:{type:"boolean",description:"Whether there are more messages available"},loadDirection:{type:"string",enum:["loadNext","loadPrev"],description:"Load direction of current request. Defaults to 'loadPrev' (load older messages). 'loadNext' when --after is used, 'loadPrev' when --before is used or on initial request."}}}}}}}}).action(vp)})(i)};function Ep(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Ip(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Ap(o){o.command("list").description("List project environment variables").option("--env <scope>","Environment scope: dev | prod","dev").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List project environment variables",description:"Retrieve the list of environment variables for the specified project. Supports filtering by environment (dev/prod) and displays all configured sensitive information key names.",examples:[{desc:"List dev environment variables",cmd:"coze code env list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"List prod environment variables",cmd:"coze code env list -p <projectId> --env prod"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},env:{type:"string",required:!1,enum:["dev","prod"],description:"Environment scope (default: dev)"}},output:{command:{type:"string",description:"Command name"},status:{type:"string",description:"Execution status"},data:{type:"object",properties:{project_id:{type:"string",description:"Project ID"},project_type:{type:"string",description:"Project type"},env:{type:"string",description:"Environment scope"},secrets:{type:"array",description:"Environment variable list"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action((async function(e,o){const i=o.getContext(),{projectId:s}=e,n=Ip([await t.IdeApi.GetVibeProject({project_id:s}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),r=(a=e.env,"prod"===String(a||"dev").toLowerCase()?Bi.prod:Bi.dev);var a;const c=Ip([await Wi.ListProjectSecret({env:r,project_id:s,...n===t.VibeProjectType.Skill?{with_providers:!0}:{}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[];Ip([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secrets listed successfully.")]),Ip([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 Sp(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const jp=o=>{const i=o.command("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");Ap(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(o,i,s,n){const r=n.getContext(),{projectId:a}=s,c=Ep([await t.IdeApi.GetVibeProject({project_id:a}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(c===t.VibeProjectType.Skill)throw new e.CozeError(e.ErrorCode.E3008,"Skill project secret_type logic to be supplemented",{projectId:a,projectType:c});await Wi.InsertProjectSecret({project_id:a,insert_secrets:{secrets:[{secret_key:o,secret_val:i}]}}),Ep([r,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env secret set successfully")]),Ep([r,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:a,key:o,value:i})])})),function(t){t.command("delete <key>").description("Delete a project environment variable").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete project environment variable",description:"Delete a specified environment variable from the project by its key name.",examples:[{desc:"Delete an environment variable",cmd:"coze code env delete <KEY> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},key:{type:"string",required:!0,description:"Environment variable key name to delete"}},output:{message:{type:"string",description:"Result message"},key:{type:"string",description:"Deleted key"}}},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 s=i.getContext(),{projectId:n}=o,r=[t],a=Sp([await Wi.ListProjectSecret({env:Bi.dev,project_id:n}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],c=new Set(r.map((e=>String(e)))),l=a.filter((e=>c.has(String(e.secret_key||"")))).map((e=>e.secret_id)).filter(Boolean);if(0===l.length)throw new e.CozeError(e.ErrorCode.E3003,`No matched secrets by keys: ${r.join(", ")}`,{projectId:n,keys:r});await Wi.DeleteProjectSecret({project_id:n,keys:l}),Sp([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Env has been delete successfully")]),Sp([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({message:"env has been delete successfully",key:t,project_id:n,keys:r,secret_ids:l})])}))}(i)};var Pp,kp,Tp,zp,Rp,xp,Lp,Op,Dp,Up,Bp,qp,Mp,Np,$p,Gp,Fp,Vp,Wp,Hp,Jp,Kp,Qp,Yp,Zp,Xp,eu,tu,ou,iu,su;function nu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}!function(e){e[e.Image=1]="Image";e[e.Android=2]="Android";e[e.IOS=3]="IOS";e[e.GitCode=4]="GitCode";e[e.FaasRuntimePkg=5]="FaasRuntimePkg";e[e.SkillPkg=6]="SkillPkg";e[e.H5=7]="H5"}(Pp||(Pp={})),function(e){e[e.Unknown=0]="Unknown";e[e.FreeCertificate=1]="FreeCertificate"}(kp||(kp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Normal=1]="Normal"}(Tp||(Tp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Existing=1]="Existing";e[e.Free=2]="Free"}(zp||(zp={})),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"}(Rp||(Rp={})),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"}(Lp||(Lp={})),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"}(Op||(Op={})),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"}(Dp||(Dp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Success=1]="Success";e[e.Pending=2]="Pending";e[e.Failed=3]="Failed"}(Up||(Up={})),function(e){e[e.Unknown=0]="Unknown";e[e.Default=1]="Default";e[e.Custom=2]="Custom"}(Bp||(Bp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Active=1]="Active";e[e.Disabled=2]="Disabled";e[e.Redirected=3]="Redirected";e[e.Primary=4]="Primary"}(qp||(qp={})),function(e){e[e.Published=1]="Published";e[e.Unpublished=2]="Unpublished"}(Mp||(Mp={})),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"}(Np||(Np={})),function(e){e[e.Created=1]="Created";e[e.Ready=3]="Ready";e[e.Stopped=4]="Stopped";e[e.Banned=5]="Banned";e[e.Paused=6]="Paused"}($p||($p={})),function(e){e[e.Unknown=0]="Unknown";e[e.VefaasFunction=1]="VefaasFunction"}(Gp||(Gp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Dev=1]="Dev";e[e.Prod=2]="Prod";e[e.Audit=3]="Audit"}(Fp||(Fp={})),function(e){e[e.A=1]="A";e[e.CNAME=2]="CNAME"}(Vp||(Vp={})),function(e){e[e.Unknown=0]="Unknown";e[e.Single=1]="Single";e[e.Wildcard=2]="Wildcard";e[e.Multi=3]="Multi"}(Wp||(Wp={})),function(e){e[e.Unknown=0]="Unknown";e[e.DV=1]="DV";e[e.OV=2]="OV";e[e.EV=3]="EV"}(Hp||(Hp={})),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"}(Jp||(Jp={})),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"}(Kp||(Kp={})),function(e){e[e.NeedAuthorize=1]="NeedAuthorize";e[e.BindSuccess=2]="BindSuccess";e[e.BoundToOtherProject=3]="BoundToOtherProject";e[e.BoundToOtherUser=4]="BoundToOtherUser"}(Qp||(Qp={})),function(e){e[e.BoundToSelf=1]="BoundToSelf";e[e.BoundToOtherUser=2]="BoundToOtherUser";e[e.NotAuthorized=3]="NotAuthorized"}(Yp||(Yp={})),function(e){e[e.Line=1]="Line"}(Zp||(Zp={})),function(e){e[e.Default=0]="Default";e[e.WechatMini=1]="WechatMini";e[e.DouyinMini=2]="DouyinMini"}(Xp||(Xp={})),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"}(eu||(eu={})),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"}(tu||(tu={})),function(e){e[e.Recorded=1]="Recorded"}(ou||(ou={})),function(e){e[e.Sum=1]="Sum";e[e.Avg=2]="Avg"}(iu||(iu={})),function(e){e[e.Next=1]="Next";e[e.Third=3]="Third";e[e.Seventh=7]="Seventh"}(su||(su={}));class ru{__init(){this.request=e.request}__init2(){this.baseURL=""}constructor(e){ru.prototype.__init.call(this),ru.prototype.__init2.call(this),this.request=nu([e,"optionalAccess",e=>e.request])||this.request,this.baseURL=nu([e,"optionalAccess",e=>e.baseURL])||this.baseURL}genBaseURL(e){return"string"==typeof this.baseURL?this.baseURL+e:this.baseURL(e)}PublicCreateDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/create"),s={project_id:o.project_id,is_sync_db_to_prod:o.is_sync_db_to_prod,encrypt_env_variable:o.encrypt_env_variable,table_sync_configs:o.table_sync_configs,encrypt_deploy:o.encrypt_deploy,commit_hash:o.commit_hash,connector_configs:o.connector_configs};return this.request({url:i,method:"POST",data:s},t)}PublicRollbackDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/rollback"),s={project_id:o.project_id,target_deploy_history_id:o.target_deploy_history_id,rollback_database:o.rollback_database};return this.request({url:i,method:"POST",data:s},t)}PublicCancelDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/cancel"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_config/get"),s={project_id:o.project_id,commit_hash:o.commit_hash};return this.request({url:i,method:"GET",params:s},t)}PublicListDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/list"),s={project_id:o.project_id,page_token:o.page_token,page_size:o.page_size};return this.request({url:i,method:"GET",params:s},t)}PublicSearchRuntimeLog(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/runtime_log/search"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id,start_time:o.start_time,end_time:o.end_time,limit:o.limit,cursor:o.cursor,query:o.query,level:o.level};return this.request({url:i,method:"GET",params:s},t)}PublicGetDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"GET",params:s},t)}PublicBindCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/bind"),s={project_id:o.project_id,certificate_id:o.certificate_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicApplyFreeCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/apply_free"),s={project_id:o.project_id,domain:o.domain,auto_renew_free_cert:o.auto_renew_free_cert};return this.request({url:i,method:"POST",data:s},t)}PublicListDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/list"),s={project_id:o.project_id,unit_type:o.unit_type};return this.request({url:i,method:"GET",params:s},t)}PublicDeleteDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/delete"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicCreateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/create"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/get"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetCertificateDetail(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/get"),s={project_id:o.project_id,certificate_id:o.certificate_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/get"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicListVolcanoDomain(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/volcano_domain/list"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicListVolcanoCertificate(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/list_volcano"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicListProjectTraces(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/traces/list"),s={project_id:o.project_id,start_time:o.start_time,end_time:o.end_time,filter:o.filter,page_token:o.page_token,page_size:o.page_size};return this.request({url:i,method:"POST",data:s},t)}PublicDownloadProjectTraces(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/traces/download"),s={project_id:o.project_id,start_time:o.start_time,end_time:o.end_time,filter:o.filter};return this.request({url:i,method:"POST",data:s},t)}PublicGetProjectMetrics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/metrics/get"),s={project_id:o.project_id,time_range:o.time_range,retention_days:o.retention_days};return this.request({url:i,method:"GET",params:s},t)}PublicDeleteDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/delete"),s={project_id:o.project_id,deploy_unit_id:o.deploy_unit_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetHelpCenterLink(e,t){const o=this.genBaseURL("/api/coding/deployment/help_center/link");return this.request({url:o,method:"GET"},t)}PublicCheckRollbackDatabase(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/check_rollback_database"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetMiniProgramPreview(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/mini_program/preview"),s={project_id:o.project_id,app_id:o.app_id,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}PublicSubmitAuthCode(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/submit_code"),s={project_id:o.project_id,connector_id:o.connector_id,code:o.code,verify_state:o.verify_state,auth_params:o.auth_params};return this.request({url:i,method:"POST",data:s},t)}PublicGetAuthStatus(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/status"),s={project_id:o.project_id,connector_id:o.connector_id,redirect_url:o.redirect_url};return this.request({url:i,method:"POST",data:s},t)}PublicBindAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/bind"),s={project_id:o.project_id,connector_id:o.connector_id,redirect_url:o.redirect_url,auth_params:o.auth_params,override:o.override};return this.request({url:i,method:"POST",data:s},t)}PublicUnbindAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/unbind"),s={project_id:o.project_id,connector_id:o.connector_id};return this.request({url:i,method:"POST",data:s},t)}PublicGetBoundProject(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/get_bound_project"),s={connector_id:o.connector_id,related_id:o.related_id};return this.request({url:i,method:"GET",params:s},t)}PublicUpdateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/update"),s={project_id:o.project_id,domain:o.domain,auto_renew_free_cert:o.auto_renew_free_cert,visit_status:o.visit_status,next_primary_domain:o.next_primary_domain};return this.request({url:i,method:"POST",data:s},t)}PublicGetCertificateQuota(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/quota"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicListDomainCertificates(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/certificate/list"),s={project_id:o.project_id,domain:o.domain};return this.request({url:i,method:"GET",params:s},t)}PublicUnpublishConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/unpublish_project"),s={project_id:o.project_id,connector_ids:o.connector_ids};return this.request({url:i,method:"POST",data:s},t)}PublicListConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/list"),s={project_id:o.project_id,project_publish_status:o.project_publish_status};return this.request({url:i,method:"GET",params:s},t)}PublicPublishConnector(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/connector/publish_project"),s={project_id:o.project_id,connector_configs:o.connector_configs};return this.request({url:i,method:"POST",data:s},t)}PublicGetDeployCount(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get_count"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}GetRuntimeLogCount(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/runtime_log/count"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicExchangeFeishuAuthCode(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/auth/exchange_code"),s={project_id:o.project_id,code:o.code,verify_state:o.verify_state};return this.request({url:i,method:"POST",data:s},t)}PublicRevokeFeishuAuth(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/auth/revoke"),s={project_id:o.project_id};return this.request({url:i,method:"POST",data:s},t)}PublicUpdateDefaultDomainPrefix(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/update_default_prefix"),s={project_id:o.project_id,prefix:o.prefix};return this.request({url:i,method:"POST",data:s},t)}PublicFeishuWebhookEvent(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/feishu/webhook/event"),s={body:o.body};return this.request({url:i,method:"POST",data:s},t)}PublicCheckCreateDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/check_create"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetHostedUsageMonthly(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/hosted_usage/monthly"),s={project_id:o.project_id,bill_month:o.bill_month};return this.request({url:i,method:"GET",params:s},t)}PublicGetEstimateHostedCost(e,t){const o=this.genBaseURL("/api/coding/deployment/hosted_usage/estimate_cost");return this.request({url:o,method:"GET"},t)}PublicGetDeployHistoryLog(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/log"),s={deploy_history_id:o.deploy_history_id,key:o.key};return this.request({url:i,method:"GET",params:s},t)}PublicGetMPICPStatus(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/mini_program/icp_status"),s={project_id:o.project_id,app_id:o.app_id,connector_id:o.connector_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetOnlineDeployHistory(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_history/get_online"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicGetUserAnalyticsMetrics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/metrics/user_analytics/get"),s={project_id:o.project_id,time_range:o.time_range};return this.request({url:i,method:"GET",params:s},t)}PublicPauseDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/pause"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicStopDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/stop"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicResumeDeployUnit(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/deploy_unit/resume"),s={project_id:o.project_id,deploy_history_id:o.deploy_history_id};return this.request({url:i,method:"POST",data:s},t)}PublicReportUserAnalytics(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/analytics/report"),s={events:o.events},n={project_id:o.project_id,did:o.did};return this.request({url:i,method:"POST",data:s,params:n},t)}PublicCreateDefaultDomainRelated(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/domain_related/create_default"),s={project_id:o.project_id,prefix:o.prefix};return this.request({url:i,method:"POST",data:s},t)}PublicGetProtectionConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/protection_config/get"),s={project_id:o.project_id};return this.request({url:i,method:"GET",params:s},t)}PublicUpdateProtectionConfig(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/protection_config/update"),s={project_id:o.project_id,config:o.config};return this.request({url:i,method:"POST",data:s},t)}PublicAuthRedirect(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/redirect"),s={url:o.url};return this.request({url:i,method:"GET",params:s},t)}PublicAuthCallback(e,t){const o=e||{},i=this.genBaseURL("/api/coding/deployment/auth/callback"),s={redirect_url:o.redirect_url};return this.request({url:i,method:"GET",params:s},t)}}const au=new ru({});function cu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function lu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function du(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const pu=t=>{const o=t.command("domain").config({help:{brief:"Manage custom domains for the project",description:"Manage custom domains for deployed projects. Supports adding, listing, and removing domains associated with a project, used to access deployed applications.",examples:[{desc:"List project domains",cmd:"coze code domain list -p <projectId>"},{desc:"Add custom domain",cmd:"coze code domain add example.com -p <projectId>"},{desc:"Delete domain",cmd:"coze code domain remove example.com -p <projectId>"}],seeAlso:["coze code deploy"]}}).description("Manage custom domains for the project");o.command("list").description("List custom domains of the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"List all domains bound to the project",description:"Retrieve a list of all custom domains bound to the specified project.",examples:[{desc:"List domains",cmd:"coze code domain list -p <projectId>",tags:["[RECOMMENDED]"]},{desc:"Output in JSON format",cmd:"coze code domain list -p <projectId> --format json"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Domain ID"},domain_host:{type:"string",description:"Domain host"}}}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Please confirm if the project ID is correct"}]}}).action((async function(e,t){const o=t.getContext(),{projectId:i}=e,s=lu([await au.PublicListDomainRelated({project_id:i}),"access",e=>e.data,"optionalAccess",e=>e.items])||[];lu([o,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e("Fetched domains List successfully")]),lu([o,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(s.map((e=>({id:e.id,domain_host:e.domain_host}))))])})),function(t){t.command("add <domain>").description("Add a custom domain to the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Add custom domain to project",description:"Bind a custom domain to a specified project. The domain must follow standard format (e.g., example.com). Once bound, the deployed application can be accessed via this domain.",examples:[{desc:"Add domain",cmd:"coze code domain add <domain> -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to add (e.g., example.com)"}},output:{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 s=i.getContext(),{projectId:n}=o;if(!/^[a-zA-Z0-9][a-zA-Z0-9-]*\.[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(t))throw new e.CozeError(e.ErrorCode.E1004,"Invalid domain",{domain:t});await au.PublicCreateDomainRelated({project_id:n,domain:t}),du([s,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",e=>e(`Domain '${t}' added.`)]),du([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({project_id:n,domain:t})])}))}(o),function(t){t.command("remove <domain>").description("Remove a custom domain from the project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Delete custom domain of the project",description:"Remove a bound custom domain from the specified project.",examples:[{desc:"Delete domain",cmd:"coze code domain remove example.com -p <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},domain:{type:"string",required:!0,description:"Domain to delete"}},output:{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:s}=t;await au.PublicDeleteDomainRelated({project_id:s,domain:e}),cu([i,"optionalAccess",e=>e.ui,"access",e=>e.success,"call",t=>t(`Domain '${e}' removed.`)]),cu([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({message:`Domain '${e}' removed.`,domain:e})])}))}(o)},uu={[Dp.Pending]:"Pending",[Dp.Running]:"Running",[Dp.Succeeded]:"Succeeded",[Dp.Failed]:"Failed",[Dp.Canceled]:"Canceled",[Dp.Interrupted]:"Interrupted"},mu=[Dp.Succeeded,Dp.Failed,Dp.Canceled],gu=e=>e&&uu[e]||"Unknown";function hu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class fu{static __initStatic(){this.INSTANCE=new fu}static getInstance(){return fu.INSTANCE||(fu.INSTANCE=new fu),this.INSTANCE}async pollDeployStatus(t){const{projectId:o,deployHistoryId:i,onBeforePoll:s,onStatusChange:n}=t;let r;for(;;){hu([s,"optionalCall",e=>e()]);const t=hu([await au.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,hu([n,"optionalCall",e=>e(t)])),mu.includes(a))return t;await new Promise((e=>setTimeout(e,3e3)))}}async getLatestDeployHistoryId(e){const{projectId:t}=e;return hu([await au.PublicListDeployHistory({page_size:1,project_id:t}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list,"optionalAccess",e=>e[0],"optionalAccess",e=>e.deploy_history_id])}async getDeployHistory(t){const{projectId:o,deployHistoryId:i}=t,s=await au.PublicGetDeployHistory({project_id:o,deploy_history_id:i});if(!hu([s,"optionalAccess",e=>e.data]))throw new e.CozeError(e.ErrorCode.E5000,"Failed to get deploy history data");return s.data}canDeploy(e){return[t.VibeProjectType.AssistantAgent,t.VibeProjectType.WechatMiniProgram,t.VibeProjectType.GeneralWeb,t.VibeProjectType.App,t.VibeProjectType.Skill,t.VibeProjectType.Agent,t.VibeProjectType.Automation].includes(e)}async getCommitList({projectId:o}){const i=await t.IdeApi.ProxySandboxMessage({ProjectID:o,Method:"repo_version.commit.list",Params:JSON.stringify({project_id:o})});return e.safeJsonParse(i.data,{commits:[]}).commits||[]}}fu.__initStatic();const _u=fu.getInstance();function yu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function bu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function vu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function wu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Cu(o){const i=o.command("deploy <projectId>").description("Deploy the project to production environment").option("--commit-id <commitId>","Commit ID (optional, queries latest if omitted)").option("--wait","Wait for deployment to complete").option("--table-name <tableName...>","Database table names to sync to production",((e,t)=>t.concat(e)),[]).option("--encrypt-deploy <encrypt_deploy>","Pre-encrypted environment variable string (for Skill projects)").option("--connector-id <connectorId>","Connector IDs for mini-program deployment channels (can specify multiple times, e.g. 10000127 for WeChat, 10000126 for TikTok)",((e,t)=>t.concat(e)),[]).config({help:{brief:"Deploy the project to production environment",description:"Deploy the specified project to the production environment. Supports multiple project types (Agent, Workflow, Skill, Web, Mini-program, etc.), automatically fetches the latest commit, and triggers the deployment process.",examples:[{desc:"Deploy latest project",cmd:"coze code deploy <projectId>",tags:["[RECOMMENDED]"]},{desc:"Deploy and wait for completion",cmd:"coze code deploy <projectId> --wait"},{desc:"Deploy a specific commit",cmd:"coze code deploy <projectId> --commit-id <commitId>"},{desc:"View deployment status",cmd:"coze code deploy status <projectId>"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},commitId:{type:"string",required:!1,description:"Commit ID (optional, queries latest if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"},tableName:{type:"array",required:!1,description:"Database table names to sync to production (can specify multiple times)"},encryptDeploy:{type:"string",required:!1,description:"Pre-encrypted environment variable string (for Skill projects)"},connectorId:{type:"array",required:!1,description:"Connector IDs for mini-program channels (10000127=WeChat, 10000126=TikTok). If omitted, auto-detects authorized channels."}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.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(o,i,s){const n=s.getContext(),{wait:r,commitId:a,tableName:c,encryptDeploy:l,connectorId:d}=i;let p;try{p=await t.IdeApi.GetVibeProject({project_id:o})}catch(t){W(t,e.ErrorCode.E3001,`Project '${o}' not found`,{projectId:o})}const u=wu([p.data||{},"access",e=>e.project_info,"optionalAccess",e=>e.project_type]);if(!_u.canDeploy(u)){const t=`Project type ${Nd(u)} is not supported for deployment`;throw new e.CozeError(e.ErrorCode.E1006,t,{projectType:u})}if(u===t.VibeProjectType.AssistantAgent)return wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying (AssistantAgent)...")]),await e.axiosInstance$1.post("api/sandbox/coze_coding/devbox/open_claw/deploy",{project_id:o}),void wu([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({status:"ok",type:u,message:`Assistant project deployment successfully, Please access the ${sp(o,wu([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))} to view the project`})]);let m,g=a;if(!g){wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Fetching latest commit...")]);const e=await _u.getCommitList({projectId:o});g=wu([e,"optionalAccess",e=>e[0],"optionalAccess",e=>e.id])}if(!g){const t="No commits found: commit your changes first, or pass --commit-id <commitId>";throw new e.CozeError(e.ErrorCode.E3007,t,{projectId:o})}if(u===t.VibeProjectType.WechatMiniProgram)if(d&&d.length>0)m=d.map((e=>({connector_id:e})));else{wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking Mini-program authorization...")]);const t=[{name:"WeChat",id:"10000127"},{name:"TikTok",id:"10000126"}],i=(await Promise.all(t.map((async e=>{const t=await au.PublicGetAuthStatus({project_id:o,connector_id:e.id});return{...e,authorized:Boolean(wu([t,"access",e=>e.data,"optionalAccess",e=>e.bound_related_id]))}})))).filter((e=>e.authorized));if(0===i.length){const t=`Deployment failed, no authorized Mini-program channels found. Please visit ${sp(o,wu([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))} to complete WeChat or TikTok AppID configuration.`;throw new e.CozeError(e.ErrorCode.E2002,t)}m=i.map((e=>({connector_id:e.id})))}wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Checking deploy config...")]),await au.PublicGetDeployConfig({project_id:o,commit_hash:g},{__disableErrorToast:!0});let h="";const f=await Wi.ListProjectSecret({env:Bi.dev,project_id:o,with_providers:!0}),_=wu([f,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_secrets,"optionalAccess",e=>e.secrets])||[],y=wu([f,"optionalAccess",e=>e.data,"optionalAccess",e=>e.project_cred_providers])||[];wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Encrypting secrets...")]);h=wu([await Wi.EncryptProjectSecret({project_id:o,project_type:u===t.VibeProjectType.Skill?Ui.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===qi.consumer?ui.consumer3:ui.user_custom2}))),cred_providers:y}}),"optionalAccess",e=>e.data,"optionalAccess",e=>e.sealed_secrets])||"",wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploying...")]);const b={project_id:o,encrypt_env_variable:h,commit_hash:g,encrypt_deploy:u===t.VibeProjectType.Skill?Boolean(l):void 0,connector_configs:m};if(c&&c.length>0){const e=new Map,i=["knowledge","public"];await Promise.all(i.map((async i=>{((await t.IdeApi.GetSchemaTables({project_id:o,database_env:t.MemoryEnv.develop,schema:i})).table_names||[]).forEach((t=>{e.set(t,i)}))}))),b.table_sync_configs=c.map((t=>({table_name:t,schema:e.get(t)||"",sync_data:!0})))}const v=wu([await au.PublicCreateDeployHistory(b),"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_id]);wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Deploy started.")]),r&&v?await _u.pollDeployStatus({projectId:o,deployHistoryId:v,onBeforePoll:()=>{wu([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const t=gu(e.status);wu([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",i=>i({projectId:o,status:t,domain:wu([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:v,commitHash:e.commit_hash})])}}):wu([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({projectId:o,status:gu(Dp.Pending),domain:"",deployHistoryId:v,commitHash:g})])}));!function(t){t.command("status <projectId>").description("Check deployment status").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest if omitted)").config({help:{brief:"Query project deployment status",description:"Query the deployment status of a specified project. If no deployment history ID is specified, it automatically queries the latest deployment record. Supports viewing deployment progress, results, and error messages.",examples:[{desc:"Query latest deployment status",cmd:"coze code deploy status <projectId>",tags:["[RECOMMENDED]"]},{desc:"Query specific deployment record",cmd:"coze code deploy status <projectId> --deploy-id <deployHistoryId>"},{desc:"Wait for deployment to complete",cmd:"coze code deploy status <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (optional, queries latest if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for deployment to complete"}},output:{projectId:{type:"string",description:"Project ID"},status:{type:"string",description:"Deployment status"},domain:{type:"string",description:"Deployed domain"},deployHistoryId:{type:"string",description:"Deployment history ID"},commitHash:{type:"string",description:"Commit hash"}}},errors:[{code:e.ErrorCode.E3006,name:"NO_DEPLOYMENT_HISTORY",desc:"No deployment history found for this project",fix:"Please deploy the project first using `coze code deploy <projectId>`"}]}}).action((async function(t,o,i){const s=i.getContext(),{deployId:n}=o,{wait:r}=yu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=n;if(!a&&(yu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("get latest deployment record...")]),a=await _u.getLatestDeployHistoryId({projectId:t}),!a))throw new e.CozeError(e.ErrorCode.E3006,"No deployment history found for this project");if(r)await _u.pollDeployStatus({projectId:t,deployHistoryId:a,onBeforePoll:()=>{yu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Polling deployment status...")])},onStatusChange:e=>{const o=gu(e.status);yu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",i=>i({projectId:t,status:o,domain:yu([e,"access",e=>e.domain_list,"optionalAccess",e=>e[0]]),deployHistoryId:a,commitHash:e.commit_hash})])}});else{yu([s,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e("Querying deployment status...")]);const e=await _u.getDeployHistory({projectId:t,deployHistoryId:a}),o=gu(e.status),i=e.domain_list||[];yu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",s=>s({projectId:t,status:o,domain:i[0],deployHistoryId:a,commitHash:e.commit_hash})])}}))}(i),function(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:"object",properties:{items:{type:"array",items:{deploy_history_id:{type:"string",description:"Deployment history ID"},status:{type:"string",description:"Deployment status"},commit_hash:{type:"string",description:"Commit hash"},domain_list:{type:"array",description:"Deployed domains"},created_at:{type:"string",description:"Creation timestamp"}}},next_page_token:{type:"string",description:"Token for fetching the next page, empty if no more pages"},has_more:{type:"boolean",description:"Whether there are more records"}}}}}}).action((async function(e,t,o){const i=o.getContext(),s=Number(t.pageSize)||10,n=await au.PublicListDeployHistory({project_id:e,page_size:s,page_token:t.pageToken}),r=(bu([n,"optionalAccess",e=>e.data,"optionalAccess",e=>e.deploy_history_list])||[]).map((e=>({deploy_history_id:e.deploy_history_id,project_id:e.project_id,status:gu(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})));bu([i,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>{return e({items:r,next_page_token:bu([n,"optionalAccess",e=>e.data,"optionalAccess",e=>e.next_page_token])||"",has_more:(t=bu([n,"optionalAccess",e=>e.data,"optionalAccess",e=>e.has_more]),o=()=>!1,null!=t?t:o())});var t,o}])}))}(i),function(t){t.command("fix <projectId>").description("Fix a failed deployment by sending deploy logs to AI").option("--deploy-id <deployId>","Deployment history ID (optional, queries latest failed if omitted)").option("--wait","Wait for fix message response").config({help:{brief:"Fix a failed deployment",description:"Diagnose and fix a failed deployment. Retrieves deploy logs and sends them to AI for analysis and automatic fix. Only works when the deployment status is Failed.",examples:[{desc:"Fix latest failed deployment",cmd:"coze code deploy fix <projectId>",tags:["[RECOMMENDED]"]},{desc:"Fix a specific deployment",cmd:"coze code deploy fix <projectId> --deploy-id <deployId>"},{desc:"Fix and wait for result",cmd:"coze code deploy fix <projectId> --wait"}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"},deployId:{type:"string",required:!1,description:"Deployment history ID (queries latest failed if omitted)"},wait:{type:"boolean",required:!1,description:"Wait for fix message response"}},output:{type:"object",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 s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const{deployId:n}=o,{wait:r}=vu([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e()])||{};let a=n;if(n||(a=await _u.getLatestDeployHistoryId({projectId:t})),!a)throw new e.CozeError(e.ErrorCode.E5002,`No deploy history found for project ${t}`,{project_id:t});const c=vu([await au.PublicGetDeployHistory({project_id:t,deploy_history_id:a}),"optionalAccess",e=>e.data]);if(vu([c,"optionalAccess",e=>e.status])!==Dp.Failed){const t=gu(vu([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:vu([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 d=await e.customFetch.fetch(l,{method:"GET"}),p=await d.text();if(!p)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${p}`,m=await vu([s,"access",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");const g=await Fc.getDefaultConversation(t);if(r){const e=await Kd.sendMessage({projectId:t,prompt:u,apiBaseUrl:s.config.apiBaseUrl,accessToken:m,xTTEnv:s.config.xTTEnv,conversationId:g.id,key:`coze-coding-cli:message:${t}`});vu([s,"optionalAccess",e=>e.response,"access",e=>e.print,"call",t=>t({deploy_history_id:a,status:"fix_sent",message:e.lastAnswerMessage})])}else Kd.sendMessageRunTask({projectId:t,prompt:u,apiBaseUrl:s.config.apiBaseUrl,accessToken:m,xTTEnv:s.config.xTTEnv,conversationId:g.id,key:`coze-coding-cli:message:${t}`})}))}(i)}function Eu(e,t){return null!=e?e:t()}function Iu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}class Au{static getInstance(){return Au.INSTANCE||(Au.INSTANCE=new Au),Au.INSTANCE}async createSpaceDatabase(o){const i=await t.IdeApi.CreateSpaceDatabase({space_id:o},{});if(!i.database)throw new e.CozeError(e.ErrorCode.E5000,"Failed to create database");return i.database}async listSpaceDatabases(e,o){const i=await t.IdeApi.ListSpaceDatabase({space_id:e,cursor_id:Iu([o,"optionalAccess",e=>e.cursor_id]),limit:Eu(Iu([o,"optionalAccess",e=>e.limit]),(()=>20))},{});return{databases:Eu(Iu([i,"optionalAccess",e=>e.databases]),(()=>[])),next_cursor_id:i.next_cursor_id}}async getSpaceDatabase(o,i){let s;try{s=await t.IdeApi.GetSpaceDatabase({space_id:o,database_id:i},{})}catch(t){W(t,e.ErrorCode.E3010,`Database '${i}' not found or no permission`,{databaseId:i})}if(!s.database)throw new e.CozeError(e.ErrorCode.E3010,`Database '${i}' not found or no permission`,{databaseId:i});return s.database}async deleteSpaceDatabase(e,o){await t.IdeApi.DeleteSpaceDatabase({space_id:e,database_id:o},{})}async rollbackSpaceDatabase(e,o,i){return await t.IdeApi.RollbackSpaceDatabase({space_id:e,database_id:o,timestamp:i},{})}async getSpaceDatabaseStatus(e,o){return await t.IdeApi.GetSpaceDatabaseStatus({space_id:e,database_id:o},{})}}const Su=Au.getInstance(),ju={0:"active",1:"creating"},Pu={0:"dev",1:"prod"},ku={0:"restoring",1:"success",2:"failed"},Tu=e=>e&&"0"!==e?new Date(Number(e)).toLocaleString():"-";function zu(e,t){return null!=e?e:t()}function Ru(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function xu(e,t){return null!=e?e:t()}function Lu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Ou=[{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 Du(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function Uu(e,t){return null!=e?e:t()}function Bu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const qu=async(t,o,i,s)=>{const n=`${t}/api/platform/pg-meta/default/query`,r=Buffer.from(`${o}:${i}`).toString("base64"),a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${r}`},body:JSON.stringify({query:s})});if(!a.ok){const t=await a.text(),o=e.safeJsonParse(t,void 0),i=Uu(Uu(Bu([o,"optionalAccess",e=>e.message]),(()=>Bu([o,"optionalAccess",e=>e.error,"optionalAccess",e=>e.message]))),(()=>`pg-meta request failed: ${a.status}`));throw new Error(i)}const c=await a.json();return Array.isArray(c)?c:[]};function Mu(e,t){return null!=e?e:t()}function Nu(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,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Mu(Mu(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const n=t.sql||t.file?void 0:await async function(e,t){return null!=e?e:await t()}(await oa(),(async()=>{})),r=await(async e=>{if(Du([e,"optionalAccess",e=>e.sql]))return e.sql.trim();if(Du([e,"optionalAccess",e=>e.file])){const t=g.resolve(e.file),o=(await h.readFile(t,"utf-8")).trim();if(!o)throw new Error(`SQL file is empty: ${t}`);return o}if(Du([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}),a=(e=>{const t=[];let o="safe";const i=e.replace(/--.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const{pattern:e,level:s,reason:n}of Ou)e.test(i)&&(t.push(n),"critical"===s?o="critical":"safe"===o&&(o="warning"));return{isDangerous:"safe"!==o,level:o,reasons:t}})(r);if(a.isDangerous&&!t.confirm){const o="json"===i.format,s=!0===process.stdin.isTTY;if(o||!s)throw new e.CozeError(e.ErrorCode.E1007,`SQL contains dangerous operation: ${a.reasons.join(", ")}`,{sql:r.substring(0,200),analysis:a},{trigger:"Dangerous SQL detected without --confirm",fix:"Add --confirm flag to proceed, or modify the SQL to remove dangerous operations",example:`coze code db query --db-id ${t.dbId} --sql "..." --confirm`});i.ui.info(`⚠ Warning: SQL contains dangerous operation:\n ${a.reasons.join("\n ")}`);const{confirm:n}=await import("@inquirer/prompts").then((e=>({confirm:e.confirm})));if(!await n({message:"Are you sure you want to execute this SQL?",default:!1}))return void i.ui.info("Operation cancelled.")}i.ui.info("Fetching database connection info...");const c=await Su.getSpaceDatabase(s,t.dbId);if(!c.supabase_url)throw new e.CozeError(e.ErrorCode.E5005,"Database does not have supabase_url. Cannot execute SQL via pg-meta.",{databaseId:t.dbId});if(!c.super_user||!c.super_user_password)throw new e.CozeError(e.ErrorCode.E5005,"Database does not have super_user credentials. Cannot authenticate against pg-meta.",{databaseId:t.dbId});let l;i.ui.info("Executing SQL...");try{l=await qu(c.supabase_url,c.super_user,c.super_user_password,r)}catch(t){throw new e.CozeError(e.ErrorCode.E5004,`SQL execution failed: ${t.message}`,{sql:r.substring(0,200)})}const d=Mu(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([r,"access",e=>e.trim,"call",e=>e(),"access",e=>e.split,"call",e=>e(/\s+/),"access",e=>e[0],"optionalAccess",e=>e.toUpperCase,"call",e=>e()]),(()=>"UNKNOWN")),p="SELECT"===d,u=a.isDangerous?a.reasons:[],m=l.length>0,f=p||m?l.length:null;p||m?i.response.print("json"===i.format?{result:l,rows_affected:f,command:d,warnings:u}:l):(i.ui.success("SQL executed successfully (rows_affected unavailable from pg-meta)."),i.response.print("json"===i.format?{result:[],rows_affected:null,command:d,warnings:u,note:"pg-meta does not expose rows_affected for DDL/DML without RETURNING"}:{command:d,message:"SQL executed successfully."}))}))}function $u(e,t){return null!=e?e:t()}function Gu(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Fu=e=>({database_id:e.database_id,name:e.name,status:$u(ju[$u(e.status,(()=>0))],(()=>String(e.status))),database_env:$u(Pu[$u(e.database_env,(()=>0))],(()=>String(e.database_env))),created_at:Tu(e.created_at)});async function Vu(t,o){const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=$u($u(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const n=$u(t.limit,(()=>20)),r="json"!==i.format;if(r||!0===t.all){const e=$u(t.maxPages,(()=>10)),o=[];let a,c=t.cursor,l=0;for(i.ui.info("Fetching databases...");l<e;){const e=await Su.listSpaceDatabases(s,{cursor_id:c,limit:n});if(o.push(...$u(e.databases,(()=>[])).map(Fu)),l+=1,i.ui.verbose(`Page ${l}: ${$u(Gu([e,"access",e=>e.databases,"optionalAccess",e=>e.length]),(()=>0))} item(s)`),a=e.next_cursor_id,!a||"0"===a){a=void 0;break}c=a}return a&&i.ui.info(`Reached --max-pages=${e}. More results available (cursor: ${a}). Pass --max-pages to fetch more.`),i.ui.info(`Fetched ${o.length} database(s).`),void(r?i.response.print(o):i.response.print({databases:o,next_cursor_id:$u(a,(()=>"0"))}))}const a=await Su.listSpaceDatabases(s,{cursor_id:t.cursor,limit:n});i.response.print({databases:$u(a.databases,(()=>[])).map(Fu),next_cursor_id:a.next_cursor_id})}function Wu(e,t){return null!=e?e:t()}function Hu(e,t){return null!=e?e:t()}async function Ju(t,o){const n=o.getContext();if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const r=Hu(Hu(t.spaceId,(()=>n.config.spaceId)),(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");const a=t.includeSchema&&t.includeSchema.length>0?t.includeSchema:["public"];n.ui.info("Fetching database connection info...");const c=await Su.getSpaceDatabase(r,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});n.ui.info("Fetching OpenAPI schema from PostgREST...");const l=`${c.supabase_url}/rest/v1/`;let d,p;try{const e=await fetch(l,{headers:{apikey:c.anon_key}});if(!e.ok)throw new Error(`PostgREST returned ${e.status}`);const t=await e.json();d=await async function(e){if("string"==typeof e.openapi)return e;if("string"==typeof e.swagger){const{convertObj:t}=await import("swagger2openapi");return(await t(e,{patch:!0,warnOnly:!0})).openapi}return e}(t)}catch(o){throw new e.CozeError(e.ErrorCode.E5006,`Failed to fetch OpenAPI schema: ${o.message}`,{databaseId:t.dbId})}n.ui.info("Generating TypeScript types...");try{const e=await import("openapi-typescript"),t=await e.default(d,{exportType:!0});p="string"==typeof t?t:e.astToString(t)}catch(o){throw new e.CozeError(e.ErrorCode.E5006,`Type generation failed: ${o.message}`,{databaseId:t.dbId},{fix:"The CLI auto-converts PostgREST Swagger 2.0 to OpenAPI 3.0 before generation. If it still fails, the schema may use constructs the generator cannot map — re-run with --debug for the underlying error."})}const u=i.resolve(Hu(t.output,(()=>"types/database.ts")));await s.mkdir(i.dirname(u),{recursive:!0}),await s.writeFile(u,"// Auto-generated by coze code db gen-types\n// Do not edit manually\n\n"+p,"utf-8"),n.ui.success(`Types generated: ${u}`),n.response.print({output_path:u,schemas:a})}function Ku(e,t){return null!=e?e:t()}const Qu=/^[a-zA-Z_][a-zA-Z0-9_$]{0,62}$/,Yu=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 Zu(e,t){const[o,i,s,n]=await Promise.all([qu(e.supabaseUrl,e.username,e.password,t.tables),qu(e.supabaseUrl,e.username,e.password,t.columns),qu(e.supabaseUrl,e.username,e.password,t.constraints),qu(e.supabaseUrl,e.username,e.password,t.indexes)]),r=(e=>{const t=new Map;for(const o of e){const e=`${o.table_schema}.${o.table_name}`,i=t.get(e);i?i.push(o):t.set(e,[o])}return t})(i);let a="";for(const e of o){const t=`${e.table_schema}.${e.table_name}`,o=Ku(r.get(t),(()=>[]));a+=`CREATE TABLE IF NOT EXISTS ${e.table_schema}.${e.table_name} (\n`,a+=o.map(Yu).join(",\n"),a+="\n);\n\n"}for(const e of s){const t=e.constraint_type;("p"===t||"u"===t||"f"===t||"c"===t)&&e.definition&&(a+=`ALTER TABLE ${e.schema_name}.${e.table_name} ADD CONSTRAINT ${e.constraint_name} ${e.definition};\n`)}s.length>0&&(a+="\n");const c=new Set(s.filter((e=>"p"===e.constraint_type||"u"===e.constraint_type)).map((e=>`${e.schema_name}.${e.constraint_name}`)));for(const e of n){const t=`${e.schemaname}.${e.indexname}`;!c.has(t)&&e.indexdef&&(a+=`${e.indexdef};\n`)}return n.length>0&&(a+="\n"),a}async function Xu(t,o){const n=o.getContext();if(!n)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const r=Ku(Ku(t.spaceId,(()=>n.config.spaceId)),(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");if(!0===t.schemaOnly&&!0===t.dataOnly)throw new e.CozeError(e.ErrorCode.E1000,"--schema-only and --data-only are mutually exclusive");const a=!t.dataOnly,c=!0===t.dataOnly,l=c?"data-only":"schema-only",d=(t=>{const o=t&&t.length>0?Array.from(new Set(t)):["public"];for(const t of o)if(!Qu.test(t))throw new e.CozeError(e.ErrorCode.E1000,`Invalid schema name '${t}'. Must be a plain PostgreSQL identifier (letters, digits, underscore, $; max 63 chars; starts with letter or underscore).`);return o})(t.includeSchema),p=(e=>{const t=e.map((e=>`'${e}'`)).join(", ");return{tables:`\n SELECT table_name, table_schema\n FROM information_schema.tables\n WHERE table_schema IN (${t})\n AND table_type = 'BASE TABLE'\n ORDER BY table_schema, table_name;\n `,columns:`\n SELECT table_name, table_schema, column_name, data_type,\n is_nullable, column_default, character_maximum_length,\n numeric_precision, numeric_scale\n FROM information_schema.columns\n WHERE table_schema IN (${t})\n ORDER BY table_schema, table_name, ordinal_position;\n `,constraints:`\n SELECT n.nspname AS schema_name,\n cl.relname AS table_name,\n c.conname AS constraint_name,\n c.contype AS constraint_type,\n pg_get_constraintdef(c.oid) AS definition\n FROM pg_catalog.pg_constraint c\n JOIN pg_catalog.pg_class cl ON c.conrelid = cl.oid\n JOIN pg_catalog.pg_namespace n ON cl.relnamespace = n.oid\n WHERE n.nspname IN (${t})\n ORDER BY n.nspname, cl.relname,\n CASE c.contype WHEN 'p' THEN 1 WHEN 'u' THEN 2 WHEN 'f' THEN 3 ELSE 4 END,\n c.conname;\n `,indexes:`\n SELECT schemaname, tablename, indexname, indexdef\n FROM pg_indexes\n WHERE schemaname IN (${t})\n ORDER BY schemaname, tablename, indexname;\n `}})(d);n.ui.info("Fetching database connection info...");const u=await Su.getSpaceDatabase(r,t.dbId);if(!u.supabase_url)throw new e.CozeError(e.ErrorCode.E5007,"Database does not have supabase_url. Cannot access pg-meta.",{databaseId:t.dbId});if(!u.super_user||!u.super_user_password)throw new e.CozeError(e.ErrorCode.E5007,"Database does not have super_user credentials. Cannot authenticate against pg-meta.",{databaseId:t.dbId});const m={supabaseUrl:u.supabase_url,username:u.super_user,password:u.super_user_password};let g="";g+="-- Dump generated by coze code db dump\n",g+=`-- Database: ${t.dbId}\n`,g+=`-- Mode: ${l}\n`,g+=`-- Schemas: ${d.join(", ")}\n`,g+=`-- Date: ${(new Date).toISOString()}\n\n`;try{a&&(n.ui.info("Exporting schema..."),g+=await Zu(m,p)),c&&(n.ui.info("Exporting data..."),g+=await async function(e,t){const o=await qu(e.supabaseUrl,e.username,e.password,t.tables);let i="";for(const t of o){const o=`SELECT * FROM ${t.table_schema}.${t.table_name};`,s=await qu(e.supabaseUrl,e.username,e.password,o);if(0===s.length)continue;const n=Object.keys(s[0]);for(const e of s){const o=n.map((t=>{return null==(o=e[t])?"NULL":"number"==typeof o?Number.isFinite(o)?String(o):"NULL":"boolean"==typeof o?o?"TRUE":"FALSE":"bigint"==typeof o?String(o):o instanceof Date?`'${o.toISOString()}'`:"object"==typeof o?`'${JSON.stringify(o).replace(/'/g,"''")}'`:`'${String(o).replace(/'/g,"''")}'`;var o}));i+=`INSERT INTO ${t.table_schema}.${t.table_name} (${n.join(", ")}) VALUES (${o.join(", ")});\n`}i+="\n"}return i}(m,p))}catch(o){throw new e.CozeError(e.ErrorCode.E5007,`Dump failed: ${o.message}`,{databaseId:t.dbId})}const h=i.resolve(Ku(t.output,(()=>"db/schema.sql")));await s.mkdir(i.dirname(h),{recursive:!0}),await s.writeFile(h,g,"utf-8"),n.ui.success(`Dump completed: ${h}`),n.response.print({output_path:h,mode:l,schemas:d})}function em(e,t){return null!=e?e:t()}function tm(e,t){return null!=e?e:t()}const om=t=>{const o=t.command("db").description("Manage Coze space databases").config({help:{brief:"Database management for Coze spaces",description:"Create, query, and manage Supabase-backed databases in your Coze space. Supports database lifecycle management, SQL execution, TypeScript type generation, and schema export.",examples:[{desc:"Create a new database",cmd:"coze code db create",tags:["[RECOMMENDED]"]},{desc:"List all databases",cmd:"coze code db list"},{desc:"Execute SQL query",cmd:'coze code db query --db-id <id> --sql "SELECT 1"'},{desc:"Generate TypeScript types",cmd:"coze code db gen-types --db-id <id>"},{desc:"Export database schema",cmd:"coze code db dump --db-id <id>"}],seeAlso:["coze code project","coze code env"],schema:{input:{},output:{}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found or no permission",fix:"Check --db-id is correct, run `coze code db list`"},{code:e.ErrorCode.E1007,name:"DB_SQL_DANGEROUS",desc:"SQL contains dangerous operation",fix:"Add --confirm flag or modify SQL"}]}});o.command("create").description("Create a new database in current space").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Create a new database",description:"Create a new Supabase database in the current space. The database name and credentials are auto-generated. Use `coze code db get` to retrieve connection info.",examples:[{desc:"Create a database",cmd:"coze code db create",tags:["[RECOMMENDED]"]}],schema:{input:{spaceId:{type:"string",required:!1,description:"Space ID (optional, reads from context)"}},output:{database_id:{type:"string",description:"Created database ID"},status:{type:"string",description:"Database status"},database_env:{type:"string",description:"Environment"}}},errors:[{code:e.ErrorCode.E1003,name:"MISSING_SPACE_ID",desc:"Space ID is required",fix:"Use --space-id or run `coze space use <spaceId>` first"},{code:e.ErrorCode.E4002,name:"DB_QUOTA_EXCEEDED",desc:"Space database quota exceeded",fix:"Delete unused databases with `coze code db delete`"}]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=tm(tm(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info("Creating database in space...");const n=await Su.createSpaceDatabase(s);i.ui.success("Database created successfully!"),i.response.print({database_id:n.database_id,database_url:n.database_url,status:tm(ju[tm(n.status,(()=>0))],(()=>n.status)),database_env:tm(Pu[tm(n.database_env,(()=>0))],(()=>n.database_env)),created_at:Tu(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(Vu)}(o),function(t){t.command("get").description("Get database details").requiredOption("--db-id <dbId>","Database ID").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Get database details",description:"Get detailed information about a specific database, including connection URLs and credentials. The console URL can be constructed from supabase_url.",examples:[{desc:"Get database details",cmd:"coze code db get --db-id <databaseId>",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"}},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,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=Wu(Wu(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Fetching database '${t.dbId}'...`);const n=await Su.getSpaceDatabase(s,t.dbId);i.ui.success("Database details:"),i.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:Wu(ju[Wu(n.status,(()=>0))],(()=>n.status)),database_env:Wu(Pu[Wu(n.database_env,(()=>0))],(()=>n.database_env)),created_at:Tu(n.created_at)})}))}(o),function(t){t.command("delete").description("Delete a database").requiredOption("--db-id <dbId>","Database ID").option("--confirm","Confirm deletion (required)").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Delete a database",description:"Delete a database from the current space. This operation cannot be undone. The --confirm flag is required to proceed.",examples:[{desc:"Delete a database",cmd:"coze code db delete --db-id <databaseId> --confirm",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID to delete"},confirm:{type:"boolean",required:!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,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!t.confirm){const o="json"===i.format,s=!0===process.stdin.isTTY;if(o||!s)throw new e.CozeError(e.ErrorCode.E1007,"Deletion requires --confirm flag to proceed",{databaseId:t.dbId},{trigger:"Database deletion is a destructive operation",fix:"Add --confirm flag to confirm deletion",example:`coze code db delete --db-id ${t.dbId} --confirm`});i.ui.warn(`⚠ You are about to delete database '${t.dbId}'. This operation cannot be undone.`);const{confirm:n}=await import("@inquirer/prompts").then((e=>({confirm:e.confirm})));if(!await n({message:`Are you sure you want to delete database '${t.dbId}'?`,default:!1}))return void i.ui.info("Operation cancelled.")}const s=em(em(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Deleting database '${t.dbId}'...`),await Su.deleteSpaceDatabase(s,t.dbId),i.ui.success(`Database '${t.dbId}' deleted successfully.`),i.response.print({deleted:!0,database_id:t.dbId})}))}(o),Nu(o),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,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(!t.confirm)throw new e.CozeError(e.ErrorCode.E1007,"Rollback requires --confirm flag to proceed",{databaseId:t.dbId,timestamp:t.timestamp},{trigger:"Rollback is a potentially destructive operation",fix:"Add --confirm flag to confirm rollback",example:`coze code db rollback --db-id ${t.dbId} --timestamp ${t.timestamp} --confirm`});const s=xu(xu(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Rolling back database '${t.dbId}' to ${new Date(Number(t.timestamp)).toLocaleString()}...`);const n=await Su.rollbackSpaceDatabase(s,t.dbId,t.timestamp);i.ui.success(`Rollback initiated. Use 'coze code db status --db-id ${t.dbId}' to check progress.`),i.response.print({restore_history_id:Lu([n,"optionalAccess",e=>e.restore_history_id])})}))}(o),function(t){t.command("status").description("Get database status and restore info").requiredOption("--db-id <dbId>","Database ID").option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Check database status",description:"Get the status of a database including restore/rollback information. Shows whether the database can be rolled back, current restore status, and earliest restore time.",examples:[{desc:"Check database status",cmd:"coze code db status --db-id <databaseId>",tags:["[RECOMMENDED]"]}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"}},output:{can_restore:{type:"boolean",description:"Whether PITR restore is available"},is_restoring:{type:"boolean",description:"Whether a restore is in progress"},latest_restore_status:{type:"string",description:"Latest restore status"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"}]}}).action((async(t,o)=>{const i=o.getContext();if(!i)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const s=zu(zu(t.spaceId,(()=>i.config.spaceId)),(()=>""));if(!s)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or coze space use <spaceId>");i.ui.info(`Fetching status for database '${t.dbId}'...`);const n=await Su.getSpaceDatabaseStatus(s,t.dbId);i.ui.success("Database status:"),i.response.print({can_restore:Ru([n,"optionalAccess",e=>e.can_restore]),is_restoring:Ru([n,"optionalAccess",e=>e.is_restoring]),earliest_restore_time:Tu(Ru([n,"optionalAccess",e=>e.earliest_restore_time])),latest_restore_status:zu(ku[zu(Ru([n,"optionalAccess",e=>e.latest_restore_status]),(()=>-1))],(()=>Ru([n,"optionalAccess",e=>e.latest_restore_status]))),latest_restore_error:Ru([n,"optionalAccess",e=>e.latest_restore_error]),latest_restore_start_time:Tu(Ru([n,"optionalAccess",e=>e.latest_restore_start_time])),latest_restore_end_time:Tu(Ru([n,"optionalAccess",e=>e.latest_restore_end_time]))})}))}(o),function(t){t.command("gen-types").description("Generate TypeScript types from database schema").requiredOption("--db-id <dbId>","Database ID").option("--output <path>","Output file path","types/database.ts").option("--include-schema <name>","Schema name (can be specified multiple times)",((e,t=[])=>[...t,e]),[]).option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Generate TypeScript types",description:"Generate TypeScript type definitions from database schema using PostgREST OpenAPI. The generated types follow the Supabase database type format.",examples:[{desc:"Generate types for public schema",cmd:"coze code db gen-types --db-id <id>",tags:["[RECOMMENDED]"]},{desc:"Generate types for multiple schemas",cmd:"coze code db gen-types --db-id <id> --include-schema public --include-schema auth"},{desc:"Custom output path",cmd:"coze code db gen-types --db-id <id> --output src/types/db.ts"}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},output:{type:"string",required:!1,description:"Output file path (default: types/database.ts)"},includeSchema:{type:"array",required:!1,description:"Schema names (default: public)"}},output:{output_path:{type:"string",description:"Generated file path"},schemas:{type:"array",description:"Generated schemas"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E5006,name:"DB_GEN_TYPES_FAILED",desc:"Type generation failed",fix:"Ensure the database is active. PostgREST Swagger 2.0 is auto-converted to OpenAPI 3.0; re-run with --debug to see the underlying generator error."}]}}).action(Ju)}(o),function(t){t.command("dump").description("Export database schema or data").requiredOption("--db-id <dbId>","Database ID").option("--output <path>","Output file path","db/schema.sql").option("--schema-only","Export schema only (default if neither flag set)").option("--data-only","Export data only").option("--include-schema <name>","Schema name to dump (repeatable, default: public)",((e,t=[])=>[...t,e]),[]).option("--space-id <spaceId>","Space ID (optional, reads from context)").config({help:{brief:"Export database schema or data",description:"Export database schema (DDL) or data as SQL. Uses pg-meta API to query information_schema. Default mode is schema-only, default schema is public. Pass --include-schema multiple times to include additional schemas (e.g. auth, storage).",examples:[{desc:"Export public schema",cmd:"coze code db dump --db-id <id>",tags:["[RECOMMENDED]"]},{desc:"Export data only",cmd:"coze code db dump --db-id <id> --data-only"},{desc:"Include multiple schemas",cmd:"coze code db dump --db-id <id> --include-schema public --include-schema auth"},{desc:"Custom output path",cmd:"coze code db dump --db-id <id> --output backups/schema.sql"}],schema:{input:{dbId:{type:"string",required:!0,description:"Database ID"},output:{type:"string",required:!1,description:"Output file path (default: db/schema.sql)"},schemaOnly:{type:"boolean",required:!1,description:"Export schema only (default: true)"},dataOnly:{type:"boolean",required:!1,description:"Export data only"},includeSchema:{type:"array",required:!1,description:"Schema name(s) to include (repeatable, default: public)"}},output:{output_path:{type:"string",description:"Output file path"},mode:{type:"string",description:"Export mode"},schemas:{type:"array",description:"Schemas included in the dump"}}},errors:[{code:e.ErrorCode.E3010,name:"DB_NOT_FOUND",desc:"Database not found",fix:"Check --db-id is correct"},{code:e.ErrorCode.E5007,name:"DB_DUMP_FAILED",desc:"Schema export failed",fix:"Check database status and permissions"}]}}).action(Xu)}(o)};function im(e,t){return null!=e?e:t()}function sm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const nm=["github","gitlab"];function rm(e,t){return null!=e?e:t()}function am(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const cm=["github","gitlab"];function lm(e,t){return null!=e?e:t()}function dm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const pm=["github","gitlab"];const um=o=>{const i=o.command("auth").description("Git platform OAuth authorization management").config({help:{brief:"Manage Git platform OAuth authorization",description:"Manage OAuth authorization for Git platforms. Supports login, status check, and logout.",examples:[{desc:"Login",cmd:"coze code git auth login"},{desc:"Check status",cmd:"coze code git auth status"},{desc:"Logout",cmd:"coze code git auth logout"}],seeAlso:["coze code git search"]}});i.command("login").description("Authorize a Git platform via OAuth").config({help:{brief:"Authorize a Git platform via OAuth",description:"Initiate OAuth authorization flow for a Git platform. Opens a browser for the user to complete authorization. The authorization is stored at the space level and can be reused across projects. Defaults to GitHub if --provider is not specified.",examples:[{desc:"Authorize GitHub (minimal)",cmd:"coze code git auth login"},{desc:"Authorize GitHub explicitly",cmd:"coze code git auth login --provider github",tags:["[RECOMMENDED]"]},{desc:"[TEMPLATE] Authorize any provider",cmd:"coze code git auth login --provider <github|gitlab>",tags:["[TEMPLATE]"]}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",description:"Authorization status",example:"authorized"},user:{type:"string",description:"Authorized user name",example:"octocat"}}},enums:{provider:{github:"GitHub OAuth authorization",gitlab:"GitLab OAuth authorization (future)"}},errors:[{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"},{code:e.ErrorCode.E2005,name:"OAUTH_TIMEOUT",desc:"OAuth authorization timed out",fix:"Re-run `coze code git auth login`"},{code:e.ErrorCode.E2006,name:"OAUTH_CANCELLED",desc:"User cancelled the authorization",fix:"Re-run `coze code git auth login`"}],seeAlso:["coze code git auth status","coze code git auth logout"],caveats:["Authorization requires a browser. In headless environments, copy the URL from terminal output and open it manually","Authorization is stored at the space level, not per-project"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=im(im(o.provider,(()=>sm([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!nm.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${nm.join(", ")}`);const r=im(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id: pass --space-id or run `coze space use <spaceId>` first");s.ui.info("Fetching integration list...");const a=im(sm([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>sm([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=im(sm([a,"optionalAccess",e=>e.id]),(()=>""));if(!c)throw new e.CozeError(e.ErrorCode.E5000,`No integration found for provider: ${n}`);s.ui.info(`Initiating OAuth for ${n}...`);const l=im(sm([await t.IdeApi.GetOauthConfig({integration_id:c,space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.auth_url]),(()=>""));if(!l)throw new e.CozeError(e.ErrorCode.E5000,"Failed to get OAuth authorization URL");s.ui.info(`Opening browser for ${n} authorization...`),s.ui.info(`Authorization URL: ${l}`),s.ui.info("Waiting for authorization... (timeout: 120s)");const d=Date.now();let p=!1;for(;Date.now()-d<12e4;)if(await new Promise((e=>setTimeout(e,2e3))),sm([await t.IdeApi.GetOauthStatus({integration_id:c,space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.success])){p=!0;break}if(!p)throw new e.CozeError(e.ErrorCode.E2005,"OAuth authorization timed out after 120 seconds");const u=await t.IdeApi.GetUser({space_id:r,integration_id:c}),m=im(im(sm([u,"access",e=>e.data,"optionalAccess",e=>e.login]),(()=>sm([u,"access",e=>e.data,"optionalAccess",e=>e.name]))),(()=>"unknown"));s.ui.success(`${n} authorized successfully.`),s.ui.info(` User: ${m}`),s.response.print({provider:n,status:"authorized",user:m})})),function(o){o.command("status").description("Check the Git platform OAuth authorization status").config({help:{brief:"Check the Git platform OAuth authorization status",description:"Display the current OAuth authorization status and user info for the specified Git platform.",examples:[{desc:"Check GitHub auth status (minimal)",cmd:"coze code git auth status"},{desc:"[PIPELINE] Check if authorized",cmd:"coze code git auth status --format json | jq .status",tags:["[PIPELINE]"]}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",enum:["authorized","not-authorized"],description:"Authorization status",example:"authorized"},user:{type:"object",description:"Authorized user info"}}},errors:[{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"}],seeAlso:["coze code git auth login","coze code git auth logout"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=rm(rm(o.provider,(()=>am([i,"access",e=>e.parent,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!cm.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${cm.join(", ")}`);const r=rm(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");const a=rm(am([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>am([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=rm(am([a,"optionalAccess",e=>e.id]),(()=>""));if(2!==am([a,"optionalAccess",e=>e.status])||!c)return s.ui.info("Git Authorization:"),s.ui.info(` Provider: ${n}`),s.ui.info(" Status: not-authorized"),void s.response.print({provider:n,status:"not-authorized"});const l=(await t.IdeApi.GetUser({space_id:r,integration_id:c})).data;s.ui.info("Git Authorization:"),s.ui.info(` Provider: ${n}`),s.ui.info(" Status: authorized"),s.ui.info(` User: ${rm(rm(am([l,"optionalAccess",e=>e.login]),(()=>am([l,"optionalAccess",e=>e.name]))),(()=>"unknown"))}`),am([l,"optionalAccess",e=>e.avatar_url])&&s.ui.info(` Avatar: ${l.avatar_url}`),s.response.print({provider:n,status:"authorized",user:{login:rm(rm(am([l,"optionalAccess",e=>e.login]),(()=>am([l,"optionalAccess",e=>e.name]))),(()=>"unknown")),avatar_url:rm(am([l,"optionalAccess",e=>e.avatar_url]),(()=>""))}})}))}(i),function(o){o.command("logout").description("Revoke OAuth authorization for a Git platform").option("--force","Skip confirmation and revoke directly",!1).config({help:{brief:"Revoke OAuth authorization for a Git platform",description:"Cancel the OAuth authorization for the specified Git platform in the current space. This will revoke access for all projects in the space that use this provider. Use --force to skip the confirmation prompt.",examples:[{desc:"Logout GitHub (minimal)",cmd:"coze code git auth logout"},{desc:"Force logout without confirmation",cmd:"coze code git auth logout --force",tags:["[RECOMMENDED]"]},{desc:"Logout a specific provider",cmd:"coze code git auth logout --provider gitlab"}],schema:{input:{provider:{type:"string",required:!1,enum:["github","gitlab"],description:"Git platform provider",example:"github"},force:{type:"boolean",required:!1,description:"Skip confirmation",example:!1}},output:{provider:{type:"string",description:"Provider name",example:"github"},status:{type:"string",description:"Result status",example:"deauthorized"}}},errors:[{code:e.ErrorCode.E1015,name:"INVALID_PROVIDER",desc:"Invalid Git service provider",fix:"Currently only github is supported"},{code:e.ErrorCode.E2007,name:"NOT_AUTHORIZED",desc:"Git service is not authorized",fix:"Use `coze code git auth status` to check status"}],seeAlso:["coze code git auth login","coze code git auth status"],caveats:["Revoking authorization affects ALL projects in the current space that use this provider","Projects bound to repos via this provider will lose sync capability until re-authorized"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=lm(lm(o.provider,(()=>dm([i,"access",e=>e.parent,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!pm.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}. Supported: ${pm.join(", ")}`);const r=lm(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");const a=lm(dm([await t.IdeApi.ListIntegration({space_id:r}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])).find((e=>dm([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===n)),c=lm(dm([a,"optionalAccess",e=>e.id]),(()=>""));if(2!==dm([a,"optionalAccess",e=>e.status])||!c)throw new e.CozeError(e.ErrorCode.E2007,`${n} is not currently authorized`);await t.IdeApi.CancelOauth({integration_id:c,space_id:r}),s.ui.success(`${n} authorization revoked successfully.`),s.response.print({provider:n,status:"deauthorized"})}))}(i)};function mm(e,t){return null!=e?e:t()}function gm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const hm=["github","gitlab"];const fm=o=>{const i=o.command("git").description("Git platform integration management").option("--provider <provider>","Git service provider: github / gitlab","github").config({help:{brief:"Manage Git platform integrations (OAuth authorization and repository search)",description:"Manage Git platform integrations including OAuth authorization and repository search. Use --provider to specify the Git service provider (default: github).",examples:[{desc:"Authorize GitHub",cmd:"coze code git auth login"},{desc:"Search repos",cmd:"coze code git search --keyword react"}],seeAlso:["coze code repo"]}});um(i),i.command("search").description("Search repositories on the authorized Git platform").option("-k, --keyword <keyword>","Search keyword").option("--page <page>","Page number",parseInt).option("--page-size <size>","Results per page",parseInt).config({help:{brief:"Search repositories on the authorized Git platform",description:"Search through repositories accessible to the authorized Git user. Supports keyword filtering and pagination. Requires prior OAuth authorization.",examples:[{desc:"List all repos (minimal)",cmd:"coze code git search"},{desc:"Search by keyword",cmd:"coze code git search --keyword react",tags:["[RECOMMENDED]"]},{desc:"Paginated search",cmd:"coze code git search -k react --page 2 --page-size 10"},{desc:"[PIPELINE] Find empty repos for binding",cmd:'coze code git search -k my-repo --format json | jq ".items[] | select(.size == 0)"',tags:["[PIPELINE]"]}],schema:{input:{keyword:{type:"string",required:!1,description:"Search keyword",example:"react"},page:{type:"number",required:!1,description:"Page number",example:1},pageSize:{type:"number",required:!1,description:"Results per page",example:20}},output:{items:{type:"array",description:"Matching repositories"},total_count:{type:"number",description:"Total matching count",example:15}}},errors:[{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"}],seeAlso:["coze code repo bind","coze code repo create"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=mm(mm(o.provider,(()=>gm([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github"));if(!hm.includes(n))throw new e.CozeError(e.ErrorCode.E1015,`Invalid provider: ${n}`);const r=mm(s.config.spaceId,(()=>""));if(!r)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");s.ui.info("Searching repositories...");const a=await t.IdeApi.SearchRepo({space_id:r,name_search:mm(o.keyword,(()=>"")),per_page:mm(o.pageSize,(()=>20)),page:mm(o.page,(()=>1))}),c=mm(gm([a,"access",e=>e.data,"optionalAccess",e=>e.items]),(()=>[])),l=mm(gm([a,"access",e=>e.data,"optionalAccess",e=>e.total_count]),(()=>0));if(0===c.length)s.ui.info("No repositories found.");else{s.ui.info(`Found ${l} repositories:`);for(const e of c){const t=e.private?"private":"public";s.ui.info(` ${e.full_name} (${t})`)}}s.response.print({items:c.map((e=>({full_name:e.full_name,private:mm(e.private,(()=>!1)),size:mm(e.size,(()=>0)),updated_at:mm(e.updated_at,(()=>""))}))),total_count:l})}))};function _m(e,t){return null!=e?e:t()}function ym(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function bm(e,t){return null!=e?e:t()}function vm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}function wm(e,t){return null!=e?e:t()}function Cm(e,t){return null!=e?e:t()}function Em(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Im=o=>{const i=o.command("repo").description("Manage remote repositories for projects").option("--provider <provider>","Git service provider: github / gitlab","github").config({help:{brief:"Manage remote repository bindings for Coze Coding projects",description:"Manage remote repository bindings and sync operations for Coze Coding projects. Supports creating, binding, unbinding, pushing, pulling, and checking status of remote repositories.",examples:[{desc:"Bind repo",cmd:"coze code repo bind -p proj_abc -r user/my-repo"},{desc:"Push changes",cmd:"coze code repo push -p proj_abc"},{desc:"Check status",cmd:"coze code repo status -p proj_abc"}],seeAlso:["coze code git"]}});i.command("create").description("Create a new repository on the remote Git platform").option("-n, --name <name>","Repository name").option("--private","Create as private repository",!1).config({help:{brief:"Create a new repository on the remote Git platform",description:"Create a new empty repository under the authorized user account on the Git platform. The created repo can then be bound to a project using `coze code repo bind`.",examples:[{desc:"Create a public repo (minimal)",cmd:"coze code repo create --name my-app"},{desc:"Create a private repo",cmd:"coze code repo create -n my-app --private",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Create and bind",cmd:"coze code repo create -n my-repo --private && coze code repo bind -p proj_abc -r user/my-repo",tags:["[PIPELINE]"]}],schema:{input:{name:{type:"string",required:!0,description:"Repository name",example:"my-new-repo"},private:{type:"boolean",required:!1,description:"Create as private [RECOMMENDED]",example:!0}},output:{full_name:{type:"string",description:"Created repo full name",example:"user/my-new-repo"},html_url:{type:"string",description:"Repository URL",example:"https://github.com/user/my-new-repo"},private:{type:"boolean",description:"Visibility",example:!0}}},errors:[{code:e.ErrorCode.E1014,name:"MISSING_REPO_CREATION_NAME",desc:"Missing repo name",fix:"Use --name <name>"},{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"},{code:e.ErrorCode.E3009,name:"CONFLICT",desc:"Repository name already exists",fix:"Use a different name"}],seeAlso:["coze code repo bind","coze code git search"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=_m(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");if(!o.name)throw new e.CozeError(e.ErrorCode.E1014,"Missing repository name: use --name <name>");s.ui.info(`Creating repository "${o.name}"...`);const r=(await t.IdeApi.CreateRepo({space_id:n,name:o.name,private:_m(o.private,(()=>!1))})).data;s.ui.success("Repository created successfully."),s.ui.info(` Name: ${_m(ym([r,"optionalAccess",e=>e.full_name]),(()=>o.name))}`),s.ui.info(` URL: ${_m(ym([r,"optionalAccess",e=>e.html_url]),(()=>""))}`),s.ui.info(" Visibility: "+(o.private?"private":"public")),s.response.print({full_name:_m(ym([r,"optionalAccess",e=>e.full_name]),(()=>o.name)),html_url:_m(ym([r,"optionalAccess",e=>e.html_url]),(()=>"")),private:_m(o.private,(()=>!1))})})),function(o){o.command("bind").description("Bind a remote repository to a project").requiredOption("-p, --project-id <projectId>","Project ID").option("-r, --repo <fullName>","Remote repo full name (e.g. user/repo)").config({help:{brief:"Bind a remote repository to a project",description:"Bind an empty remote repository to the specified project. The repository must be empty (non-empty repo binding is not supported in this version). Requires prior Git OAuth authorization.",examples:[{desc:"Bind a repo (minimal)",cmd:"coze code repo bind -p proj_abc -r user/my-repo"},{desc:"Bind after creating a new repo",cmd:"coze code repo create --name my-repo && coze code repo bind -p proj_abc -r user/my-repo",tags:["[RECOMMENDED]"]},{desc:"[ERROR RECOVERY] E3015: Repo not empty",cmd:"coze code repo create --name my-new-repo --private && coze code repo bind -p proj_abc -r user/my-new-repo",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},repo:{type:"string",required:!0,description:"Remote repo full name (must be empty)",example:"user/my-repo"}},output:{project_id:{type:"string",description:"Project ID",example:"proj_abc123"},repo_full_name:{type:"string",description:"Bound repo full name",example:"user/my-repo"},status:{type:"string",description:"Binding result",example:"bound"}}},errors:[{code:e.ErrorCode.E1013,name:"MISSING_REPO_NAME",desc:"Missing repo name",fix:"Use --repo <owner/name>"},{code:e.ErrorCode.E2004,name:"GIT_NOT_AUTHORIZED",desc:"Git service not authorized",fix:"Run `coze code git auth login`"},{code:e.ErrorCode.E3015,name:"REPO_NOT_EMPTY",desc:"Repo not empty",fix:"Use `coze code repo create` to create an empty repo"},{code:e.ErrorCode.E3016,name:"REPO_ALREADY_BOUND",desc:"Project already bound",fix:"Run `coze code repo unbind -p <id>` first"}],seeAlso:["coze code repo unbind","coze code repo create","coze code repo status"],caveats:["Only empty repositories are supported for binding in this version","A project can only be bound to one repository at a time"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");const n=bm(s.config.spaceId,(()=>""));if(!n)throw new e.CozeError(e.ErrorCode.E1003,"Missing space_id");if(!o.repo)throw new e.CozeError(e.ErrorCode.E1013,"Missing repository full name: use --repo <owner/name>");const r=bm(vm([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]),(()=>1));if(3===r)throw new e.CozeError(e.ErrorCode.E3016,"Project is already bound to a remote repository. Run `coze code repo unbind -p <projectId>` first.");if(1===r)throw new e.CozeError(e.ErrorCode.E2004,"Git service is not authorized. Run `coze code git auth login` first.");const a=bm(vm([await t.IdeApi.ListIntegration({space_id:n}),"access",e=>e.data,"optionalAccess",e=>e.integration_list]),(()=>[])),c=bm(bm(o.provider,(()=>vm([i,"access",e=>e.parent,"optionalAccess",e=>e.opts,"call",e=>e(),"access",e=>e.provider]))),(()=>"github")),l=a.find((e=>vm([e,"access",e=>e.display_name,"optionalAccess",e=>e.toLowerCase,"call",e=>e()])===c)),d=bm(vm([l,"optionalAccess",e=>e.id]),(()=>""));s.ui.info(`Binding repository "${o.repo}" to project "${o.projectId}"...`),await t.IdeApi.AddRemote({project_id:o.projectId,repo_full_name:o.repo,integration_id:d}),s.ui.success("Repository bound successfully."),s.ui.info(` Project: ${o.projectId}`),s.ui.info(` Repository: ${o.repo}`),s.response.print({project_id:o.projectId,repo_full_name:o.repo,status:"bound"})}))}(i),function(o){o.command("unbind").description("Unbind the remote repository from a project").requiredOption("-p, --project-id <projectId>","Project ID").option("--force","Skip confirmation and unbind directly",!1).config({help:{brief:"Unbind the remote repository from a project",description:"Remove the remote repository binding from the specified project. This operation does not delete the remote repository itself. Use --force to skip confirmation.",examples:[{desc:"Unbind repo (minimal)",cmd:"coze code repo unbind -p proj_abc"},{desc:"Force unbind",cmd:"coze code repo unbind -p proj_abc --force",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},force:{type:"boolean",required:!1,description:"Skip confirmation",example:!1}},output:{project_id:{type:"string",description:"Project ID",example:"proj_abc123"},status:{type:"string",description:"Result status",example:"unbound"}}},errors:[{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Use `coze code repo status -p <id>` to check status"}],seeAlso:["coze code repo bind","coze code repo status"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");var n;if(3!==(null!=(n=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]))?n:(()=>1)()))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Use `coze code repo status -p <projectId>` to check status.");s.ui.info(`Unbinding remote repository from project "${o.projectId}"...`),await t.IdeApi.RemoveRemote({project_id:o.projectId}),s.ui.success("Repository unbound successfully."),s.ui.info(` Project: ${o.projectId}`),s.response.print({project_id:o.projectId,status:"unbound"})}))}(i),function(o){o.command("push").description("Push local commits to the bound remote repository").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Push local commits to the bound remote repository",description:"Push local commits to the bound remote repository. Requires the project to be bound to a remote repository. If the remote has new commits, you must pull first before pushing.",examples:[{desc:"Push changes (minimal)",cmd:"coze code repo push -p proj_abc"},{desc:"[PIPELINE] Push and check status",cmd:"coze code repo push -p proj_abc && coze code repo status -p proj_abc",tags:["[PIPELINE]"]},{desc:"[ERROR RECOVERY] E3018: Pull first",cmd:"coze code repo pull -p proj_abc && coze code repo push -p proj_abc",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"}},output:{status:{type:"string",enum:["success","failed"],description:"Push result",example:"success"},pushed_commits:{type:"number",description:"Number of commits pushed",example:2}}},errors:[{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Bind a repo first"},{code:e.ErrorCode.E3017,name:"NOTHING_TO_PUSH",desc:"Nothing to push",fix:"Already in sync with remote"},{code:e.ErrorCode.E3018,name:"REMOTE_HAS_UPDATES",desc:"Remote has updates",fix:"Run `coze code repo pull -p <id>` first"}],seeAlso:["coze code repo pull","coze code repo status"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");var n;if(3!==(null!=(n=function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]))?n:(()=>1)()))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Run `coze code repo bind` first.");s.ui.info("Pushing to remote..."),s.ui.success("Push completed successfully."),s.response.print({status:"success",pushed_commits:0})}))}(i),function(o){o.command("pull").description("Pull remote changes from the bound repository").requiredOption("-p, --project-id <projectId>","Project ID").option("--conflict-strategy <strategy>","Auto conflict resolution strategy: ours / theirs").config({help:{brief:"Pull remote changes from the bound repository",description:"Pull the latest changes from the bound remote repository. If conflicts occur and --conflict-strategy is provided, conflicts will be auto-resolved. Without --conflict-strategy, the command will fail on conflict with exit code 1.",examples:[{desc:"Pull changes (minimal)",cmd:"coze code repo pull -p proj_abc"},{desc:"Auto-resolve keeping local",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours",tags:["[RECOMMENDED]"]},{desc:"Auto-resolve using remote",cmd:"coze code repo pull -p proj_abc --conflict-strategy theirs"},{desc:"[PIPELINE] Pull then push",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours && coze code repo push -p proj_abc",tags:["[PIPELINE]"]},{desc:"[ERROR RECOVERY] E3019: Resolve conflict",cmd:"coze code repo pull -p proj_abc --conflict-strategy ours",tags:["[ERROR RECOVERY]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"},conflictStrategy:{type:"string",required:!1,enum:["ours","theirs"],description:"Auto conflict resolution strategy",example:"ours"}},output:{status:{type:"string",enum:["success","conflict_resolved","failed"],description:"Pull result",example:"success"},conflict_resolved:{type:"boolean",description:"Whether conflicts were resolved",example:!1},conflict_strategy:{type:"string",description:"Strategy used",example:"ours"},conflict_files:{type:"array",items:{type:"string"},description:"Conflicting files",example:["src/index.ts"]}}},enums:{"conflict-strategy":{ours:"Keep local version for all conflicting files",theirs:"Use remote version for all conflicting files"}},errors:[{code:e.ErrorCode.E3014,name:"REPO_NOT_BOUND",desc:"No repo bound",fix:"Bind a repo first"},{code:e.ErrorCode.E3019,name:"MERGE_CONFLICT",desc:"Merge conflict without strategy",fix:"Use --conflict-strategy ours or theirs"},{code:e.ErrorCode.E3020,name:"WOULD_OVERWRITE",desc:"Local changes would be overwritten",fix:"Commit local changes first"}],seeAlso:["coze code repo push","coze code repo status"],caveats:["Without --conflict-strategy, conflicts will cause the command to fail","Conflict resolution applies to ALL conflicting files (no per-file selection in CLI)"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");if(3!==wm(function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([await t.IdeApi.GetRemote({project_id:o.projectId}),"access",e=>e.data,"optionalAccess",e=>e.status]),(()=>1)))throw new e.CozeError(e.ErrorCode.E3014,"Project has no bound remote repository. Run `coze code repo bind` first.");s.ui.info("Pulling from remote..."),s.ui.success("Pull completed successfully."),s.response.print({status:"success",conflict_resolved:!1,conflict_strategy:wm(o.conflictStrategy,(()=>null)),conflict_files:[]})}))}(i),function(o){o.command("status").description("Show remote repository binding and sync status for a project").requiredOption("-p, --project-id <projectId>","Project ID").config({help:{brief:"Show remote repository binding and sync status for a project",description:"Display the current remote repository binding status of a project, including the bind status and (when bound) the repository full name and URL.",examples:[{desc:"Check repo status (minimal)",cmd:"coze code repo status -p proj_abc"},{desc:"JSON output for scripting",cmd:"coze code repo status -p proj_abc --format json",tags:["[RECOMMENDED]"]},{desc:"[PIPELINE] Check binding status",cmd:"coze code repo status -p proj_abc --format json | jq .bind_status",tags:["[PIPELINE]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID",example:"proj_abc123"}},output:{bind_status:{type:"string",enum:["unauth","not-bound","bound"],description:"Binding status",example:"bound"},repo_full_name:{type:"string",description:"Remote repo full name",example:"user/my-app"},html_url:{type:"string",description:"Repository URL",example:"https://github.com/user/my-app"}}},errors:[{code:e.ErrorCode.E3001,name:"PROJECT_NOT_FOUND",desc:"Project not found",fix:"Confirm the project ID is correct"}],seeAlso:["coze code repo bind","coze code repo push","coze code repo pull"]}}).action((async(o,i)=>{const s=i.getContext();if(!s)throw new e.CozeError(e.ErrorCode.E5000,"CLI context is not initialized");s.ui.info("Fetching remote repository status...");const n=await t.IdeApi.GetRemote({project_id:o.projectId}),{data:r}=n,a=Cm(Em([r,"optionalAccess",e=>e.status]),(()=>1)),c=Cm({1:"unauth",2:"not-bound",3:"bound"}[a],(()=>"unauth"));if(3!==a)return s.ui.info("Remote Repository:"),s.ui.info(` Status: ${c}`),void s.response.print({bind_status:c});const l=Em([r,"optionalAccess",e=>e.basic_info]),d=Cm(Em([l,"optionalAccess",e=>e.full_name]),(()=>"")),p=Cm(Em([l,"optionalAccess",e=>e.html_url]),(()=>""));s.ui.info("Remote Repository:"),s.ui.info(` Status: ${c}`),s.ui.info(` Repository: ${d}`),s.ui.info(` URL: ${p}`),s.response.print({bind_status:c,repo_full_name:d,html_url:p})}))}(i)};function Am(o){const i=o.command("code").description("Coze Coding CLI utilities").config({help:{brief:"Coze Coding project management",description:"Manage Coze Coding projects, including project creation, messaging, deployment, environment variables, domains, skills, and previews.",examples:[{desc:"Create a new project",cmd:'coze code project create --message "Create a chatbot" --type web'},{desc:"Send a message",cmd:'coze code message send "Fix the bug" -p <projectId>'},{desc:"Deploy project",cmd:"coze code deploy <projectId>"},{desc:"Preview project",cmd:"coze code preview <projectId>"}],seeAlso:["coze auth","coze space","coze organization"]}});Cp(i),Cu(i),ep(i),jp(i),pu(i),tl(i),function(o){o.command("preview <projectId>").description("Get deployment preview info for the project").config({help:{brief:"Get project preview URL",description:"Get the sandbox preview URL for the project. Supported for general Web/App project types, returning an accessible preview URL. Sandbox initialization takes 1-3 minutes. WechatMiniProgram, Agent, Automation, Skill, and AssistantAgent projects are not previewable from the CLI.",examples:[{desc:"Get preview URL",cmd:"coze code preview <projectId>",tags:["[RECOMMENDED]"]}],schema:{input:{projectId:{type:"string",required:!0,description:"Project ID"}},output:{type:{type:"string",description:"Project type"},preview_url:{type:"string",description:"Preview URL"}}},errors:[{code:e.ErrorCode.E1006,name:"UNSUPPORTED_PROJECT_TYPE",desc:"Unsupported project type for CLI preview",fix:`Preview is not available for MiniProgram, Agent, Automation, Skill, or AssistantAgent projects. Use the Web dashboard: ${ip().replace(/\/$/,"")}`},{code:e.ErrorCode.E1000,name:"INVALID_ARGUMENT",desc:"Missing required argument: projectId",fix:"Pass <projectId> as the first argument: `coze code preview <projectId>`",example:"coze code preview 123456"}]}}).action((async function(o,i,s){const n=s.getContext();if(!o)throw new e.CozeError(e.ErrorCode.E1000,"Missing projectId: pass <projectId> as argument");const r=np([await t.IdeApi.GetVibeProject({project_id:o}),"access",e=>e.data,"optionalAccess",e=>e.project_info,"optionalAccess",e=>e.project_type]),a={type:Nd(r)};if(rp.has(r))return void np([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e({type:a.type,message:`Project type '${a.type}' does not support CLI preview. Please visit the Web dashboard: ${sp(o,np([n,"optionalAccess",e=>e.config,"access",e=>e.apiBaseUrl]))}`})]);const c=await t.IdeApi.InitSandbox({project_id:o});a.preview_url=c.token?`https://${c.project_host}?token=${c.token}`:`https://${c.project_host}`,np([n,"optionalAccess",e=>e.ui,"access",e=>e.info,"call",e=>e(`Sandbox initialization started. Please access the preview URL in 1-3 minutes,preview_url: ${a.preview_url}`)]),np([n,"optionalAccess",e=>e.response,"access",e=>e.print,"call",e=>e(a)])}))}(i),om(i),Jc(i),lp(i),fm(i),Im(i)}const Sm=async e=>await new Promise((t=>setTimeout(t,e)));function jm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Pm=e=>{if(!e)return;const t=e.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);if(jm([t,"optionalAccess",e=>e[1]]))return(e=>{try{return decodeURIComponent(e)}catch(t){return URIError,e}})(t[1]);const o=e.match(/filename\s*=\s*"([^"]+)"/i);if(jm([o,"optionalAccess",e=>e[1]]))return o[1];const i=e.match(/filename\s*=\s*([^;]+)/i);return jm([i,"optionalAccess",e=>e[1]])?i[1].trim():void 0},km=async({url:t,outputPath:o,fetchImpl:s=t=>e.customFetch.fetch(t)})=>{const{buffer:n,response:r}=await(async(t,o)=>{const i=await o(t);if(!i.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to download session file: ${i.status} ${i.statusText}`);return{buffer:Buffer.from(await i.arrayBuffer()),response:i}})(t,s),a=o||(e=>{const t=Pm((o=e.contentDisposition,s=()=>null,null!=o?o:s()));var o,s;if(t)return t;for(const t of[e.responseUrl,e.requestUrl]){if(!t||!URL.canParse(t))continue;const e=new URL(t),o=i.basename(decodeURIComponent(e.pathname));if(o&&"/"!==o&&"."!==o)return o}return"session-file.bin"})({requestUrl:t,responseUrl:r.url,contentDisposition:r.headers.get("content-disposition")}),c=await na(a,n);return{path:c,filename:i.basename(c),size:n.byteLength,url:t,logid:r.headers.get("x-tt-logid")||void 0}},Tm="1008033";function zm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Rm=async({baseUrl:t,headers:o,xTTEnv:i})=>{const s=new URL("/api/coze_claw/resource/get_frontier_key",l.normalizeBaseUrl(t));l.appendSearchParams(s,{aid:Tm});const n={...o,...l.getPpeHeaders(i)},r=await e.customFetch.fetch(s.toString(),{method:"GET",headers:n}),a=await l.parseServiceResponseBody(r,{}),c=l.getServiceResponseLogId(r);if(!r.ok)throw new Error(l.formatServiceErrorWithLogId({fallback:`Failed to get frontier key: ${r.status} ${r.statusText}`,logId:c,message:a.msg}));const d=zm([a,"access",e=>e.data,"optionalAccess",e=>e.access_key]),p=zm([a,"access",e=>e.data,"optionalAccess",e=>e.device_id]);if(!d||!p)throw new Error(l.formatServiceErrorWithLogId({fallback:"Frontier key response is incomplete",logId:c,message:a.msg}));return{accessKey:d,deviceId:p}};function xm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Lm=async({filePaths:t,clawId:o,sessionId:n,accessFile:a=s.access,createFileReadStream:c=r.openAsBlob,uploadFile:l})=>{const d=[];for(const s of t){try{await a(s)}catch(t){throw new e.CozeError(e.ErrorCode.E3000,`File not found or not readable: ${s}${t instanceof Error?` (${t.message})`:""}`)}const t=i.basename(s),r=await l({fileName:t,fileContent:await c(s),clawId:o,sessionId:n}),p=xm([r,"access",e=>e.data,"optionalAccess",e=>e.file]);if(!xm([p,"optionalAccess",e=>e.file_uri])||!xm([p,"optionalAccess",e=>e.file_url]))throw new e.CozeError(e.ErrorCode.E5002,r.msg||`Failed to upload session file: ${s}`);d.push({file_name:p.file_name||t,file_uri:p.file_uri,file_url:p.file_url})}return d},Om=async({filePaths:e,sessionId:t,apiBaseUrl:o,sessionApiBaseUrl:i,sessionSpaceWebId:s,xTTEnv:n,service:r,deps:a})=>{if(!e||0===e.length)return[];const c=xm([a,"optionalAccess",e=>e.store])||l.createSessionConfigStore(),{sessionClawId:d}=await c.get(),p=d||(await r.getStatus()).clawId;if(!p)throw new l.SessionServiceError("Session token is missing or invalid","SESSION_AUTH_INVALID");const u=i||o,m=await(async({sessionSpaceWebId:e,baseUrl:t,xTTEnv:o})=>{if(e)return e;try{return(await Rm({baseUrl:t,headers:{},xTTEnv:o})).deviceId}catch(e){return}})({sessionSpaceWebId:s,baseUrl:u,xTTEnv:n}),g=(xm([a,"optionalAccess",e=>e.createApi])||l.createSessionApiClient)({baseUrl:u,webOrigin:u,xSpaceWebId:m,xTTEnv:n}),h=xm([a,"optionalAccess",e=>e.uploadFiles])||Lm;return await h({filePaths:e,clawId:p,sessionId:t,uploadFile:({fileName:e,fileContent:t,clawId:o,sessionId:i})=>g.uploadFile({fileName:e,fileContent:t,clawId:o,sessionId:i})})};function Dm(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}const Um=1048576,Bm=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,qm=({absolutePath:e,root:t})=>{const o=i.relative(t,e);return Boolean(o)&&!o.startsWith("..")&&!i.isAbsolute(o)},Mm=async({onWarn:e,shouldWarnInvalidMention:t=()=>!0,statFile:o=s.stat,userInput:n,workTree:r})=>{(e=>{if(e.length>Um)throw new Error("Message input is too long: max 1048576 characters")})(n);const a=[...n.matchAll(Bm)];if(0===a.length)return[{type:"text",text:n}];const c=[],l=i.resolve(r);let d=0;for(const s of a){const r=s.index,a=s[0],p=s[1];r>d&&c.push({type:"text",text:n.slice(d,r)});const u=i.resolve(l,p);let m=!1;if(qm({absolutePath:u,root:l}))try{(await o(u)).isFile()?m=!0:t(p)&&Dm([e,"optionalCall",e=>e(`Uploading directories is not supported: ${p}`)])}catch(o){t(p)&&Dm([e,"optionalCall",e=>e(`File not found: ${p}`)])}m?c.push({type:"file",absolutePath:u,rawMention:a,relativePath:p}):c.push({type:"text",text:a}),d=r+a.length}return d<n.length&&c.push({type:"text",text:n.slice(d)}),c};const Nm=e=>{if(null==e)return null;const t=e.trim();return 0===t.length?null:t},$m=e=>e.includes("/")||e.includes("\\")||e.includes(".")||e.startsWith("."),Gm=async(e,t={})=>{const o=await(async e=>{const t=await oa(),o=Nm(e),i=Nm(t);return o||i?o&&i?`${o}\n\n${i}`:(n=()=>i,null!=(s=o)?s:n()):null;var s,n})(e);if(!o)return{content:o,filePaths:[]};const i=await Mm({onWarn:t.onWarn,shouldWarnInvalidMention:$m,userInput:o,workTree:t.cwd||process.cwd()}),s=[];return{content:Nm(i.map((e=>"text"===e.type?e.text:(s.push(e.absolutePath),""))).join("")),filePaths:s}};const Fm=e=>function(e){let t,o=e[0],i=1;for(;i<e.length;){const s=e[i],n=e[i+1];if(i+=2,("optionalAccess"===s||"optionalCall"===s)&&null==o)return;"access"===s||"optionalAccess"===s?(t=o,o=n(o)):"call"!==s&&"optionalCall"!==s||(o=n(((...e)=>o.call(t,...e))),t=void 0)}return o}([e,"optionalAccess",e=>e.trim,"call",e=>e(),"access",e=>e.toLowerCase,"call",e=>e()])||"",Vm=async({baseUrl:t,xTTEnv:o,fetchImpl:i=e.customFetch.fetch.bind(e.customFetch)})=>{const s={"content-type":"application/json"};o&&(s["x-use-ppe"]="1",s["x-tt-env"]=o);const n=await i(`${(e=>new URL(e).origin)(t)}/api/coze_space/get_podcast_config`,{method:"POST",headers:s,body:"{}"});if(!n.ok)throw new e.CozeError(e.ErrorCode.E5001,`Failed to fetch podcast config: ${String(n.status||"")} ${String(n.statusText||"")}`.trim());const r=await n.json();if(0!==r.code&&void 0!==r.code)throw new e.CozeError(e.ErrorCode.E5002,r.msg||"Failed to fetch podcast config");return r.data||{}},Wm=({config:t,mode:o,keyword:i})=>{const s=(({config:t,mode:o})=>{if(!o)return;const i=Fm(o),s=(t.mode_options||[]).find((e=>Fm(e.value)===i||Fm(e.label)===i));if(!s)throw new e.CozeError(e.ErrorCode.E1000,`Podcast mode not found: ${o}`);return s})({config:t,mode:o}),n=Fm(i);return(s?[s]:t.mode_options||[]).flatMap((e=>(e.voice_options||[]).map((t=>({mode_label:e.label,mode_value:e.value,label:t.label,value:t.value,sample:t.sample,color_code:t.color_code}))).filter((e=>!n||(Fm(e.label).includes(n)||Fm(e.value).includes(n))))))};
17
17
  /*! *****************************************************************************
18
18
  Copyright (c) Microsoft Corporation.
19
19