@contak/cli 0.1.0 → 0.2.0

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/README.md CHANGED
@@ -15,6 +15,12 @@ Contak 记录**线下面对面**的对话:录音传上去,它转写、分离
15
15
  ```bash
16
16
  contak login # 设备码登录,密码不进终端
17
17
  contak whoami # 当前登录态
18
+ contak open voiceprint # 生成已登录的网页声纹录入链接
19
+ contak contacts list # 查看人脉
20
+ contak meetings upload <file> # 上传会议音频
21
+ contak todos list # 查看待办
22
+ contak search ask <question> # AI 搜索
23
+ contak context imports # 查看个人上下文导入状态
18
24
  contak skills install # 把 Agent Skill 装进 ~/.claude/skills
19
25
  ```
20
26
 
@@ -1,5 +1,5 @@
1
- @contak/cli 0.1.0 内联了以下开源组件,它们按各自的许可证授权;以下为原始许可证与版权声明。
2
- The following open-source components are bundled into @contak/cli 0.1.0 and licensed under their respective licenses.
1
+ @contak/cli 0.2.0 内联了以下开源组件,它们按各自的许可证授权;以下为原始许可证与版权声明。
2
+ The following open-source components are bundled into @contak/cli 0.2.0 and licensed under their respective licenses.
3
3
 
4
4
  ========================================================================
5
5
  commander 15.0.0 (MIT) git+https://github.com/tj/commander.js.git
package/dist/index.js CHANGED
@@ -1,53 +1,64 @@
1
- import{pathToFileURL as Ct}from"node:url";var C=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},b=class extends C{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var P=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new b(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function H(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}import{EventEmitter as He}from"node:events";import Y from"node:child_process";import _ from"node:path";import j from"node:fs";import m from"node:process";import{stripVTControlCharacters as Ve}from"node:util";import{stripVTControlCharacters as De}from"node:util";var R=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(i=>!i._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((i,s)=>i.name().localeCompare(s.name())),t}compareOptions(e,t){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(i=>!i.hidden),n=e._getHelpOption();if(n&&!n.hidden){let i=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);!i&&!s?t.push(n):n.long&&!s?t.push(e.createOption(n.long,n.description)):n.short&&!i&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let i=n.options.filter(s=>!s.hidden);t.push(...i)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>H(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,""]}groupItems(e,t,n){let i=new Map;return e.forEach(s=>{let o=n(s);i.has(o)||i.set(o,[])}),t.forEach(s=>{let o=n(s);i.has(o)||i.set(o,[]),i.get(o).push(s)}),i}formatHelp(e,t){let n=t.padWidth(e,t),i=t.helpWidth??80;function s(l,h){return t.formatItem(l,n,h,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(a),i),""]));let c=t.visibleArguments(e).map(l=>s(t.styleArgumentTerm(t.argumentTerm(l)),t.styleArgumentDescription(t.argumentDescription(l))));if(o=o.concat(this.formatItemList("Arguments:",c,t)),this.groupItems(e.options,t.visibleOptions(e),l=>l.helpGroupHeading??"Options:").forEach((l,h)=>{let k=l.map(w=>s(t.styleOptionTerm(t.optionTerm(w)),t.styleOptionDescription(t.optionDescription(w))));o=o.concat(this.formatItemList(h,k,t))}),t.showGlobalOptions){let l=t.visibleGlobalOptions(e).map(h=>s(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));o=o.concat(this.formatItemList("Global Options:",l,t))}return this.groupItems(e.commands,t.visibleCommands(e),l=>l.helpGroup()||"Commands:").forEach((l,h)=>{let k=l.map(w=>s(t.styleSubcommandTerm(t.subcommandTerm(w)),t.styleSubcommandDescription(t.subcommandDescription(w))));o=o.concat(this.formatItemList(h,k,t))}),o.join(`
2
- `)}displayWidth(e){return De(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,i){let o=" ".repeat(2);if(!n)return o+e;let a=e.padEnd(t+e.length-i.displayWidth(e)),c=2,u=(this.helpWidth??80)-t-c-2,l;return u<this.minWidthToWrap||i.preformatted(n)?l=n:l=i.boxWrap(n,u).replace(/\n/g,`
3
- `+" ".repeat(t+c)),o+a+" ".repeat(c)+l.replace(/\n/g,`
4
- ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,s=[];return n.forEach(o=>{let a=o.match(i);if(a===null){s.push("");return}let c=[a.shift()],d=this.displayWidth(c[0]);a.forEach(u=>{let l=this.displayWidth(u);if(d+l<=t){c.push(u),d+=l;return}s.push(c.join(""));let h=u.trimStart();c=[h],d=this.displayWidth(h)}),s.push(c.join(""))}),s.join(`
5
- `)}};var A=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Ie(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new b(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?me(this.name().replace(/^no-/,"")):me(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},V=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let i=this.negativeOptions.get(n).presetArg,s=i!==void 0?i:!1;return t.negate===(s===e)}};function me(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ie(r){let e,t,n=/^-[^-]$/,i=/^--[^-]/,s=r.split(/[ |,]+/).concat("guard");if(n.test(s[0])&&(e=s.shift()),i.test(s[0])&&(t=s.shift()),!e&&n.test(s[0])&&(e=s.shift()),!e&&i.test(s[0])&&(e=t,t=s.shift()),s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${r}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
1
+ import{pathToFileURL as Mn}from"node:url";var v=class extends Error{constructor(t,e,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}},E=class extends v{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var j=class{constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new E(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function L(i){let t=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+t+">":"["+t+"]"}import{EventEmitter as ge}from"node:events";import ot from"node:child_process";import k from"node:path";import q from"node:fs";import h from"node:process";import{stripVTControlCharacters as _e}from"node:util";import{stripVTControlCharacters as me}from"node:util";var H=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let e=t.commands.filter(r=>!r._hidden),n=t._getHelpCommand();return n&&!n._hidden&&e.push(n),this.sortSubcommands&&e.sort((r,o)=>r.name().localeCompare(o.name())),e}compareOptions(t,e){let n=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return n(t).localeCompare(n(e))}visibleOptions(t){let e=t.options.filter(r=>!r.hidden),n=t._getHelpOption();if(n&&!n.hidden){let r=n.short&&t._findOption(n.short),o=n.long&&t._findOption(n.long);!r&&!o?e.push(n):n.long&&!o?e.push(t.createOption(n.long,n.description)):n.short&&!r&&e.push(t.createOption(n.short,n.description))}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let e=[];for(let n=t.parent;n;n=n.parent){let r=n.options.filter(o=>!o.hidden);e.push(...r)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||""}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(n=>L(n)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((n,r)=>Math.max(n,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(r)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((n,r)=>Math.max(n,this.displayWidth(e.styleOptionTerm(e.optionTerm(r)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((n,r)=>Math.max(n,this.displayWidth(e.styleOptionTerm(e.optionTerm(r)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((n,r)=>Math.max(n,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(r)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let n="";for(let r=t.parent;r;r=r.parent)n=r.name()+" "+n;return n+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let n=`(${e.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let n=`(${e.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatItemList(t,e,n){return e.length===0?[]:[n.styleTitle(t),...e,""]}groupItems(t,e,n){let r=new Map;return t.forEach(o=>{let s=n(o);r.has(s)||r.set(s,[])}),e.forEach(o=>{let s=n(o);r.has(s)||r.set(s,[]),r.get(s).push(o)}),r}formatHelp(t,e){let n=e.padWidth(t,e),r=e.helpWidth??80;function o(d,f){return e.formatItem(d,n,f,e)}let s=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(s=s.concat([e.boxWrap(e.styleCommandDescription(a),r),""]));let u=e.visibleArguments(t).map(d=>o(e.styleArgumentTerm(e.argumentTerm(d)),e.styleArgumentDescription(e.argumentDescription(d))));if(s=s.concat(this.formatItemList("Arguments:",u,e)),this.groupItems(t.options,e.visibleOptions(t),d=>d.helpGroupHeading??"Options:").forEach((d,f)=>{let b=d.map(_=>o(e.styleOptionTerm(e.optionTerm(_)),e.styleOptionDescription(e.optionDescription(_))));s=s.concat(this.formatItemList(f,b,e))}),e.showGlobalOptions){let d=e.visibleGlobalOptions(t).map(f=>o(e.styleOptionTerm(e.optionTerm(f)),e.styleOptionDescription(e.optionDescription(f))));s=s.concat(this.formatItemList("Global Options:",d,e))}return this.groupItems(t.commands,e.visibleCommands(t),d=>d.helpGroup()||"Commands:").forEach((d,f)=>{let b=d.map(_=>o(e.styleSubcommandTerm(e.subcommandTerm(_)),e.styleSubcommandDescription(e.subcommandDescription(_))));s=s.concat(this.formatItemList(f,b,e))}),s.join(`
2
+ `)}displayWidth(t){return me(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e==="[command]"?this.styleSubcommandText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,e,n,r){let s=" ".repeat(2);if(!n)return s+t;let a=t.padEnd(e+t.length-r.displayWidth(t)),u=2,c=(this.helpWidth??80)-e-u-2,d;return c<this.minWidthToWrap||r.preformatted(n)?d=n:d=r.boxWrap(n,c).replace(/\n/g,`
3
+ `+" ".repeat(e+u)),s+a+" ".repeat(u)+d.replace(/\n/g,`
4
+ ${s}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let n=t.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,o=[];return n.forEach(s=>{let a=s.match(r);if(a===null){o.push("");return}let u=[a.shift()],l=this.displayWidth(u[0]);a.forEach(c=>{let d=this.displayWidth(c);if(l+d<=e){u.push(c),l+=d;return}o.push(u.join(""));let f=c.trimStart();u=[f],l=this.displayWidth(f)}),o.push(u.join(""))}),o.join(`
5
+ `)}};var I=class{constructor(t,e){this.flags=t,this.description=e||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let n=fe(t);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;return typeof t=="string"&&(e={[t]:!0}),this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new E(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?At(this.name().replace(/^no-/,"")):At(this.name())}helpGroup(t){return this.helpGroupHeading=t,this}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},W=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(t,e){let n=e.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,o=r!==void 0?r:!1;return e.negate===(o===t)}};function At(i){return i.split("-").reduce((t,e)=>t+e[0].toUpperCase()+e.slice(1))}function fe(i){let t,e,n=/^-[^-]$/,r=/^--[^-]/,o=i.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(t=o.shift()),r.test(o[0])&&(e=o.shift()),!t&&n.test(o[0])&&(t=o.shift()),!t&&r.test(o[0])&&(t=e,e=o.shift()),o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${i}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
6
6
  - a short flag is a single dash and a single character
7
7
  - either use a single dash and a single character (for a short flag)
8
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(o)?new Error(`${a}
9
- - too many short flags`):i.test(o)?new Error(`${a}
8
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(s)?new Error(`${a}
9
+ - too many short flags`):r.test(s)?new Error(`${a}
10
10
  - too many long flags`):new Error(`${a}
11
- - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}function Fe(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=r.length;i++){let s;r[i-1]===e[n-1]?s=0:s=1,t[i][n]=Math.min(t[i-1][n]+1,t[i][n-1]+1,t[i-1][n-1]+s),i>1&&n>1&&r[i-1]===e[n-2]&&r[i-2]===e[n-1]&&(t[i][n]=Math.min(t[i][n],t[i-2][n-2]+1))}return t[r.length][e.length]}function X(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let n=[],i=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Fe(r,o),c=Math.max(r.length,o.length);(c-a)/c>s&&(a<i?(i=a,n=[o]):a===i&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
11
+ - unrecognised flag format`)}if(t===void 0&&e===void 0)throw new Error(`option creation failed due to no flags found in '${i}'.`);return{shortFlag:t,longFlag:e}}function he(i,t){if(Math.abs(i.length-t.length)>3)return Math.max(i.length,t.length);let e=[];for(let n=0;n<=i.length;n++)e[n]=[n];for(let n=0;n<=t.length;n++)e[0][n]=n;for(let n=1;n<=t.length;n++)for(let r=1;r<=i.length;r++){let o;i[r-1]===t[n-1]?o=0:o=1,e[r][n]=Math.min(e[r-1][n]+1,e[r][n-1]+1,e[r-1][n-1]+o),r>1&&n>1&&i[r-1]===t[n-2]&&i[r-2]===t[n-1]&&(e[r][n]=Math.min(e[r][n],e[r-2][n-2]+1))}return e[i.length][t.length]}function rt(i,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let e=i.startsWith("--");e&&(i=i.slice(2),t=t.map(s=>s.slice(2)));let n=[],r=3,o=.4;return t.forEach(s=>{if(s.length<=1)return;let a=he(i,s),u=Math.max(i.length,s.length);(u-a)/u>o&&(a<r?(r=a,n=[s]):a===r&&n.push(s))}),n.sort((s,a)=>s.localeCompare(a)),e&&(n=n.map(s=>`--${s}`)),n.length>1?`
12
12
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
13
- (Did you mean ${n[0]}?)`:""}var E=class r extends He{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>m.stdout.write(t),writeErr:t=>m.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,getOutHasColors:()=>fe()??(m.stdout.isTTY&&m.stdout.hasColors?.()),getErrHasColors:()=>fe()??(m.stderr.isTTY&&m.stderr.hasColors?.()),stripColor:t=>Ve(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let i=t,s=n;typeof i=="object"&&i!==null&&(s=i,i=null),s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return i&&(c.description(i),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),i?this:c}createCommand(e){return new r(e)}createHelp(){return Object.assign(new R,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
14
- - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new P(e,t)}argument(e,t,n,i){let s=this.createArgument(e,t);return typeof n=="function"?s.default(i).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let n=e??"help [command]",[,i,s]=n.match(/([^ ]+) *(.*)/),o=t??"display help for command",a=this.createCommand(i);return a.helpOption(!1),s&&a.arguments(s),o&&a.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
15
- Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new C(e,t,n)),m.exit(e)}action(e){let t=n=>{let i=this.registeredArguments.length,s=n.slice(0,i);return this._storeOptionsAsProperties?s[i]=this:s[i]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new A(e,t)}_callParseArg(e,t,n,i){try{return e.parseArg(t,n)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${i} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
16
- - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=i=>[i.name()].concat(i.aliases()),n=t(e).find(i=>this._findCommand(i));if(n){let i=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,o):s!==null&&e.variadic&&(s=e._collectValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+t,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;i(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;i(s,o,"env")}),this}_optionEx(e,t,n,i,s){if(typeof t=="object"&&t instanceof A)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof i=="function")o.default(s).argParser(i);else if(i instanceof RegExp){let a=i;i=(c,d)=>{let u=a.exec(c);return u?u[0]:d},o.default(s).argParser(i)}else o.default(i);return this.addOption(o)}option(e,t,n,i){return this._optionEx({},e,t,n,i)}requiredOption(e,t,n,i){return this._optionEx({mandatory:!0},e,t,n,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){m.versions?.electron&&(t.from="electron");let i=m.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=m.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":m.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,"--");this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
17
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(j.existsSync(e))return;let i=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${e}' does not exist
13
+ (Did you mean ${n[0]}?)`:""}var N=class i extends ge{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>h.stdout.write(e),writeErr:e=>h.stderr.write(e),outputError:(e,n)=>n(e),getOutHelpWidth:()=>h.stdout.isTTY?h.stdout.columns:void 0,getErrHelpWidth:()=>h.stderr.isTTY?h.stderr.columns:void 0,getOutHasColors:()=>Tt()??(h.stdout.isTTY&&h.stdout.hasColors?.()),getErrHasColors:()=>Tt()??(h.stderr.isTTY&&h.stderr.hasColors?.()),stripColor:e=>_e(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,n){let r=e,o=n;typeof r=="object"&&r!==null&&(o=r,r=null),o=o||{};let[,s,a]=t.match(/([^ ]+) *(.*)/),u=this.createCommand(s);return r&&(u.description(r),u._executableHandler=!0),o.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(o.noHelp||o.hidden),u._executableFile=o.executableFile||null,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),r?this:u}createCommand(t){return new i(t)}createHelp(){return Object.assign(new H,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...t},this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
14
+ - specify the name in Command constructor or using .name()`);return e=e||{},e.isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new j(t,e)}argument(t,e,n,r){let o=this.createArgument(t,e);return typeof n=="function"?o.default(r).argParser(n):o.default(n),this.addArgument(o),this}arguments(t){return t.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(t){let e=this.registeredArguments.slice(-1)[0];if(e?.variadic)throw new Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let n=t??"help [command]",[,r,o]=n.match(/([^ ]+) *(.*)/),s=e??"display help for command",a=this.createCommand(r);return a.helpOption(!1),o&&a.arguments(o),s&&a.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=a,(t||e)&&this._initCommandGroup(a),this}addHelpCommand(t,e){return typeof t!="object"?(this.helpCommand(t,e),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this._initCommandGroup(t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,e){let n=["preSubcommand","preAction","postAction"];if(!n.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
15
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync")throw e},this}_exit(t,e,n){this._exitCallback&&this._exitCallback(new v(t,e,n)),h.exit(t)}action(t){let e=n=>{let r=this.registeredArguments.length,o=n.slice(0,r);return this._storeOptionsAsProperties?o[r]=this:o[r]=this.opts(),o.push(this),t.apply(this,o)};return this._actionHandler=e,this}createOption(t,e){return new I(t,e)}_callParseArg(t,e,n,r){try{return t.parseArg(e,n)}catch(o){if(o.code==="commander.invalidArgument"){let s=`${r} ${o.message}`;this.error(s,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(t){let e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){let n=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
16
+ - already used by option '${e.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){let e=r=>[r.name()].concat(r.aliases()),n=e(t).find(r=>this._findCommand(r));if(n){let r=e(this._findCommand(n)).join("|"),o=e(t).join("|");throw new Error(`cannot add command '${o}' as already have command '${r}'`)}this._initCommandGroup(t),this.commands.push(t)}addOption(t){this._registerOption(t);let e=t.name(),n=t.attributeName();t.defaultValue!==void 0&&this.setOptionValueWithSource(n,t.defaultValue,"default");let r=(o,s,a)=>{o==null&&t.presetArg!==void 0&&(o=t.presetArg);let u=this.getOptionValue(n);o!==null&&t.parseArg?o=this._callParseArg(t,o,u,s):o!==null&&t.variadic&&(o=t._collectValue(o,u)),o==null&&(t.negate?o=!1:t.isBoolean()||t.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,a)};return this.on("option:"+e,o=>{let s=`error: option '${t.flags}' argument '${o}' is invalid.`;r(o,s,"cli")}),t.envVar&&this.on("optionEnv:"+e,o=>{let s=`error: option '${t.flags}' value '${o}' from env '${t.envVar}' is invalid.`;r(o,s,"env")}),this}_optionEx(t,e,n,r,o){if(typeof e=="object"&&e instanceof I)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(e,n);if(s.makeOptionMandatory(!!t.mandatory),typeof r=="function")s.default(o).argParser(r);else if(r instanceof RegExp){let a=r;r=(u,l)=>{let c=a.exec(u);return c?c[0]:l},s.default(o).argParser(r)}else s.default(r);return this.addOption(s)}option(t,e,n,r){return this._optionEx({},t,e,n,r)}requiredOption(t,e,n,r){return this._optionEx({mandatory:!0},t,e,n,r)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,n){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=n,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(t)!==void 0&&(e=n.getOptionValueSource(t))}),e}_prepareUserArgs(t,e){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(e=e||{},t===void 0&&e.from===void 0){h.versions?.electron&&(e.from="electron");let r=h.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(e.from="eval")}t===void 0&&(t=h.argv),this.rawArgs=t.slice();let n;switch(e.from){case void 0:case"node":this._scriptPath=t[1],n=t.slice(2);break;case"electron":h.defaultApp?(this._scriptPath=t[1],n=t.slice(2)):n=t.slice(1);break;case"user":n=t.slice(0);break;case"eval":n=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(t,e){this._prepareForParse();let n=this._prepareUserArgs(t,e);return this._parseCommand([],n),this}async parseAsync(t,e){this._prepareForParse();let n=this._prepareUserArgs(t,e);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(t=>t.negate&&t.defaultValue===void 0&&this.getOptionValue(t.attributeName())===void 0).forEach(t=>{let e=t.long.replace(/^--no-/,"--");this._findOption(e)||this.setOptionValueWithSource(t.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
17
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,e,n){if(q.existsSync(t))return;let r=e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${t}' does not exist
18
18
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
19
19
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
20
- - ${i}`;throw new Error(s)}_executeSubCommand(e,t){t=t.slice();let n=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,l){let h=_.resolve(u,l);if(j.existsSync(h))return h;if(n.includes(_.extname(l)))return;let k=n.find(w=>j.existsSync(`${h}${w}`));if(k)return`${h}${k}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,o=this._executableDir||"";if(this._scriptPath){let u;try{u=j.realpathSync(this._scriptPath)}catch{u=this._scriptPath}o=_.resolve(_.dirname(u),o)}if(o){let u=i(o,s);if(!u&&!e._executableFile&&this._scriptPath){let l=_.basename(this._scriptPath,_.extname(this._scriptPath));l!==this._name&&(u=i(o,`${l}-${e._name}`))}s=u||s}let a=n.includes(_.extname(s)),c;m.platform!=="win32"?a?(t.unshift(s),t=pe(m.execArgv).concat(t),c=Y.spawn(m.argv[0],t,{stdio:"inherit"})):c=Y.spawn(s,t,{stdio:"inherit"}):(this._checkForMissingExecutable(s,o,e._name),t.unshift(s),t=pe(m.execArgv).concat(t),c=Y.spawn(m.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(l=>{m.on(l,()=>{c.killed===!1&&c.exitCode===null&&c.kill(l)})});let d=this._exitCallback;c.on("close",u=>{u=u??1,d?d(new C(u,"commander.executeSubCommandAsync","(close)")):m.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(s,o,e._name);else if(u.code==="EACCES")throw new Error(`'${s}' not executable`);if(!d)m.exit(1);else{let l=new C(1,"commander.executeSubCommandAsync","(error)");l.nestedError=u,d(l)}}),this.runningCommand=c}_dispatchSubcommand(e,t,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,i,"preSubcommand"),s=this._chainOrCall(s,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(n));else return i._parseCommand(t,n)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,i,s)=>{let o=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,i,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,i)=>{let s=n.defaultValue;n.variadic?i<this.args.length?(s=this.args.slice(i),n.parseArg&&(s=s.reduce((o,a)=>e(n,a,o),n.defaultValue))):s===void 0&&(s=[]):i<this.args.length&&(s=this.args[i],n.parseArg&&(s=e(n,s,n.defaultValue))),t[i]=s}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,i=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{i.push({hookedCommand:s,callback:o})})}),t==="postAction"&&i.reverse(),i.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{i=this._chainOrCall(i,()=>s(this,t))}),i}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(s,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(s))i(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=e.find(s=>n.conflictsWith.includes(s.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],i=t;function s(u){return u.length>1&&u[0]==="-"}let o=u=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u)?!this._getCommandAndAncestors().some(l=>l.options.map(h=>h.short).some(h=>/^-\d$/.test(h))):!1,a=null,c=null,d=0;for(;d<e.length||c;){let u=c??e[d++];if(c=null,u==="--"){i===n&&i.push(u),i.push(...e.slice(d));break}if(a&&(!s(u)||o(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,s(u)){let l=this._findOption(u);if(l){if(l.required){let h=e[d++];h===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,h)}else if(l.optional){let h=null;d<e.length&&(!s(e[d])||o(e[d]))&&(h=e[d++]),this.emit(`option:${l.name()}`,h)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let l=this._findOption(`-${u[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,u.slice(2)):(this.emit(`option:${l.name()}`),c=`-${u.slice(2)}`);continue}}if(/^--[^=]+=/.test(u)){let l=u.indexOf("="),h=this._findOption(u.slice(0,l));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,u.slice(l+1));continue}}if(i===t&&s(u)&&!(this.commands.length===0&&o(u))&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),n.push(...e.slice(d));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u,...e.slice(d));break}else if(this._defaultCommandName){n.push(u,...e.slice(d));break}}if(this._passThroughOptions){i.push(u,...e.slice(d));break}i.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let i=this.options[n].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
20
+ - ${r}`;throw new Error(o)}_executeSubCommand(t,e){e=e.slice();let n=[".js",".ts",".tsx",".mjs",".cjs"];function r(c,d){let f=k.resolve(c,d);if(q.existsSync(f))return f;if(n.includes(k.extname(d)))return;let b=n.find(_=>q.existsSync(`${f}${_}`));if(b)return`${f}${b}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,s=this._executableDir||"";if(this._scriptPath){let c;try{c=q.realpathSync(this._scriptPath)}catch{c=this._scriptPath}s=k.resolve(k.dirname(c),s)}if(s){let c=r(s,o);if(!c&&!t._executableFile&&this._scriptPath){let d=k.basename(this._scriptPath,k.extname(this._scriptPath));d!==this._name&&(c=r(s,`${d}-${t._name}`))}o=c||o}let a=n.includes(k.extname(o)),u;h.platform!=="win32"?a?(e.unshift(o),e=Et(h.execArgv).concat(e),u=ot.spawn(h.argv[0],e,{stdio:"inherit"})):u=ot.spawn(o,e,{stdio:"inherit"}):(this._checkForMissingExecutable(o,s,t._name),e.unshift(o),e=Et(h.execArgv).concat(e),u=ot.spawn(h.execPath,e,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{h.on(d,()=>{u.killed===!1&&u.exitCode===null&&u.kill(d)})});let l=this._exitCallback;u.on("close",c=>{c=c??1,l?l(new v(c,"commander.executeSubCommandAsync","(close)")):h.exit(c)}),u.on("error",c=>{if(c.code==="ENOENT")this._checkForMissingExecutable(o,s,t._name);else if(c.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)h.exit(1);else{let d=new v(1,"commander.executeSubCommandAsync","(error)");d.nestedError=c,l(d)}}),this.runningCommand=u}_dispatchSubcommand(t,e,n){let r=this._findCommand(t);r||this.help({error:!0}),r._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,r,"preSubcommand"),o=this._chainOrCall(o,()=>{if(r._executableHandler)this._executeSubCommand(r,e.concat(n));else return r._parseCommand(e,n)}),o}_dispatchHelpCommand(t){t||this.help();let e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,e)=>{t.required&&this.args[e]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(n,r,o)=>{let s=r;if(r!==null&&n.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;s=this._callParseArg(n,r,o,a)}return s};this._checkNumberOfArguments();let e=[];this.registeredArguments.forEach((n,r)=>{let o=n.defaultValue;n.variadic?r<this.args.length?(o=this.args.slice(r),n.parseArg&&(o=o.reduce((s,a)=>t(n,a,s),n.defaultValue))):o===void 0&&(o=[]):r<this.args.length&&(o=this.args[r],n.parseArg&&(o=t(n,o,n.defaultValue))),e[r]=o}),this.processedArgs=e}_chainOrCall(t,e){return t?.then&&typeof t.then=="function"?t.then(()=>e()):e()}_chainOrCallHooks(t,e){let n=t,r=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[e]!==void 0).forEach(o=>{o._lifeCycleHooks[e].forEach(s=>{r.push({hookedCommand:o,callback:s})})}),e==="postAction"&&r.reverse(),r.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(t,e,n){let r=t;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{r=this._chainOrCall(r,()=>o(this,e))}),r}_parseCommand(t,e){let n=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(n.operands),e=n.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(o,t,e)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(o))r(),this._processArguments(),this.parent.emit(o,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(e=>e._name===t||e._aliases.includes(t))}_findOption(t){return this.options.find(e=>e.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(e=>{e.mandatory&&t.getOptionValue(e.attributeName())===void 0&&t.missingMandatoryOptionValue(e)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(n=>{let r=n.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});t.filter(n=>n.conflictsWith.length>0).forEach(n=>{let r=t.find(o=>n.conflictsWith.includes(o.attributeName()));r&&this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let e=[],n=[],r=e;function o(c){return c.length>1&&c[0]==="-"}let s=c=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(c)?!this._getCommandAndAncestors().some(d=>d.options.map(f=>f.short).some(f=>/^-\d$/.test(f))):!1,a=null,u=null,l=0;for(;l<t.length||u;){let c=u??t[l++];if(u=null,c==="--"){r===n&&r.push(c),r.push(...t.slice(l));break}if(a&&(!o(c)||s(c))){this.emit(`option:${a.name()}`,c);continue}if(a=null,o(c)){let d=this._findOption(c);if(d){if(d.required){let f=t[l++];f===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,f)}else if(d.optional){let f=null;l<t.length&&(!o(t[l])||s(t[l]))&&(f=t[l++]),this.emit(`option:${d.name()}`,f)}else this.emit(`option:${d.name()}`);a=d.variadic?d:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let d=this._findOption(`-${c[1]}`);if(d){d.required||d.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${d.name()}`,c.slice(2)):(this.emit(`option:${d.name()}`),u=`-${c.slice(2)}`);continue}}if(/^--[^=]+=/.test(c)){let d=c.indexOf("="),f=this._findOption(c.slice(0,d));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,c.slice(d+1));continue}}if(r===e&&o(c)&&!(this.commands.length===0&&s(c))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&n.length===0){if(this._findCommand(c)){e.push(c),n.push(...t.slice(l));break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){e.push(c,...t.slice(l));break}else if(this._defaultCommandName){n.push(c,...t.slice(l));break}}if(this._passThroughOptions){r.push(c,...t.slice(l));break}r.push(c)}return{operands:e,unknown:n}}opts(){if(this._storeOptionsAsProperties){let t={},e=this.options.length;for(let n=0;n<e;n++){let r=this.options[n].attributeName();t[r]=r===this._versionOptionName?this._version:this[r]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){this._outputConfiguration.outputError(`${t}
21
21
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
22
22
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
23
- `),this.outputHelp({error:!0}));let n=t||{},i=n.exitCode||1,s=n.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in m.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,m.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new V(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!t(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let a=o.attributeName(),c=this.getOptionValue(a),d=this.options.find(l=>l.negate&&a===l.attributeName()),u=this.options.find(l=>!l.negate&&a===l.attributeName());return d&&(d.presetArg===void 0&&c===!1||d.presetArg!==void 0&&c===d.presetArg)?d:u||o},i=o=>{let a=n(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);i=i.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=X(e,i)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",i=e.length,s=this.parent?` for '${this.name()}'`:"",o=e.join(", "),a=`error: too many arguments${s}. Expected ${t} argument${n} but got ${i}: ${o}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(s=>{i.push(s.name()),s.alias()&&i.push(s.alias())}),t=X(e,i)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let i=this.createOption(t,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
24
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>H(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=_.basename(e,_.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let i=t.formatHelp(this,t);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let t=!!e.error,n,i,s;return t?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:s}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let s=this.helpInformation({error:n.error});if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(m.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
25
- Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,s=>{let o;typeof t=="function"?o=t({error:s.error,command:s.command}):o=t,o&&s.write(`${o}
26
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function pe(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?i=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],n=s[3],i=s[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}function fe(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return!1;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return!0}var Xt=new E;var S={deviceStart(r,e){return r.cap("auth.device.start",{client_name:e},{auth:"none"})},devicePoll(r,e){return r.cap("auth.device.poll",{device_code:e},{auth:"none"})},logout(r,e){return r.cap("auth.logout",{refresh_token:e})},me(r){return r.cap("user.me",{})}};import ge from"node:fs";import je from"node:os";import G from"node:path";var Q="https://api.contak.ai",Z="https://contak.ai";function D(){let r=process.env.CONTAK_CONFIG_DIR;if(r&&r.trim())return G.resolve(r);let e=process.env.XDG_CONFIG_HOME,t=e&&e.trim()?e:G.join(je.homedir(),".config");return G.join(t,"contak")}function Ge(){return G.join(D(),"config.json")}function _e(){let r=D();return ge.mkdirSync(r,{recursive:!0,mode:448}),r}var z={currentProfile:"default",profiles:{default:{baseUrl:Q,siteUrl:Z}}};function Me(){try{let r=ge.readFileSync(Ge(),"utf8"),e=JSON.parse(r);return{currentProfile:e.currentProfile||z.currentProfile,profiles:{...z.profiles,...e.profiles||{}}}}catch{return structuredClone(z)}}function Ce(r={}){let e=Me(),t=r.profile||process.env.CONTAK_PROFILE||e.currentProfile,n=e.profiles[t]||{baseUrl:Q,siteUrl:Z};return{name:t,baseUrl:r.baseUrl||process.env.CONTAK_BASE_URL||n.baseUrl||Q,siteUrl:n.siteUrl||Z}}import{createHash as Ue}from"node:crypto";import U from"node:fs";import We from"node:path";var ee="contak-cli";function te(r,e=D(),t=process.env){return(t.CONTAK_CONFIG_DIR||"").trim()?`${r}@${Ue("sha256").update(e).digest("hex").slice(0,12)}`:r}var T;async function ne(){if(T!==void 0)return T;if((process.env.CONTAK_CREDENTIALS_BACKEND||"").toLowerCase()==="file")return T=null,null;try{let r=await import("@napi-rs/keyring");T=typeof r.Entry=="function"?r:null}catch{T=null}return T}function ye(){return We.join(D(),"credentials.json")}function M(){try{return JSON.parse(U.readFileSync(ye(),"utf8"))}catch{return{}}}function re(r){_e();let e=ye(),t=e+".tmp";U.writeFileSync(t,JSON.stringify(r,null,2)+`
27
- `,{mode:384}),U.renameSync(t,e),U.chmodSync(e,384)}var W=class{constructor(e){this.profile=e}profile;memory=null;envCredentials(){let e=process.env.CONTAK_ACCESS_TOKEN?.trim(),t=process.env.CONTAK_REFRESH_TOKEN?.trim();return!e&&!t?null:{accessToken:e||"",refreshToken:t||"",savedAt:new Date(0).toISOString()}}async load(){let e=this.envCredentials();if(e)return{credentials:this.memory||e,source:"env"};let t=await ne();if(t)try{let s=new t.Entry(ee,te(this.profile)).getPassword();if(s)return{credentials:JSON.parse(s),source:"keyring"}}catch{}let i=M()[this.profile];return i?{credentials:i,source:"file"}:{credentials:null,source:"none"}}async save(e){if(this.envCredentials())return this.memory=e,"env";let t=await ne();if(t)try{new t.Entry(ee,te(this.profile)).setPassword(JSON.stringify(e));let i=M();return i[this.profile]&&(delete i[this.profile],re(i)),"keyring"}catch{}let n=M();return n[this.profile]=e,re(n),"file"}async clear(){this.memory=null;let e=await ne();if(e)try{new e.Entry(ee,te(this.profile)).deletePassword()}catch{}let t=M();t[this.profile]&&(delete t[this.profile],re(t))}};var f={ok:0,generic:1,auth:2,validation:3,confirmation_required:4,rate_limited:5,network:7,forbidden:8,not_found:9,quota_exhausted:11,conflict:12};function Le(r){switch(r){case"auth":return f.auth;case"validation":return f.validation;case"confirmation_required":return f.confirmation_required;case"rate_limited":return f.rate_limited;case"network":return f.network;case"forbidden":return f.forbidden;case"not_found":return f.not_found;case"quota_exhausted":return f.quota_exhausted;case"conflict":return f.conflict;default:return f.generic}}var p=class extends Error{type;code;status;hint;details;cause;constructor(e){super(e.message),this.name="ContakError",this.type=e.type,this.code=e.code,this.status=e.status,this.hint=e.hint,this.details=e.details,this.cause=e.cause}get exitCode(){return Le(this.type)}toJSON(){let e={type:this.type,message:this.message};return this.code&&(e.code=this.code),this.status&&(e.status=this.status),this.hint&&(e.hint=this.hint),this.details&&(e.details=this.details),e}};function we(r){return r instanceof p}var Oe=new Set(["ECONNREFUSED","ENOTFOUND","ECONNRESET","ETIMEDOUT","EAI_AGAIN","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]);function L(r){if(we(r))return r;let e=r,t=e?.cause?.code;return e?.name==="AbortError"||e?.code&&Oe.has(e.code)||t&&Oe.has(t)||/fetch failed/i.test(e?.message??"")?new p({type:"network",message:e?.name==="AbortError"?"\u8BF7\u6C42\u8D85\u65F6":`\u65E0\u6CD5\u8FDE\u63A5\u5230 Contak\uFF1A${e?.message??"\u7F51\u7EDC\u9519\u8BEF"}`,hint:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5\uFF1B\u5982\u679C\u5728 Codex \u6C99\u7BB1\u91CC\uFF0C\u7F51\u7EDC\u9ED8\u8BA4\u662F\u5173\u95ED\u7684",cause:r}):new p({type:"internal",message:e?.message?String(e.message):String(r),cause:r})}function v(r,e){return new p({type:"validation",message:r,hint:e})}function ie(r=process.env){if(r.CODEX_SANDBOX_NETWORK_DISABLED)throw new p({type:"network",message:"Codex \u6C99\u7BB1\u5DF2\u7981\u7528\u7F51\u7EDC\u8BBF\u95EE\uFF0C\u65E0\u6CD5\u8BF7\u6C42 Contak",hint:"Codex \u9ED8\u8BA4\u65AD\u7F51\u3002\u4E34\u65F6\u653E\u5F00\uFF1Acodex -c 'sandbox_workspace_write.network_access=true'\uFF1B\u957F\u671F\u653E\u5F00\uFF1A\u5728 ~/.codex/config.toml \u52A0 [sandbox_workspace_write] network_access = true"})}function be(r){let e=r.split(".");if(e.length<2)return null;try{let t=Buffer.from(e[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8");return JSON.parse(t)}catch{return null}}function xe(r,e=30,t=Date.now()){let n=be(r);return!n||typeof n.exp!="number"?!0:n.exp*1e3<=t+e*1e3}function se(r){let e=be(r);return!e||typeof e.exp!="number"?null:new Date(e.exp*1e3)}var qe={validation:"validation",unauthorized:"auth",forbidden:"forbidden",not_found:"not_found",conflict:"conflict",rate_limit:"rate_limited",payment_required:"quota_exhausted",unavailable:"server",internal:"server"};function Ke(r){return r===401?"auth":r===402?"quota_exhausted":r===403?"forbidden":r===404?"not_found":r===409?"conflict":r===429?"rate_limited":r>=500?"server":r>=400?"validation":"api"}function Be(r,e){switch(r){case"auth":return"\u5148\u6267\u884C contak login \u5B8C\u6210\u767B\u5F55";case"quota_exhausted":return"\u989D\u5EA6\u5DF2\u7528\u5C3D\uFF0C\u91CD\u8BD5\u65E0\u7528\u3002\u7528 contak credits \u67E5\u770B\u4F59\u91CF\uFF0C\u6216\u5230 contak.ai \u5347\u7EA7\u5957\u9910";case"rate_limited":return"\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u7B49\u51E0\u79D2\u540E\u91CD\u8BD5";case"conflict":return e==="meeting.voiceprint_required"?"\u4E0A\u4F20\u5F55\u97F3\u524D\u9700\u8981\u5148\u6CE8\u518C\u672C\u4EBA\u58F0\u7EB9\uFF1Acontak voiceprint enroll <\u97F3\u9891\u6587\u4EF6>":void 0;default:return}}var I=class extends Error{constructor(t){super("dry-run");this.request=t;this.name="DryRunSignal"}request};function Je(r){let e={...r};return e.Authorization&&(e.Authorization="Bearer <redacted>"),e}var q=class{baseUrl;credentials;dryRun;userAgent;debug;refreshing=null;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.credentials=e.credentials,this.dryRun=e.dryRun??!1,this.userAgent=e.userAgent??"contak-cli",this.debug=e.debug}async cap(e,t={},n={}){let i=await this.send(`/api/cap/${e}`,t,n,!0);return await this.parse(i,e)}async open(e,t,n={}){let i=await this.send(e,t,{...n,timeoutMs:0},!0);return i.ok||await this.parse(i,e),i}async loadCredentials(){return this.credentials.load()}async setCredentials(e){return this.credentials.save(e)}async clearCredentials(){await this.credentials.clear()}async accessToken(e){let{credentials:t}=await this.credentials.load();if(!t?.accessToken){if(e)throw new p({type:"auth",message:"\u5C1A\u672A\u767B\u5F55",hint:"\u5148\u6267\u884C contak login \u5B8C\u6210\u767B\u5F55"});return null}if(!xe(t.accessToken,30))return t.accessToken;let n=await this.refresh();if(n?.accessToken)return n.accessToken;if(e)throw new p({type:"auth",message:"\u767B\u5F55\u6001\u5DF2\u5931\u6548",hint:"\u91CD\u65B0\u6267\u884C contak login"});return null}async refresh(){if(this.refreshing)return this.refreshing;this.refreshing=(async()=>{let{credentials:e}=await this.credentials.load();if(!e?.refreshToken)return null;ie();let t=await fetch(`${this.baseUrl}/api/cap/auth.refresh`,{method:"POST",headers:{"content-type":"application/json","user-agent":this.userAgent},body:JSON.stringify({refresh_token:e.refreshToken}),signal:AbortSignal.timeout(3e4)});if(!t.ok)return await t.body?.cancel().catch(()=>{}),null;let n=await t.json().catch(()=>null);if(!n?.access_token)return null;let i={accessToken:n.access_token,refreshToken:n.refresh_token||e.refreshToken,userId:n.user?.id??e.userId,email:n.user?.email??e.email,name:n.user?.name??e.name,savedAt:new Date().toISOString()};return await this.credentials.save(i),i})();try{return await this.refreshing}finally{this.refreshing=null}}async send(e,t,n,i){let o=(n.auth??"required")==="none"?null:await this.accessToken(!0),a=`${this.baseUrl}${e}`,c={"content-type":"application/json","user-agent":this.userAgent};if(o&&(c.Authorization=`Bearer ${o}`),this.dryRun)throw new I({method:"POST",url:a,headers:Je(c),body:t});ie(),this.debug?.(`POST ${a}`);let d=n.timeoutMs??6e4,u;try{u=await fetch(a,{method:"POST",headers:c,body:JSON.stringify(t??{}),signal:d>0?AbortSignal.timeout(d):void 0})}catch(l){throw L(l)}return u.status===401&&o&&i?(await u.body?.cancel().catch(()=>{}),await this.refresh().catch(()=>null)?this.send(e,t,n,!1):u):u}async parse(e,t){let n=(e.headers.get("content-type")||"").includes("application/json"),i=n?await e.json().catch(()=>null):null;if(e.ok)return e.status===204?void 0:i??void 0;let s=i??{},o=s.kind&&qe[s.kind]||Ke(e.status),a=s.error?.trim()||(n?"":(await e.text().catch(()=>"")).slice(0,300))||`${t} \u5931\u8D25\uFF08HTTP ${e.status}\uFF09`;throw new p({type:o,status:e.status,code:s.code,message:a,hint:Be(o,s.code)})}};import ae from"node:fs";import K from"node:path";import{fileURLToPath as Xe}from"node:url";var ke="@contak/cli",oe=null;function Ye(){if(oe)return oe;let r=K.dirname(Xe(import.meta.url));for(;;){let e=K.join(r,"package.json");if(ae.existsSync(e))try{if(JSON.parse(ae.readFileSync(e,"utf8")).name===ke)return oe=r,r}catch{}let t=K.dirname(r);if(t===r)throw new Error(`\u627E\u4E0D\u5230 ${ke} \u7684 package.json`);r=t}}function ue(...r){return K.join(Ye(),...r)}function Ae(){try{return JSON.parse(ae.readFileSync(ue("package.json"),"utf8")).version}catch{return"0.0.0"}}function ze(r){return r>=4352&&r<=4447||r>=11904&&r<=12350||r>=12353&&r<=13311||r>=13312&&r<=19903||r>=19968&&r<=40959||r>=40960&&r<=42191||r>=44032&&r<=55203||r>=63744&&r<=64255||r>=65040&&r<=65049||r>=65072&&r<=65135||r>=65280&&r<=65376||r>=65504&&r<=65510||r>=127744&&r<=128591||r>=129280&&r<=129535||r>=131072&&r<=262141}function Qe(r){return r===8203||r>=768&&r<=879||r>=65024&&r<=65039||r===8205}function $(r){let e=0;for(let t of r){let n=t.codePointAt(0);n!==void 0&&(Qe(n)||n<32||n>=127&&n<160||(e+=ze(n)?2:1))}return e}function le(){return!!process.stdout.isTTY}var J=["json","pretty","ndjson","table"];function B(r){return typeof r=="string"&&J.includes(r)}function Ee(r){if(r.json)return"json";if(r.format!==void 0){if(!B(r.format))throw new p({type:"validation",message:`--format \u53EA\u80FD\u662F ${J.join(" / ")}\uFF0C\u6536\u5230 "${r.format}"`});return r.format}let e=(process.env.CONTAK_FORMAT||"").toLowerCase();return B(e)?e:le()?"pretty":"json"}function ce(r,e=process.env,t=le()){if(r.includes("--json"))return"json";for(let i=0;i<r.length;i++){let s=r[i],o=s.startsWith("--format=")?s.slice(9):s==="--format"?r[i+1]:void 0;if(o!==void 0)return B(o)?o:"json"}let n=(e.CONTAK_FORMAT||"").toLowerCase();return B(n)?n:t?"pretty":"json"}function Se(r,e){let t=process.stdout;switch(e){case"json":t.write(JSON.stringify({ok:!0,data:r.data,...r.meta?{meta:r.meta}:{}},null,2)+`
28
- `);return;case"ndjson":{let n=Array.isArray(r.data)?r.data:[r.data];for(let i of n)t.write(JSON.stringify(i)+`
29
- `);return}case"table":if(r.table){t.write(Ze(r.table.columns,r.table.rows(r.data))+`
30
- `);return}default:r.pretty?t.write(r.pretty(r.data).replace(/\n?$/,`
31
- `)):t.write(JSON.stringify(r.data,null,2)+`
32
- `)}}function Te(r,e){if(e==="pretty"||e==="table"){process.stdout.write(`[dry-run] \u672A\u6267\u884C\uFF0C\u5C06\u53D1\u9001\uFF1A
33
- ${JSON.stringify(r.request,null,2)}
34
- `);return}process.stdout.write(JSON.stringify({ok:!0,data:{dry_run:!0,request:r.request}},null,2)+`
35
- `)}function F(r,e){let t=L(r);if(e==="pretty"||e==="table"){let n=`\u9519\u8BEF [${t.type}${t.code?`/${t.code}`:""}${t.status?` HTTP ${t.status}`:""}]\uFF1A${t.message}`;t.hint&&(n+=`
36
- \u63D0\u793A\uFF1A${t.hint}`),process.stderr.write(n+`
37
- `),process.env.CONTAK_DEBUG&&t.cause&&process.stderr.write(String(t.cause.stack||t.cause)+`
38
- `)}else process.stderr.write(JSON.stringify({ok:!1,error:t.toJSON()})+`
39
- `);return t.exitCode}function de(r,e={}){e.quiet||process.stderr.write(r.replace(/\n?$/,`
40
- `))}function Ze(r,e){let t=e.map(a=>r.map(c=>et(a[c.key]))),n=r.map((a,c)=>{let d=Math.max($(a.title),...t.map(u=>$(u[c])),0);return a.width?Math.min(a.width,d):d}),i=a=>a.map((c,d)=>{let u=tt(c,n[d]),l=n[d]-$(u);return r[d].align==="right"?" ".repeat(l)+u:u+" ".repeat(l)}).join(" "),s=i(r.map(a=>a.title)),o=n.map(a=>"-".repeat(a)).join(" ");return[s,o,...t.map(i)].join(`
41
- `)}function et(r){return r==null?"":typeof r=="object"?JSON.stringify(r):String(r).replace(/\s+/g," ")}function tt(r,e){if($(r)<=e)return r;let t="",n=0;for(let i of r){let s=$(i);if(n+s>e-1)break;t+=i,n+=s}return t+"\u2026"}function x(r,e="-"){return r==null||r===""?e:String(r)}var y=Ae();function nt(r){let e=r.optsWithGlobals();return{format:e.format,json:e.json,profile:e.profile,dryRun:e.dryRun,yes:e.yes,quiet:e.quiet,debug:e.debug,baseUrl:e.baseUrl}}function rt(r){let e=nt(r),t=Ce({profile:e.profile,baseUrl:e.baseUrl}),n=new q({baseUrl:t.baseUrl,credentials:new W(t.name),dryRun:e.dryRun,userAgent:`contak-cli/${y} (+https://contak.ai)`,debug:e.debug||process.env.CONTAK_DEBUG?i=>process.stderr.write(`[debug] ${i}
42
- `):void 0});return{opts:e,format:Ee(e),profile:t,client:n,siteUrl:t.siteUrl}}function g(r,e){return(async()=>{let t="json";try{let n=rt(r);t=n.format;let i=await e(n);i&&Se(i,t),process.exitCode=0}catch(n){if(n instanceof I){Te(n,t),process.exitCode=0;return}process.exitCode=F(n,t)}})()}var it=600*1e3;function ve(r){r.command("login").description("\u767B\u5F55 Contak\uFF08\u8BBE\u5907\u7801\uFF1A\u5728\u6D4F\u89C8\u5668\u91CC\u786E\u8BA4\uFF0C\u5BC6\u7801\u4E0D\u8FDB\u7EC8\u7AEF\uFF09").option("--device-code <code>","\u7528\u4E0A\u4E00\u6B65\u62FF\u5230\u7684 device_code \u5B8C\u6210\u767B\u5F55").option("--wait","\u5C31\u5730\u8F6E\u8BE2\u76F4\u5230\u7528\u6237\u5B8C\u6210\u6388\u6743\uFF08\u53EA\u9002\u5408\u4EBA\u5728\u7EC8\u7AEF\u524D\u65F6\u7528\uFF09").action(async function(){await g(this,e=>st(e,this.opts()))}),r.command("logout").description("\u9000\u51FA\u767B\u5F55\u5E76\u6E05\u9664\u672C\u673A\u51ED\u636E").action(async function(){await g(this,e=>ut(e))}),r.command("whoami").description("\u5F53\u524D\u767B\u5F55\u6001\uFF08\u672A\u767B\u5F55\u4E5F\u8FD4\u56DE 0\uFF0C\u770B data.logged_in\uFF09").action(async function(){await g(this,e=>lt(e))})}async function st(r,e){if(e.deviceCode)return ot(r,e.deviceCode);let t=await S.deviceStart(r.client,`contak-cli/${y}`);if(e.wait){de(`
23
+ `),this.outputHelp({error:!0}));let n=e||{},r=n.exitCode||1,o=n.code||"commander.error";this._exit(r,o,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in h.env){let e=t.attributeName();(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,h.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new W(this.options),e=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&e(n.attributeName())&&t.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(r=>!e(r)).forEach(r=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){let n=s=>{let a=s.attributeName(),u=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),c=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&u===!1||l.presetArg!==void 0&&u===l.presetArg)?l:c||s},r=s=>{let a=n(s),u=a.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${r(t)} cannot be used with ${r(e)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let r=[],o=this;do{let s=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);r=r.concat(s),o=o.parent}while(o&&!o._enablePositionalOptions);e=rt(t,r)}let n=`error: unknown option '${t}'${e}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,n=e===1?"":"s",r=t.length,o=this.parent?` for '${this.name()}'`:"",s=t.join(", "),a=`error: too many arguments${o}. Expected ${e} argument${n} but got ${r}: ${s}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(o=>{r.push(o.name()),o.alias()&&r.push(o.alias())}),e=rt(t,r)}let n=`error: unknown command '${t}'${e}`;this.error(n,{code:"commander.unknownCommand"})}version(t,e,n){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",n=n||"output the version number";let r=this.createOption(e,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${t}
24
+ `),this._exit(0,"commander.version",t)}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(t);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${r}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(n=>L(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=k.basename(t,k.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp(),n=this._getOutputContext(t);e.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=e.formatHelp(this,e);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(t){t=t||{};let e=!!t.error,n,r,o;return e?(n=a=>this._outputConfiguration.writeErr(a),r=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),r=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:e,write:a=>(r||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:r,helpWidth:o}}outputHelp(t){let e;typeof t=="function"&&(e=t,t=void 0);let n=this._getOutputContext(t),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let o=this.helpInformation({error:n.error});if(e&&(o=e(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",r))}helpOption(t,e){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",e??"display help for command"),(t||e)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let e=Number(h.exitCode??0);e===0&&t&&typeof t!="function"&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){let n=["beforeAll","before","after","afterAll"];if(!n.includes(t))throw new Error(`Unexpected value for position to addHelpText.
25
+ Expecting one of '${n.join("', '")}'`);let r=`${t}Help`;return this.on(r,o=>{let s;typeof e=="function"?s=e({error:o.error,command:o.command}):s=e,s&&o.write(`${s}
26
+ `)}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(r=>e.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Et(i){return i.map(t=>{if(!t.startsWith("--inspect"))return t;let e,n="127.0.0.1",r="9229",o;return(o=t.match(/^(--inspect(-brk)?)$/))!==null?e=o[1]:(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=o[1],/^\d+$/.test(o[3])?r=o[3]:n=o[3]):(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=o[1],n=o[3],r=o[4]),e&&r!=="0"?`${e}=${n}:${parseInt(r)+1}`:t})}function Tt(){if(h.env.NO_COLOR||h.env.FORCE_COLOR==="0"||h.env.FORCE_COLOR==="false")return!1;if(h.env.FORCE_COLOR||h.env.CLICOLOR_FORCE!==void 0)return!0}var gi=new N;var O={deviceStart(i,t){return i.cap("auth.device.start",{client_name:t},{auth:"none"})},devicePoll(i,t){return i.cap("auth.device.poll",{device_code:t},{auth:"none"})},logout(i,t){return i.cap("auth.logout",{refresh_token:t})},me(i){return i.cap("user.me",{})},sessionTransferCreate(i){return i.cap("auth.session_transfer.create",{protocol_version:1,target:"browser",purpose:"voiceprint.enrollment",context:{}})},sessionTransferStatus(i,t){return i.cap("auth.session_transfer.status",{transfer_id:t})}};import $t from"node:fs";import ye from"node:os";import G from"node:path";var at="https://api.contak.ai",ct="https://contak.ai";function F(){let i=process.env.CONTAK_CONFIG_DIR;if(i&&i.trim())return G.resolve(i);let t=process.env.XDG_CONFIG_HOME,e=t&&t.trim()?t:G.join(ye.homedir(),".config");return G.join(e,"contak")}function Ce(){return G.join(F(),"config.json")}function Rt(){let i=F();return $t.mkdirSync(i,{recursive:!0,mode:448}),i}var st={currentProfile:"default",profiles:{default:{baseUrl:at,siteUrl:ct}}};function we(){try{let i=$t.readFileSync(Ce(),"utf8"),t=JSON.parse(i);return{currentProfile:t.currentProfile||st.currentProfile,profiles:{...st.profiles,...t.profiles||{}}}}catch{return structuredClone(st)}}function It(i={}){let t=we(),e=i.profile||process.env.CONTAK_PROFILE||t.currentProfile,n=t.profiles[e]||{baseUrl:at,siteUrl:ct};return{name:e,baseUrl:i.baseUrl||process.env.CONTAK_BASE_URL||n.baseUrl||at,siteUrl:n.siteUrl||ct}}import{createHash as be}from"node:crypto";import J from"node:fs";import ke from"node:path";var ut="contak-cli";function dt(i,t=F(),e=process.env){return(e.CONTAK_CONFIG_DIR||"").trim()?`${i}@${be("sha256").update(t).digest("hex").slice(0,12)}`:i}var P;async function lt(){if(P!==void 0)return P;if((process.env.CONTAK_CREDENTIALS_BACKEND||"").toLowerCase()==="file")return P=null,null;try{let i=await import("@napi-rs/keyring");P=typeof i.Entry=="function"?i:null}catch{P=null}return P}function Nt(){return ke.join(F(),"credentials.json")}function B(){try{return JSON.parse(J.readFileSync(Nt(),"utf8"))}catch{return{}}}function pt(i){Rt();let t=Nt(),e=t+".tmp";J.writeFileSync(e,JSON.stringify(i,null,2)+`
27
+ `,{mode:384}),J.renameSync(e,t),J.chmodSync(t,384)}var Y=class{constructor(t){this.profile=t}profile;memory=null;envCredentials(){let t=process.env.CONTAK_ACCESS_TOKEN?.trim(),e=process.env.CONTAK_REFRESH_TOKEN?.trim();return!t&&!e?null:{accessToken:t||"",refreshToken:e||"",savedAt:new Date(0).toISOString()}}async load(){let t=this.envCredentials();if(t)return{credentials:this.memory||t,source:"env"};let e=await lt();if(e)try{let o=new e.Entry(ut,dt(this.profile)).getPassword();if(o)return{credentials:JSON.parse(o),source:"keyring"}}catch{}let r=B()[this.profile];return r?{credentials:r,source:"file"}:{credentials:null,source:"none"}}async save(t){if(this.envCredentials())return this.memory=t,"env";let e=await lt();if(e)try{new e.Entry(ut,dt(this.profile)).setPassword(JSON.stringify(t));let r=B();return r[this.profile]&&(delete r[this.profile],pt(r)),"keyring"}catch{}let n=B();return n[this.profile]=t,pt(n),"file"}async clear(){this.memory=null;let t=await lt();if(t)try{new t.Entry(ut,dt(this.profile)).deletePassword()}catch{}let e=B();e[this.profile]&&(delete e[this.profile],pt(e))}};var y={ok:0,generic:1,auth:2,validation:3,confirmation_required:4,rate_limited:5,action_required:6,network:7,forbidden:8,not_found:9,quota_exhausted:11,conflict:12};function Oe(i){switch(i){case"auth":return y.auth;case"validation":return y.validation;case"confirmation_required":return y.confirmation_required;case"rate_limited":return y.rate_limited;case"action_required":return y.action_required;case"network":return y.network;case"forbidden":return y.forbidden;case"not_found":return y.not_found;case"quota_exhausted":return y.quota_exhausted;case"conflict":return y.conflict;default:return y.generic}}var m=class extends Error{type;code;status;hint;details;cause;constructor(t){super(t.message),this.name="ContakError",this.type=t.type,this.code=t.code,this.status=t.status,this.hint=t.hint,this.details=t.details,this.cause=t.cause}get exitCode(){return Oe(this.type)}toJSON(){let t={type:this.type,message:this.message};return this.code&&(t.code=this.code),this.status&&(t.status=this.status),this.hint&&(t.hint=this.hint),this.details&&(t.details=this.details),t}};function Dt(i){return i instanceof m}var Pt=new Set(["ECONNREFUSED","ENOTFOUND","ECONNRESET","ETIMEDOUT","EAI_AGAIN","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT"]);function M(i){if(Dt(i))return i;let t=i,e=t?.cause?.code;return t?.name==="AbortError"||t?.code&&Pt.has(t.code)||e&&Pt.has(e)||/fetch failed/i.test(t?.message??"")?new m({type:"network",message:t?.name==="AbortError"?"\u8BF7\u6C42\u8D85\u65F6":`\u65E0\u6CD5\u8FDE\u63A5\u5230 Contak\uFF1A${t?.message??"\u7F51\u7EDC\u9519\u8BEF"}`,hint:"\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5\uFF1B\u5982\u679C\u5728 Codex \u6C99\u7BB1\u91CC\uFF0C\u7F51\u7EDC\u9ED8\u8BA4\u662F\u5173\u95ED\u7684",cause:i}):new m({type:"internal",message:t?.message?String(t.message):String(i),cause:i})}function p(i,t){return new m({type:"validation",message:i,hint:t})}function X(i=process.env){if(i.CODEX_SANDBOX_NETWORK_DISABLED)throw new m({type:"network",message:"Codex \u6C99\u7BB1\u5DF2\u7981\u7528\u7F51\u7EDC\u8BBF\u95EE\uFF0C\u65E0\u6CD5\u8BF7\u6C42 Contak",hint:"Codex \u9ED8\u8BA4\u65AD\u7F51\u3002\u4E34\u65F6\u653E\u5F00\uFF1Acodex -c 'sandbox_workspace_write.network_access=true'\uFF1B\u957F\u671F\u653E\u5F00\uFF1A\u5728 ~/.codex/config.toml \u52A0 [sandbox_workspace_write] network_access = true"})}function jt(i){let t=i.split(".");if(t.length<2)return null;try{let e=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8");return JSON.parse(e)}catch{return null}}function Ht(i,t=30,e=Date.now()){let n=jt(i);return!n||typeof n.exp!="number"?!0:n.exp*1e3<=e+t*1e3}function mt(i){let t=jt(i);return!t||typeof t.exp!="number"?null:new Date(t.exp*1e3)}var xe={validation:"validation",unauthorized:"auth",forbidden:"forbidden",not_found:"not_found",conflict:"conflict",rate_limit:"rate_limited",payment_required:"quota_exhausted",unavailable:"server",internal:"server"};function ve(i){return i===401?"auth":i===402?"quota_exhausted":i===403?"forbidden":i===404?"not_found":i===409?"conflict":i===429?"rate_limited":i>=500?"server":i>=400?"validation":"api"}function Se(i,t){switch(i){case"auth":return"\u5148\u6267\u884C contak login \u5B8C\u6210\u767B\u5F55";case"quota_exhausted":return"\u989D\u5EA6\u5DF2\u7528\u5C3D\uFF0C\u91CD\u8BD5\u65E0\u7528\u3002\u7528 contak credits \u67E5\u770B\u4F59\u91CF\uFF0C\u6216\u5230 contak.ai \u5347\u7EA7\u5957\u9910";case"rate_limited":return"\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u7B49\u51E0\u79D2\u540E\u91CD\u8BD5";case"conflict":return t==="meeting.voiceprint_required"?"\u4E0A\u4F20\u5F55\u97F3\u524D\u9700\u8981\u5148\u5B8C\u6210\u58F0\u7EB9\u5F55\u5165\uFF1Acontak open voiceprint":void 0;default:return}}var V=class extends Error{constructor(e){super("dry-run");this.request=e;this.name="DryRunSignal"}request};function Ae(i){let t={...i};return t.Authorization&&(t.Authorization="Bearer <redacted>"),t}var z=class i{static versionNoticeShown=!1;baseUrl;credentials;dryRun;userAgent;debug;refreshing=null;constructor(t){this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.credentials=t.credentials,this.dryRun=t.dryRun??!1,this.userAgent=t.userAgent??"contak-cli",this.debug=t.debug}async cap(t,e={},n={}){let r=await this.send(`/api/cap/${t}`,e,n,!0);return await this.parse(r,t)}async open(t,e,n={}){let r=await this.send(t,e,{...n,timeoutMs:0},!0);return r.ok||await this.parse(r,t),r}async getPublicJSON(t){X();let e=`${this.baseUrl}${t}`;this.debug?.(`GET ${e}`);let n;try{n=await fetch(e,{headers:{"user-agent":this.userAgent},signal:AbortSignal.timeout(3e4)})}catch(r){throw M(r)}return await this.parse(n,t)}async loadCredentials(){return this.credentials.load()}async setCredentials(t){return this.credentials.save(t)}async clearCredentials(){await this.credentials.clear()}async accessToken(t){let{credentials:e}=await this.credentials.load();if(!e?.accessToken){if(t)throw new m({type:"auth",message:"\u5C1A\u672A\u767B\u5F55",hint:"\u5148\u6267\u884C contak login \u5B8C\u6210\u767B\u5F55"});return null}if(!Ht(e.accessToken,30))return e.accessToken;let n=await this.refresh();if(n?.accessToken)return n.accessToken;if(t)throw new m({type:"auth",message:"\u767B\u5F55\u6001\u5DF2\u5931\u6548",hint:"\u91CD\u65B0\u6267\u884C contak login"});return null}async refresh(){if(this.refreshing)return this.refreshing;this.refreshing=(async()=>{let{credentials:t}=await this.credentials.load();if(!t?.refreshToken)return null;X();let e=await fetch(`${this.baseUrl}/api/cap/auth.refresh`,{method:"POST",headers:{"content-type":"application/json","user-agent":this.userAgent},body:JSON.stringify({refresh_token:t.refreshToken}),signal:AbortSignal.timeout(3e4)});if(!e.ok)return await e.body?.cancel().catch(()=>{}),null;let n=await e.json().catch(()=>null);if(!n?.access_token)return null;let r={accessToken:n.access_token,refreshToken:n.refresh_token||t.refreshToken,userId:n.user?.id??t.userId,email:n.user?.email??t.email,name:n.user?.name??t.name,savedAt:new Date().toISOString()};return await this.credentials.save(r),r})();try{return await this.refreshing}finally{this.refreshing=null}}async send(t,e,n,r){let s=(n.auth??"required")==="none"?null:await this.accessToken(!0),a=`${this.baseUrl}${t}`,u={"content-type":"application/json","user-agent":this.userAgent};if(s&&(u.Authorization=`Bearer ${s}`),this.dryRun&&!n.dryRunRead)throw new V({method:"POST",url:a,headers:Ae(u),body:e});X(),this.debug?.(`POST ${a}`);let l=n.timeoutMs??6e4,c;try{c=await fetch(a,{method:"POST",headers:u,body:JSON.stringify(e??{}),signal:l>0?AbortSignal.timeout(l):void 0})}catch(d){throw M(d)}return this.emitVersionNotice(c),c.status===401&&s&&r?(await c.body?.cancel().catch(()=>{}),await this.refresh().catch(()=>null)?this.send(t,e,n,!1):c):c}emitVersionNotice(t){if(i.versionNoticeShown)return;let e=t.headers.get("x-contak-version-status");if(!e||e==="current")return;i.versionNoticeShown=!0;let n=t.headers.get("x-contak-latest-version"),r=t.headers.get("x-contak-minimum-version"),o=t.headers.get("x-contak-version-notification")||"Contak CLI \u7248\u672C\u72B6\u6001\u5DF2\u66F4\u65B0";process.stderr.write(`[version] ${o}\uFF08status=${e}, latest=${n}, minimum=${r}\uFF09
28
+ `)}async parse(t,e){let n=(t.headers.get("content-type")||"").includes("application/json"),r=n?await t.json().catch(()=>null):null;if(t.ok)return t.status===204?void 0:r??void 0;let o=r??{},s=o.kind&&xe[o.kind]||ve(t.status),a=o.error?.trim()||(n?"":(await t.text().catch(()=>"")).slice(0,300))||`${e} \u5931\u8D25\uFF08HTTP ${t.status}\uFF09`;throw new m({type:s,status:t.status,code:o.code,message:a,hint:Se(s,o.code)})}};import ht from"node:fs";import Z from"node:path";import{fileURLToPath as Ee}from"node:url";var Ft="@contak/cli",ft=null;function Te(){if(ft)return ft;let i=Z.dirname(Ee(import.meta.url));for(;;){let t=Z.join(i,"package.json");if(ht.existsSync(t))try{if(JSON.parse(ht.readFileSync(t,"utf8")).name===Ft)return ft=i,i}catch{}let e=Z.dirname(i);if(e===i)throw new Error(`\u627E\u4E0D\u5230 ${Ft} \u7684 package.json`);i=e}}function gt(...i){return Z.join(Te(),...i)}function Mt(){try{return JSON.parse(ht.readFileSync(gt("package.json"),"utf8")).version}catch{return"0.0.0"}}function $e(i){return i>=4352&&i<=4447||i>=11904&&i<=12350||i>=12353&&i<=13311||i>=13312&&i<=19903||i>=19968&&i<=40959||i>=40960&&i<=42191||i>=44032&&i<=55203||i>=63744&&i<=64255||i>=65040&&i<=65049||i>=65072&&i<=65135||i>=65280&&i<=65376||i>=65504&&i<=65510||i>=127744&&i<=128591||i>=129280&&i<=129535||i>=131072&&i<=262141}function Re(i){return i===8203||i>=768&&i<=879||i>=65024&&i<=65039||i===8205}function D(i){let t=0;for(let e of i){let n=e.codePointAt(0);n!==void 0&&(Re(n)||n<32||n>=127&&n<160||(t+=$e(n)?2:1))}return t}import Ie from"node:readline";function Q(){return!!process.stdout.isTTY}function Ne(){return!!process.stdin.isTTY}function _t(){return Q()&&Ne()&&!process.env.CI&&!process.env.CONTAK_NO_INPUT}async function Pe(i,t={}){let e=Ie.createInterface({input:process.stdin,output:process.stderr,terminal:!0});try{if(t.hidden){let n=process.stdin;n.setRawMode?.(!0);try{return await new Promise(r=>e.question(i,r))}finally{n.setRawMode?.(!1),process.stderr.write(`
29
+ `)}}return await new Promise(n=>e.question(i,n))}finally{e.close()}}async function Vt(i){let t=(await Pe(`${i} [y/N] `)).trim().toLowerCase();return t==="y"||t==="yes"}var et=["json","pretty","ndjson","table"];function tt(i){return typeof i=="string"&&et.includes(i)}function Ut(i){if(i.json)return"json";if(i.format!==void 0){if(!tt(i.format))throw new m({type:"validation",message:`--format \u53EA\u80FD\u662F ${et.join(" / ")}\uFF0C\u6536\u5230 "${i.format}"`});return i.format}let t=(process.env.CONTAK_FORMAT||"").toLowerCase();return tt(t)?t:Q()?"pretty":"json"}function yt(i,t=process.env,e=Q()){if(i.includes("--json"))return"json";for(let r=0;r<i.length;r++){let o=i[r],s=o.startsWith("--format=")?o.slice(9):o==="--format"?i[r+1]:void 0;if(s!==void 0)return tt(s)?s:"json"}let n=(t.CONTAK_FORMAT||"").toLowerCase();return tt(n)?n:e?"pretty":"json"}function Kt(i,t){let e=process.stdout;switch(t){case"json":e.write(JSON.stringify({ok:!0,data:i.data,...i.meta?{meta:i.meta}:{}},null,2)+`
30
+ `);return;case"ndjson":{let n=Array.isArray(i.data)?i.data:[i.data];for(let r of n)e.write(JSON.stringify(r)+`
31
+ `);return}case"table":if(i.table){e.write(De(i.table.columns,i.table.rows(i.data))+`
32
+ `);return}default:i.pretty?e.write(i.pretty(i.data).replace(/\n?$/,`
33
+ `)):e.write(JSON.stringify(i.data,null,2)+`
34
+ `)}}function Lt(i,t){if(t==="pretty"||t==="table"){process.stdout.write(`[dry-run] \u672A\u6267\u884C\uFF0C\u5C06\u53D1\u9001\uFF1A
35
+ ${JSON.stringify(i.request,null,2)}
36
+ `);return}process.stdout.write(JSON.stringify({ok:!0,data:{dry_run:!0,request:i.request}},null,2)+`
37
+ `)}function U(i,t){let e=M(i);if(t==="pretty"||t==="table"){let n=`\u9519\u8BEF [${e.type}${e.code?`/${e.code}`:""}${e.status?` HTTP ${e.status}`:""}]\uFF1A${e.message}`;e.hint&&(n+=`
38
+ \u63D0\u793A\uFF1A${e.hint}`),process.stderr.write(n+`
39
+ `),process.env.CONTAK_DEBUG&&e.cause&&process.stderr.write(String(e.cause.stack||e.cause)+`
40
+ `)}else process.stderr.write(JSON.stringify({ok:!1,error:e.toJSON()})+`
41
+ `);return e.exitCode}function x(i,t={}){t.quiet||process.stderr.write(i.replace(/\n?$/,`
42
+ `))}function Ct(i){return new m({type:"confirmation_required",message:`${i} \u9700\u8981\u786E\u8BA4`,hint:"\u5728\u539F\u547D\u4EE4\u672B\u5C3E\u52A0 --yes \u518D\u6267\u884C\uFF08agent \u5FC5\u987B\u5148\u5411\u7528\u6237\u8BF4\u660E\u5C06\u8981\u6267\u884C\u7684\u64CD\u4F5C\uFF0C\u83B7\u5F97\u540C\u610F\u540E\u518D\u52A0\uFF09",details:{action:i}})}function De(i,t){let e=t.map(a=>i.map(u=>je(a[u.key]))),n=i.map((a,u)=>{let l=Math.max(D(a.title),...e.map(c=>D(c[u])),0);return a.width?Math.min(a.width,l):l}),r=a=>a.map((u,l)=>{let c=He(u,n[l]),d=n[l]-D(c);return i[l].align==="right"?" ".repeat(d)+c:c+" ".repeat(d)}).join(" "),o=r(i.map(a=>a.title)),s=n.map(a=>"-".repeat(a)).join(" ");return[o,s,...e.map(r)].join(`
43
+ `)}function je(i){return i==null?"":typeof i=="object"?JSON.stringify(i):String(i).replace(/\s+/g," ")}function He(i,t){if(D(i)<=t)return i;let e="",n=0;for(let r of i){let o=D(r);if(n+o>t-1)break;e+=r,n+=o}return e+"\u2026"}function T(i,t="-"){return i==null||i===""?t:String(i)}var S=Mt();function Fe(i){let t=i.optsWithGlobals();return{format:t.format,json:t.json,profile:t.profile,dryRun:t.dryRun,yes:t.yes,quiet:t.quiet,debug:t.debug,baseUrl:t.baseUrl}}function Me(i){let t=Fe(i),e=It({profile:t.profile,baseUrl:t.baseUrl}),n=new z({baseUrl:e.baseUrl,credentials:new Y(e.name),dryRun:t.dryRun,userAgent:`contak-cli/${S} (+https://contak.ai)`,debug:t.debug||process.env.CONTAK_DEBUG?r=>process.stderr.write(`[debug] ${r}
44
+ `):void 0});return{opts:t,format:Ut(t),profile:e,client:n,siteUrl:e.siteUrl}}function g(i,t){return(async()=>{let e="json";try{let n=Me(i);e=n.format;let r=await t(n);r&&Kt(r,e),process.exitCode=0}catch(n){if(n instanceof V){Lt(n,e),process.exitCode=0;return}process.exitCode=U(n,e)}})()}function C(i,t,e){let n=i.commands.find(o=>o.name()===t);if(n)return n;let r=i.command(t);return e&&r.description(e),r}var Ve=600*1e3;function Wt(i){i.command("login").description("\u767B\u5F55 Contak\uFF08\u8BBE\u5907\u7801\uFF1A\u5728\u6D4F\u89C8\u5668\u91CC\u786E\u8BA4\uFF0C\u5BC6\u7801\u4E0D\u8FDB\u7EC8\u7AEF\uFF09").option("--device-code <code>","\u7528\u4E0A\u4E00\u6B65\u62FF\u5230\u7684 device_code \u5B8C\u6210\u767B\u5F55").option("--wait","\u5C31\u5730\u8F6E\u8BE2\u76F4\u5230\u7528\u6237\u5B8C\u6210\u6388\u6743\uFF08\u53EA\u9002\u5408\u4EBA\u5728\u7EC8\u7AEF\u524D\u65F6\u7528\uFF09").action(async function(){await g(this,t=>Ue(t,this.opts()))}),i.command("logout").description("\u9000\u51FA\u767B\u5F55\u5E76\u6E05\u9664\u672C\u673A\u51ED\u636E").action(async function(){await g(this,t=>We(t))}),i.command("whoami").description("\u5F53\u524D\u767B\u5F55\u6001\uFF08\u672A\u767B\u5F55\u4E5F\u8FD4\u56DE 0\uFF0C\u770B data.logged_in\uFF09").action(async function(){await g(this,t=>qe(t))})}async function Ue(i,t){if(t.deviceCode)return Ke(i,t.deviceCode);let e=await O.deviceStart(i.client,`contak-cli/${S}`);if(t.wait){x(`
43
45
  \u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u5E76\u786E\u8BA4\uFF1A
44
- ${t.verification_url}
45
- \u77ED\u7801\uFF1A${t.user_code}
46
- `,r.opts);let n=await at(r,t.device_code,t.interval,t.expires_in);return Ne(r,n,"\u5DF2\u767B\u5F55")}return{data:{logged_in:!1,verification_url:t.verification_url,user_code:t.user_code,device_code:t.device_code,expires_in:t.expires_in,next_step:`contak login --device-code ${t.device_code}`},pretty:()=>["\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u5E76\u786E\u8BA4\uFF1A",` ${t.verification_url}`,`\u77ED\u7801\uFF1A${t.user_code}`,"","\u786E\u8BA4\u4E4B\u540E\u6267\u884C\uFF1A",` contak login --device-code ${t.device_code}`].join(`
47
- `)}}async function ot(r,e){try{let t=await S.devicePoll(r.client,e);return Ne(r,t,"\u5DF2\u767B\u5F55")}catch(t){throw $e(t)}}async function at(r,e,t,n){let i=Math.max(1,t||5)*1e3,s=Date.now()+Math.min(Math.max(1,n||600)*1e3,it);for(;;){if(Date.now()>=s)throw new p({type:"auth",message:"\u7B49\u5F85\u6388\u6743\u8D85\u65F6",hint:"\u91CD\u65B0\u6267\u884C contak login"});await ct(i);try{return await S.devicePoll(r.client,e)}catch(o){let a=o instanceof p?o.code:void 0;if(a==="auth.device.poll.authorization_pending")continue;if(a==="auth.device.poll.slow_down"){i=Math.min(i*2,3e4);continue}throw $e(o)}}}function $e(r){if(!(r instanceof p))return r;switch(r.code){case"auth.device.poll.access_denied":return new p({type:"auth",code:r.code,message:"\u6388\u6743\u88AB\u62D2\u7EDD",hint:"\u5982\u679C\u8FD9\u4E0D\u662F\u4F60\u672C\u4EBA\u64CD\u4F5C\u7684\uFF0C\u5FFD\u7565\u5373\u53EF\uFF1B\u8981\u91CD\u6765\u5C31\u518D\u6267\u884C\u4E00\u6B21 contak login"});case"auth.device.poll.expired_token":return new p({type:"auth",code:r.code,message:"\u8FD9\u4E2A\u8BBE\u5907\u7801\u5DF2\u5931\u6548\uFF08\u8D85\u65F6\u6216\u5DF2\u7ECF\u7528\u8FC7\uFF09",hint:"\u91CD\u65B0\u6267\u884C contak login \u62FF\u4E00\u4E2A\u65B0\u7684"});case"auth.device.poll.authorization_pending":return new p({type:"auth",code:r.code,message:"\u7528\u6237\u8FD8\u6CA1\u6709\u5728\u6D4F\u89C8\u5668\u91CC\u786E\u8BA4",hint:"\u7B49\u7528\u6237\u786E\u8BA4\u540E\u518D\u6267\u884C contak login --device-code <code>"});default:return r}}async function Ne(r,e,t){if(!e.access_token||!e.refresh_token)throw new p({type:"api",message:"\u767B\u5F55\u54CD\u5E94\u7F3A\u5C11 access_token / refresh_token",details:{keys:Object.keys(e)}});let n={accessToken:e.access_token,refreshToken:e.refresh_token,userId:e.user?.id,email:e.user?.email,name:e.user?.name,savedAt:new Date().toISOString()},i=await r.client.setCredentials(n);return{data:{logged_in:!0,user_id:n.userId,email:n.email,name:n.name,stored_in:i,profile:r.profile.name,access_expires_at:se(n.accessToken)?.toISOString()},pretty:s=>{let o=s;return`${t}\uFF1A${x(o.name??o.email)}\uFF08\u51ED\u636E\u5B58\u4E8E ${x(o.stored_in)}\uFF09`}}}async function ut(r){let{credentials:e}=await r.client.loadCredentials();return e?.refreshToken&&await S.logout(r.client,e.refreshToken).catch(()=>{}),await r.client.clearCredentials(),{data:{logged_out:!0},pretty:()=>"\u5DF2\u9000\u51FA\u767B\u5F55"}}async function lt(r){let{credentials:e,source:t}=await r.client.loadCredentials();if(!e?.accessToken)return{data:{logged_in:!1,profile:r.profile.name,base_url:r.profile.baseUrl},pretty:()=>"\u672A\u767B\u5F55\u3002\u6267\u884C contak login \u5B8C\u6210\u767B\u5F55\u3002"};let n=null,i;try{n=await S.me(r.client)}catch(s){i=s instanceof Error?s.message:String(s)}return{data:{logged_in:!!n,profile:r.profile.name,base_url:r.profile.baseUrl,stored_in:t,user:n??void 0,access_expires_at:se(e.accessToken)?.toISOString(),error:i},pretty:s=>{let o=s;if(!o.logged_in)return`\u767B\u5F55\u6001\u5DF2\u5931\u6548\uFF1A${x(o.error)}
48
- \u6267\u884C contak login \u91CD\u65B0\u767B\u5F55\u3002`;let a=o.user??{};return`${x(a.name??a.email)}\uFF08profile ${x(o.profile)}\uFF0C\u51ED\u636E\u5B58\u4E8E ${x(o.stored_in)}\uFF09`}}}function ct(r){return new Promise(e=>setTimeout(e,r))}import O from"node:fs";import N from"node:path";var dt=[],ht=["login","logout","skills install"];function Pe(r){r.command("schema").description("\u8F93\u51FA\u5B8C\u6574\u547D\u4EE4\u5951\u7EA6\uFF08\u53C2\u6570\u3001\u7C7B\u578B\u3001\u9000\u51FA\u7801\u3001\u8F93\u51FA\u683C\u5F0F\uFF09\uFF0C\u7ED9 agent \u8BFB").action(async function(){await g(this,async()=>pt(r))});let e=r.command("skills").description("\u5185\u7F6E Agent Skill\uFF1A\u968F CLI \u7248\u672C\u8D70\uFF0C\u6C38\u4E0D\u4E0E\u547D\u4EE4\u6F02\u79FB");e.command("list").description("\u5217\u51FA\u5185\u7F6E skill").action(async function(){await g(this,async()=>ft())}),e.command("read [name]").description("\u8BFB skill \u6B63\u6587\uFF08\u9ED8\u8BA4\u8F93\u51FA\u88F8 markdown\uFF0C--json \u624D\u5305\u4FE1\u5C01\uFF09").action(async function(t){await g(this,async n=>gt(n,t))}),e.command("install").description("\u628A skill \u88C5\u5230 ~/.claude/skills \u4E0E ~/.agents/skills").option("--project","\u88C5\u5230\u5F53\u524D\u76EE\u5F55\u800C\u4E0D\u662F\u7528\u6237\u4E3B\u76EE\u5F55").action(async function(){await g(this,async()=>_t(!!this.opts().project))}),r.command("config").description("\u663E\u793A\u5F53\u524D\u914D\u7F6E\uFF08profile\u3001API \u57FA\u5740\u3001\u914D\u7F6E\u76EE\u5F55\uFF09").action(async function(){await g(this,async t=>({data:{version:y,profile:t.profile.name,base_url:t.profile.baseUrl,site_url:t.siteUrl}}))})}function mt(r){return!!r._hidden}function Re(r,e=""){let t=r.name(),n=e?`${e} ${t}`:t==="contak"?"":t,i=dt.includes(n),s=ht.includes(n);return{name:t,path:n||void 0,description:r.description()||void 0,usage:r.usage(),mutating:i||s||void 0,requires_yes:i||void 0,arguments:r.registeredArguments.map(o=>({name:o.name(),required:o.required,variadic:o.variadic,description:o.description||void 0})),options:r.options.filter(o=>!o.hidden).map(o=>({flags:o.flags,description:o.description||void 0,takes_value:o.required||o.optional||void 0,mandatory:o.mandatory||void 0,default:o.defaultValue})),subcommands:r.commands.filter(o=>!mt(o)).map(o=>Re(o,n))}}function pt(r){return{data:{schema_version:1,cli_version:y,output_contract:{success:'stdout \u8F93\u51FA {"ok":true,"data":...}\uFF0C\u9000\u51FA\u7801 0',failure:'stderr \u8F93\u51FA {"ok":false,"error":{type,code,message,hint}}\uFF0C\u9000\u51FA\u7801\u89C1 exit_codes',judge_success:"\u53EA\u770B ok \u6216\u9000\u51FA\u7801\uFF0C\u4E0D\u8981\u770B data \u91CC\u7684\u5B57\u6BB5",formats:J,default_format:"\u975E TTY \u4E0B\u662F json\uFF0CTTY \u4E0B\u662F pretty",stdout_discipline:"stdout \u53EA\u653E\u6570\u636E\uFF1B\u8FDB\u5EA6\u4E0E\u63D0\u793A\u4E00\u5F8B\u8D70 stderr"},exit_codes:f,environment:{CONTAK_BASE_URL:"\u8986\u76D6 API \u57FA\u5740",CONTAK_PROFILE:"\u9009\u62E9 profile",CONTAK_FORMAT:"\u9ED8\u8BA4\u8F93\u51FA\u683C\u5F0F",CONTAK_CONFIG_DIR:"\u914D\u7F6E\u76EE\u5F55\uFF08\u9ED8\u8BA4 ~/.config/contak\uFF09",CONTAK_ACCESS_TOKEN:"\u76F4\u63A5\u6CE8\u5165 access token\uFF0C\u53EA\u8BFB\u4E0D\u843D\u76D8",CONTAK_REFRESH_TOKEN:"\u76F4\u63A5\u6CE8\u5165 refresh token\uFF0C\u53EA\u8BFB\u4E0D\u843D\u76D8",CONTAK_CREDENTIALS_BACKEND:"\u8BBE\u4E3A file \u5219\u4E0D\u4F7F\u7528\u7CFB\u7EDF\u94A5\u5319\u4E32",CONTAK_NO_INPUT:"\u8BBE\u7F6E\u540E\u4E00\u5F8B\u4E0D\u5411\u7528\u6237\u63D0\u95EE",CONTAK_DEBUG:"\u628A\u8BF7\u6C42\u4E0E\u9519\u8BEF\u6808\u6253\u5230 stderr"},commands:Re(r)}}}function he(){return ue("skills")}function ft(){let r=he();return{data:(O.existsSync(r)?O.readdirSync(r).filter(t=>!t.startsWith(".")):[]).map(t=>({name:t,path:N.join(r,t,"SKILL.md")}))}}function gt(r,e){let t=he(),n=e||"contak",i=N.join(t,n,"SKILL.md");if(!O.existsSync(i))throw v(`\u6CA1\u6709\u540D\u4E3A "${n}" \u7684 skill`,"\u7528 contak skills list \u770B\u53EF\u7528\u7684 skill");let s=O.readFileSync(i,"utf8");if(r.format==="pretty"||r.format==="table"){process.stdout.write(s.replace(/\n?$/,`
49
- `));return}return{data:{name:n,path:i,content:s}}}function _t(r){let e=he();if(!O.existsSync(e))throw v("\u8FD9\u4E2A\u5B89\u88C5\u5305\u91CC\u6CA1\u6709\u9644\u5E26 skills \u76EE\u5F55");let t=r?process.cwd():process.env.HOME||process.env.USERPROFILE||"";if(!t)throw v("\u627E\u4E0D\u5230\u7528\u6237\u4E3B\u76EE\u5F55\uFF0C\u7528 --project \u88C5\u5230\u5F53\u524D\u76EE\u5F55");let i=[N.join(t,".claude","skills"),N.join(t,".agents","skills")].map(s=>{let o=N.join(s,"contak"),a=O.existsSync(o);return O.mkdirSync(o,{recursive:!0}),O.cpSync(N.join(e,"contak"),o,{recursive:!0}),{path:o,action:a?"overwritten":"created"}});return{data:{installed:i},pretty:()=>i.map(s=>`${s.action==="created"?"\u5DF2\u5B89\u88C5":"\u5DF2\u66F4\u65B0"}\uFF1A${s.path}`).join(`
50
- `)}}var yt=`
46
+ ${e.verification_url}
47
+ \u77ED\u7801\uFF1A${e.user_code}
48
+ `,i.opts);let n=await Le(i,e.device_code,e.interval,e.expires_in);return Gt(i,n,"\u5DF2\u767B\u5F55")}return{data:{logged_in:!1,verification_url:e.verification_url,user_code:e.user_code,device_code:e.device_code,expires_in:e.expires_in,next_step:`contak login --device-code ${e.device_code}`},pretty:()=>["\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u5E76\u786E\u8BA4\uFF1A",` ${e.verification_url}`,`\u77ED\u7801\uFF1A${e.user_code}`,"","\u786E\u8BA4\u4E4B\u540E\u6267\u884C\uFF1A",` contak login --device-code ${e.device_code}`].join(`
49
+ `)}}async function Ke(i,t){try{let e=await O.devicePoll(i.client,t);return Gt(i,e,"\u5DF2\u767B\u5F55")}catch(e){throw qt(e)}}async function Le(i,t,e,n){let r=Math.max(1,e||5)*1e3,o=Date.now()+Math.min(Math.max(1,n||600)*1e3,Ve);for(;;){if(Date.now()>=o)throw new m({type:"auth",message:"\u7B49\u5F85\u6388\u6743\u8D85\u65F6",hint:"\u91CD\u65B0\u6267\u884C contak login"});await Ge(r);try{return await O.devicePoll(i.client,t)}catch(s){let a=s instanceof m?s.code:void 0;if(a==="auth.device.poll.authorization_pending")continue;if(a==="auth.device.poll.slow_down"){r=Math.min(r*2,3e4);continue}throw qt(s)}}}function qt(i){if(!(i instanceof m))return i;switch(i.code){case"auth.device.poll.access_denied":return new m({type:"auth",code:i.code,message:"\u6388\u6743\u88AB\u62D2\u7EDD",hint:"\u5982\u679C\u8FD9\u4E0D\u662F\u4F60\u672C\u4EBA\u64CD\u4F5C\u7684\uFF0C\u5FFD\u7565\u5373\u53EF\uFF1B\u8981\u91CD\u6765\u5C31\u518D\u6267\u884C\u4E00\u6B21 contak login"});case"auth.device.poll.expired_token":return new m({type:"auth",code:i.code,message:"\u8FD9\u4E2A\u8BBE\u5907\u7801\u5DF2\u5931\u6548\uFF08\u8D85\u65F6\u6216\u5DF2\u7ECF\u7528\u8FC7\uFF09",hint:"\u91CD\u65B0\u6267\u884C contak login \u62FF\u4E00\u4E2A\u65B0\u7684"});case"auth.device.poll.authorization_pending":return new m({type:"auth",code:i.code,message:"\u7528\u6237\u8FD8\u6CA1\u6709\u5728\u6D4F\u89C8\u5668\u91CC\u786E\u8BA4",hint:"\u7B49\u7528\u6237\u786E\u8BA4\u540E\u518D\u6267\u884C contak login --device-code <code>"});default:return i}}async function Gt(i,t,e){if(!t.access_token||!t.refresh_token)throw new m({type:"api",message:"\u767B\u5F55\u54CD\u5E94\u7F3A\u5C11 access_token / refresh_token",details:{keys:Object.keys(t)}});let n={accessToken:t.access_token,refreshToken:t.refresh_token,userId:t.user?.id,email:t.user?.email,name:t.user?.name,savedAt:new Date().toISOString()},r=await i.client.setCredentials(n);return{data:{logged_in:!0,user_id:n.userId,email:n.email,name:n.name,stored_in:r,profile:i.profile.name,access_expires_at:mt(n.accessToken)?.toISOString()},pretty:o=>{let s=o;return`${e}\uFF1A${T(s.name??s.email)}\uFF08\u51ED\u636E\u5B58\u4E8E ${T(s.stored_in)}\uFF09`}}}async function We(i){let{credentials:t}=await i.client.loadCredentials();return t?.refreshToken&&await O.logout(i.client,t.refreshToken).catch(()=>{}),await i.client.clearCredentials(),{data:{logged_out:!0},pretty:()=>"\u5DF2\u9000\u51FA\u767B\u5F55"}}async function qe(i){let{credentials:t,source:e}=await i.client.loadCredentials();if(!t?.accessToken)return{data:{logged_in:!1,profile:i.profile.name,base_url:i.profile.baseUrl},pretty:()=>"\u672A\u767B\u5F55\u3002\u6267\u884C contak login \u5B8C\u6210\u767B\u5F55\u3002"};let n=null,r;try{n=await O.me(i.client)}catch(o){r=o instanceof Error?o.message:String(o)}return{data:{logged_in:!!n,profile:i.profile.name,base_url:i.profile.baseUrl,stored_in:e,user:n??void 0,access_expires_at:mt(t.accessToken)?.toISOString(),error:r},pretty:o=>{let s=o;if(!s.logged_in)return`\u767B\u5F55\u6001\u5DF2\u5931\u6548\uFF1A${T(s.error)}
50
+ \u6267\u884C contak login \u91CD\u65B0\u767B\u5F55\u3002`;let a=s.user??{};return`${T(a.name??a.email)}\uFF08profile ${T(s.profile)}\uFF0C\u51ED\u636E\u5B58\u4E8E ${T(s.stored_in)}\uFF09`}}}function Ge(i){return new Promise(t=>setTimeout(t,i))}async function A(i,t,e){if(i.opts.dryRun||i.opts.yes)return;if(!_t())throw Ct(t);if(x(`
51
+ ${e}
52
+ `,i.opts),!await Vt(`\u786E\u8BA4${t}\uFF1F`))throw new m({type:"confirmation_required",message:"\u5DF2\u53D6\u6D88"})}function $(i,t){if(!i.opts.dryRun&&!(i.opts.yes||_t()))throw Ct(t)}function Bt(i){process.env.CONTAK_EXPERIMENTAL==="1"&&i.command("api <capability-id>").description("\u5B9E\u9A8C\u6027\uFF1A\u7ECF Core OpenAPI \u6821\u9A8C\u540E\u8C03\u7528\u539F\u59CB Capability").requiredOption("--input <json>","Capability JSON \u8F93\u5165").action(async function(t){await g(this,async e=>{let n=Be(this.opts().input),r=await e.client.getPublicJSON("/openapi.json"),o=r.paths?.[`/api/cap/${t}`]?.post;if(!o||o.operationId!==t)throw p(`Core OpenAPI \u4E2D\u4E0D\u5B58\u5728 Capability\uFF1A${t}`);let s=Je(r,o);return Ye(n,s),o["x-destructive"]?await A(e,`\u8C03\u7528 ${t}`,JSON.stringify(n,null,2)):o["x-readonly"]||$(e,`\u8C03\u7528 ${t}`),{data:await e.client.cap(t,n)}})})}function Be(i){try{let t=JSON.parse(i);if(!t||typeof t!="object"||Array.isArray(t))throw new Error;return t}catch{throw p("--input \u5FC5\u987B\u662F JSON \u5BF9\u8C61")}}function Je(i,t){let e=t.requestBody?.content?.["application/json"]?.schema?.$ref,n="#/components/schemas/";if(e?.startsWith(n))return i.components?.schemas?.[e.slice(n.length)]}function Ye(i,t){if(!t)throw p("Core OpenAPI \u7F3A\u5C11\u8F93\u5165 schema\uFF0C\u62D2\u7EDD\u5B9E\u9A8C\u8C03\u7528");for(let e of t.required||[])if(!(e in i))throw p(`--input \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5\uFF1A${e}`);if(t.additionalProperties===!1){for(let e of Object.keys(i))if(!t.properties?.[e])throw p(`--input \u5305\u542B\u672A\u5B9A\u4E49\u5B57\u6BB5\uFF1A${e}`)}for(let[e,n]of Object.entries(t.properties||{})){if(!(e in i)||!n.type)continue;let r=i[e];if(!(n.type==="array"?Array.isArray(r):n.type==="integer"?Number.isInteger(r):n.type==="object"?!!r&&typeof r=="object"&&!Array.isArray(r):typeof r===n.type))throw p(`--input.${e} \u5FC5\u987B\u662F ${n.type}`)}}import{createReadStream as en}from"node:fs";import{stat as nn}from"node:fs/promises";import{basename as Xt,extname as Zt}from"node:path";import{Readable as rn}from"node:stream";import{spawn as Xe}from"node:child_process";function Jt(i){C(i,"open","\u5728\u5176\u4ED6\u7EC8\u7AEF\u7EE7\u7EED\u9700\u8981\u4EBA\u4EA4\u4E92\u7684 Contak \u6D41\u7A0B").command("voiceprint").description("\u751F\u6210\u5DF2\u767B\u5F55\u7684\u58F0\u7EB9\u5F55\u5165\u9875\u9762\uFF08CLI \u4E0D\u5F55\u5236\u58F0\u7EB9\uFF09").option("--open","\u663E\u5F0F\u4F7F\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u6D4F\u89C8\u5668\u6253\u5F00").option("--wait","\u7B49\u5F85\u672C\u6B21\u751F\u6210\u7684\u94FE\u63A5\u5B8C\u6210\u58F0\u7EB9\u5F55\u5165\u540E\u8FD4\u56DE").option("--timeout <duration>","\u7B49\u5F85\u4E0A\u9650\uFF0C\u5982 30s / 5m","5m").action(async function(){await g(this,e=>Ze(e,this.opts()))})}var ze="\u6253\u5F00 transfer_url\uFF1B\u5982\u9700\u963B\u585E\u7B49\u5F85\uFF0C\u8BF7\u9996\u6B21\u6267\u884C\u65F6\u76F4\u63A5\u4F7F\u7528 --wait";async function Ze(i,t){let e=await wt(i);return t.open&&Qe(e.transfer_url),t.wait?(await bt(i,e,kt(t.timeout??"5m")),{data:{...e,completed:!0},pretty:()=>"\u7F51\u9875\u5DF2\u9886\u53D6\u4F1A\u8BDD\uFF0C\u53EF\u4EE5\u7EE7\u7EED\u539F\u64CD\u4F5C\u3002"}):{data:{...e,completed:!1,next_step:ze},pretty:()=>["\u8BF7\u6253\u5F00\u4E0B\u9762\u7684\u4E00\u6B21\u6027\u94FE\u63A5\u5B8C\u6210\u58F0\u7EB9\u5F55\u5165\uFF1A",` ${e.transfer_url}`,"","CLI \u4E0D\u4F1A\u5F55\u5236\u6216\u4FDD\u5B58\u4F60\u7684\u58F0\u7EB9\u97F3\u9891\u3002"].join(`
53
+ `)}}function wt(i){return O.sessionTransferCreate(i.client)}async function bt(i,t,e){let n=Date.parse(t.expires_at),r=Math.min(Date.now()+e,Number.isNaN(n)?1/0:n),o=1e3;for(;;){if(Date.now()>=r)throw new m({type:"action_required",code:"auth.session_transfer.wait_timeout",message:"\u7B49\u5F85\u7F51\u9875\u5B8C\u6210\u8D85\u65F6",hint:"\u5B8C\u6210\u7F51\u9875\u64CD\u4F5C\u540E\u91CD\u65B0\u6267\u884C\u539F\u547D\u4EE4",details:{session_transfer:t}});await tn(o);let s=await O.sessionTransferStatus(i.client,t.transfer_id);if(s.status==="completed")return;if(s.status==="expired")throw new m({type:"action_required",code:"auth.session_transfer.expired",message:"\u4F1A\u8BDD\u8F6C\u79FB\u5DF2\u8FC7\u671F",hint:"\u91CD\u65B0\u6267\u884C\u539F\u547D\u4EE4\u751F\u6210\u65B0\u94FE\u63A5"});o=Math.min(o*1.5,3e3)}}function Yt(i){return new m({type:"action_required",code:"meeting.voiceprint_required",message:"\u4E0A\u4F20\u4F1A\u8BAE\u97F3\u9891\u524D\u9700\u8981\u5728\u7F51\u9875\u5B8C\u6210\u58F0\u7EB9\u5F55\u5165",hint:`\u6253\u5F00 ${i.transfer_url}\uFF0C\u5B8C\u6210\u540E\u91CD\u65B0\u6267\u884C\u539F\u547D\u4EE4`,details:{session_transfer:i}})}function kt(i){let t=/^(\d+)(ms|s|m)$/.exec(i.trim());if(!t)throw p("--timeout \u683C\u5F0F\u5FC5\u987B\u662F 500ms\u300130s \u6216 5m");let e=Number(t[1]),n=t[2],r=e*(n==="m"?6e4:n==="s"?1e3:1);if(r<1e3||r>10*6e4)throw p("--timeout \u5FC5\u987B\u5728 1s \u5230 10m \u4E4B\u95F4");return r}function Qe(i){let t=process.platform==="darwin"?{command:"open",args:[i]}:process.platform==="win32"?{command:"cmd",args:["/c","start","",i]}:{command:"xdg-open",args:[i]},e=Xe(t.command,t.args,{detached:!0,stdio:"ignore"});e.once("error",n=>x(`\u65E0\u6CD5\u6253\u5F00\u6D4F\u89C8\u5668\uFF1A${n.message}`)),e.unref()}function tn(i){return new Promise(t=>setTimeout(t,i))}var Qt=[{path:["contacts","list"],capability:"identity.contact.list",risk:"read",description:"\u5217\u51FA\u8054\u7CFB\u4EBA"},{path:["contacts","get"],capability:"identity.contact.get",risk:"read",idKey:"id",description:"\u67E5\u770B\u8054\u7CFB\u4EBA"},{path:["contacts","create"],capability:"identity.contact.create",risk:"write",description:"\u521B\u5EFA\u8054\u7CFB\u4EBA"},{path:["contacts","update"],capability:"identity.contact.update",risk:"write",idKey:"id",description:"\u66F4\u65B0\u8054\u7CFB\u4EBA"},{path:["contacts","confirm"],capability:"identity.contact.confirm",risk:"write",idKey:"id",description:"\u786E\u8BA4\u5EFA\u8BAE\u8054\u7CFB\u4EBA"},{path:["contacts","archive"],capability:"identity.contact.archive",risk:"destructive",idKey:"id",description:"\u5F52\u6863\u8054\u7CFB\u4EBA"},{path:["contacts","voiceprint","remove"],capability:"identity.contact.voiceprint.remove",risk:"destructive",idKey:"contact_id",description:"\u5220\u9664\u8054\u7CFB\u4EBA\u58F0\u7EB9"},{path:["contacts","merges","list"],capability:"identity.merge.list_pending",risk:"read",description:"\u5217\u51FA\u5F85\u5904\u7406\u5408\u5E76"},{path:["contacts","merges","confirm"],capability:"identity.merge.confirm",risk:"destructive",idKey:"from",secondIdKey:"into",description:"\u786E\u8BA4\u8054\u7CFB\u4EBA\u5408\u5E76"},{path:["contacts","merges","dismiss"],capability:"identity.merge.dismiss",risk:"write",idKey:"from",secondIdKey:"into",description:"\u5FFD\u7565\u5408\u5E76\u5EFA\u8BAE"},{path:["meetings","list"],capability:"episodic.meeting.list",risk:"read",description:"\u5217\u51FA\u4F1A\u8BAE"},{path:["meetings","get"],capability:"episodic.meeting.get",risk:"read",idKey:"id",description:"\u67E5\u770B\u4F1A\u8BAE"},{path:["meetings","create"],capability:"episodic.meeting.create",risk:"write",description:"\u521B\u5EFA\u4F1A\u8BAE"},{path:["meetings","update"],capability:"episodic.meeting.update",risk:"write",idKey:"id",description:"\u66F4\u65B0\u4F1A\u8BAE"},{path:["meetings","archive"],capability:"episodic.meeting.archive",risk:"destructive",idKey:"id",description:"\u5F52\u6863\u4F1A\u8BAE"},{path:["meetings","transcript","get"],capability:"episodic.transcript.get",risk:"read",idKey:"id",description:"\u83B7\u53D6\u8F6C\u5199"},{path:["meetings","transcript","update"],capability:"episodic.transcript.update",risk:"write",idKey:"id",description:"\u4FEE\u6539\u8F6C\u5199"},{path:["meetings","reprocess"],capability:"episodic.meeting.reprocess",risk:"write",idKey:"meeting_id",description:"\u91CD\u65B0\u5904\u7406\u4F1A\u8BAE"},{path:["meetings","retranscribe"],capability:"episodic.meeting.retranscribe",risk:"write",idKey:"meeting_id",description:"\u91CD\u65B0\u8F6C\u5199\u4F1A\u8BAE"},{path:["meetings","reidentify"],capability:"episodic.meeting.reidentify",risk:"write",idKey:"meeting_id",description:"\u91CD\u65B0\u8BC6\u522B\u8BF4\u8BDD\u4EBA"},{path:["meetings","suggestions","resolve"],capability:"episodic.meeting.suggestion.resolve",risk:"write",idKey:"meeting_id",description:"\u5904\u7406\u4F1A\u8BAE\u5EFA\u8BAE"},{path:["meetings","followups"],capability:"meeting.followups.recent",risk:"read",description:"\u67E5\u770B\u8FD1\u671F\u8DDF\u8FDB"},{path:["todos","list"],capability:"todo.list",risk:"read",description:"\u5217\u51FA\u5F85\u529E"},{path:["todos","get"],capability:"todo.get",risk:"read",idKey:"id",description:"\u67E5\u770B\u5F85\u529E"},{path:["todos","create"],capability:"todo.create",risk:"write",description:"\u521B\u5EFA\u5F85\u529E"},{path:["todos","update"],capability:"todo.update",risk:"write",idKey:"id",description:"\u66F4\u65B0\u5F85\u529E"},{path:["todos","complete"],capability:"todo.complete",risk:"write",idKey:"id",description:"\u5B8C\u6210\u5F85\u529E"},{path:["todos","reopen"],capability:"todo.reopen",risk:"write",idKey:"id",description:"\u91CD\u65B0\u6253\u5F00\u5F85\u529E"},{path:["todos","cancel"],capability:"todo.cancel",risk:"write",idKey:"id",description:"\u53D6\u6D88\u5F85\u529E"},{path:["todos","archive"],capability:"todo.archive",risk:"destructive",idKey:"id",description:"\u5F52\u6863\u5F85\u529E"},{path:["todos","unarchive"],capability:"todo.unarchive",risk:"write",idKey:"id",description:"\u53D6\u6D88\u5F52\u6863\u5F85\u529E"},{path:["todos","delete"],capability:"todo.delete",risk:"destructive",idKey:"id",description:"\u5220\u9664\u5F85\u529E"},{path:["todos","restore"],capability:"todo.restore",risk:"write",idKey:"id",description:"\u6062\u590D\u5F85\u529E"},{path:["search","conversations","list"],capability:"aisearch.conversation.list",risk:"read",description:"\u5217\u51FA AI \u641C\u7D22\u5BF9\u8BDD"},{path:["search","conversations","get"],capability:"aisearch.conversation.get",risk:"read",idKey:"id",description:"\u67E5\u770B AI \u641C\u7D22\u5BF9\u8BDD"},{path:["search","conversations","delete"],capability:"aisearch.conversation.delete",risk:"destructive",idKey:"id",description:"\u5220\u9664 AI \u641C\u7D22\u5BF9\u8BDD"},{path:["billing","plans"],capability:"billing.catalog.list",risk:"read",description:"\u67E5\u770B\u5957\u9910"},{path:["billing","checkout"],capability:"billing.checkout.create",risk:"write",description:"\u521B\u5EFA\u652F\u4ED8\u9875"},{path:["billing","portal"],capability:"billing.portal.create",risk:"write",description:"\u521B\u5EFA\u8D26\u5355\u95E8\u6237"},{path:["vocabulary","list"],capability:"vocabulary.term.list",risk:"read",description:"\u5217\u51FA\u4E2A\u4EBA\u8BCD\u5E93"},{path:["vocabulary","add"],capability:"vocabulary.term.add",risk:"write",description:"\u6DFB\u52A0\u4E2A\u4EBA\u8BCD\u6C47"},{path:["vocabulary","remove"],capability:"vocabulary.term.remove",risk:"destructive",idKey:"id",numericId:!0,description:"\u5220\u9664\u4E2A\u4EBA\u8BCD\u6C47"},{path:["events","join"],capability:"event.join",risk:"write",idKey:"code",description:"\u52A0\u5165\u6D3B\u52A8"},{path:["events","leave"],capability:"event.leave",risk:"destructive",idKey:"event_id",description:"\u9000\u51FA\u6D3B\u52A8"},{path:["events","profile"],capability:"event.profile.publish",risk:"write",idKey:"event_id",description:"\u53D1\u5E03\u6D3B\u52A8\u8D44\u6599"},{path:["events","roster"],capability:"event.roster.list",risk:"read",idKey:"event_id",description:"\u67E5\u770B\u6D3B\u52A8\u540D\u5355"},{path:["events","matches"],capability:"event.match.list",risk:"read",idKey:"event_id",description:"\u67E5\u770B\u6D3B\u52A8\u5339\u914D"},{path:["profile","questions","get"],capability:"user.profile.questions.get",risk:"read",description:"\u67E5\u770B\u8D44\u6599\u95EE\u9898"},{path:["profile","questions","generate"],capability:"user.profile.questions.generate",risk:"write",description:"\u751F\u6210\u8D44\u6599\u95EE\u9898"},{path:["profile","questions","answer"],capability:"user.profile.questions.answer",risk:"write",description:"\u56DE\u7B54\u8D44\u6599\u95EE\u9898"}],te=[...Qt.filter(i=>i.risk!=="read").map(i=>i.path.join(" ")),"profile update","voiceprint remove","account delete","meetings upload"];function ee(i){on(i);for(let t of Qt)sn(i,t);cn(i)}function on(i){i.command("credits").description("\u67E5\u770B\u989D\u5EA6").action(async function(){await g(this,async r=>({data:await r.client.cap("user.credits.get",{})}))});let t=C(i,"profile","\u7BA1\u7406\u4E2A\u4EBA\u8D44\u6599");nt(t,"get","user.profile.get","read"),nt(t,"update","user.profile.update","write");let e=C(i,"voiceprint","\u67E5\u8BE2\u6216\u5220\u9664\u58F0\u7EB9\uFF1B\u5F55\u5165\u53EA\u5728\u7F51\u9875\u5B8C\u6210");nt(e,"status","user.voiceprint.status","read"),nt(e,"remove","user.voiceprint.remove","destructive"),C(i,"account","\u8D26\u53F7\u5B89\u5168\u64CD\u4F5C").command("delete").description("\u4E0D\u53EF\u9006\u5220\u9664\u8D26\u53F7").requiredOption("--confirm <identifier>","\u590D\u6838\u5F53\u524D\u8D26\u53F7\u6807\u8BC6").action(async function(){await g(this,async r=>{let o=String(this.opts().confirm);return await A(r,"\u5220\u9664\u8D26\u53F7",`\u5C06\u4E0D\u53EF\u9006\u5220\u9664\u8D26\u53F7 ${o}`),{data:await r.client.cap("user.account.delete",{confirm_email:o})}})})}function nt(i,t,e,n){let r=i.command(t).description(e).option("--input <json>","JSON \u8F93\u5165\uFF0C\u9ED8\u8BA4 {}");n==="destructive"&&r.option("--confirm <identifier>","\u590D\u6838\u8D44\u6E90\u6807\u8BC6"),r.action(async function(){await g(this,o=>{if(n==="destructive"&&!o.opts.dryRun&&!String(this.opts().confirm||"").trim())throw p("--confirm \u4E0D\u80FD\u4E3A\u7A7A");return ne(o,e,ie(this.opts().input),n,`${i.name()} ${t}`)})})}function sn(i,t){let e=i;for(let s of t.path.slice(0,-1))e=C(e,s);let n=t.path.at(-1),r=t.secondIdKey?`${n} <id> <second-id>`:t.idKey?`${n} <id>`:n,o=e.command(r).description(t.description).option("--input <json>","\u9644\u52A0 JSON \u8F93\u5165\uFF0C\u9ED8\u8BA4 {}");t.risk==="destructive"&&o.option("--confirm <identifier>","\u5FC5\u987B\u4E0E\u8D44\u6E90 id \u4E00\u81F4"),o.action(async function(s,a){await g(this,async u=>{let l=t.secondIdKey?`${s}->${a}`:s;if(t.risk==="destructive"&&!u.opts.dryRun&&t.idKey&&String(this.opts().confirm)!==l)throw p(`--confirm \u5FC5\u987B\u7CBE\u786E\u586B\u5199 ${l}`);let c=ie(this.opts().input);return t.idKey&&(c[t.idKey]=t.numericId?an(s):s),t.secondIdKey&&(c[t.secondIdKey]=a),ne(u,t.capability,c,t.risk,t.path.join(" "),s)})})}function an(i){let t=Number(i);if(!Number.isSafeInteger(t)||t<1)throw p("id \u5FC5\u987B\u662F\u6B63\u6574\u6570");return t}async function ne(i,t,e,n,r,o){return n==="write"&&$(i,r),n==="destructive"&&await A(i,r,`\u5C06\u6267\u884C ${r}${o?`\uFF1A${o}`:""}`),{data:await i.client.cap(t,e)}}function ie(i){if(i===void 0)return{};try{let t=JSON.parse(String(i));if(!t||typeof t!="object"||Array.isArray(t))throw new Error;return t}catch{throw p("--input \u5FC5\u987B\u662F JSON \u5BF9\u8C61")}}function cn(i){C(i,"meetings").command("upload <file>").description("\u4E0A\u4F20\u4F1A\u8BAE\u97F3\u9891\uFF1B\u58F0\u7EB9\u4E0D\u8DB3\u65F6\u53EA\u8FD4\u56DE\u7F51\u9875\u64CD\u4F5C\u94FE\u63A5").option("--meeting-id <id>","\u4E0A\u4F20\u5230\u5DF2\u6709 draft \u4F1A\u8BAE\uFF1B\u4E0D\u4F20\u5219\u65B0\u5EFA").option("--title <title>","\u65B0\u5EFA\u4F1A\u8BAE\u6807\u9898").option("--lang <lang>","\u8F6C\u5199\u8BED\u8A00\u63D0\u793A").option("--wait","\u7B49\u5F85\u7F51\u9875\u58F0\u7EB9\u5B8C\u6210\u540E\u7EED\u8DD1").option("--timeout <duration>","\u7B49\u5F85\u4E0A\u9650\uFF0C\u5982 30s / 5m","5m").action(async function(e){await g(this,n=>un(n,e,this.opts()))})}async function un(i,t,e){$(i,"\u4E0A\u4F20\u4F1A\u8BAE\u97F3\u9891");let n=await nn(t).catch(()=>null);if(!n?.isFile()||n.size<=0)throw p(`\u65E0\u6CD5\u8BFB\u53D6\u97F3\u9891\u6587\u4EF6\uFF1A${t}`);let r=async()=>{let o=e.meetingId;if(!o){let f=await i.client.cap("episodic.meeting.create",{title:e.title||Xt(t,Zt(t)),title_source:"file_upload",source_filename:Xt(t)});if(o=String(f.id||""),!o)throw new m({type:"api",message:"\u521B\u5EFA\u4F1A\u8BAE\u540E\u672A\u8FD4\u56DE id"})}let s=dn(t),a=await i.client.cap("episodic.meeting.audio.request_upload",{meeting_id:o,content_type:s,size_bytes:n.size,upload_source:"file_upload",client_mime_type:s}),u=String(a.upload_url||""),l=String(a.object_key||""),c=String(a.reservation_id||"");if(!u||!l||!c)throw new m({type:"api",message:"\u4E0A\u4F20\u51ED\u636E\u7F3A\u5C11 URL\u3001object_key \u6216 reservation_id"});let d;try{let f=rn.toWeb(en(t));d=await fetch(u,{method:"PUT",headers:{"content-type":s,"content-length":String(n.size)},body:f,duplex:"half"})}catch(f){throw await zt(i,o,c),new m({type:"network",message:"\u97F3\u9891 PUT \u5931\u8D25",cause:f})}if(!d.ok)throw await d.body?.cancel().catch(()=>{}),await zt(i,o,c),new m({type:"api",status:d.status,message:`\u97F3\u9891 PUT \u5931\u8D25\uFF08HTTP ${d.status}\uFF09`});return i.client.cap("episodic.meeting.audio.attach",{meeting_id:o,object_key:l,reservation_id:c,lang:e.lang,client_mime_type:s})};try{return{data:await r()}}catch(o){if(!(o instanceof m)||o.code!=="meeting.voiceprint_required")throw o;let s=await wt(i);if(!e.wait)throw Yt(s);return await bt(i,s,kt(e.timeout||"5m")),{data:await r()}}}async function zt(i,t,e){await i.client.cap("episodic.meeting.audio.release_upload",{meeting_id:t,reservation_id:e}).catch(()=>{})}function dn(i){switch(Zt(i).toLowerCase()){case".wav":return"audio/wav";case".mp3":return"audio/mpeg";case".m4a":case".mp4":return"audio/mp4";case".ogg":return"audio/ogg";case".webm":return"audio/webm";default:return"application/octet-stream"}}import{readFile as ln}from"node:fs/promises";import{createHash as pn}from"node:crypto";var oe=256*1024,re=100,se=/^sha256:[0-9a-f]{64}$/,mn=new Set(["codex","claude_code"]),fn=new Set(["profile","preference","vocabulary"]),hn=new Set(["communication","workflow","tooling","decision","privacy","scheduling","other"]);function ae(i){let t=C(i,"context","\u5BFC\u5165\u548C\u7BA1\u7406\u7ECF\u7528\u6237\u786E\u8BA4\u7684\u957F\u671F\u4E2A\u4EBA\u4E0A\u4E0B\u6587");for(let e of["import","sync"])t.command(e).description(e==="import"?"\u5BFC\u5165\u7ED3\u6784\u5316 Context manifest":"\u663E\u5F0F\u589E\u91CF\u540C\u6B65 Context manifest").requiredOption("--manifest <file>","manifest \u6587\u4EF6\uFF1B\u7528 - \u4ECE stdin \u8BFB\u53D6").option("--prune","\u5220\u9664\u8BE5\u6765\u6E90\u4E2D\u672C\u6B21\u5DF2\u7F3A\u5931\u7684\u504F\u597D\uFF08\u5F3A\u786E\u8BA4\uFF09").action(async function(){await g(this,n=>gn(n,this.opts()))});t.command("list").description("\u5217\u51FA\u5DF2\u786E\u8BA4\u7684\u957F\u671F\u504F\u597D").action(async function(){await g(this,async e=>({data:await e.client.cap("user.context.fact.list",{})}))}),t.command("imports").description("\u5217\u51FA\u5DF2\u5E94\u7528\u7684\u6765\u6E90 revision\uFF08\u4E0D\u8FD4\u56DE\u5019\u9009\u6B63\u6587\uFF09").action(async function(){await g(this,async e=>({data:await e.client.cap("user.context.import.state",{})}))}),t.command("update <id>").description("\u4EBA\u5DE5\u4FEE\u6539\u4E00\u6761\u957F\u671F\u504F\u597D").requiredOption("--category <category>","\u504F\u597D\u5206\u7C7B").requiredOption("--statement <text>","\u786E\u8BA4\u540E\u7684\u9648\u8FF0").action(async function(e){await g(this,async n=>{$(n,"\u4FEE\u6539\u4E2A\u4EBA\u4E0A\u4E0B\u6587");let r=this.opts(),o=ce(r.category,r.statement);return{data:await n.client.cap("user.context.fact.update",{id:e,...o})}})}),t.command("remove <id>").description("\u5220\u9664\u4E00\u6761\u957F\u671F\u504F\u597D").option("--confirm <identifier>","\u5FC5\u987B\u4E0E\u4E8B\u5B9E id \u4E00\u81F4").action(async function(e){await g(this,async n=>{if(!n.opts.dryRun&&String(this.opts().confirm)!==e)throw p(`--confirm \u5FC5\u987B\u7CBE\u786E\u586B\u5199 ${e}`);return await A(n,"\u5220\u9664\u4E2A\u4EBA\u4E0A\u4E0B\u6587",`\u5C06\u5220\u9664 ${e}`),{data:await n.client.cap("user.context.fact.remove",{id:e})}})})}async function gn(i,t){let e=Cn(await _n(t.manifest)),n=await i.client.cap("user.context.import.state",{},{dryRunRead:!0}),r=Sn(e,n,!!t.prune),o=An(e,r,!!t.prune);return i.opts.dryRun?{data:{dry_run:!0,manifest_submitted:!1,...o}}:(await A(i,t.prune?"\u5BFC\u5165\u5E76\u5220\u9664\u7F3A\u5931\u9879":"\u5BFC\u5165\u4E2A\u4EBA\u4E0A\u4E0B\u6587",En(r)),{data:await i.client.cap("user.context.import.apply",{...e,prune:!!t.prune}),pretty:()=>"\u4E2A\u4EBA\u4E0A\u4E0B\u6587\u5DF2\u5E94\u7528"})}async function _n(i){let t=i==="-"?await yn():await ln(i,"utf8");if(Buffer.byteLength(t,"utf8")>oe)throw p("manifest \u8D85\u8FC7 256 KiB");try{return JSON.parse(t)}catch{throw p("manifest \u4E0D\u662F\u6709\u6548 JSON")}}async function yn(){let i=[];for await(let t of process.stdin)if(i.push(Buffer.isBuffer(t)?t:Buffer.from(t)),i.reduce((e,n)=>e+n.length,0)>oe)throw p("manifest \u8D85\u8FC7 256 KiB");return Buffer.concat(i).toString("utf8")}function Cn(i){if(!i||typeof i!="object"||Array.isArray(i))throw p("manifest \u5FC5\u987B\u662F JSON \u5BF9\u8C61");let t=i,e=t.source;if(t.schema_version!==1)throw p("\u4EC5\u652F\u6301 schema_version=1");if(!e||!mn.has(String(e.provider)))throw p("provider \u4EC5\u652F\u6301 codex / claude_code");if(e.scope!=="global")throw p("\u9996\u7248\u53EA\u5141\u8BB8\u5168\u5C40\u7528\u6237\u8BB0\u5FC6\uFF0C\u9879\u76EE\u7EA7 scope \u5DF2\u62D2\u7EDD");if(!String(e.source_id||"").trim())throw p("source_id \u4E0D\u80FD\u4E3A\u7A7A");if(!se.test(String(e.revision_hash||"")))throw p("revision_hash \u5FC5\u987B\u662F sha256:<64\u4F4D\u5C0F\u5199\u5341\u516D\u8FDB\u5236>");if(!Array.isArray(t.items)||t.items.length>re)throw p(`items \u5FC5\u987B\u662F\u6570\u7EC4\u4E14\u6700\u591A ${re} \u6761`);let n=new Set;for(let[s,a]of t.items.entries())wn(a,s,n);if(t.items.some(s=>s.kind==="profile")&&!String(t.base_profile_updated_at||"").trim())throw p("profile \u6761\u76EE\u5FC5\u987B\u5E26 base_profile_updated_at\uFF1B\u5148\u8FD0\u884C contak context imports \u83B7\u53D6\u5F53\u524D revision");kn(t.items);let o=vn(t.items);if(e.revision_hash!==o)throw p(`revision_hash \u4E0E items \u4E0D\u4E00\u81F4\uFF0C\u5E94\u4E3A ${o}`);return t}function wn(i,t,e){if(!i||typeof i!="object"||Array.isArray(i))throw p(`items[${t}] \u5FC5\u987B\u662F\u5BF9\u8C61`);let n=i,r=String(n.item_id||"");if(!r||e.has(r))throw p(`items[${t}].item_id \u4E3A\u7A7A\u6216\u91CD\u590D`);if(e.add(r),!fn.has(String(n.kind)))throw p(`items[${t}].kind \u4E0D\u652F\u6301`);if(!se.test(String(n.content_hash||"")))throw p(`items[${t}].content_hash \u65E0\u6548`);if(Array.isArray(n.sensitivity_flags)&&n.sensitivity_flags.length>0)throw Ot(t,"\u5019\u9009\u9879\u542B sensitivity_flags\uFF0C\u5FC5\u987B\u5148\u5220\u9664\u6216\u6539\u5199");if(n.kind==="preference"&&ce(String(n.category||""),String(n.statement||"")),n.kind==="vocabulary"&&!String(n.surface||"").trim())throw p(`items[${t}].surface \u4E0D\u80FD\u4E3A\u7A7A`);let o=xn(n);if(n.content_hash!==o)throw p(`items[${t}].content_hash \u4E0E\u89C4\u8303\u5316\u5185\u5BB9\u4E0D\u4E00\u81F4\uFF0C\u5E94\u4E3A ${o}`);if(JSON.stringify(n).length>16384)throw p(`items[${t}] \u8D85\u8FC7\u5355\u6761\u957F\u5EA6\u4E0A\u9650`)}function ce(i,t){if(!hn.has(i))throw p(`\u4E0D\u652F\u6301\u7684\u504F\u597D category\uFF1A${i}`);let e=t.trim();if(!e||[...e].length>500)throw p("statement \u5FC5\u987B\u4E3A 1-500 \u5B57\u7B26");return{category:i,statement:e}}var bn=[["\u79C1\u94A5",/-----BEGIN [A-Z ]*PRIVATE KEY-----/i],["Bearer \u8BA4\u8BC1\u5934",/authorization\s*:\s*bearer\s+\S+/i],["Cookie",/\b(?:cookie|set-cookie)\s*[:=]/i],["\u5E26\u51ED\u636E URL",/\b[a-z][a-z0-9+.-]*:\/\/[^\s/:]+:[^\s/@]+@/i],["\u8FDE\u63A5\u4E32",/\b(?:postgres(?:ql)?|mysql|mongodb|redis):\/\/\S+/i],["\u5BC6\u94A5\u8D4B\u503C",/\b(?:api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret)\s*[:=]\s*\S+/i],[".env \u5185\u5BB9",/(?:^|\n)\s*[A-Z][A-Z0-9_]{2,}\s*=\s*\S+/],["\u7528\u6237\u7EDD\u5BF9\u8DEF\u5F84",/(?:\/Users\/[^/\s]+\/|\/home\/[^/\s]+\/|[A-Z]:\\Users\\[^\\\s]+\\)/i]];function kn(i){i.forEach((t,e)=>{let n=JSON.stringify(t);for(let[o,s]of bn)if(s.test(n))throw Ot(e,`\u68C0\u6D4B\u5230${o}`);if((n.match(/[A-Za-z0-9_+\/-]{40,}={0,2}/g)||[]).some(On))throw Ot(e,"\u68C0\u6D4B\u5230\u9AD8\u71B5\u51ED\u636E\u5F62\u6001")})}function On(i){return/^[0-9a-f]{64}$/i.test(i)?!1:[/[a-z]/,/[A-Z]/,/[0-9]/,/[_+\/-]/].filter(e=>e.test(i)).length>=3&&new Set(i).size>=16}function Ot(i,t){return new m({type:"validation",code:"context.secret_detected",message:`items[${i}] ${t}\uFF0C\u5DF2\u963B\u6B62\u63D0\u4EA4`,hint:"\u5220\u9664\u6216\u624B\u5DE5\u6539\u5199\u8BE5\u6761\u540E\u91CD\u65B0\u9884\u89C8\uFF1B--yes \u4E0D\u80FD\u7ED5\u8FC7\u6B64\u68C0\u67E5"})}function xn(i){let t;switch(i.kind){case"preference":t={kind:i.kind,category:String(i.category||"").trim(),statement:String(i.statement||"").trim()};break;case"vocabulary":t={kind:i.kind,category:String(i.category||"").trim(),surface:String(i.surface||"").trim(),aliases:[...new Set((i.aliases||[]).map(e=>String(e).trim()).filter(Boolean))].sort(vt)};break;case"profile":t={kind:i.kind,field:String(i.field||"").trim(),value:xt(i.value)};break}return ue(JSON.stringify(t))}function vn(i){let t=i.map(e=>`${e.item_id}
54
+ ${e.content_hash}
55
+ `).sort(vt).join("");return ue(t)}function xt(i){return Array.isArray(i)?i.map(xt):i&&typeof i=="object"?Object.fromEntries(Object.entries(i).sort(([t],[e])=>vt(t,e)).map(([t,e])=>[t,xt(e)])):i}function vt(i,t){return Buffer.compare(Buffer.from(i,"utf8"),Buffer.from(t,"utf8"))}function ue(i){return`sha256:${pn("sha256").update(i,"utf8").digest("hex")}`}function Sn(i,t,e){let n=(t.imports||[]).find(a=>a.provider===i.source.provider&&a.source_id===i.source.source_id),r=new Map((n?.items||[]).map(a=>[a.item_id,a])),o=new Set(i.items.map(a=>a.item_id)),s={created:[],updated:[],skipped:[],pruned:[]};for(let a of i.items){let u={item_id:a.item_id,kind:a.kind,content_hash:a.content_hash},l=r.get(a.item_id);l?l.kind!==a.kind||l.content_hash!==a.content_hash?s.updated.push(u):s.skipped.push(u):s.created.push(u)}return e&&(s.pruned=(t.active_items||[]).filter(a=>a.provider===i.source.provider&&a.source_id===i.source.source_id&&a.kind==="preference"&&!o.has(a.item_id)).map(({item_id:a,kind:u,content_hash:l})=>({item_id:a,kind:u,content_hash:l}))),s}function An(i,t,e){let n={profile:0,preference:0,vocabulary:0};return i.items.forEach(r=>n[r.kind]++),{provider:i.source.provider,source_id:i.source.source_id,revision_hash:i.source.revision_hash,item_count:i.items.length,counts:n,prune:e,diff:t}}function En(i){let t=(e,n)=>`${e} ${n.length}${n.length?`\uFF1A${n.map(r=>`${r.kind}/${r.item_id}`).join("\u3001")}`:""}`;return[t("\u65B0\u589E",i.created),t("\u66F4\u65B0",i.updated),t("\u8DF3\u8FC7",i.skipped),t("\u5220\u9664",i.pruned)].join(`
56
+ `)}import w from"node:fs";import R from"node:path";var Tn=[...te,"context import","context sync","context update","context remove"],$n=["login","logout","skills install"];function de(i){i.command("schema").description("\u8F93\u51FA\u5B8C\u6574\u547D\u4EE4\u5951\u7EA6\uFF08\u53C2\u6570\u3001\u7C7B\u578B\u3001\u9000\u51FA\u7801\u3001\u8F93\u51FA\u683C\u5F0F\uFF09\uFF0C\u7ED9 agent \u8BFB").action(async function(){await g(this,async()=>In(i))});let t=i.command("skills").description("\u5185\u7F6E Agent Skill\uFF1A\u968F CLI \u7248\u672C\u8D70\uFF0C\u6C38\u4E0D\u4E0E\u547D\u4EE4\u6F02\u79FB");t.command("list").description("\u5217\u51FA\u5185\u7F6E skill").action(async function(){await g(this,async()=>Nn())}),t.command("read [name]").description("\u8BFB skill \u6B63\u6587\uFF08\u9ED8\u8BA4\u8F93\u51FA\u88F8 markdown\uFF0C--json \u624D\u5305\u4FE1\u5C01\uFF09").action(async function(e){await g(this,async n=>Pn(n,e))}),t.command("install").description("\u628A skill \u88C5\u5230 ~/.claude/skills \u4E0E ~/.agents/skills").option("--project","\u88C5\u5230\u5F53\u524D\u76EE\u5F55\u800C\u4E0D\u662F\u7528\u6237\u4E3B\u76EE\u5F55").action(async function(){await g(this,async()=>Dn(!!this.opts().project))}),i.command("config").description("\u663E\u793A\u5F53\u524D\u914D\u7F6E\uFF08profile\u3001API \u57FA\u5740\u3001\u914D\u7F6E\u76EE\u5F55\uFF09").action(async function(){await g(this,async e=>({data:{version:S,profile:e.profile.name,base_url:e.profile.baseUrl,site_url:e.siteUrl}}))})}function Rn(i){return!!i._hidden}function le(i,t=""){let e=i.name(),n=t?`${t} ${e}`:e==="contak"?"":e,r=Tn.includes(n),o=$n.includes(n),s=i.options.some(a=>a.long==="--confirm");return{name:e,path:n||void 0,description:i.description()||void 0,usage:i.usage(),mutating:r||o||void 0,requires_yes:r||void 0,confirmation_level:s?"resource_identifier":r?"write":o?"local_write":"read",arguments:i.registeredArguments.map(a=>({name:a.name(),required:a.required,variadic:a.variadic,description:a.description||void 0})),options:i.options.filter(a=>!a.hidden).map(a=>({flags:a.flags,description:a.description||void 0,takes_value:a.required||a.optional||void 0,mandatory:a.mandatory||void 0,default:a.defaultValue})),subcommands:i.commands.filter(a=>!Rn(a)).map(a=>le(a,n))}}function In(i){return{data:{schema_version:1,cli_version:S,output_contract:{success:'stdout \u8F93\u51FA {"ok":true,"data":...}\uFF0C\u9000\u51FA\u7801 0',failure:'stderr \u8F93\u51FA {"ok":false,"error":{type,code,message,hint}}\uFF0C\u9000\u51FA\u7801\u89C1 exit_codes',judge_success:"\u53EA\u770B ok \u6216\u9000\u51FA\u7801\uFF0C\u4E0D\u8981\u770B data \u91CC\u7684\u5B57\u6BB5",formats:et,default_format:"\u975E TTY \u4E0B\u662F json\uFF0CTTY \u4E0B\u662F pretty",stdout_discipline:"stdout \u53EA\u653E\u6570\u636E\uFF1B\u8FDB\u5EA6\u4E0E\u63D0\u793A\u4E00\u5F8B\u8D70 stderr"},exit_codes:y,environment:{CONTAK_BASE_URL:"\u8986\u76D6 API \u57FA\u5740",CONTAK_PROFILE:"\u9009\u62E9 profile",CONTAK_FORMAT:"\u9ED8\u8BA4\u8F93\u51FA\u683C\u5F0F",CONTAK_CONFIG_DIR:"\u914D\u7F6E\u76EE\u5F55\uFF08\u9ED8\u8BA4 ~/.config/contak\uFF09",CONTAK_ACCESS_TOKEN:"\u76F4\u63A5\u6CE8\u5165 access token\uFF0C\u53EA\u8BFB\u4E0D\u843D\u76D8",CONTAK_REFRESH_TOKEN:"\u76F4\u63A5\u6CE8\u5165 refresh token\uFF0C\u53EA\u8BFB\u4E0D\u843D\u76D8",CONTAK_CREDENTIALS_BACKEND:"\u8BBE\u4E3A file \u5219\u4E0D\u4F7F\u7528\u7CFB\u7EDF\u94A5\u5319\u4E32",CONTAK_NO_INPUT:"\u8BBE\u7F6E\u540E\u4E00\u5F8B\u4E0D\u5411\u7528\u6237\u63D0\u95EE",CONTAK_DEBUG:"\u628A\u8BF7\u6C42\u4E0E\u9519\u8BEF\u6808\u6253\u5230 stderr",CONTAK_EXPERIMENTAL:"\u8BBE\u4E3A 1 \u624D\u6CE8\u518C\u5B9E\u9A8C\u6027 contak api \u5165\u53E3"},context_manifest:{schema_version:1,max_bytes:262144,max_items:100,providers:["codex","claude_code"],scope:"global",kinds:["profile","preference","vocabulary"],preference_categories:["communication","workflow","tooling","decision","privacy","scheduling","other"],profile_requires_base_revision:!0,raw_memory_allowed:!1,hash_algorithm:"sha256 over canonical item JSON; revision is sha256 of sorted item_id/content_hash records"},commands:le(i)}}}function St(){return gt("skills")}function Nn(){let i=St();return{data:(w.existsSync(i)?w.readdirSync(i).filter(e=>!e.startsWith(".")):[]).map(e=>({name:e,path:R.join(i,e,"SKILL.md")}))}}function Pn(i,t){let e=St(),n=t||"contak",r=R.join(e,n,"SKILL.md");if(!w.existsSync(r))throw p(`\u6CA1\u6709\u540D\u4E3A "${n}" \u7684 skill`,"\u7528 contak skills list \u770B\u53EF\u7528\u7684 skill");let o=w.readFileSync(r,"utf8");if(i.format==="pretty"||i.format==="table"){process.stdout.write(o.replace(/\n?$/,`
57
+ `));return}return{data:{name:n,path:r,content:o}}}function Dn(i){let t=St();if(!w.existsSync(t))throw p("\u8FD9\u4E2A\u5B89\u88C5\u5305\u91CC\u6CA1\u6709\u9644\u5E26 skills \u76EE\u5F55");let e=i?process.cwd():process.env.HOME||process.env.USERPROFILE||"";if(!e)throw p("\u627E\u4E0D\u5230\u7528\u6237\u4E3B\u76EE\u5F55\uFF0C\u7528 --project \u88C5\u5230\u5F53\u524D\u76EE\u5F55");let n=[R.join(e,".claude","skills"),R.join(e,".agents","skills")],r=w.readdirSync(t).filter(s=>w.existsSync(R.join(t,s,"SKILL.md"))),o=n.flatMap(s=>r.map(a=>{let u=R.join(s,a),l=w.existsSync(u);return w.mkdirSync(u,{recursive:!0}),w.cpSync(R.join(t,a),u,{recursive:!0}),{path:u,action:l?"overwritten":"created"}}));return{data:{installed:o},pretty:()=>o.map(s=>`${s.action==="created"?"\u5DF2\u5B89\u88C5":"\u5DF2\u66F4\u65B0"}\uFF1A${s.path}`).join(`
58
+ `)}}var jn=9e4;function pe(i){C(i,"search","AI \u641C\u7D22\u4E0E\u5BF9\u8BDD").command("ask <question>").description("\u57FA\u4E8E Contak \u8BB0\u5FC6\u6D41\u5F0F\u56DE\u7B54\u95EE\u9898").option("--conversation-id <id>","\u7EED\u95EE\u5DF2\u6709\u5BF9\u8BDD").action(async function(e){await g(this,n=>Hn(n,e,this.opts().conversationId))})}async function Hn(i,t,e){if(!t.trim())throw p("\u95EE\u9898\u4E0D\u80FD\u4E3A\u7A7A");let n=await i.client.open("/api/ai/search/stream",{question:t.trim(),conversation_id:e||""});if(!n.body)throw new m({type:"stream",message:"AI \u641C\u7D22\u54CD\u5E94\u6CA1\u6709\u6D41"});let r=n.body.getReader(),o=new TextDecoder,s="",a,u;try{for(;;){let c=await Fn(r);if(c.done)break;if(!c.value)continue;s+=o.decode(c.value,{stream:!0});let d=s.split(`
59
+
60
+ `);s=d.pop()||"";for(let f of d){let b=f.split(`
61
+ `).filter(it=>it.startsWith("data:")).map(it=>it.slice(5).trim()).join("");if(!b)continue;let _=JSON.parse(b),K=String(_.type||"");if(K==="start"&&(u=_),K==="reasoning"&&x(String(_.text||""),i.opts),K==="error")throw new m({type:"stream",code:String(_.code||"aisearch.stream.error"),message:String(_.message||"AI \u641C\u7D22\u6D41\u8FD4\u56DE\u9519\u8BEF"),details:_});K==="finish"&&(a=_)}}}finally{await r.cancel().catch(()=>{})}if(!a)throw new m({type:"stream",code:"aisearch.stream.incomplete",message:"AI \u641C\u7D22\u5728 finish \u4E4B\u524D\u4E2D\u65AD",hint:"\u7F51\u7EDC\u7A33\u5B9A\u540E\u91CD\u8BD5"});return{data:{...u,...a},pretty:()=>String(a?.content||"")}}async function Fn(i){let t;try{return await Promise.race([i.read(),new Promise((e,n)=>{t=setTimeout(()=>n(new m({type:"stream",code:"aisearch.stream.idle_timeout",message:"AI \u641C\u7D22\u6D41\u957F\u65F6\u95F4\u65E0\u6570\u636E"})),jn)})])}finally{t&&clearTimeout(t)}}var Vn=`
51
62
  AGENT QUICKSTART\uFF08\u7ED9 AI agent \u7684\u51E0\u884C\u8BF4\u660E\uFF09:
52
63
  contak schema --json \u4E00\u6B21\u62FF\u5230\u5168\u90E8\u547D\u4EE4/\u53C2\u6570/\u8F93\u51FA\u5951\u7EA6/\u9000\u51FA\u7801
53
64
  contak skills read \u8BFB\u5185\u7F6E SKILL.md\uFF08\u6982\u5FF5\u3001\u7EA6\u675F\u3001\u5E38\u89C1\u4EFB\u52A1\uFF09
@@ -61,6 +72,6 @@ AGENT QUICKSTART\uFF08\u7ED9 AI agent \u7684\u51E0\u884C\u8BF4\u660E\uFF09:
61
72
  contak login \u8BBE\u5907\u7801\u767B\u5F55\uFF1A\u7ED9\u51FA\u94FE\u63A5\u548C\u77ED\u7801\uFF0C\u8BA9\u7528\u6237\u5728\u6D4F\u89C8\u5668\u91CC\u786E\u8BA4
62
73
  contak skills install \u628A Agent Skill \u88C5\u8FDB ~/.claude/skills \u4E0E ~/.agents/skills
63
74
  contak config \u5F53\u524D profile\u3001API \u57FA\u5740\u3001\u914D\u7F6E\u76EE\u5F55
64
- `;function Ot(r={text:""}){let e=new E;return e.name("contak").description("Contak \u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u7ED9\u4EBA\u548C AI agent \u7528\u3002\u5F53\u524D\u63D0\u4F9B\u767B\u5F55\u4E0E\u81EA\u7701\u9762\uFF0C\u5F55\u97F3\u4E0E\u4EBA\u8109\u547D\u4EE4\u9646\u7EED\u52A0\u5165").version(y,"-v, --version","\u8F93\u51FA\u7248\u672C\u53F7").option("--format <format>","\u8F93\u51FA\u683C\u5F0F\uFF1Ajson | pretty | ndjson | table\uFF08\u975E TTY \u9ED8\u8BA4 json\uFF09").option("--json","\u7B49\u4EF7\u4E8E --format json").option("--profile <name>","\u4F7F\u7528\u6307\u5B9A profile\uFF08\u591A\u8D26\u53F7/\u591A\u73AF\u5883\uFF09").option("--base-url <url>","\u8986\u76D6 API \u57FA\u5740").option("--dry-run","\u5199\u64CD\u4F5C\u53EA\u6253\u5370\u5C06\u8981\u53D1\u9001\u7684\u8BF7\u6C42\uFF0C\u4E0D\u6267\u884C").option("-y, --yes","\u8DF3\u8FC7\u786E\u8BA4\uFF08\u5199\u64CD\u4F5C\u5FC5\u987B\u663E\u5F0F\u5E26\u4E0A\uFF09").option("-q, --quiet","\u4E0D\u8F93\u51FA\u8FDB\u5EA6\u63D0\u793A").option("--debug","\u628A\u6BCF\u4E2A\u8BF7\u6C42\u7684\u65B9\u6CD5\u4E0E URL \u6253\u5230 stderr").showHelpAfterError("\uFF08\u52A0 --help \u67E5\u770B\u7528\u6CD5\uFF09").showSuggestionAfterError(!0).addHelpText("after",yt).configureOutput({writeErr:t=>{r.text+=t}}).exitOverride(),ve(e),Pe(e),wt(e),e}function wt(r){for(let e of r.commands){if(!e.commands.length)continue;let t=()=>e.commands.map(n=>n.name()).join(" / ");e.allowExcessArguments(!0).action(async(...n)=>{let i=n[n.length-1],s=i.args[0];await g(i,async()=>{throw v(s?`contak ${e.name()} \u6CA1\u6709\u5B50\u547D\u4EE4 "${s}"`:`contak ${e.name()} \u9700\u8981\u6307\u5B9A\u5B50\u547D\u4EE4`,`\u53EF\u7528\uFF1A${t()}\uFF1B\u8BE6\u89C1 contak ${e.name()} --help`)})})}}async function bt(r){let e={text:""},t=Ot(e);try{await t.parseAsync(r)}catch(n){let i=n;if(i&&typeof i.code=="string"&&i.code.startsWith("commander.")){if(i.code==="commander.helpDisplayed"||i.code==="commander.version"||i.code==="commander.help"&&i.exitCode===0){process.exitCode=0;return}let s=ce(r);if(s==="pretty"||s==="table"){process.stderr.write(e.text),process.exitCode=3;return}let o=(i.message||e.text).replace(/^error:\s*/i,"").split(`
65
- `)[0].trim()||"\u53C2\u6570\u9519\u8BEF";process.exitCode=F(new p({type:"validation",message:o,hint:i.code==="commander.unknownCommand"?"\u7528 contak --help \u770B\u5168\u90E8\u547D\u4EE4\uFF0C\u6216 contak schema --json \u8BFB\u5B8C\u6574\u5951\u7EA6":"\u52A0 --help \u67E5\u770B\u8BE5\u547D\u4EE4\u7684\u7528\u6CD5"}),s);return}process.exitCode=F(n,ce(r))}}process.argv[1]&&import.meta.url===Ct(process.argv[1]).href&&bt(process.argv).catch(r=>{process.stderr.write(String(r?.stack||r)+`
66
- `),process.exit(1)});export{Ot as buildProgram,bt as main};
75
+ `;function Un(i={text:""}){let t=new N;return t.name("contak").description("Contak \u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u7ED9\u4EBA\u548C AI agent \u7528\u3002\u5F53\u524D\u63D0\u4F9B\u767B\u5F55\u4E0E\u81EA\u7701\u9762\uFF0C\u5F55\u97F3\u4E0E\u4EBA\u8109\u547D\u4EE4\u9646\u7EED\u52A0\u5165").version(S,"-v, --version","\u8F93\u51FA\u7248\u672C\u53F7").option("--format <format>","\u8F93\u51FA\u683C\u5F0F\uFF1Ajson | pretty | ndjson | table\uFF08\u975E TTY \u9ED8\u8BA4 json\uFF09").option("--json","\u7B49\u4EF7\u4E8E --format json").option("--profile <name>","\u4F7F\u7528\u6307\u5B9A profile\uFF08\u591A\u8D26\u53F7/\u591A\u73AF\u5883\uFF09").option("--base-url <url>","\u8986\u76D6 API \u57FA\u5740").option("--dry-run","\u5199\u64CD\u4F5C\u53EA\u6253\u5370\u5C06\u8981\u53D1\u9001\u7684\u8BF7\u6C42\uFF0C\u4E0D\u6267\u884C").option("-y, --yes","\u8DF3\u8FC7\u786E\u8BA4\uFF08\u5199\u64CD\u4F5C\u5FC5\u987B\u663E\u5F0F\u5E26\u4E0A\uFF09").option("-q, --quiet","\u4E0D\u8F93\u51FA\u8FDB\u5EA6\u63D0\u793A").option("--debug","\u628A\u6BCF\u4E2A\u8BF7\u6C42\u7684\u65B9\u6CD5\u4E0E URL \u6253\u5230 stderr").showHelpAfterError("\uFF08\u52A0 --help \u67E5\u770B\u7528\u6CD5\uFF09").showSuggestionAfterError(!0).addHelpText("after",Vn).configureOutput({writeErr:e=>{i.text+=e}}).exitOverride(),Wt(t),Bt(t),ee(t),ae(t),de(t),Jt(t),pe(t),Kn(t),t}function Kn(i){for(let t of i.commands){if(!t.commands.length)continue;let e=()=>t.commands.map(n=>n.name()).join(" / ");t.allowExcessArguments(!0).action(async(...n)=>{let r=n[n.length-1],o=r.args[0];await g(r,async()=>{throw p(o?`contak ${t.name()} \u6CA1\u6709\u5B50\u547D\u4EE4 "${o}"`:`contak ${t.name()} \u9700\u8981\u6307\u5B9A\u5B50\u547D\u4EE4`,`\u53EF\u7528\uFF1A${e()}\uFF1B\u8BE6\u89C1 contak ${t.name()} --help`)})})}}async function Ln(i){let t={text:""},e=Un(t);try{await e.parseAsync(i)}catch(n){let r=n;if(r&&typeof r.code=="string"&&r.code.startsWith("commander.")){if(r.code==="commander.helpDisplayed"||r.code==="commander.version"||r.code==="commander.help"&&r.exitCode===0){process.exitCode=0;return}let o=yt(i);if(o==="pretty"||o==="table"){process.stderr.write(t.text),process.exitCode=3;return}let s=(r.message||t.text).replace(/^error:\s*/i,"").split(`
76
+ `)[0].trim()||"\u53C2\u6570\u9519\u8BEF";process.exitCode=U(new m({type:"validation",message:s,hint:r.code==="commander.unknownCommand"?"\u7528 contak --help \u770B\u5168\u90E8\u547D\u4EE4\uFF0C\u6216 contak schema --json \u8BFB\u5B8C\u6574\u5951\u7EA6":"\u52A0 --help \u67E5\u770B\u8BE5\u547D\u4EE4\u7684\u7528\u6CD5"}),o);return}process.exitCode=U(n,yt(i))}}process.argv[1]&&import.meta.url===Mn(process.argv[1]).href&&Ln(process.argv).catch(i=>{process.stderr.write(String(i?.stack||i)+`
77
+ `),process.exit(1)});export{Un as buildProgram,Ln as main};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contak/cli",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Contak 命令行客户端,人和 AI agent 共用:设备码登录、给 agent 读的命令契约、随包附带 Agent Skill;非 TTY 默认 JSON",
5
5
  "keywords": [
6
6
  "contak",
@@ -44,7 +44,7 @@
44
44
  "dev": "tsx src/index.ts",
45
45
  "typecheck": "tsc -p tsconfig.json --noEmit",
46
46
  "test": "vitest run",
47
- "test:contract": "CONTAK_CONTRACT_TEST=1 vitest run test/contract",
47
+ "test:contract": "CONTAK_CONTRACT_TEST=1 vitest run test/unit/cli-contract.test.ts",
48
48
  "prepack": "npm run build"
49
49
  },
50
50
  "devDependencies": {
@@ -30,7 +30,8 @@ contak whoami # 当前登录态
30
30
  - 非 TTY 下自动用 JSON;`pretty` 是给人看的,不要解析它
31
31
 
32
32
  退出码:`0` 成功 / `2` 未登录 / `3` 参数错 / `4` 需要 `--yes` / `5` 被限流 /
33
- `7` 网络不通 / `8` 无权限 / `9` 找不到 / `11` 额度用尽 / `12` 状态冲突 / `1` 其他。
33
+ `6` 需要用户到其他界面完成操作 / `7` 网络不通 / `8` 无权限 / `9` 找不到 /
34
+ `11` 额度用尽 / `12` 状态冲突 / `1` 其他。
34
35
 
35
36
  `11` 和 `5` 要分开对待:`5` 等几秒重试就好,`11` 是额度用尽,重试多少次都没用,
36
37
  出口是让用户升级套餐。
@@ -60,13 +61,18 @@ contak login --device-code <code> # 用户确认后由你执行,完成登
60
61
 
61
62
  ## 上传录音前要先注册声纹
62
63
 
63
- Contak 靠声纹认出「哪一段是你说的」,所以本人声纹是上传的前置条件。没注册就上传会
64
- 拿到退出码 `12` `meeting.voiceprint_required`,这时候引导用户先跑:
64
+ Contak 靠声纹认出「哪一段是你说的」,所以本人声纹是上传的前置条件。CLI 不录制、
65
+ 不接收声纹文件。需要录入时,生成一次性 Session Transfer 链接:
65
66
 
66
67
  ```bash
67
- contak voiceprint enroll <一段你本人说话的音频>
68
+ contak open voiceprint # 只打印链接
69
+ contak open voiceprint --open # 明确要求时才打开浏览器
70
+ contak open voiceprint --wait # 等待网页完成录入
68
71
  ```
69
72
 
73
+ `contak meetings upload` 遇到 `meeting.voiceprint_required` 时会在 stderr 返回
74
+ `action_required` 和一次性链接,退出码为 `6`。此时还没有执行音频 PUT。
75
+
70
76
  ## 写操作
71
77
 
72
78
  任何会改服务端状态的命令,在非交互环境必须带 `--yes`。看到退出码 `4`:
@@ -90,13 +96,14 @@ contak voiceprint enroll <一段你本人说话的音频>
90
96
 
91
97
  ## 逃生舱
92
98
 
93
- 没有对应命令的能力可以直接打:
99
+ 原始 Capability 入口默认不注册。只在调试时显式开启:
94
100
 
95
101
  ```bash
96
- contak api <capability-id> --data '{"...":"..."}'
102
+ CONTAK_EXPERIMENTAL=1 contak api <capability-id> --input '{"...":"..."}'
97
103
  ```
98
104
 
99
- 它不做参数校验、没有风险分级、没有确认门槛。有对应命令时一律用命令。
105
+ 它会先读 Core OpenAPI,校验输入,并根据 `x-readonly` / `x-destructive`
106
+ 应用确认门槛。有对应正式命令时一律用正式命令。
100
107
 
101
108
  ## 环境
102
109
 
@@ -0,0 +1,34 @@
1
+ ---
2
+ name: contak-context-bootstrap
3
+ description: 把用户授权的 Codex 或 Claude Code 全局记忆在本地提炼为 Contak Context manifest,经脱敏、预览和用户确认后导入。
4
+ compatibility: Requires contak CLI 0.2.0 or newer
5
+ allowed-tools: Bash(contak context *)
6
+ ---
7
+
8
+ # Contak Context Bootstrap
9
+
10
+ 只处理用户明确授权的全局用户记忆。不读当前项目或其他项目的记忆,不扫描聊天、
11
+ 环境变量、代码仓库或客户资料。不持续监听文件。
12
+
13
+ 原始记忆只在本机阅读。上传的只能是跨项目仍成立的结构化事实:`profile`、
14
+ `preference` 或 `vocabulary`。不得把原文、文件路径、对话、token、Cookie、密码、
15
+ 连接串或项目专属事实放进 manifest。
16
+
17
+ 流程:
18
+
19
+ 1. 说明要读取的 provider 和全局来源,获得用户同意。
20
+ 2. 使用 provider 提供的全局记忆入口。如果无法确定边界,停止并请用户指定,
21
+ 不得递归扫描用户主目录。
22
+ 3. 在本地提炼 manifest v1;`source.scope` 必须是 `global`,并生成稳定的
23
+ `item_id`、`content_hash` 和整体 `revision_hash`。
24
+ 4. 用 stdin 预览,避免必须生成中间文件:
25
+
26
+ `contak context sync --manifest - --dry-run`
27
+
28
+ 5. 逐项向用户展示将新增或修改的内容。用户可以要求改写或删除任何一项。
29
+ 6. 只在用户明确同意后,再用同一 manifest 执行:
30
+
31
+ `contak context sync --manifest - --yes`
32
+
33
+ `--yes` 不能绕过秘密扫描。如果 CLI 拒绝某条,必须删除或手工改写,
34
+ 不得尝试绕过。`--prune` 会删除云端缺失项,必须单独列出并再次确认。