@contak/cli 0.1.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/LICENSE ADDED
@@ -0,0 +1,57 @@
1
+ Contak CLI — Proprietary Software License
2
+
3
+ Copyright (c) 2026 Contak Inc. All rights reserved.
4
+
5
+ 1. Grant of Licence
6
+ Contak Inc. ("Contak") grants you a personal, non-exclusive, non-transferable,
7
+ revocable licence to install and run this software (the "Software") for the sole
8
+ purpose of accessing the Contak service with an account you are authorised to use.
9
+
10
+ 2. Restrictions
11
+ Except to the extent the following restrictions are prohibited by applicable law,
12
+ you may not:
13
+ (a) redistribute, publish, sell, rent, lease, or sublicense the Software;
14
+ (b) modify, adapt, translate, or create derivative works of the Software;
15
+ (c) reverse engineer, decompile, or disassemble the Software;
16
+ (d) remove or alter any proprietary notices contained in the Software.
17
+
18
+ 3. Third-Party Components
19
+ The Software bundles open-source components, each governed by its own licence.
20
+ Those licences and their copyright notices are reproduced in
21
+ THIRD-PARTY-NOTICES.txt, which accompanies this distribution. Nothing in this
22
+ licence limits your rights under those third-party licences.
23
+
24
+ 4. Ownership
25
+ The Software is licensed, not sold. Contak retains all right, title, and interest
26
+ in and to the Software, including all intellectual property rights.
27
+
28
+ 5. Service Terms
29
+ Use of the Contak service through the Software is additionally governed by the
30
+ Contak Terms of Service at https://contak.ai/terms and the Privacy Policy at
31
+ https://contak.ai/privacy.
32
+
33
+ 6. Termination
34
+ This licence terminates automatically if you breach any of its terms. On
35
+ termination you must stop using the Software and remove all copies of it.
36
+
37
+ 7. No Warranty
38
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
40
+ FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
41
+
42
+ 8. Limitation of Liability
43
+ TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL CONTAK BE
44
+ LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF
45
+ CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE
46
+ SOFTWARE OR THE USE OF OR OTHER DEALINGS IN THE SOFTWARE.
47
+
48
+ Contact: support@contak.ai
49
+
50
+ ---
51
+
52
+ 以下中文摘要仅供理解,不构成许可条款;发生歧义时以上方英文文本为准。
53
+
54
+ Contak CLI 是 Contak Inc. 的专有软件,保留所有权利。你被授予的是一份可撤销的使用
55
+ 许可:可以安装并运行它来访问自己有权使用的 Contak 账号。不得再分发、转售、修改或
56
+ 逆向工程;内置的开源组件各自遵循其原有许可,见 THIRD-PARTY-NOTICES.txt。软件按
57
+ "现状"提供,不附带任何担保。
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # contak
2
+
3
+ Contak 的命令行客户端。给人用,也给 AI agent 用。
4
+
5
+ ```bash
6
+ npm install -g @contak/cli
7
+ contak login
8
+ ```
9
+
10
+ ## 它能做什么
11
+
12
+ Contak 记录**线下面对面**的对话:录音传上去,它转写、分离说话人、用声纹认出谁是谁,
13
+ 再把对话里出现的人沉淀成你的人脉。
14
+
15
+ ```bash
16
+ contak login # 设备码登录,密码不进终端
17
+ contak whoami # 当前登录态
18
+ contak skills install # 把 Agent Skill 装进 ~/.claude/skills
19
+ ```
20
+
21
+ ## 给 AI agent
22
+
23
+ ```bash
24
+ contak schema --json # 全部命令、参数、退出码、输出契约
25
+ contak skills read # 内置说明书,版本永远跟 CLI 一致
26
+ ```
27
+
28
+ 非 TTY 下默认输出 JSON:成功 stdout `{"ok":true,"data":...}`,失败 stderr
29
+ `{"ok":false,"error":{...}}` 加非零退出码。判成功只看 `ok` 或退出码。
30
+
31
+ ## 许可
32
+
33
+ 见 LICENSE。
@@ -0,0 +1,28 @@
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.
3
+
4
+ ========================================================================
5
+ commander 15.0.0 (MIT) git+https://github.com/tj/commander.js.git
6
+ ========================================================================
7
+ (The MIT License)
8
+
9
+ Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining
12
+ a copy of this software and associated documentation files (the
13
+ 'Software'), to deal in the Software without restriction, including
14
+ without limitation the rights to use, copy, modify, merge, publish,
15
+ distribute, sublicense, and/or sell copies of the Software, and to
16
+ permit persons to whom the Software is furnished to do so, subject to
17
+ the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be
20
+ included in all copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
23
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
25
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
26
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
27
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
28
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/bin/contak.js ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ // 旧版 Node 会在解析 dist 时直接报语法错误,这里先给一句人话。
3
+ // 这段必须待在 bin 而不是 dist 里——dist 用的语法本身就要新版 Node 才解析得动。
4
+ const major = Number(process.versions.node.split('.')[0])
5
+ if (major < 22) {
6
+ process.stderr.write(`contak 需要 Node.js >= 22,当前是 ${process.versions.node}\n`)
7
+ process.exit(1)
8
+ }
9
+
10
+ const { main } = await import('../dist/index.js')
11
+
12
+ main(process.argv).catch((err) => {
13
+ // 已知错误都在 main 内部处理并设置了退出码;这里只兜底未知崩溃。
14
+ // 连崩溃都吐合法信封,agent 任何情况下都能 JSON.parse stderr。
15
+ process.stderr.write(
16
+ JSON.stringify({ ok: false, error: { type: 'internal', message: String(err?.stack || err) } }) + '\n',
17
+ )
18
+ process.exit(1)
19
+ })
package/dist/index.js ADDED
@@ -0,0 +1,66 @@
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}
6
+ - a short flag is a single dash and a single character
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}
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?`
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
18
+ - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
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}
21
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
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(`
43
+ \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=`
51
+ AGENT QUICKSTART\uFF08\u7ED9 AI agent \u7684\u51E0\u884C\u8BF4\u660E\uFF09:
52
+ contak schema --json \u4E00\u6B21\u62FF\u5230\u5168\u90E8\u547D\u4EE4/\u53C2\u6570/\u8F93\u51FA\u5951\u7EA6/\u9000\u51FA\u7801
53
+ contak skills read \u8BFB\u5185\u7F6E SKILL.md\uFF08\u6982\u5FF5\u3001\u7EA6\u675F\u3001\u5E38\u89C1\u4EFB\u52A1\uFF09
54
+ contak whoami \u5F53\u524D\u767B\u5F55\u6001\uFF1B\u672A\u767B\u5F55\u4E5F\u8FD4\u56DE 0\uFF0C\u770B data.logged_in
55
+ \u975E TTY \u4E0B\u9ED8\u8BA4\u8F93\u51FA JSON\uFF1Astdout {"ok":true,"data":...}\uFF1B\u5931\u8D25\u8D70 stderr {"ok":false,"error":{...}} + \u975E\u96F6\u9000\u51FA\u7801\u3002
56
+ \u5224\u6210\u529F\u53EA\u770B ok \u6216\u9000\u51FA\u7801\uFF0C\u4E0D\u8981\u770B data \u91CC\u7684\u5B57\u6BB5\u3002
57
+ \u5199\u64CD\u4F5C\u5728\u975E\u4EA4\u4E92\u73AF\u5883\u5FC5\u987B --yes\uFF0C\u4E14\u5148\u628A\u8981\u505A\u7684\u4E8B\u8BB2\u7ED9\u7528\u6237\u542C\u3001\u62FF\u5230\u540C\u610F\u518D\u52A0\u3002
58
+ \u9000\u51FA\u7801 2 = \u672A\u767B\u5F55\uFF1A\u628A error.hint \u539F\u6837\u8F6C\u8FBE\u7ED9\u7528\u6237\uFF0C\u767B\u5F55\u662F\u4EBA\u7684\u52A8\u4F5C\uFF0C\u4E0D\u8981\u66FF\u7528\u6237\u731C\u3002
59
+
60
+ \u5E38\u7528:
61
+ 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
+ contak skills install \u628A Agent Skill \u88C5\u8FDB ~/.claude/skills \u4E0E ~/.agents/skills
63
+ 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};
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@contak/cli",
3
+ "version": "0.1.0",
4
+ "description": "Contak 命令行客户端,人和 AI agent 共用:设备码登录、给 agent 读的命令契约、随包附带 Agent Skill;非 TTY 默认 JSON",
5
+ "keywords": [
6
+ "contak",
7
+ "cli",
8
+ "command-line",
9
+ "ai-agent",
10
+ "agent-skills",
11
+ "claude-code",
12
+ "codex",
13
+ "meeting-notes",
14
+ "transcription",
15
+ "networking",
16
+ "crm"
17
+ ],
18
+ "homepage": "https://contak.ai",
19
+ "bugs": {
20
+ "email": "support@contak.ai"
21
+ },
22
+ "author": "Contak",
23
+ "license": "SEE LICENSE IN LICENSE",
24
+ "type": "module",
25
+ "bin": {
26
+ "contak": "bin/contak.js"
27
+ },
28
+ "files": [
29
+ "bin",
30
+ "dist/index.js",
31
+ "skills",
32
+ "README.md",
33
+ "LICENSE",
34
+ "THIRD-PARTY-NOTICES.txt"
35
+ ],
36
+ "engines": {
37
+ "node": ">=22"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "node scripts/build.mjs",
44
+ "dev": "tsx src/index.ts",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit",
46
+ "test": "vitest run",
47
+ "test:contract": "CONTAK_CONTRACT_TEST=1 vitest run test/contract",
48
+ "prepack": "npm run build"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^26.2.0",
52
+ "commander": "^15.0.0",
53
+ "esbuild": "^0.28.2",
54
+ "tsx": "^4.23.12",
55
+ "typescript": "^5.9.3",
56
+ "vitest": "^4.1.11"
57
+ },
58
+ "optionalDependencies": {
59
+ "@napi-rs/keyring": "^1.3.0"
60
+ }
61
+ }
@@ -0,0 +1,106 @@
1
+ ---
2
+ name: contak
3
+ description: 用 contak 命令行操作 Contak(线下见面的 AI 会议记忆与人脉工具):上传录音跑转写与分析、导出逐字稿、标注说话人、查人脉、参加线下活动的现场匹配。触发词:Contak、contak.ai、会议录音、逐字稿导出、说话人标注、人脉、现场匹配。Use when the user mentions Contak / contak.ai, wants to transcribe an in-person meeting recording, export a transcript, or look up people they have met.
4
+ license: SEE LICENSE IN LICENSE
5
+ compatibility: Requires the contak CLI on PATH (npm i -g @contak/cli, Node >= 22) and network access to api.contak.ai
6
+ metadata:
7
+ help: "contak --help"
8
+ schema: "contak schema --json"
9
+ allowed-tools: Bash(contak *)
10
+ ---
11
+
12
+ # contak
13
+
14
+ Contak 记录**线下面对面**的对话:录音传上去,它转写、分离说话人、用声纹认出谁是谁,
15
+ 再把对话里出现的人沉淀成你的人脉。它不是会议室视频会议工具,主场景是当面聊天。
16
+
17
+ ## 先读这两条
18
+
19
+ ```bash
20
+ contak schema --json # 全部命令、参数、退出码、输出契约
21
+ contak whoami # 当前登录态
22
+ ```
23
+
24
+ ## 输出契约
25
+
26
+ - 成功:stdout 是 `{"ok":true,"data":...}`,退出码 0
27
+ - 失败:stderr 是 `{"ok":false,"error":{type,code,message,hint}}`,退出码非 0
28
+ - **判成功只看 `ok` 或退出码**,不要看 `data` 里的任何字段
29
+ - stdout 只有数据,进度与提示都在 stderr——放心直接管道给 `jq`
30
+ - 非 TTY 下自动用 JSON;`pretty` 是给人看的,不要解析它
31
+
32
+ 退出码:`0` 成功 / `2` 未登录 / `3` 参数错 / `4` 需要 `--yes` / `5` 被限流 /
33
+ `7` 网络不通 / `8` 无权限 / `9` 找不到 / `11` 额度用尽 / `12` 状态冲突 / `1` 其他。
34
+
35
+ `11` 和 `5` 要分开对待:`5` 等几秒重试就好,`11` 是额度用尽,重试多少次都没用,
36
+ 出口是让用户升级套餐。
37
+
38
+ ## 登录是人的动作
39
+
40
+ ```bash
41
+ contak login # 返回一个链接和短码
42
+ contak login --device-code <code> # 用户确认后由你执行,完成登录
43
+ ```
44
+
45
+ 登录走设备码,**密码永远不进终端**。流程分两步,这是刻意的:
46
+
47
+ 1. 你执行 `contak login`,拿到 `verification_url` 与 `user_code`
48
+ 2. **把链接原样发给用户,作为你这一轮的最终回复,然后结束这一轮**
49
+ 3. 用户回来说确认好了,你再执行 `contak login --device-code <上一步的 device_code>`
50
+
51
+ 为什么不能一步做完:多数 agent 宿主只把「本轮最终消息」投递给用户,命令的中间输出
52
+ 人根本看不见。如果你原地阻塞轮询,用户永远看不到链接,命令必然超时。
53
+
54
+ 两条硬规则:
55
+
56
+ - **URL 是不可修改的字符串**。不要做 URL 编解码、不要加标点、不要重拼 query。
57
+ - **不要缓存 device_code**。每次需要登录都重新执行 `contak login` 生成新的。
58
+
59
+ 遇到退出码 `2`,把 `error.hint` 原样转达给用户,不要替用户猜验证码或密码。
60
+
61
+ ## 上传录音前要先注册声纹
62
+
63
+ Contak 靠声纹认出「哪一段是你说的」,所以本人声纹是上传的前置条件。没注册就上传会
64
+ 拿到退出码 `12` 和 `meeting.voiceprint_required`,这时候引导用户先跑:
65
+
66
+ ```bash
67
+ contak voiceprint enroll <一段你本人说话的音频>
68
+ ```
69
+
70
+ ## 写操作
71
+
72
+ 任何会改服务端状态的命令,在非交互环境必须带 `--yes`。看到退出码 `4`:
73
+
74
+ 1. 把将要执行的操作、涉及的数据讲给用户听
75
+ 2. 得到明确同意后,**在原命令末尾追加 `--yes` 重新执行**
76
+ 3. 用参数数组的形式重试,不要用 `sh -c` 拼字符串——用户的参数里可能有 shell 元字符
77
+
78
+ 不要看到退出码 `4` 就自动加 `--yes` 重试,那等于把这道闸拆了。
79
+
80
+ 想先让用户看看会发出什么请求,加 `--dry-run`:它不触发确认门槛,会打印完整请求
81
+ (Authorization 已脱敏)。注意 dry-run 只校验请求形状,不代表真跑一定成功。
82
+
83
+ ## 现场活动
84
+
85
+ 线下活动里,参会者把自我介绍和录音传上来,Contak 给每个人算出「今天最该认识的人」。
86
+
87
+ 发布自我介绍前,CLI 会打印一段告知文案并要求确认——那段话说明了「同一场活动里其他
88
+ 参会者会看到你写的内容」。**必须把它原样展示给用户并拿到同意**,不要自己改写措辞、
89
+ 也不要替用户跳过。活动结束后这些内容自动对他人不可见。
90
+
91
+ ## 逃生舱
92
+
93
+ 没有对应命令的能力可以直接打:
94
+
95
+ ```bash
96
+ contak api <capability-id> --data '{"...":"..."}'
97
+ ```
98
+
99
+ 它不做参数校验、没有风险分级、没有确认门槛。有对应命令时一律用命令。
100
+
101
+ ## 环境
102
+
103
+ - `CONTAK_BASE_URL` 换环境,`CONTAK_PROFILE` 换账号
104
+ - `CONTAK_ACCESS_TOKEN` / `CONTAK_REFRESH_TOKEN` 可直接注入凭据(只读,不落盘),适合 CI
105
+ - `CONTAK_NO_INPUT=1` 一律不提问
106
+ - 在 Codex 沙箱里默认断网,会直接报错并给出放开网络的配置方法,不会干等超时