@newbeebox/newbeebox-debug-bridge 0.1.1
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 +56 -0
- package/dist/cli.cjs +34 -0
- package/package.json +33 -0
package/README.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# ndb —— NewBeeDebugBridge 工程师端 CLI
|
|
2
|
+
|
|
3
|
+
远程运维客户机(截图 / 执行命令 / 读文件),默认人类可读,`-o json` / `-c` 供脚本与 LLM Agent 解析。
|
|
4
|
+
|
|
5
|
+
## 安装
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i -g @newbeebox/newbeebox-debug-bridge # 或 npx @newbeebox/newbeebox-debug-bridge ...
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## 快速上手
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
ndb login --token ndbk_xxx # token 由服务端管理面板签发,落 ~/.ndb/config.json(600)
|
|
15
|
+
ndb status 81268383 # 查客户机在线/授权
|
|
16
|
+
ndb connect 81268383 # 校验可达
|
|
17
|
+
ndb exec 81268383 -- ipconfig /all
|
|
18
|
+
ndb ls 81268383 C:\logs
|
|
19
|
+
ndb get 81268383 C:\logs\app.log --out app.log # >2MB 自动走资产桶异步下载
|
|
20
|
+
ndb screenshot 81268383 --window "*.txt" --out shot.png
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## 全局选项
|
|
24
|
+
|
|
25
|
+
| 选项 | 说明 |
|
|
26
|
+
|------|------|
|
|
27
|
+
| `--base-url <url>` | 服务端地址(或 env `NDB_BASE_URL`,默认 `http://127.0.0.1:8080`) |
|
|
28
|
+
| `--token <token>` | 覆盖 token(或 env `NDB_TOKEN` / `~/.ndb/config.json`) |
|
|
29
|
+
| `-o, --output <fmt>` | `text`(默认) \| `json` |
|
|
30
|
+
| `-c, --compact` | 紧凑单行 JSON(隐含 `-o json`) |
|
|
31
|
+
|
|
32
|
+
## 给 LLM Agent
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
ndb schema -c # 导出全部命令的 function-calling 友好 schema
|
|
36
|
+
ndb <cmd> ... -c # 结构化调用,输出 { ok, data? , error? }
|
|
37
|
+
```
|
|
38
|
+
`-o json` 输出**始终**为 `{ ok: boolean, data?, error?: {code,message} }`,退出码与 `ok` 对应。字段只增不改义。
|
|
39
|
+
|
|
40
|
+
## 开发 / 测试
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
npm install
|
|
44
|
+
npm run typecheck
|
|
45
|
+
npm run build
|
|
46
|
+
|
|
47
|
+
# 全链路 e2e(需先构建 Rust 二进制):
|
|
48
|
+
# cargo build -p ndb-server -p newbee-debug-bridge
|
|
49
|
+
npm test
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`npm test` 会拉起真实 server(内存后端) + 真实 desktop agent + 本 CLI,覆盖
|
|
53
|
+
login/status/connect/exec(放行+黑名单拦截)/ls/get(内联+资产)/schema/未登录保护。
|
|
54
|
+
|
|
55
|
+
命令定义是**单一数据结构**(`src/commands.ts`),一处定义同时驱动 human help、
|
|
56
|
+
JSON 输出与 `ndb schema`。协议契约见 `../docs/02-PROTOCOL.md`。
|
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";var Oe=Object.create;var J=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var w=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Ee=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of we(e))!Ae.call(r,i)&&i!==t&&J(r,i,{get:()=>e[i],enumerable:!(n=ye(e,i))||n.enumerable});return r};var xe=(r,e,t)=>(t=r!=null?Oe(Ce(r)):{},Ee(e||!r||!r.__esModule?J(t,"default",{value:r,enumerable:!0}):t,r));var A=w(H=>{var x=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}},S=class extends x{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};H.CommanderError=x;H.InvalidArgumentError=S});var $=w(N=>{var{InvalidArgumentError:$e}=A(),V=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.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}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 $e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ke(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}N.Argument=V;N.humanReadableArgName=ke});var P=w(K=>{var{humanReadableArgName:ve}=$(),T=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}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=>ve(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,t.subcommandTerm(i).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,i)=>Math.max(n,t.optionTerm(i).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,t.optionTerm(i).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,i)=>Math.max(n,t.argumentTerm(i).length),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=[];return 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?`${e.description} (${t.join(", ")})`: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}formatHelp(e,t){let n=t.padWidth(e,t),i=t.helpWidth||80,s=2,o=2;function u(m,O){if(O){let v=`${m.padEnd(n+o)}${O}`;return t.wrap(v,i-s,n+o)}return m}function a(m){return m.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${t.commandUsage(e)}`,""],c=t.commandDescription(e);c.length>0&&(l=l.concat([t.wrap(c,i,0),""]));let h=t.visibleArguments(e).map(m=>u(t.argumentTerm(m),t.argumentDescription(m)));h.length>0&&(l=l.concat(["Arguments:",a(h),""]));let f=t.visibleOptions(e).map(m=>u(t.optionTerm(m),t.optionDescription(m)));if(f.length>0&&(l=l.concat(["Options:",a(f),""])),this.showGlobalOptions){let m=t.visibleGlobalOptions(e).map(O=>u(t.optionTerm(O),t.optionDescription(O)));m.length>0&&(l=l.concat(["Global Options:",a(m),""]))}let y=t.visibleCommands(e).map(m=>u(t.subcommandTerm(m),t.subcommandDescription(m)));return y.length>0&&(l=l.concat(["Commands:",a(y),""])),l.join(`
|
|
4
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,i=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${s}]+`);if(e.match(o))return e;let u=t-n;if(u<i)return e;let a=e.slice(0,n),l=e.slice(n).replace(`\r
|
|
5
|
+
`,`
|
|
6
|
+
`),c=" ".repeat(n),f="\\s\u200B",y=new RegExp(`
|
|
7
|
+
|.{1,${u-1}}([${f}]|$)|[^${f}]+?([${f}]|$)`,"g"),m=l.match(y)||[];return a+m.map((O,v)=>O===`
|
|
8
|
+
`?"":(v>0?c:"")+O.trimEnd()).join(`
|
|
9
|
+
`)}};K.Help=T});var j=w(I=>{var{InvalidArgumentError:Se}=A(),D=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=Ve(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}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}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Se(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return He(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},q=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 He(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ve(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}I.Option=D;I.DualOptions=q});var X=w(Q=>{function Ne(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=1;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 Te(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 u=Ne(r,o),a=Math.max(r.length,o.length);(a-u)/a>s&&(u<i?(i=u,n=[o]):u===i&&n.push(o))}),n.sort((o,u)=>o.localeCompare(u)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
10
|
+
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}Q.suggestSimilar=Te});var ne=w(te=>{var Pe=require("node:events").EventEmitter,F=require("node:child_process"),b=require("node:path"),R=require("node:fs"),d=require("node:process"),{Argument:De,humanReadableArgName:qe}=$(),{CommanderError:M}=A(),{Help:Ie}=P(),{Option:Y,DualOptions:je}=j(),{suggestSimilar:Z}=X(),U=class r extends Pe{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,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._outputConfiguration={writeOut:t=>d.stdout.write(t),writeErr:t=>d.stderr.write(t),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}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,u]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return i&&(a.description(i),a._executableHandler=!0),s.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(s.noHelp||s.hidden),a._executableFile=s.executableFile||null,u&&a.arguments(u),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),i?this:a}createCommand(e){return new r(e)}createHelp(){return Object.assign(new Ie,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(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
|
|
12
|
+
- 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 De(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&&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,this;e=e??"help [command]";let[,n,i]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),i&&o.arguments(i),s&&o.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=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}'.
|
|
13
|
+
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 M(e,t,n)),d.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 Y(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}'
|
|
14
|
+
- already used by option '${t.flags}'`)}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.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(s,o,u)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let a=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,a,o):s!==null&&e.variadic&&(s=e._concatValue(s,a)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,u)};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 Y)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 u=i;i=(a,l)=>{let c=u.exec(a);return c?c[0]:l},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){d.versions?.electron&&(t.from="electron");let i=d.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=d.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":d.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){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(c,h){let f=b.resolve(c,h);if(R.existsSync(f))return f;if(i.includes(b.extname(h)))return;let y=i.find(m=>R.existsSync(`${f}${m}`));if(y)return`${f}${y}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,u=this._executableDir||"";if(this._scriptPath){let c;try{c=R.realpathSync(this._scriptPath)}catch{c=this._scriptPath}u=b.resolve(b.dirname(c),u)}if(u){let c=s(u,o);if(!c&&!e._executableFile&&this._scriptPath){let h=b.basename(this._scriptPath,b.extname(this._scriptPath));h!==this._name&&(c=s(u,`${h}-${e._name}`))}o=c||o}n=i.includes(b.extname(o));let a;d.platform!=="win32"?n?(t.unshift(o),t=ee(d.execArgv).concat(t),a=F.spawn(d.argv[0],t,{stdio:"inherit"})):a=F.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=ee(d.execArgv).concat(t),a=F.spawn(d.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{d.on(h,()=>{a.killed===!1&&a.exitCode===null&&a.kill(h)})});let l=this._exitCallback;a.on("close",c=>{c=c??1,l?l(new M(c,"commander.executeSubCommandAsync","(close)")):d.exit(c)}),a.on("error",c=>{if(c.code==="ENOENT"){let h=u?`searched for local subcommand relative to directory '${u}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",f=`'${o}' does not exist
|
|
15
|
+
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
+
- ${h}`;throw new Error(f)}else if(c.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)d.exit(1);else{let h=new M(1,"commander.executeSubCommandAsync","(error)");h.nestedError=c,l(h)}}),this.runningCommand=a}_dispatchSubcommand(e,t,n){let i=this._findCommand(e);i||this.help({error:!0});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 u=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,i,s,u)}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,u)=>e(n,u,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&&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&&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,s=e.slice();function o(a){return a.length>1&&a[0]==="-"}let u=null;for(;s.length;){let a=s.shift();if(a==="--"){i===n&&i.push(a),i.push(...s);break}if(u&&!o(a)){this.emit(`option:${u.name()}`,a);continue}if(u=null,o(a)){let l=this._findOption(a);if(l){if(l.required){let c=s.shift();c===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,c)}else if(l.optional){let c=null;s.length>0&&!o(s[0])&&(c=s.shift()),this.emit(`option:${l.name()}`,c)}else this.emit(`option:${l.name()}`);u=l.variadic?l:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let l=this._findOption(`-${a[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,a.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let l=a.indexOf("="),c=this._findOption(a.slice(0,l));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,a.slice(l+1));continue}}if(o(a)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(a)){t.push(a),s.length>0&&n.push(...s);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){n.push(a),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){i.push(a),s.length>0&&i.push(...s);break}i.push(a)}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}
|
|
18
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
+
`),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 d.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()}`,d.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new je(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 u=o.attributeName(),a=this.getOptionValue(u),l=this.options.find(h=>h.negate&&u===h.attributeName()),c=this.options.find(h=>!h.negate&&u===h.attributeName());return l&&(l.presetArg===void 0&&a===!1||l.presetArg!==void 0&&a===l.presetArg)?l:c||o},i=o=>{let u=n(o),a=u.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${u.envVar}'`:`option '${u.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(u=>u.long).map(u=>u.long);i=i.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=Z(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",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(s,{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=Z(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}
|
|
21
|
+
`),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=>qe(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)}nameFromFilename(e){return this._name=b.basename(e,b.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=i=>this._outputConfiguration.writeErr(i):n=i=>this._outputConfiguration.writeOut(i),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let i=this.helpInformation(n);if(t&&(i=t(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=d.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.
|
|
22
|
+
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}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ee(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})}te.Command=U});var oe=w(g=>{var{Argument:ie}=$(),{Command:B}=ne(),{CommanderError:Fe,InvalidArgumentError:se}=A(),{Help:Re}=P(),{Option:re}=j();g.program=new B;g.createCommand=r=>new B(r);g.createOption=(r,e)=>new re(r,e);g.createArgument=(r,e)=>new ie(r,e);g.Command=B;g.Option=re;g.Argument=ie;g.Help=Re;g.CommanderError=Fe;g.InvalidArgumentError=se;g.InvalidOptionArgumentError=se});var ae=xe(oe(),1),{program:ut,createCommand:lt,createArgument:ct,createOption:ht,CommanderError:dt,InvalidArgumentError:mt,InvalidOptionArgumentError:pt,Command:ue,Argument:ft,Option:gt,Help:_t}=ae.default;var G=require("node:fs");function le(r){let e=r.replace(/\/+$/,"");return e.startsWith("wss://")?e="https://"+e.slice(6):e.startsWith("ws://")?e="http://"+e.slice(5):!e.startsWith("http://")&&!e.startsWith("https://")&&(e="http://"+e),e}var Me=35e3,Ue=300,Be=3e4,We=30*60*1e3,Le=1e4,Ge=r=>new Promise(e=>setTimeout(e,r)),p=class extends Error{code;constructor(e){super(e.message),this.code=e.code}},E=class r{httpBase;token;constructor(e){this.httpBase=le(e)}static async open(e){return new r(e)}close(){}async request(e,t,n){let i=this.httpBase+t,s={};this.token&&(s.authorization=`Bearer ${this.token}`),n!==void 0&&(s["content-type"]="application/json");let o;try{o=await fetch(i,{method:e,headers:s,body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(Me)})}catch(l){throw new p({code:"TIMEOUT",message:`\u8BF7\u6C42\u5931\u8D25 ${i}: ${l.message}`})}let u=await o.text(),a;if(u)try{a=JSON.parse(u)}catch{}if(!o.ok){let l=a?.error;throw l&&typeof l.code=="string"?new p({code:l.code,message:l.message??`HTTP ${o.status}`}):new p({code:"INTERNAL",message:`HTTP ${o.status}: ${u||o.statusText}`})}return a}async login(e,t){return this.token=e,await this.request("GET","/api/whoami")}async connect(e){return this.request("GET",`/api/connect/${encodeURIComponent(e)}`)}async status(e){return this.request("GET",`/api/status/${encodeURIComponent(e)}`)}async exec(e,t,n,i){let o=(await this.request("POST","/api/exec",{code:e,cmd:t,args:n,timeout_ms:i}))?.job_id;if(!o)throw new p({code:"INTERNAL",message:"exec \u672A\u8FD4\u56DE job_id"});let u=Math.min((i??15e3)+Be,We),a=Date.now()+u+Le;for(;;){let l=await this.request("GET",`/api/jobs/${encodeURIComponent(o)}`);if(l?.status==="done")return l.result;if(l?.status==="error")throw new p({code:"AGENT_ERROR",message:l.error??"exec \u5931\u8D25"});if(Date.now()>a)throw new p({code:"TIMEOUT",message:"exec \u7ED3\u679C\u8F6E\u8BE2\u8D85\u65F6"});await Ge(Ue)}}async listDir(e,t){return this.request("POST","/api/list_dir",{code:e,path:t})}async readFile(e,t,n){let i=await this.request("POST","/api/read_file",{code:e,path:t,max_bytes:n});return i?.mode==="asset"?{kind:"asset",url:i.url,bytes:i.bytes,sha256:i.sha256}:{kind:"inline",bytes:Buffer.from(i?.data??"","base64"),total:i?.bytes??0}}async screenshot(e,t){let n=await this.request("POST","/api/screenshot",{code:e,...t});return n?.mode==="asset"?{kind:"asset",url:n.url,bytes:n.bytes,w:n.w,h:n.h}:{kind:"inline",bytes:Buffer.from(n?.data??"","base64"),total:n?.bytes??0}}async download(e){let t=e.startsWith("http")?e:this.httpBase+e,n=await fetch(t);if(!n.ok)throw new Error(`\u4E0B\u8F7D\u5931\u8D25 HTTP ${n.status}: ${t}`);return Buffer.from(await n.arrayBuffer())}};var ce=require("node:os"),W=require("node:path"),_=require("node:fs"),ze="http://127.0.0.1:8080";function he(){return(0,W.join)((0,ce.homedir)(),".ndb")}function k(){return(0,W.join)(he(),"config.json")}function de(){try{return JSON.parse((0,_.readFileSync)(k(),"utf8"))}catch{return{}}}function L(r){(0,_.mkdirSync)(he(),{recursive:!0}),(0,_.writeFileSync)(k(),JSON.stringify(r,null,2),{encoding:"utf8",mode:384});try{(0,_.chmodSync)(k(),384)}catch{}}function me(){let r=de();return r.token===void 0?!1:(delete r.token,L(r),!0)}function pe(){return k()}function fe(r){let e=de(),t=r.baseUrl||process.env.NDB_BASE_URL||e.base_url||ze,n=r.token||process.env.NDB_TOKEN||e.token;return{baseUrl:t,token:n}}var _e=r=>`ndb/${r.version}`;async function C(r,e){if(!r.token)throw new p({code:"UNAUTHORIZED",message:"\u672A\u767B\u5F55\uFF0C\u8BF7\u5148\u6267\u884C\uFF1Andb login --token <token>"});let t=await E.open(r.baseUrl);try{let n=await t.login(r.token,_e(r));return await e(t,n)}finally{t.close()}}function ge(r){return Object.entries(r).map(([e,t])=>`${e.padEnd(14)} ${t}`).join(`
|
|
24
|
+
`)}var z=[{name:"login",summary:"\u4FDD\u5B58 token \u5230 ~/.ndb/config.json \u5E76\u6821\u9A8C\u8EAB\u4EFD",description:"token \u7531\u670D\u52A1\u7AEF\u7BA1\u7406\u9762\u677F\u9884\u5148\u7B7E\u53D1\u3002\u6821\u9A8C\u901A\u8FC7\u540E\u843D\u672C\u5730\u914D\u7F6E\uFF08\u6743\u9650 600\uFF09\u3002",args:[],options:[{flag:"--token <token>",name:"token",type:"string",desc:"\u8981\u4FDD\u5B58\u7684 token\uFF08\u4E5F\u53EF\u7528\u5168\u5C40 --token\uFF09"}],auth:"none",returns:"{ saved, uid, username }",async handler(r,e,t){let n=t.token||r.token;if(!n)throw new p({code:"BAD_REQUEST",message:"\u7F3A\u5C11 token\uFF1Andb login --token <token>"});let i=await E.open(r.baseUrl),s;try{s=await i.login(n,_e(r))}finally{i.close()}return L({base_url:r.baseUrl,token:n}),{saved:pe(),uid:s.uid,username:s.username}},render:r=>`\u5DF2\u767B\u5F55 ${r.username} (uid=${r.uid})
|
|
25
|
+
\u914D\u7F6E\u5DF2\u4FDD\u5B58\uFF1A${r.saved}`},{name:"logout",summary:"\u6E05\u9664\u672C\u5730\u4FDD\u5B58\u7684 token",args:[],options:[],auth:"none",returns:"{ cleared }",async handler(){return{cleared:me()}},render:r=>r.cleared?"\u5DF2\u6E05\u9664\u672C\u5730 token":"\u672C\u5730\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684 token"},{name:"whoami",summary:"\u663E\u793A\u5F53\u524D\u8EAB\u4EFD\uFF08uid/username\uFF09",args:[],options:[],auth:"token",returns:"{ uid, username, session_expires }",async handler(r){return C(r,async(e,t)=>({uid:t.uid,username:t.username,session_expires:t.session_expires}))},render:r=>ge(r)},{name:"status",summary:"\u67E5\u5BA2\u6237\u673A\u5728\u7EBF/\u6388\u6743\u72B6\u6001",args:[{name:"code",required:!0,desc:"\u8FDC\u7A0B\u7801"}],options:[],auth:"token",returns:"{ online, authorized, last_seen }",async handler(r,e){return C(r,t=>t.status(e[0]))},render:r=>ge(r)},{name:"connect",summary:"\u6821\u9A8C\u4F1A\u8BDD\u53EF\u8FBE\u5E76\u8FD4\u56DE\u5BA2\u6237\u673A\u4FE1\u606F",description:"\u767B\u5F55\u540E\u8C03\u7528\uFF1B\u8FD4\u56DE\u76EE\u6807 online/authorized/host/os\u3002exec \u7B49\u9AD8\u5371\u64CD\u4F5C\u8981\u6C42 authorized=true\u3002",args:[{name:"code",required:!0,desc:"\u8FDC\u7A0B\u7801"}],options:[],auth:"token",returns:"{ ok, online, authorized, host, os }",async handler(r,e){return C(r,t=>t.connect(e[0]))},render:r=>`${r.host} (${r.os}) online=${r.online} authorized=${r.authorized}`+(r.online&&r.authorized?`
|
|
26
|
+
\u53EF\u6267\u884C\u8FDC\u7A0B\u64CD\u4F5C\u3002`:`
|
|
27
|
+
\u76EE\u6807\u672A\u5728\u7EBF\u6216\u672A\u6388\u6743\uFF0C\u6682\u4E0D\u53EF\u64CD\u4F5C\u3002`)},{name:"exec",summary:"\u5728\u6307\u5B9A\u5BA2\u6237\u673A\u6267\u884C\u4E00\u6761\u547D\u4EE4",description:"\u53D7\u670D\u52A1\u7AEF\u547D\u4EE4\u9ED1\u767D\u540D\u5355\u7EA6\u675F\uFF1B\u88AB\u62D2\u56DE FORBIDDEN\u3002\u7528 -- \u5206\u9694\u547D\u4EE4\uFF0C\u907F\u514D\u53C2\u6570\u88AB\u5F53\u4F5C\u9009\u9879\u3002",args:[{name:"code",required:!0,desc:"\u8FDC\u7A0B\u7801"},{name:"cmd",required:!0,variadic:!0,desc:"\u547D\u4EE4\u4E0E\u53C2\u6570\uFF0C\u5982 -- ipconfig /all"}],options:[{flag:"--timeout <ms>",name:"timeout",type:"number",desc:"\u6267\u884C\u8D85\u65F6(\u6BEB\u79D2)",default:15e3}],auth:"token+authorized",returns:"{ exit_code, stdout, stderr, duration_ms, truncated }",async handler(r,e,t){let n=e[0],i=e.slice(1);if(i.length===0)throw new p({code:"BAD_REQUEST",message:"\u7F3A\u5C11\u547D\u4EE4\uFF1Andb exec <code> -- <cmd...>"});let s=t.timeout!=null?Number(t.timeout):void 0;return C(r,o=>o.exec(n,i[0],i.slice(1),s))},render:r=>{let e=`exit=${r.exit_code} (${r.duration_ms}ms)${r.truncated?" [truncated]":""}`,t=r.stdout?`
|
|
28
|
+
${r.stdout.replace(/\n$/,"")}`:"",n=r.stderr?`
|
|
29
|
+
[stderr]
|
|
30
|
+
${r.stderr.replace(/\n$/,"")}`:"";return e+t+n}},{name:"ls",summary:"\u5217\u51FA\u8FDC\u7A0B\u76EE\u5F55\uFF08\u4FBF\u4E8E\u5B9A\u4F4D\u6587\u4EF6\uFF09",args:[{name:"code",required:!0,desc:"\u8FDC\u7A0B\u7801"},{name:"path",required:!0,desc:"\u76EE\u5F55\u8DEF\u5F84"}],options:[],auth:"token+authorized",returns:"{ entries: [{ name, size, dir, mtime }] }",async handler(r,e){return C(r,t=>t.listDir(e[0],e[1]))},render:r=>{let e=r.entries.map(t=>{let n=t.dir?"D":"-",i=t.dir?"":String(t.size);return`${n} ${i.padStart(10)} ${t.name}`});return e.length?e.join(`
|
|
31
|
+
`):"(\u7A7A\u76EE\u5F55)"}},{name:"get",summary:"\u8BFB\u53D6/\u4E0B\u8F7D\u8FDC\u7A0B\u6587\u4EF6",description:"\u5C0F\u6587\u4EF6\u5185\u8054\u56DE\u4F20\uFF1B\u5927\u6587\u4EF6(>\u670D\u52A1\u7AEF\u9608\u503C,\u9ED8\u8BA42MB)\u81EA\u52A8\u843D\u8D44\u4EA7\u6876\u5E76 HTTP \u5F02\u6B65\u4E0B\u8F7D\u3002--out \u5B58\u6587\u4EF6\uFF0C\u5426\u5219\u5199 stdout\u3002",args:[{name:"code",required:!0,desc:"\u8FDC\u7A0B\u7801"},{name:"path",required:!0,desc:"\u8FDC\u7A0B\u6587\u4EF6\u8DEF\u5F84"}],options:[{flag:"--out <file>",name:"out",type:"string",desc:"\u4FDD\u5B58\u5230\u672C\u5730\u6587\u4EF6\uFF08\u7F3A\u7701\u5199 stdout\uFF09"},{flag:"--max-bytes <n>",name:"maxBytes",type:"number",desc:"\u6700\u5927\u8BFB\u53D6\u5B57\u8282\u6570"}],auth:"token+authorized",returns:"{ mode: inline|asset, bytes, sha256?, out? }",async handler(r,e,t){let n=t.maxBytes!=null?Number(t.maxBytes):void 0;return C(r,async i=>{let s=await i.readFile(e[0],e[1],n),o=s.kind==="inline"?s.bytes:await i.download(s.url),u={mode:s.kind,bytes:o.length,...s.kind==="asset"?{sha256:s.sha256,url:s.url}:{}};return t.out?((0,G.writeFileSync)(t.out,o),u.out=t.out):r.output==="json"?u.base64=o.toString("base64"):process.stdout.write(o),u})},render:r=>r.out?`\u5DF2\u4FDD\u5B58 ${r.bytes} \u5B57\u8282\u5230 ${r.out} (${r.mode})`:""},{name:"screenshot",summary:"\u8FDC\u7A0B\u622A\u56FE\u5E76\u4E0B\u8F7D\u5230\u672C\u5730",description:"\u9ED8\u8BA4\u5168\u5C4F\uFF1B--window/--app \u6307\u5B9A\u7A97\u53E3\u3002\u5927\u56FE\u540C\u6837\u8D70\u8D44\u4EA7\u6876\u3002\u8FD4\u56DE\u56FE\u7247\u4FDD\u5B58\u8DEF\u5F84\u3002",args:[{name:"code",required:!0,desc:"\u8FDC\u7A0B\u7801"}],options:[{flag:"--out <file>",name:"out",type:"string",desc:"\u4FDD\u5B58\u8DEF\u5F84\uFF08\u7F3A\u7701 ndb-shot-<code>.png\uFF09"},{flag:"--app <name>",name:"app",type:"string",desc:"\u76EE\u6807\u5E94\u7528\u540D\uFF08\u7A97\u53E3\u622A\u56FE\uFF09"},{flag:"--window <title>",name:"window",type:"string",desc:"\u7A97\u53E3\u6807\u9898\u5339\u914D"},{flag:"--monitor <n>",name:"monitor",type:"number",desc:"\u663E\u793A\u5668\u5E8F\u53F7\uFF08\u5168\u5C4F\uFF09"}],auth:"token+authorized",returns:"{ bytes, out }",async handler(r,e,t){let n=e[0],i=t.app||t.window?"window":"screen";return C(r,async s=>{let o=await s.screenshot(n,{target:i,app:t.app,window_title:t.window,monitor:t.monitor!=null?Number(t.monitor):void 0}),u=o.kind==="inline"?o.bytes:await s.download(o.url),a=t.out||`ndb-shot-${n}.png`;return(0,G.writeFileSync)(a,u),{bytes:u.length,out:a,mode:o.kind}})},render:r=>`\u5DF2\u4FDD\u5B58\u622A\u56FE ${r.bytes} \u5B57\u8282 \u2192 ${r.out}`},{name:"schema",summary:"\u5BFC\u51FA\u5168\u90E8\u547D\u4EE4\u7684\u673A\u5668\u53EF\u8BFB schema\uFF08\u7ED9 LLM Agent\uFF09",description:"\u8F93\u51FA function-calling \u53CB\u597D\u7684\u5DE5\u5177\u63CF\u8FF0\u3002\u914D\u5408 -c \u8F93\u51FA\u7D27\u51D1\u5355\u884C JSON\u3002",args:[],options:[],auth:"none",async handler(r){return Je(r.version)},returns:"{ tool, version, commands: [...] }"}];function Je(r){let e=z.filter(t=>t.name!=="schema").map(t=>{let n={},i=[];for(let s of t.args)n[s.name]={type:"string",description:s.desc+(s.variadic?"\uFF08\u53EF\u591A\u503C\uFF09":"")},s.required&&i.push(s.name);for(let s of t.options)n[s.name]={type:s.type,description:s.desc,...s.default!=null?{default:s.default}:{}};return n.output={type:"string",enum:["text","json"],default:"text",description:"\u8F93\u51FA\u683C\u5F0F"},{name:t.name,summary:t.summary,description:t.description??t.summary,parameters:{type:"object",properties:n,required:i},returns:t.returns,auth:t.auth}});return{tool:"ndb",version:r,commands:e}}var be="0.1.1";function Ke(r){let e=r.args.map(t=>{let n=t.variadic?`${t.name}...`:t.name;return t.required?`<${n}>`:`[${n}]`});return[r.name,...e].join(" ")}function Qe(r){let e=r.opts(),{baseUrl:t,token:n}=fe({baseUrl:e.baseUrl,token:e.token}),i=!!e.compact,s=i||e.output==="json"?"json":"text";return{baseUrl:t,token:n,output:s,compact:i,version:be}}function Xe(r,e,t){if(r.output==="json"){let i={ok:!0,data:t};console.log(r.compact?JSON.stringify(i):JSON.stringify(i,null,2));return}let n=e.render?e.render(t):t===void 0?"":JSON.stringify(t,null,2);n&&console.log(n)}function Ye(r,e){let t=e instanceof p?e.code:e?.code??"INTERNAL",n=e?.message??String(e);if(r.output==="json"){let i={ok:!1,error:{code:t,message:n}};console.log(r.compact?JSON.stringify(i):JSON.stringify(i,null,2))}else process.stderr.write(`error: [${t}] ${n}
|
|
32
|
+
`);process.exitCode=1}function Ze(){let r=new ue;r.name("ndb").description("NewBeeDebugBridge \u5DE5\u7A0B\u5E08\u7AEF CLI \u2014\u2014 \u8FDC\u7A0B\u8FD0\u7EF4(\u622A\u56FE/\u6267\u884C/\u8BFB\u6587\u4EF6)\uFF0C\u5BF9 LLM Agent \u53CB\u597D\u3002").version(be,"-V, --version").option("--base-url <url>","\u670D\u52A1\u7AEF\u5730\u5740\uFF08\u6216 env NDB_BASE_URL\uFF09").option("--token <token>","token\uFF08\u6216 env NDB_TOKEN / ~/.ndb/config.json\uFF09").option("-o, --output <fmt>","\u8F93\u51FA\u683C\u5F0F text|json","text").option("-c, --compact","\u7D27\u51D1\u5355\u884C JSON\uFF08\u9690\u542B -o json\uFF09").showHelpAfterError();for(let e of z){let t=r.command(Ke(e));t.summary(e.summary),t.description(e.description?`${e.summary}
|
|
33
|
+
|
|
34
|
+
${e.description}`:e.summary);for(let n of e.options)t.option(n.flag,n.desc,n.default);t.action(async(...n)=>{let i=n.slice(0,e.args.length),s=n[e.args.length]??{},o=i.flatMap(a=>Array.isArray(a)?a:a==null?[]:[a]),u=Qe(r);try{let a=await e.handler(u,o,s);Xe(u,e,a)}catch(a){Ye(u,a)}})}return r}Ze().parseAsync(process.argv);
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@newbeebox/newbeebox-debug-bridge",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "NewBeeDebugBridge 工程师端 CLI —— 远程运维(截图/执行/读文件),对 LLM Agent 友好。",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"ndb": "dist/cli.cjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsc --noEmit && node build.mjs",
|
|
17
|
+
"dev": "tsx src/cli.ts",
|
|
18
|
+
"typecheck": "tsc --noEmit",
|
|
19
|
+
"test": "node test/e2e.mjs",
|
|
20
|
+
"prepublishOnly": "npm run build"
|
|
21
|
+
},
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=18"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^20.14.0",
|
|
27
|
+
"commander": "^12.1.0",
|
|
28
|
+
"esbuild": "^0.23.0",
|
|
29
|
+
"tsx": "^4.16.0",
|
|
30
|
+
"typescript": "^5.5.0"
|
|
31
|
+
},
|
|
32
|
+
"license": "MIT"
|
|
33
|
+
}
|