bailian-cli-commands 0.0.0-beta-46d8474-20260626
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 +202 -0
- package/dist/index.d.mts +138 -0
- package/dist/index.mjs +119 -0
- package/package.json +51 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Aliyun Model Studio (DashScope) AI Platform
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import * as _$bailian_cli_core0 from "bailian-cli-core";
|
|
2
|
+
|
|
3
|
+
//#region src/commands/auth/login.d.ts
|
|
4
|
+
declare const _default$3: _$bailian_cli_core0.Command;
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region src/commands/auth/status.d.ts
|
|
7
|
+
declare const _default$5: _$bailian_cli_core0.Command;
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/commands/auth/logout.d.ts
|
|
10
|
+
declare const _default$4: _$bailian_cli_core0.Command;
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/commands/text/chat.d.ts
|
|
13
|
+
declare const _default$32: _$bailian_cli_core0.Command;
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/commands/omni/chat.d.ts
|
|
16
|
+
declare const _default$33: _$bailian_cli_core0.Command;
|
|
17
|
+
//#endregion
|
|
18
|
+
//#region src/commands/image/generate.d.ts
|
|
19
|
+
declare const _default$11: _$bailian_cli_core0.Command;
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/commands/image/edit.d.ts
|
|
22
|
+
declare const _default$10: _$bailian_cli_core0.Command;
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/commands/video/generate.d.ts
|
|
25
|
+
declare const _default$40: _$bailian_cli_core0.Command;
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/commands/video/edit.d.ts
|
|
28
|
+
declare const _default$39: _$bailian_cli_core0.Command;
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/commands/video/ref.d.ts
|
|
31
|
+
declare const _default$41: _$bailian_cli_core0.Command;
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/commands/video/task-get.d.ts
|
|
34
|
+
declare const _default$42: _$bailian_cli_core0.Command;
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/commands/video/download.d.ts
|
|
37
|
+
declare const _default$38: _$bailian_cli_core0.Command;
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/commands/vision/describe.d.ts
|
|
40
|
+
declare const _default$43: _$bailian_cli_core0.Command;
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/commands/config/show.d.ts
|
|
43
|
+
declare const _default$7: _$bailian_cli_core0.Command;
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region src/commands/config/set.d.ts
|
|
46
|
+
declare const _default$6: _$bailian_cli_core0.Command;
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/commands/update.d.ts
|
|
49
|
+
declare const _default$34: _$bailian_cli_core0.Command;
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/commands/app/call.d.ts
|
|
52
|
+
declare const _default$1: _$bailian_cli_core0.Command;
|
|
53
|
+
//#endregion
|
|
54
|
+
//#region src/commands/app/list.d.ts
|
|
55
|
+
declare const _default$2: _$bailian_cli_core0.Command;
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/commands/memory/add.d.ts
|
|
58
|
+
declare const _default$16: _$bailian_cli_core0.Command;
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/commands/memory/search.d.ts
|
|
61
|
+
declare const _default$21: _$bailian_cli_core0.Command;
|
|
62
|
+
//#endregion
|
|
63
|
+
//#region src/commands/memory/list.d.ts
|
|
64
|
+
declare const _default$18: _$bailian_cli_core0.Command;
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region src/commands/memory/update.d.ts
|
|
67
|
+
declare const _default$22: _$bailian_cli_core0.Command;
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region src/commands/memory/delete.d.ts
|
|
70
|
+
declare const _default$17: _$bailian_cli_core0.Command;
|
|
71
|
+
//#endregion
|
|
72
|
+
//#region src/commands/memory/profile-create.d.ts
|
|
73
|
+
declare const _default$19: _$bailian_cli_core0.Command;
|
|
74
|
+
//#endregion
|
|
75
|
+
//#region src/commands/memory/profile-get.d.ts
|
|
76
|
+
declare const _default$20: _$bailian_cli_core0.Command;
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/commands/knowledge/retrieve.d.ts
|
|
79
|
+
declare const _default$12: _$bailian_cli_core0.Command;
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/commands/mcp/call.d.ts
|
|
82
|
+
declare const _default$13: _$bailian_cli_core0.Command;
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region src/commands/mcp/list.d.ts
|
|
85
|
+
declare const _default$14: _$bailian_cli_core0.Command;
|
|
86
|
+
//#endregion
|
|
87
|
+
//#region src/commands/mcp/tools.d.ts
|
|
88
|
+
declare const _default$15: _$bailian_cli_core0.Command;
|
|
89
|
+
//#endregion
|
|
90
|
+
//#region src/commands/search/web.d.ts
|
|
91
|
+
declare const _default$29: _$bailian_cli_core0.Command;
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/commands/speech/synthesize.d.ts
|
|
94
|
+
declare const _default$31: _$bailian_cli_core0.Command;
|
|
95
|
+
//#endregion
|
|
96
|
+
//#region src/commands/speech/recognize.d.ts
|
|
97
|
+
declare const _default$30: _$bailian_cli_core0.Command;
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region src/commands/file/upload.d.ts
|
|
100
|
+
declare const _default$9: _$bailian_cli_core0.Command;
|
|
101
|
+
//#endregion
|
|
102
|
+
//#region src/commands/console/call.d.ts
|
|
103
|
+
declare const _default$8: _$bailian_cli_core0.Command;
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region src/commands/usage/free.d.ts
|
|
106
|
+
declare const _default$35: _$bailian_cli_core0.Command;
|
|
107
|
+
//#endregion
|
|
108
|
+
//#region src/commands/usage/freetier.d.ts
|
|
109
|
+
declare const _default$36: _$bailian_cli_core0.Command;
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region src/commands/usage/stats.d.ts
|
|
112
|
+
declare const _default$37: _$bailian_cli_core0.Command;
|
|
113
|
+
//#endregion
|
|
114
|
+
//#region src/commands/pipeline/run.d.ts
|
|
115
|
+
declare const _default$23: _$bailian_cli_core0.Command;
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/commands/pipeline/validate.d.ts
|
|
118
|
+
declare const _default$24: _$bailian_cli_core0.Command;
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/commands/advisor/recommend.d.ts
|
|
121
|
+
declare const _default: _$bailian_cli_core0.Command;
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/commands/workspace/list.d.ts
|
|
124
|
+
declare const _default$44: _$bailian_cli_core0.Command;
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region src/commands/quota/list.d.ts
|
|
127
|
+
declare const _default$27: _$bailian_cli_core0.Command;
|
|
128
|
+
//#endregion
|
|
129
|
+
//#region src/commands/quota/request.d.ts
|
|
130
|
+
declare const _default$28: _$bailian_cli_core0.Command;
|
|
131
|
+
//#endregion
|
|
132
|
+
//#region src/commands/quota/history.d.ts
|
|
133
|
+
declare const _default$26: _$bailian_cli_core0.Command;
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/commands/quota/check.d.ts
|
|
136
|
+
declare const _default$25: _$bailian_cli_core0.Command;
|
|
137
|
+
//#endregion
|
|
138
|
+
export { _default as advisorRecommend, _default$1 as appCall, _default$2 as appList, _default$3 as authLogin, _default$4 as authLogout, _default$5 as authStatus, _default$6 as configSet, _default$7 as configShow, _default$8 as consoleCall, _default$9 as fileUpload, _default$10 as imageEdit, _default$11 as imageGenerate, _default$12 as knowledgeRetrieve, _default$13 as mcpCall, _default$14 as mcpList, _default$15 as mcpTools, _default$16 as memoryAdd, _default$17 as memoryDelete, _default$18 as memoryList, _default$19 as memoryProfileCreate, _default$20 as memoryProfileGet, _default$21 as memorySearch, _default$22 as memoryUpdate, _default$23 as pipelineRun, _default$24 as pipelineValidate, _default$25 as quotaCheck, _default$26 as quotaHistory, _default$27 as quotaList, _default$28 as quotaRequest, _default$29 as searchWeb, _default$30 as speechRecognize, _default$31 as speechSynthesize, _default$32 as textChat, _default$33 as textOmni, _default$34 as update, _default$35 as usageFree, _default$36 as usageFreetier, _default$37 as usageStats, _default$38 as videoDownload, _default$39 as videoEdit, _default$40 as videoGenerate, _default$41 as videoRef, _default$42 as videoTaskGet, _default$43 as visionDescribe, _default$44 as workspaceList };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import{BailianError as e,CONSOLE_GATEWAY_NO_TOKEN_MESSAGE as t,DOCS_HOSTS as n,ExitCode as r,McpClient as i,analyzeIntent as a,appCompletionEndpoint as o,bailianMcpUrl as s,buildDocLink as c,callConsoleGateway as l,chatEndpoint as u,clearApiKey as d,defineCommand as f,detectOutputFormat as p,effectiveConsoleGatewayConfig as m,fetchModelList as h,generateFilename as g,getConfigDir as _,getConfigPath as v,getModels as y,imageEndpoint as b,imageSyncEndpoint as x,isInteractive as S,isLocalFile as C,knowledgeRetrieveEndpoint as ee,maskToken as w,mcpWebSearchEndpoint as te,memoryAddEndpoint as ne,memoryListEndpoint as re,memoryNodeEndpoint as ie,memorySearchEndpoint as ae,parseSSE as oe,profileSchemaEndpoint as se,rankModels as ce,readConfigFile as T,recallSemantic as le,request as ue,requestJson as E,resolveBooleanFlag as D,resolveConsoleGatewayCredential as O,resolveCredential as k,resolveFileUrl as A,resolveOutputDir as j,resolveWatermark as de,signRequest as fe,speechRecognizeEndpoint as pe,speechSynthesizeEndpoint as me,stripUndefined as he,taskEndpoint as M,trackingHeaders as ge,uploadFile as _e,userProfileEndpoint as ve,videoGenerateEndpoint as ye,writeConfigFile as N}from"bailian-cli-core";import{API_KEY_PAGE as be,BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT as xe,BOOL_FLAG_PROMPT_EXTEND_CLI_TRUE as Se,BOOL_FLAG_PROMPT_EXTEND_IMAGE_GENERATE as Ce,BOOL_FLAG_WATERMARK as P,cmdUsage as F,collectPipelineHints as we,collectPipelineIssues as Te,createSpinner as Ee,displayWidth as I,downloadFile as L,downloadParallel as De,emitBare as R,emitResult as z,ensureApiKey as Oe,executePipeline as ke,failIfMissing as B,fetchLatestVersion as Ae,formatBytes as je,getConcurrency as Me,initPipelineSteps as Ne,padEnd as V,poll as H,printCurrentCommandHelp as Pe,printQuickStart as Fe,promptConfirm as Ie,promptSelect as Le,promptText as U,resolveImageSize as Re,runConcurrent as W,streamPipelineEvents as ze}from"bailian-cli-runtime";import{execFile as Be}from"node:child_process";import{randomBytes as Ve}from"node:crypto";import He from"node:http";import{createWriteStream as Ue,existsSync as We,readFileSync as Ge,writeFileSync as Ke}from"fs";import{extname as qe,join as G}from"path";import{execSync as Je}from"child_process";import{readFile as Ye}from"node:fs/promises";import{dirname as Xe,extname as Ze,resolve as Qe}from"node:path";import $e from"boxen";import et,{Chalk as tt}from"chalk";const nt={domestic:`https://bailian.console.aliyun.com`,international:`https://modelstudio.console.alibabacloud.com`};function rt(e){return e&&nt[e]||nt.domestic}function it(e){return new Promise((t,n)=>{let r=0,i=[];e.on(`data`,e=>{if(r+=e.length,r>65536){n(Error(`payload too large`));return}i.push(e)}),e.on(`end`,()=>t(Buffer.concat(i).toString(`utf8`))),e.on(`error`,n)})}function at(e){let t=e.headers[`content-type`];return Array.isArray(t)?t[0]??``:typeof t==`string`?t:``}function ot(e){let t=e.split(`;`);for(let e of t){let t=e.trim();if(!t.toLowerCase().startsWith(`boundary=`))continue;let n=t.slice(9).trim();return(n.startsWith(`"`)&&n.endsWith(`"`)||n.startsWith(`'`)&&n.endsWith(`'`))&&(n=n.slice(1,-1)),n.length>0?n:null}return null}function st(e,t){let n=`--${t}`,r=e.split(n);for(let e=1;e<r.length;e++){let t=r[e];if(!/name\s*=\s*["'](?:access_token|accessToken)["']/i.test(t))continue;let n=t.match(/\r\n\r\n|\n\n/);if(!n||n.index===void 0)continue;let i=t.slice(n.index+n[0].length);if(i=i.replace(/(?:\r\n)+$/g,``).replace(/\n+$/g,``).trim(),i)return i}return null}function ct(e){for(let t of[`access_token`,`accessToken`]){let n=e[t];if(typeof n==`string`&&n.trim())return n.trim()}return null}function lt(e){for(let t of[`api_key`,`apiKey`]){let n=e[t];if(typeof n==`string`&&n.trim())return n.trim()}return null}function ut(e){let t=e.trim();if(t.charCodeAt(0)===65279&&(t=t.slice(1)),!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=n,i=ct(r);if(i)return i;let a=r.data;if(a&&typeof a==`object`&&!Array.isArray(a)){let e=ct(a);if(e)return e}return null}function dt(e,t){let n=t.toLowerCase();if(!e.trim())return null;if(n.includes(`multipart/form-data`)){let n=ot(t);if(n){let t=st(e,n);if(t)return t}}if(n.includes(`application/json`)||n.includes(`text/json`)){let t=ut(e);if(t)return t}if(n.includes(`application/x-www-form-urlencoded`))try{let t=new URLSearchParams(e.trim()),n=t.get(`access_token`)??t.get(`accessToken`);if(n?.trim())return n.trim()}catch{}let r=ut(e);if(r)return r;try{let t=new URLSearchParams(e.trim()),n=t.get(`access_token`)??t.get(`accessToken`);if(n?.trim())return n.trim()}catch{}let i=ot(t);if(i){let t=st(e,i);if(t)return t}return null}function ft(e){let t=e.trim();if(t.charCodeAt(0)===65279&&(t=t.slice(1)),!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=n,i=lt(r);if(i)return i;let a=r.data;if(a&&typeof a==`object`&&!Array.isArray(a)){let e=lt(a);if(e)return e}return null}function pt(e,t){let n=t.toLowerCase();if(!e.trim())return null;if(n.includes(`application/json`)||n.includes(`text/json`)){let t=ft(e);if(t)return t}if(n.includes(`application/x-www-form-urlencoded`))try{let t=new URLSearchParams(e.trim()),n=t.get(`api_key`)??t.get(`apiKey`);if(n?.trim())return n.trim()}catch{}let r=ft(e);if(r)return r;try{let t=new URLSearchParams(e.trim()),n=t.get(`api_key`)??t.get(`apiKey`);if(n?.trim())return n.trim()}catch{}return null}function K(e,...t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.trim())return t.trim()}return null}function mt(e,t){let n={baseUrl:null,consoleSite:null,consoleRegion:null,consoleSwitchAgent:null,workspaceId:null};if(!e.trim())return n;let r=null,i=t.toLowerCase();if(i.includes(`application/json`)||i.includes(`text/json`))try{let t=JSON.parse(e.trim());t&&typeof t==`object`&&!Array.isArray(t)&&(r=t)}catch{}if(!r&&i.includes(`application/x-www-form-urlencoded`))try{let t=new URLSearchParams(e.trim());r=Object.fromEntries(t)}catch{}if(!r)try{let t=JSON.parse(e.trim());t&&typeof t==`object`&&!Array.isArray(t)&&(r=t)}catch{}return r?{baseUrl:K(r,`base_url`,`baseUrl`),consoleSite:K(r,`console_site`,`consoleSite`),consoleRegion:K(r,`console_region`,`consoleRegion`),consoleSwitchAgent:K(r,`console_switch_agent`,`consoleSwitchAgent`),workspaceId:K(r,`workspace_id`,`workspaceId`)}:n}async function ht(e){let t=new URL(e.url??`/`,`http://127.0.0.1`),n=t.searchParams.get(`access_token`)??t.searchParams.get(`accessToken`),r=t.searchParams.get(`api_key`)??t.searchParams.get(`apiKey`),i=t.searchParams.get(`base_url`)??t.searchParams.get(`baseUrl`),a=t.searchParams.get(`console_site`)??t.searchParams.get(`consoleSite`),o=t.searchParams.get(`console_region`)??t.searchParams.get(`consoleRegion`),s=t.searchParams.get(`console_switch_agent`)??t.searchParams.get(`consoleSwitchAgent`),c=t.searchParams.get(`workspace_id`)??t.searchParams.get(`workspaceId`),l={baseUrl:i?.trim()||null,consoleSite:a?.trim()||null,consoleRegion:o?.trim()||null,consoleSwitchAgent:s?.trim()||null,workspaceId:c?.trim()||null},u=e.method??`GET`;if(u!==`POST`&&u!==`PUT`&&u!==`PATCH`)return{accessToken:n?.trim()||null,apiKey:r?.trim()||null,...l};let d=at(e),f;try{f=await it(e)}catch{return{accessToken:n?.trim()||null,apiKey:r?.trim()||null,...l}}let p=n?.trim()||dt(f,d),m=r?.trim()||pt(f,d),h=mt(f,d);return{accessToken:p,apiKey:m,baseUrl:l.baseUrl||h.baseUrl,consoleSite:l.consoleSite||h.consoleSite,consoleRegion:l.consoleRegion||h.consoleRegion,consoleSwitchAgent:l.consoleSwitchAgent||h.consoleSwitchAgent,workspaceId:l.workspaceId||h.workspaceId}}function gt(e){return new Promise((t,n)=>{let r=e=>n(e);e.once(`error`,r),e.listen({port:0,host:`127.0.0.1`,exclusive:!0},()=>{e.off(`error`,r);let i=e.address();if(!i||typeof i==`string`){n(Error(`Expected TCP socket address`));return}t(i.port)})})}function _t(e){let t=process.platform,n=t===`darwin`?`open`:t===`win32`?`cmd`:`xdg-open`,r=t===`win32`?[`/c`,`start`,``,e]:[e];return new Promise((e,t)=>{Be(n,r,{windowsHide:!0},n=>{n?t(n):e()})})}function vt(t){if(t instanceof e){if(t.exitCode===r.NETWORK||t.exitCode===r.TIMEOUT)return!0;let e=t.api?.httpStatus;return e===401||e!==void 0&&e>=500}return t instanceof Error?t.name===`AbortError`||t.name===`TimeoutError`||t.message.includes(`timed out`)||t.message===`fetch failed`:!1}async function yt(t,n,i){process.stderr.write(`Testing key... `);let a={...t,apiKey:n,baseUrl:i},o={url:u(a.baseUrl),method:`POST`,timeout:Math.min(t.timeout,30),body:{model:`qwen3.7-max`,messages:[{role:`user`,content:`hi`}],max_tokens:1}};for(let t=1;t<=3;t++)try{await E(a,o);break}catch(n){if(t>=3||!vt(n))throw process.stderr.write(`Failed
|
|
2
|
+
`),new e(`API key validation failed`,r.AUTH,`Invalid API key.`,{cause:n});let i=500*2**(t-1);await new Promise(e=>setTimeout(e,i))}process.stderr.write(`Valid
|
|
3
|
+
`);let s=T();s.api_key=n,await N(s)}async function bt(t,n,i){let a=Ve(16).toString(`hex`),o,s=He.createServer(async(e,t)=>{try{if(e.method===`OPTIONS`){t.writeHead(204,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`GET, POST, PUT, PATCH, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type`}),t.end();return}if(new URL(e.url??`/`,`http://127.0.0.1`).searchParams.get(`state`)!==a){t.writeHead(400,{"Content-Type":`text/plain; charset=utf-8`}),t.end(`bad state
|
|
4
|
+
`);return}let{accessToken:r,apiKey:i,baseUrl:c,consoleSite:l,consoleRegion:u,consoleSwitchAgent:d,workspaceId:f}=await ht(e),p=r||c||l||u||d||f;if(p||i)try{if(p){let e=T();r&&(e.access_token=r),c&&(e.base_url=c),l&&(e.console_site=l),u&&(e.console_region=u),d&&(e.console_switch_agent=Number(d)),f&&(e.workspace_id=f),await N(e),process.stderr.write(`Config saved to ${v()}\n`)}i&&await yt(n,i,c||n.baseUrl)}catch(e){o=e,t.writeHead(500,{"Content-Type":`text/plain; charset=utf-8`}),t.end(`Failed to save credentials
|
|
5
|
+
`),s.close();return}t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"Access-Control-Allow-Origin":`*`}),t.end(`OK
|
|
6
|
+
`),(p||i)&&s.close()}catch{t.statusCode=500,t.end()}}),c;try{c=await gt(s)}catch(t){throw new e(`Could not bind to 127.0.0.1 (no free port or permission denied): ${t instanceof Error?t.message:String(t)}`,r.USAGE)}let l=`${t}/console-login?notice=127.0.0.1:${c}?state=${encodeURIComponent(a)}`;i?.needApiKey&&(l+=`&needapikey=true`);try{await _t(l),process.stderr.write(`Opened the login page in your default browser. This process keeps the local port open for the console; press Ctrl+C when finished (or wait for idle timeout).
|
|
7
|
+
`)}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Could not open the default browser (${t}). Open this URL manually:\n\n`),process.stdout.write(`${l}\n`),process.stderr.write(`
|
|
8
|
+
This process keeps the local port open for the console; press Ctrl+C when finished (or wait for idle timeout).
|
|
9
|
+
`)}if(await new Promise((e,t)=>{let n=!1,r=()=>{n||(n=!0,clearTimeout(i),e())},i=setTimeout(()=>{s.close()},9e5);s.once(`close`,r),s.once(`error`,e=>{clearTimeout(i),n||(n=!0,t(e))})}),o)throw o}var xt=f({description:`Authenticate with API key or console browser login (credentials can coexist)`,skipDefaultApiKeySetup:!0,usageArgs:`--api-key <key> | --console`,options:[{flag:`--api-key <key>`,description:`DashScope API key to store`},{flag:`--base-url <url>`,description:`DashScope API base URL (used with --api-key for validation)`},{flag:`--console`,description:`Sign in via browser; use --console-site to choose domestic (default) or international`}],exampleArgs:[`--api-key sk-xxxxx`,`--console`],async run(e,t){if(t.console){if(e.dryRun){R(`Would bind a free port on 127.0.0.1 and open the console login URL in your browser.`);return}let t=!!(e.apiKey||e.fileApiKey);await bt(rt(e.consoleSite||`domestic`),e,{needApiKey:!t});return}let n=process.env.DASHSCOPE_API_KEY;if(n&&!t.apiKey){let t=w(n);S({nonInteractive:e.nonInteractive})?await Ie({message:`Detected DASHSCOPE_API_KEY in environment (${t}).\nYou are already authenticated via env.\nDo you still want to configure local persistent credentials?`,initialValue:!1})||(process.stdout.write(`Login skipped. Using environment variables.
|
|
10
|
+
`),process.exit(0)):process.stderr.write(`Warning: DASHSCOPE_API_KEY is already set in environment.
|
|
11
|
+
`)}let r=t.apiKey||e.apiKey;r||(Pe(process.stderr),process.exit(0));let i=t.baseUrl||void 0,a=i?{...e,baseUrl:i}:e;if(e.dryRun)R(`Would validate and save API key.`);else{if(i){let e=T();e.base_url=i,await N(e)}await yt(a,r,a.baseUrl),Fe()}}});function St(e){if(e.apiKey)return{configured:!0,source:`flag`,masked:w(e.apiKey)};if(e.fileApiKey)return{configured:!0,source:`config.json`,masked:w(e.fileApiKey)};let t=process.env.DASHSCOPE_API_KEY?.trim();return t?{configured:!0,source:`DASHSCOPE_API_KEY`,masked:w(t)}:{configured:!1}}function Ct(e){return e.accessTokenEnv?{configured:!0,source:`DASHSCOPE_ACCESS_TOKEN`,masked:w(e.accessTokenEnv)}:e.fileAccessToken?{configured:!0,source:`config.json`,masked:w(e.fileAccessToken)}:{configured:!1}}async function wt(e){try{return await k(e)}catch{return}}async function Tt(e){try{return await O(e)}catch{return}}async function Et(e){let t={api_key:St(e),access_token:Ct(e)},n=await wt(e);n&&(t.dashscope_commands={method:n.method,source:n.source,masked:w(n.token)});let r=await Tt(e);return r&&(t.console_gateway_commands={method:r.method,source:r.source,masked:w(r.token)}),t}function Dt(e){return e.api_key.configured||e.access_token.configured||!!e.dashscope_commands||!!e.console_gateway_commands}function Ot(e,t){R(`Authentication Status:`),R(` Stored credentials (can coexist):`),e.api_key.configured?R(` API key: ${e.api_key.source} ${e.api_key.masked}`):R(` API key: not configured`),e.access_token.configured?R(` Console token: ${e.access_token.source} ${e.access_token.masked}`):R(` Console token: not configured`),R(` Effective credential per command family:`),e.dashscope_commands?R(` DashScope API: ${e.dashscope_commands.method} (${e.dashscope_commands.source}) ${e.dashscope_commands.masked}`):R(` DashScope API: unavailable`),e.console_gateway_commands?R(` Console gateway: ${e.console_gateway_commands.method} (${e.console_gateway_commands.source}) ${e.console_gateway_commands.masked}`):R(` Console gateway: unavailable (run ${t.binName} auth login --console)`)}var kt=f({description:`Show current authentication state`,options:[{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[``,`--output json`],async run(e,t){let n=p(e.output),r=await Et(e);if(!Dt(r)){z({authenticated:!1,message:`Not authenticated.`,hint:[`DashScope API: ${e.binName} auth login --api-key <key> or DASHSCOPE_API_KEY`,`Console gateway: ${e.binName} auth login --console or DASHSCOPE_ACCESS_TOKEN`,`Get API Key: ${be}`].join(`
|
|
12
|
+
`),...r},n);return}if(n!==`text`){z({authenticated:!0,...r},n);return}Ot(r,e)}});async function At(){let e=T();return e.access_token?(delete e.access_token,await N(e),!0):!1}var jt=f({description:`Clear stored credentials`,skipDefaultApiKeySetup:!0,usageArgs:`[--console] [--yes] [--dry-run]`,options:[{flag:`--console`,description:`Only clear the console access_token, keep api_key intact`,type:`boolean`},{flag:`--yes`,description:`Skip confirmation prompt`}],exampleArgs:[``,`--console`,`--dry-run`,`--yes`],async run(e,t){let n=T();if(t.console){let t=!!n.access_token;if(e.dryRun){R(t?`Would clear access_token from ~/.bailian/config.json`:`No console access_token to clear.`),R(`No changes made.`);return}t?(await At(),process.stderr.write(`Cleared access_token from ${v()}\n`),n.api_key&&process.stderr.write(`api_key is still configured and will be used for authentication.
|
|
13
|
+
`)):process.stderr.write(`No console access_token to clear.
|
|
14
|
+
`);return}let r=!!(n.api_key||n.access_token);if(e.dryRun){R(r?`Would clear api_key / access_token from ~/.bailian/config.json`:`No credentials to clear.`),R(`No changes made.`);return}r?(await d(),process.stderr.write(`Cleared api_key / access_token from ~/.bailian/config.json
|
|
15
|
+
`)):process.stderr.write(`No credentials to clear.
|
|
16
|
+
`)}});function Mt(e){let t=[],n;if(e.system&&(n=e.system),e.messagesFile){let r=e.messagesFile,i=Ge(r===`-`?`/dev/stdin`:r,`utf-8`),a=JSON.parse(i);for(let e of a)e.role===`system`?n=typeof e.content==`string`?e.content:``:t.push(e)}if(e.message){let r=new Set([`system`,`user`,`assistant`]),i=e.message;for(let e of i){let i=e.indexOf(`:`),a=i===-1?``:e.slice(0,i);if(r.has(a)){let r=e.slice(i+1);a===`system`?n=r:t.push({role:a,content:r})}else t.push({role:`user`,content:e})}}return{system:n,messages:t}}var Nt=f({description:`Send a chat completion (OpenAI compatible, DashScope)`,usageArgs:`--message <text> [flags]`,options:[{flag:`--model <model>`,description:`Model ID (default: qwen3.7-max)`},{flag:`--message <text>`,description:`Message text (repeatable, prefix role: to set role)`,required:!0,type:`array`},{flag:`--messages-file <path>`,description:`JSON file with messages array (use - for stdin)`},{flag:`--system <text>`,description:`System prompt`},{flag:`--max-tokens <n>`,description:`Maximum tokens to generate (default: 4096)`,type:`number`},{flag:`--temperature <n>`,description:`Sampling temperature (0.0, 2.0]`,type:`number`},{flag:`--top-p <n>`,description:`Nucleus sampling threshold`,type:`number`},{flag:`--stream`,description:`Stream response tokens (default: on in TTY)`},{flag:`--tool <json-or-path>`,description:`Tool definition as JSON or file path (repeatable)`,type:`array`},{flag:`--enable-thinking`,description:`Enable thinking/reasoning mode (for qwen3/qwq models)`},{flag:`--thinking-budget <n>`,description:`Max tokens for thinking (default: 4096)`,type:`number`}],exampleArgs:[`--message "What is Qwen?"`,`--model qwen-max --system "You are a coding assistant." --message "Write fizzbuzz in Python"`,`--message "Hello" --message "assistant:Hi!" --message "How are you?"`,`--messages-file - --stream`,`--message "Hello" --output json`,`--model qwq-plus --message "Solve 1+1" --enable-thinking`],async run(e,t){let{system:n,messages:r}=Mt(t),i=r;if(i.length===0)if(S({nonInteractive:e.nonInteractive})){let e=await U({message:`Enter your message:`});e||(process.stderr.write(`Chat cancelled.
|
|
17
|
+
`),process.exit(1)),i=[{role:`user`,content:e}]}else B(`message`,F(e,`--message <text>`));let a=t.model||e.defaultTextModel||`qwen3.7-max`,o=t.stream===!0||t.stream===void 0&&process.stdout.isTTY,s=p(e.output),c=[];n&&c.push({role:`system`,content:n}),c.push(...i);let l={model:a,messages:c,max_tokens:t.maxTokens??4096,stream:o};if(t.temperature!==void 0&&(l.temperature=t.temperature),t.topP!==void 0&&(l.top_p=t.topP),t.enableThinking&&(l.enable_thinking=!0,t.thinkingBudget!==void 0&&(l.thinking_budget=t.thinkingBudget)),t.tool&&(l.tools=t.tool.map(e=>{try{return JSON.parse(e)}catch{let t=Ge(e,`utf-8`);return JSON.parse(t)}})),e.dryRun){z({request:l},s);return}let d=u(e.baseUrl);if(o){let t=await ue(e,{url:d,method:`POST`,body:l,stream:!0}),n=``,r=!1,i=s===`text`,a=e.noColor?``:`\x1B[2m`,o=e.noColor?``:`\x1B[0m`,c=process.stdout.isTTY,u=s===`json`?process.stderr:c?process.stdout:process.stderr,f=process.stdout;for await(let e of oe(t)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data);for(let e of t.choices){let t=e.delta;t.reasoning_content&&(i&&!r&&(r=!0,u.write(`${a}Thinking:\n`)),i&&u.write(t.reasoning_content)),t.content&&(i&&r&&(u.write(`${o}\n\nResponse:\n`),r=!1),n+=t.content,i&&f.write(t.content))}}catch{}}r&&u.write(o),s===`json`?z({content:n},s):f.write(`
|
|
18
|
+
`)}else{let t=await E(e,{url:d,method:`POST`,body:l}),n=t.choices?.[0]?.message?.content??``;e.quiet||s===`text`?R(n):z(t,s)}}});const Pt=[`Chelsie`,`Cherry`,`Ethan`,`Serena`,`Sunny`,`Tina`],Ft={wav:`wav`,mp3:`mp3`,amr:`amr`,aac:`aac`,m4a:`aac`,ogg:`ogg`,"3gp":`3gp`,"3gpp":`3gpp`},It=Object.keys(Ft);function Lt(t){let n=t.split(`?`)[0].split(`#`)[0],i=qe(n).slice(1).toLowerCase();if(!i)throw new e(`Cannot infer audio format from "${t}". Use a file/URL whose path ends with: ${It.join(`, `)}.`,r.USAGE);let a=Ft[i];if(!a)throw new e(`Unsupported audio extension ".${i}" for "${t}". Supported extensions: ${It.join(`, `)}.`,r.USAGE);return a}function Rt(e){let t=Buffer.alloc(44);return t.write(`RIFF`,0),t.writeUInt32LE(36+e,4),t.write(`WAVE`,8),t.write(`fmt `,12),t.writeUInt32LE(16,16),t.writeUInt16LE(1,20),t.writeUInt16LE(1,22),t.writeUInt32LE(24e3,24),t.writeUInt32LE(48e3,28),t.writeUInt16LE(2,32),t.writeUInt16LE(16,34),t.write(`data`,36),t.writeUInt32LE(e,40),t}var zt=f({description:`Multimodal chat with text + audio output (Qwen-Omni)`,usageArgs:`--message <text> [flags]`,options:[{flag:`--message <text>`,description:`Message text (repeatable, prefix role: to set role)`,required:!0,type:`array`},{flag:`--model <model>`,description:`Model ID (default: qwen3.5-omni-plus)`},{flag:`--system <text>`,description:`System prompt`},{flag:`--image <url>`,description:`Image URL or local file (repeatable)`,type:`array`},{flag:`--audio <url>`,description:`Audio URL or local file (.wav/.mp3/.amr/.aac/.m4a/.ogg/.3gp/.3gpp)`,type:`array`},{flag:`--video <url>`,description:`Video file URL / local path, or comma-separated frame URLs`,type:`array`},{flag:`--voice <voice>`,description:`Output voice (default: Cherry). Options: ${Pt.join(`, `)}`},{flag:`--audio-format <fmt>`,description:`Audio output format (default: wav)`},{flag:`--audio-out <path>`,description:`Save audio to file (default: auto-generate)`},{flag:`--text-only`,description:`Output text only, no audio generation`},{flag:`--max-tokens <n>`,description:`Maximum tokens to generate`,type:`number`},{flag:`--temperature <n>`,description:`Sampling temperature (0.0, 2.0]`,type:`number`}],exampleArgs:[`--message "Hello, who are you?"`,`--message "Describe this image" --image ./photo.jpg`,`--message "What is this audio saying?" --audio https://example.com/audio.wav`,`--message "Summarize this video" --video https://example.com/video.mp4`,`--message "What is this video about?" --video ./local-video.mp4 --text-only`,`--message "Answer in Sichuan dialect: How's the weather today?" --voice Sunny`,`--message "Hello" --text-only --output json`,`--message "Read this passage aloud" --audio-out greeting.wav`],async run(e,t){let n=[];if(t.message&&(n=t.message),n.length===0)if(S({nonInteractive:e.nonInteractive})){let e=await U({message:`Enter your message:`});e||(process.stderr.write(`Omni chat cancelled.
|
|
19
|
+
`),process.exit(1)),n=[e]}else B(`message`,F(e,`--message <text>`));let r=t.model||e.defaultOmniModel||`qwen3.5-omni-plus`,i=t.voice||`Cherry`,a=t.audioFormat||`wav`,o=t.textOnly===!0,s=p(e.output),c=[];t.system&&c.push({role:`system`,content:t.system});let l=new Set([`system`,`user`,`assistant`]);for(let e of n){let t=e.indexOf(`:`),n=t===-1?``:e.slice(0,t);if(l.has(n)){let r=e.slice(t+1);n===`system`?c.push({role:`system`,content:r}):c.push({role:n,content:r})}else c.push({role:`user`,content:e})}let d=t.image||[],f=t.audio||[],m=t.video||[],h=[],g=[],_=[];if(d.length>0||f.length>0||m.length>0){let t=await k(e);for(let e of d){let n=await A(e,t.token,r);h.push(n)}for(let e of f){let n=await A(e,t.token,r);g.push({source:e,data:n})}for(let e of m)if(e.includes(`,`)){let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);for(let e of n){let n=await A(e,t.token,r);_.push(`frame:${n}`)}}else{let n=await A(e,t.token,r);_.push(n)}}if(h.length>0||g.length>0||_.length>0){for(let e=c.length-1;e>=0;e--)if(c[e].role===`user`){let t=c[e].content,n=[];typeof t==`string`?n.push({type:`text`,text:t}):Array.isArray(t)&&n.push(...t);for(let e of h)n.push({type:`image_url`,image_url:{url:e}});for(let{source:e,data:t}of g)n.push({type:`input_audio`,input_audio:{data:t,format:Lt(e)}});let r=_.filter(e=>e.startsWith(`frame:`)).map(e=>e.slice(6)),i=_.filter(e=>!e.startsWith(`frame:`));r.length>0&&n.push({type:`video`,video:r});for(let e of i)n.push({type:`video_url`,video_url:{url:e}});c[e]={role:`user`,content:n};break}}let v={model:r,messages:c,stream:!0,stream_options:{include_usage:!0}};if(o||(v.modalities=[`text`,`audio`],v.audio={voice:i,format:a}),t.maxTokens!==void 0&&(v.max_tokens=t.maxTokens),t.temperature!==void 0&&(v.temperature=t.temperature),e.dryRun){z({request:v},s);return}if(!e.quiet){let e=o?`text-only`:`text+audio, voice: ${i}`;process.stderr.write(`[Model: ${r}] [${e}]\n`)}let y=await ue(e,{url:u(e.baseUrl),method:`POST`,body:v,stream:!0}),b=``,x=``,C=process.stdout.isTTY,ee=process.stdout;for await(let e of oe(y)){if(e.data===`[DONE]`)break;try{let t=JSON.parse(e.data);for(let e of t.choices){let t=e.delta;t.content&&(b+=t.content,C&&ee.write(t.content)),t.audio?.data&&(x+=t.audio.data)}}catch{}}C&&b&&ee.write(`
|
|
20
|
+
`);let w;if(x&&!o){let n=Buffer.from(x,`base64`),r=Rt(n.length),i=Buffer.concat([r,n]),a=t.audioOut;if(!a){let{join:t}=await import(`path`);a=t(j(e,{subDir:`omni`}),`omni_${Date.now()}.wav`)}Ke(a,i),w=a,e.quiet||process.stderr.write(`Audio saved: ${a}\n`)}if(!C||s===`json`){let e={content:b};w&&(e.audio_saved=w,e.voice=i),z(e,s)}}});const Bt=[`qwen-image-2.0`,`qwen-image-max`];function Vt(e){return Bt.some(t=>e.startsWith(t))}var Ht=f({description:`Generate images (Qwen-Image / wan2.x)`,usageArgs:`--prompt <text> [flags]`,options:[{flag:`--prompt <text>`,description:`Image description`,required:!0},{flag:`--model <model>`,description:`Model ID (default: qwen-image-2.0)`},{flag:`--size <W*H>`,description:`Image size: ratio (3:4, 16:9, 1:1) or pixels (2048*2048)`},{flag:`--n <count>`,description:`Number of images per request (default: 1, max: 6)`,type:`number`},{flag:`--seed <n>`,description:`Random seed for reproducible generation`,type:`number`},{flag:`--negative-prompt <text>`,description:`Negative prompt to exclude unwanted content`},{flag:`--prompt-extend <bool>`,description:Ce},{flag:`--watermark <bool>`,description:P},{flag:`--no-wait`,description:`Return task ID immediately without waiting (async models only)`},{flag:`--out-dir <dir>`,description:`Download images to directory`},{flag:`--out-prefix <prefix>`,description:`Filename prefix (default: image)`},{flag:`--poll-interval <seconds>`,description:`Polling interval when waiting (default: 3)`,type:`number`}],exampleArgs:[`--prompt "A cat in a spacesuit on Mars"`,`--prompt "Logo design" --n 3 --out-dir ./generated/`,`--prompt "Mountain landscape" --size 2688*1536`,`--prompt "A castle" --seed 42 --prompt-extend false`,`--prompt "Logo" --watermark false`,`--prompt "An alien in the space" --watermark false`,`--prompt "sunset" --model wan2.6-t2i --no-wait --quiet`,`--prompt "Pro quality" --model qwen-image-2.0-pro`,`--prompt "Product shots" --n 2 --concurrent 3 # 6 images in parallel`],async run(e,t){let n=t.prompt??t._positional?.[0];if(!n)if(S({nonInteractive:e.nonInteractive})){let e=await U({message:`Enter your image prompt:`});e||(process.stderr.write(`Image generation cancelled.
|
|
21
|
+
`),process.exit(1)),n=e}else B(`prompt`,F(e,`--prompt <text>`));let r=t.model||e.defaultImageModel||`qwen-image-2.0`,i=Vt(r),a=Re(t.size||`1:1`,i),o=t.n??1,s=Me(t),c=D(t.promptExtend,i?!0:void 0,`prompt-extend`),l=de(t.watermark),u={model:r,input:{messages:[{role:`user`,content:[{text:n}]}]},parameters:{size:a,n:o,seed:t.seed,prompt_extend:c,watermark:l,negative_prompt:t.negativePrompt||void 0}},d=p(e.output);if(e.dryRun){z({request:u,mode:i?`sync`:`async`},d);return}e.quiet||process.stderr.write(`[Model: ${r}] [Mode: ${i?`sync`:`async`}]\n`),i?await Ut(e,r,u,t,d,s):await Wt(e,r,u,t,d,s)}});async function Ut(t,n,i,a,o,s){let c=x(t.baseUrl),l=(await W(s,t,()=>E(t,{url:c,method:`POST`,body:i}))).flatMap(e=>e.output.choices||[]).flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean);if(l.length===0)throw new e(`Generation completed but no images returned.`,r.GENERAL);await Gt(l,a,t,o)}async function Wt(t,n,i,a,o,s){let c=b(t.baseUrl),l=(await W(s,t,()=>E(t,{url:c,method:`POST`,body:i,async:!0}),`tasks`)).map(e=>e.output.task_id);if(a.noWait||t.async){z({task_ids:l},o);return}let u=a.pollInterval??3,d=l.map(e=>H(t,{url:M(t.baseUrl,e),intervalSec:u,timeoutSec:t.timeout,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}})),f=await Promise.all(d),p=[];for(let e of f){if(e.output.choices){let t=e.output.choices.flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean);p.push(...t)}if(e.output.results){let t=e.output.results.map(e=>e.url).filter(Boolean);t.length>0&&p.length===0&&p.push(...t)}}if(p.length===0)throw new e(`All tasks completed but no images returned.`,r.GENERAL);await Gt(p,a,t,o,l.length===1?l[0]:void 0,l)}async function Gt(e,t,n,r,i,a){let o=j(n,{flagDir:t.outDir,subDir:t.outDir?void 0:`images`}),s=t.prompt||t._positional?.[0]||``,c=t.outPrefix||g(`image`,s),l=await De(e.length>1?e.map((e,t)=>({url:e,destPath:G(o,`${c}_${String(t+1).padStart(3,`0`)}.png`)})):[{url:e[0],destPath:G(o,`${c}.png`)}],L,{quiet:n.quiet});if(n.quiet)R(l.join(`
|
|
22
|
+
`));else{let t={urls:e,saved:l,total:e.length};i&&(t.task_id=i),a&&a.length>1&&(t.task_ids=a),z(t,r)}}var Kt=f({description:`Edit an existing image with text instructions (Qwen-Image)`,usageArgs:`--image <url> --prompt <text> [flags]`,options:[{flag:`--image <url>`,description:`Source image URL or local file path (repeatable for multi-image merge)`,required:!0,type:`array`},{flag:`--prompt <text>`,description:`Edit instruction text`,required:!0},{flag:`--model <model>`,description:`Model ID (default: qwen-image-2.0)`},{flag:`--size <W*H>`,description:`Output image size: ratio (3:4, 16:9) or pixels (2048*2048)`},{flag:`--n <count>`,description:`Number of images (default: 1, max: 6)`,type:`number`},{flag:`--seed <n>`,description:`Random seed for reproducible results`,type:`number`},{flag:`--negative-prompt <text>`,description:`Negative prompt to exclude unwanted content`},{flag:`--prompt-extend <bool>`,description:Se},{flag:`--watermark <bool>`,description:P},{flag:`--out-dir <dir>`,description:`Download images to directory`},{flag:`--out-prefix <prefix>`,description:`Filename prefix (default: edited)`}],exampleArgs:[`--image ./photo.png --prompt "Replace the background with a beach"`,`--image https://example.com/logo.png --prompt "Change color to blue" --n 3`,`--image ./a.png --image ./b.png --prompt "Merge two images into one collage"`,`--image https://example.com/photo.png --prompt "Remove the person" --model qwen-image-2.0-pro`,`--image ./photo.png --prompt "Replace the background with a beach" --watermark false`],async run(t,n){let i=[];Array.isArray(n.image)?i=n.image:typeof n.image==`string`&&(i=[n.image]),i.length===0&&B(`image`,F(t,`--image <url> --prompt <text>`));let a=n.prompt;if(!a)if(S({nonInteractive:t.nonInteractive})){let e=await U({message:`Enter your edit instruction:`});e||(process.stderr.write(`Image editing cancelled.
|
|
23
|
+
`),process.exit(1)),a=e}else B(`prompt`,F(t,`--image <url> --prompt <text>`));let o=n.model||t.defaultImageModel||`qwen-image-2.0`,s=await k(t),c=await Promise.all(i.map(e=>A(e,s.token,o))),l=n.n??1,u=D(n.promptExtend,!0,`prompt-extend`),d=c.map(e=>({image:e}));d.push({text:a});let f=de(n.watermark),m={model:o,input:{messages:[{role:`user`,content:d}]},parameters:{size:Re(n.size,!0),n:l,seed:n.seed,prompt_extend:u,watermark:f,negative_prompt:n.negativePrompt||void 0}};he(m.parameters);let h=p(t.output);if(t.dryRun){z({request:m},h);return}t.quiet||process.stderr.write(`[Model: ${o}] [Mode: sync] [Images: ${c.length}]\n`);let _=x(t.baseUrl),v=(await W(Me(n),t,()=>E(t,{url:_,method:`POST`,body:m}))).flatMap(e=>e.output.choices||[]).flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean);if(v.length===0)throw new e(`Edit completed but no images returned.`,r.GENERAL);let y=j(t,{flagDir:n.outDir,subDir:n.outDir?void 0:`images`}),b=n.outPrefix||g(`edited`,n?.prompt),C=await De(v.length>1?v.map((e,t)=>({url:e,destPath:G(y,`${b}_${String(t+1).padStart(3,`0`)}.png`)})):[{url:v[0],destPath:G(y,`${b}.png`)}],L,{quiet:t.quiet});t.quiet?R(C.join(`
|
|
24
|
+
`)):z({urls:v,saved:C,total:v.length},h)}}),qt=f({description:`Generate a video from text or image (happyhorse-1.0-t2v / happyhorse-1.0-i2v / wan2.6-t2v)`,usageArgs:`--prompt <text> [--image <url>] [flags]`,options:[{flag:`--model <model>`,description:`Model ID (default: happyhorse-1.0-t2v, or happyhorse-1.0-i2v with --image)`},{flag:`--prompt <text>`,description:`Video description`,required:!0},{flag:`--image <url>`,description:`Input image URL for image-to-video generation`},{flag:`--negative-prompt <text>`,description:`Negative prompt to exclude unwanted content`},{flag:`--resolution <res>`,description:`Resolution: 720P or 1080P (default: 1080P)`},{flag:`--ratio <ratio>`,description:`Aspect ratio (e.g. 16:9, 9:16, 1:1)`},{flag:`--duration <seconds>`,description:`Video duration in seconds (default: 5)`,type:`number`},{flag:`--prompt-extend <bool>`,description:xe},{flag:`--watermark <bool>`,description:P},{flag:`--seed <n>`,description:`Random seed for reproducible generation`,type:`number`},{flag:`--download <path>`,description:`Save video to file on completion`},{flag:`--no-wait`,description:`Return task ID immediately without waiting`},{flag:`--async`,description:`Return task ID immediately (agent/CI mode, same as --no-wait)`},{flag:`--poll-interval <seconds>`,description:`Polling interval when waiting (default: 5)`,type:`number`}],exampleArgs:[`--prompt "A person reading a book, static shot"`,`--prompt "Ocean waves at sunset." --download sunset.mp4`,`--image https://example.com/cat.png --prompt "Make the cat in the scene move"`,`--prompt "Mountain landscape" --resolution 720P --duration 5`,`--prompt "A cat playing with a ball" --watermark false`],async run(t,n){let i=n.prompt;if(!i)if(S({nonInteractive:t.nonInteractive})){let e=await U({message:`Enter your video prompt:`});e||(process.stderr.write(`Video generation cancelled.
|
|
25
|
+
`),process.exit(1)),i=e}else B(`prompt`,F(t,`--prompt <text>`));let a=n.model||t.defaultVideoModel||(n.image?`happyhorse-1.0-i2v`:`happyhorse-1.0-t2v`),o=p(t.output),s=n.image,c;s&&(c=await A(s,(await k(t)).token,a));let l=de(n.watermark),u=D(n.promptExtend,void 0,`prompt-extend`),d={model:a,input:{prompt:i,negative_prompt:n.negativePrompt||void 0,...c?{media:[{type:`first_frame`,url:c}]}:{}},parameters:{resolution:n.resolution||void 0,ratio:n.ratio||void 0,duration:n.duration||void 0,prompt_extend:u,watermark:l,seed:n.seed}};if(t.dryRun){z({request:d},o);return}let f=Me(n),m=ye(t.baseUrl),h=(await W(f,t,()=>E(t,{url:m,method:`POST`,body:d,async:!0}),`tasks`)).map(e=>e.output.task_id);if(t.quiet||process.stderr.write(`[Model: ${a}]\n`),n.noWait||t.async){z(h.length===1?{task_id:h[0]}:{task_ids:h},o);return}let g=n.pollInterval??5,_=h.map(e=>H(t,{url:M(t.baseUrl,e),intervalSec:g,timeoutSec:t.timeout,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}})),v=await Promise.all(_),y=[];for(let e=0;e<v.length;e++){let t=v[e],n=t.output.video_url||t.output.results&&t.output.results[0]?.url;n&&y.push({taskId:h[e],videoUrl:n})}if(y.length===0)throw new e(`All tasks completed but no video URLs returned.`,r.GENERAL);if(n.download){let e=n.download,{size:r}=await L(y[0].videoUrl,e,{quiet:t.quiet});t.quiet?R(e):z({task_id:y[0].taskId,video_url:y[0].videoUrl,status:`SUCCEEDED`,saved:e,size:je(r)},o);return}let b=j(t,{subDir:`videos`}),{join:x}=await import(`path`),C=[];await Promise.all(y.map(async({taskId:e,videoUrl:n})=>{let r=x(b,`${e}.mp4`);await L(n,r,{quiet:t.quiet}),C.push({task_id:e,video_url:n,saved:r})})),C.length===1?z(C[0],o):z({videos:C,total:C.length},o)}}),Jt=f({description:`Edit a video with happyhorse-1.0-video-edit (style transfer, object replacement, etc.)`,usageArgs:`--video <url> --prompt <text> [flags]`,options:[{flag:`--model <model>`,description:`Model ID (default: happyhorse-1.0-video-edit)`},{flag:`--video <url>`,description:`Input video URL or local file (mp4/mov, 2-10s)`,required:!0},{flag:`--prompt <text>`,description:`Edit instruction (e.g. "Convert the scene to a claymation style")`},{flag:`--ref-image <url>`,description:`Reference image URL (up to 4, comma-separated)`},{flag:`--negative-prompt <text>`,description:`Negative prompt to exclude unwanted content`},{flag:`--resolution <res>`,description:`Resolution: 720P or 1080P (default: 1080P)`},{flag:`--ratio <ratio>`,description:`Aspect ratio (16:9, 9:16, 1:1, 4:3, 3:4)`},{flag:`--duration <seconds>`,description:`Output video duration in seconds (2-10)`,type:`number`},{flag:`--audio-setting <mode>`,description:`Audio: auto (default) or origin (keep original)`},{flag:`--prompt-extend <bool>`,description:xe},{flag:`--watermark <bool>`,description:P},{flag:`--seed <n>`,description:`Random seed for reproducible generation`,type:`number`},{flag:`--download <path>`,description:`Save video to file on completion`},{flag:`--no-wait`,description:`Return task ID immediately without waiting`},{flag:`--async`,description:`Return task ID immediately (agent/CI mode, same as --no-wait)`},{flag:`--poll-interval <seconds>`,description:`Polling interval when waiting (default: 15)`,type:`number`}],exampleArgs:[`--video https://example.com/input.mp4 --prompt "Convert the entire scene to claymation style"`,`--video https://example.com/input.mp4 --prompt "Replace the outfit with the style shown in the image" --ref-image https://example.com/clothes.png`,`--video https://example.com/input.mp4 --prompt "Convert to anime style" --resolution 720P --download output.mp4`,`--video https://example.com/input.mp4 --prompt "Put clothes on the kitten in the video" --watermark false`],async run(t,n){let i=n.video;if(!i)if(S({nonInteractive:t.nonInteractive})){let e=await U({message:`Enter the video URL to edit:`});e||(process.stderr.write(`Video editing cancelled.
|
|
26
|
+
`),process.exit(1)),i=e}else B(`video`,F(t,`--video <url> --prompt <text>`));let a=n.prompt;if(!a&&S({nonInteractive:t.nonInteractive})){let e=await U({message:`Enter your edit instruction:`});e||(process.stderr.write(`Video editing cancelled.
|
|
27
|
+
`),process.exit(1)),a=e}let o=n.model||`happyhorse-1.0-video-edit`,s=p(t.output),c=await k(t),l=[{type:`video`,url:await A(i,c.token,o)}],u=n.refImage;if(u){let e=u.split(`,`).map(e=>e.trim()).filter(Boolean);for(let t of e){let e=await A(t,c.token,o);l.push({type:`reference_image`,url:e})}}let d=D(n.promptExtend,void 0,`prompt-extend`),f=de(n.watermark),m={model:o,input:{prompt:a||void 0,negative_prompt:n.negativePrompt||void 0,media:l},parameters:{resolution:n.resolution||void 0,ratio:n.ratio||void 0,duration:n.duration||void 0,audio_setting:n.audioSetting||void 0,prompt_extend:d,watermark:f,seed:n.seed}};if(t.dryRun){z({request:m},s);return}let h=(await E(t,{url:ye(t.baseUrl),method:`POST`,body:m,async:!0})).output.task_id;if(t.quiet||(process.stderr.write(`[Model: ${o}]\n`),process.stderr.write(`Note: Video editing typically takes 5-8 minutes. Please be patient.
|
|
28
|
+
`)),n.noWait||t.async){z({task_id:h},s);return}let g=n.pollInterval??15,_=await H(t,{url:M(t.baseUrl,h),intervalSec:g,timeoutSec:Math.max(t.timeout,600),isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}}),v=_.output.video_url||_.output.results&&_.output.results[0]?.url;if(!v)throw new e(`Task completed but no video URL returned.`,r.GENERAL);if(n.download){let e=n.download,{size:r}=await L(v,e,{quiet:t.quiet});t.quiet?R(e):z({task_id:h,video_url:v,status:`SUCCEEDED`,saved:e,size:je(r)},s);return}let y=await import(`path`),b=j(t,{subDir:`videos`}),x=y.join(b,`${h}.mp4`);await L(v,x,{quiet:t.quiet}),z({task_id:h,video_url:v,saved:x},s)}}),Yt=f({description:`Reference-to-video generation (happyhorse-1.0-r2v / wan2.6-r2v): multi-subject, multi-shot with voice`,usageArgs:`--prompt <text> --image <url>... [--ref-video <url>...] [flags]`,options:[{flag:`--model <model>`,description:`Model ID (default: happyhorse-1.0-r2v)`},{flag:`--prompt <text>`,description:`Video description with reference markers (image1, video1, etc.)`,required:!0},{flag:`--image <url>`,description:`Reference image URL or local file (repeatable for multiple subjects)`,type:`array`},{flag:`--ref-video <url>`,description:`Reference video URL or local file (repeatable)`,type:`array`},{flag:`--image-voice <url>`,description:`Voice URL for corresponding image (pairs by position)`,type:`array`},{flag:`--video-voice <url>`,description:`Voice URL for corresponding ref-video (pairs by position)`,type:`array`},{flag:`--resolution <res>`,description:`Resolution: 720P or 1080P (default: 1080P)`},{flag:`--ratio <ratio>`,description:`Aspect ratio (16:9, 9:16, 1:1)`},{flag:`--duration <seconds>`,description:`Video duration in seconds (default: 5)`,type:`number`},{flag:`--prompt-extend <bool>`,description:xe},{flag:`--watermark <bool>`,description:P},{flag:`--seed <n>`,description:`Random seed for reproducible generation`,type:`number`},{flag:`--download <path>`,description:`Save video to file on completion`},{flag:`--no-wait`,description:`Return task ID immediately without waiting`},{flag:`--async`,description:`Return task ID immediately (agent/CI mode, same as --no-wait)`},{flag:`--poll-interval <seconds>`,description:`Polling interval when waiting (default: 15)`,type:`number`}],exampleArgs:[`--prompt "Image1 running on the grass" --image person.jpg`,`--prompt "Video 1 plays guitar, Image 1 walks over" --ref-video scene.mp4 --image person.jpg`,`--prompt "Image 1 speaks" --image person.jpg --image-voice voice.mp3 --resolution 1080P`,`--prompt "Image 1 and Image 2 have a conversation" --image a.jpg --image b.jpg --image-voice va.mp3 --image-voice vb.mp3`,`--prompt "Image 1 drinks water" --image person.jpg --watermark false`],async run(t,n){let i=n.prompt;if(!i)if(S({nonInteractive:t.nonInteractive})){let e=await U({message:`Enter your video prompt (use Image1, Video1 to reference inputs):`});e||(process.stderr.write(`Video generation cancelled.
|
|
29
|
+
`),process.exit(1)),i=e}else B(`prompt`,F(t,`--prompt <text> --image <url>`));let a=n.image||[],o=n.refVideo||[];if(a.length===0&&o.length===0)throw new e(`At least one --image or --ref-video is required.`,r.USAGE,F(t,`--prompt "description" --image person.jpg`));let s=n.imageVoice||[],c=n.videoVoice||[],l=n.model||`happyhorse-1.0-r2v`,u=p(t.output),d=await k(t),f=[];for(let e=0;e<a.length;e++){let t={type:`reference_image`,url:await A(a[e],d.token,l)};s[e]&&(t.reference_voice=await A(s[e],d.token,l)),f.push(t)}for(let e=0;e<o.length;e++){let t={type:`reference_video`,url:await A(o[e],d.token,l)};c[e]&&(t.reference_voice=await A(c[e],d.token,l)),f.push(t)}let m=D(n.promptExtend,void 0,`prompt-extend`),h=de(n.watermark),g={model:l,input:{prompt:i,media:f},parameters:{resolution:n.resolution||void 0,ratio:n.ratio||void 0,duration:n.duration||void 0,prompt_extend:m,watermark:h,seed:n.seed}};if(t.dryRun){z({request:g},u);return}let _=(await E(t,{url:ye(t.baseUrl),method:`POST`,body:g,async:!0})).output.task_id;if(t.quiet||(process.stderr.write(`[Model: ${l}]\n`),process.stderr.write(`Note: Reference-to-video typically takes 5-10 minutes. Please be patient.
|
|
30
|
+
`)),n.noWait||t.async){z({task_id:_},u);return}let v=n.pollInterval??15,y=await H(t,{url:M(t.baseUrl,_),intervalSec:v,timeoutSec:Math.max(t.timeout,600),isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>{let t=e.output;return t.message||t.code||void 0}}),b=y.output.video_url||y.output.results&&y.output.results[0]?.url;if(!b)throw new e(`Task completed but no video URL returned.`,r.GENERAL);if(n.download){let e=n.download,{size:r}=await L(b,e,{quiet:t.quiet});t.quiet?R(e):z({task_id:_,video_url:b,status:`SUCCEEDED`,saved:e,size:je(r)},u);return}let{join:x}=await import(`path`),C=x(j(t,{subDir:`videos`}),`${_}.mp4`);await L(b,C,{quiet:t.quiet}),z({task_id:_,video_url:b,saved:C},u)}}),Xt=f({description:`Query async task status`,usageArgs:`--task-id <id>`,options:[{flag:`--task-id <id>`,description:`Async task ID`}],exampleArgs:[`--task-id 3b256896-3e70-xxxx-xxxx-xxxxxxxxxxxx`,`--task-id 3b256896-3e70-xxxx --output json`],async run(e,t){let n=t.taskId;n||B(`task-id`,F(e,`--task-id <id>`));let r=p(e.output);if(e.dryRun){z({task_id:n},r);return}let i=await E(e,{url:M(e.baseUrl,n)});if(e.quiet){R(i.output.task_status);return}z({task_id:i.output.task_id,task_status:i.output.task_status,video_url:i.output.video_url,results:i.output.results,submit_time:i.output.submit_time,end_time:i.output.end_time},r)}}),Zt=f({description:`Download a completed video by task ID`,usageArgs:`--task-id <id> --out <path>`,options:[{flag:`--task-id <id>`,description:`Task ID to download from`},{flag:`--out <path>`,description:`Output file path`}],exampleArgs:[`--task-id 3b256896-xxxx --out video.mp4`,`--task-id 3b256896-xxxx --out video.mp4 --quiet`],async run(t,n){let i=n.taskId;i||B(`task-id`,F(t,`--task-id <id> --out <path>`));let a=n.out;a||B(`out`,F(t,`--task-id <id> --out video.mp4`));let o=p(t.output);if(t.dryRun){z({task_id:i,action:`download`,out:a},o);return}let s=await E(t,{url:M(t.baseUrl,i)});if(s.output.task_status!==`SUCCEEDED`)throw new e(`Task is not complete (status: ${s.output.task_status}).`,r.GENERAL,`Wait for the task to complete before downloading.`);let c=s.output.video_url||s.output.results&&s.output.results[0]?.url;if(!c)throw new e(`No download URL available for this task.`,r.GENERAL);let{size:l}=await L(c,a,{quiet:t.quiet});if(t.quiet){R(a);return}z({saved:a,size:je(l)},o)}});const Qt={".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".png":`image/png`,".webp":`image/webp`},$t=new Set([`.mp4`,`.mov`,`.avi`,`.mkv`,`.webm`,`.flv`,`.wmv`]);function en(e){let t=qe(e).toLowerCase().split(`?`)[0];return!!($t.has(t)||/\.(mp4|mov|avi|mkv|webm|flv|wmv)(\?|$)/i.test(e))}async function tn(t){if(t.startsWith(`data:`)||t.startsWith(`http://`)||t.startsWith(`https://`)||t.startsWith(`oss://`))return t;if(!We(t))throw new e(`File not found: ${t}`,r.USAGE);let n=qe(t).toLowerCase(),i=Qt[n];if(!i)throw new e(`Unsupported image format "${n}". Supported: jpg, jpeg, png, webp`,r.USAGE);return`data:${i};base64,${Ge(t).toString(`base64`)}`}var nn=f({description:`Describe an image or video using Qwen-VL`,usageArgs:`--image <path-or-url> [--video <url>] [--prompt <text>]`,options:[{flag:`--image <path-or-url>`,description:`Local image path or URL`},{flag:`--video <url>`,description:`Video file URL or local path (mp4/mov/avi/mkv/webm)`,type:`array`},{flag:`--prompt <text>`,description:`Question about the content (default: auto-detected)`},{flag:`--model <model>`,description:`Vision model (default: qwen3-vl-plus)`}],exampleArgs:[`--image photo.jpg`,`--image https://example.com/photo.jpg --prompt "What breed is this dog?"`,`--video https://example.com/video.mp4 --prompt "Summarize the video content"`,`--video ./local-video.mp4`,`--image photo.png --prompt "Extract the text" --model qwen-vl-plus`],async run(t,n){let i=n.image??n._positional?.[0],a=n.video??[],o=n.model||`qwen3-vl-plus`;i&&en(i)&&(a.push(i),i=void 0);let s=a.length>0,c=s?`Describe the video.`:`Describe the image.`,l=n.prompt||c;if(!i&&!s)if(S({nonInteractive:t.nonInteractive})){let e=await U({message:`Enter image/video path or URL:`});e||(process.stderr.write(`Vision describe cancelled.
|
|
31
|
+
`),process.exit(1)),en(e)?a.push(e):i=e}else throw new e(`Missing required argument --image or --video.`,r.USAGE,`${F(t,`--image <path-or-url>`)}\n${F(t,`--video <url-or-path>`)}`);let d=p(t.output);if(t.dryRun){z({request:{prompt:l,image:i,video:a.length?a:void 0,model:o}},d);return}let f=[];if(a.length>0)for(let n of a){let i=n;if(C(n)){if(!We(n))throw new e(`Video file not found: ${n}`,r.USAGE);i=await A(n,(await k(t)).token,o)}f.push({type:`video_url`,video_url:{url:i}})}if(i){let e=await tn(i),n=e;if(C(i)&&e.startsWith(`data:`)){let{statSync:e}=await import(`fs`);if(e(i).size>5*1024*1024){let e=await k(t);n=await A(i,e.token,o)}}f.push({type:`image_url`,image_url:{url:n}})}f.push({type:`text`,text:l});let m={model:o,messages:[{role:`user`,content:f}]},h=await E(t,{url:u(t.baseUrl),method:`POST`,body:m}),g=h.choices?.[0]?.message?.content;if(d!==`text`){z(h,d);return}R(g||``)}}),rn=f({description:`Display current configuration`,skipDefaultApiKeySetup:!0,exampleArgs:[``,`--output json`],async run(e,t){let n=T(),r=p(e.output),i={...n,base_url:e.baseUrl,output:e.output,timeout:e.timeout,config_file:v()};typeof i.api_key==`string`&&(i.api_key=w(i.api_key)),typeof i.access_token==`string`&&(i.access_token=w(i.access_token)),typeof i.access_key_id==`string`&&(i.access_key_id=w(i.access_key_id)),typeof i.access_key_secret==`string`&&(i.access_key_secret=w(i.access_key_secret)),z(i,r)}});const an=[`base_url`,`output`,`output_dir`,`timeout`,`api_key`,`access_token`,`default_text_model`,`default_video_model`,`default_image_model`,`default_speech_model`,`default_omni_model`,`access_key_id`,`access_key_secret`,`workspace_id`],on=new Set([`api_key`,`access_token`,`access_key_id`,`access_key_secret`]),sn={"base-url":`base_url`,"output-dir":`output_dir`,"api-key":`api_key`,"access-token":`access_token`,"default-text-model":`default_text_model`,"default-video-model":`default_video_model`,"default-image-model":`default_image_model`,"default-speech-model":`default_speech_model`,"default-omni-model":`default_omni_model`,"access-key-id":`access_key_id`,"access-key-secret":`access_key_secret`,"workspace-id":`workspace_id`};var cn=f({description:`Set a config value`,skipDefaultApiKeySetup:!0,usageArgs:`--key <key> --value <value>`,options:[{flag:`--key <key>`,description:`Config key (base_url, output, output_dir, timeout, api_key, access_token, default_*_model, access_key_id, access_key_secret, workspace_id)`},{flag:`--value <value>`,description:`Value to set`}],exampleArgs:[`--key output --value json`,`--key timeout --value 600`,`--key base_url --value https://dashscope.aliyuncs.com`],async run(t,n){let i=n.key,a=n.value;if(!i||a===void 0)throw new e(`--key and --value are required.`,r.USAGE,F(t,`--key <key> --value <value>`));let o=sn[i]||i;if(!an.includes(o))throw new e(`Invalid config key "${i}". Valid keys: ${an.join(`, `)}`,r.USAGE);if(o===`output`&&![`text`,`json`].includes(a))throw new e(`Invalid output format "${a}". Valid values: text, json`,r.USAGE);if(o===`timeout`){let t=Number(a);if(isNaN(t)||t<=0)throw new e(`Invalid timeout "${a}". Must be a positive number.`,r.USAGE)}let s=p(t.output);if(t.dryRun){z({would_set:{[o]:a}},s);return}let c=T();if(c[o]=o===`timeout`?Number(a):a,await N(c),!t.quiet){let e=on.has(o)?w(String(c[o])):c[o];z({[o]:e},s)}}});const ln=`npx skills add modelstudioai/cli --all -g -y`;function un(e){return{cmd:`npm install -g ${e}@latest`,label:`npm`}}function dn(e){let{green:t,yellow:n,reset:r}=e;process.stderr.write(`
|
|
32
|
+
Updating agent skill...
|
|
33
|
+
`);try{Je(ln,{stdio:`inherit`}),process.stderr.write(`${t}\u2713 Agent skill updated.${r}\n`)}catch{process.stderr.write(`${n}Agent skill update skipped. Run manually: ${ln}${r}\n`)}}var fn=f({description:`Update the CLI to the latest version`,skipDefaultApiKeySetup:!0,exampleArgs:[``],async run(e){let t=e.npmPackage,n=e.binName,r=e.clientVersion,i=process.stderr.isTTY,a=i?`\x1B[32m`:``,o=i?`\x1B[33m`:``,s=i?`\x1B[0m`:``;process.stderr.write(`Current version: ${o}${r}${s}\n`),process.stderr.write(`Checking for updates...
|
|
34
|
+
`);let c=await Ae(5e3,t);if(c&&c===r){process.stderr.write(`${a}\u2713 Already up to date (${r}).${s}\n`),dn({green:a,yellow:o,reset:s});return}c&&process.stderr.write(`Latest version: ${a}${c}${s}\n\n`);let{cmd:l,label:u}=un(t);process.stderr.write(`Updating ${t} via ${u}...\n\n`);try{Je(l,{stdio:`inherit`});try{let e=Je(`${n} --version 2>/dev/null`,{encoding:`utf-8`}).trim().replace(RegExp(`^${n}\\s+`),``);process.stderr.write(`\n${a}\u2713 Update complete: ${r} \u2192 ${e}${s}\n`);try{Ke(G(_(),`update-state.json`),JSON.stringify({lastChecked:Date.now(),latestVersion:e}))}catch{}}catch{process.stderr.write(`\n${a}\u2713 Update complete.${s}\n`)}dn({green:a,yellow:o,reset:s})}catch{process.stderr.write(`
|
|
35
|
+
Automatic update failed. Please run manually:
|
|
36
|
+
`),process.stderr.write(` ${l}\n\n`)}}}),pn=f({description:`Call a Bailian application (agent or workflow)`,usageArgs:`--app-id <id> --prompt <text> [flags]`,options:[{flag:`--app-id <id>`,description:`Application ID (required)`,required:!0},{flag:`--prompt <text>`,description:`Input prompt text`,required:!0},{flag:`--image <url>`,description:`Image URL(s) to pass to the app (repeatable)`,type:`array`},{flag:`--file-id <id>`,description:`Pre-uploaded file ID(s) (repeatable)`,type:`array`},{flag:`--session-id <id>`,description:`Session ID for multi-turn conversation`},{flag:`--stream`,description:`Stream response (default: on in TTY)`},{flag:`--pipeline-ids <ids>`,description:`Knowledge base pipeline IDs (comma-separated)`},{flag:`--memory-id <id>`,description:`Memory ID for long-term memory`},{flag:`--biz-params <json>`,description:`Business parameters JSON (workflow variables)`},{flag:`--has-thoughts`,description:`Show agent thinking process`}],exampleArgs:[`--app-id abc123 --prompt "Hello"`,`--app-id abc123 --prompt "Describe this image" --image https://example.com/photo.jpg`,`--app-id abc123 --prompt "Analyze the image" --image img1.jpg --image img2.jpg`,`--app-id abc123 --prompt "Continue" --session-id sess_xxx --stream`,`--app-id abc123 --prompt "Search for materials" --pipeline-ids pipe1,pipe2`,`--app-id abc123 --prompt "Start" --biz-params '{"key":"value"}'`],async run(e,t){let n=t.appId;n||B(`app-id`,F(e,`--app-id <id> --prompt <text>`));let r=t.prompt;r||B(`prompt`,F(e,`--app-id <id> --prompt <text>`));let i=t.stream===!0||t.stream===void 0&&process.stdout.isTTY,a=p(e.output),s={input:{prompt:r},parameters:{incremental_output:i}};t.sessionId&&(s.input.session_id=t.sessionId);let c=t.image;c&&c.length>0&&(s.input.image_list=c);let l=t.fileId;if(l&&l.length>0&&(s.input.file_ids=l),t.hasThoughts&&(s.parameters.has_thoughts=!0),t.pipelineIds){let e=t.pipelineIds.split(`,`).map(e=>e.trim()).filter(Boolean);s.parameters.rag_options={pipeline_ids:e}}if(t.memoryId&&(s.parameters.memory_id=t.memoryId),t.bizParams)try{s.input.biz_params=JSON.parse(t.bizParams)}catch{process.stderr.write(`Error: --biz-params must be valid JSON
|
|
37
|
+
`),process.exit(1)}if(e.dryRun){z({endpoint:o(e.baseUrl,n),request:s},a);return}let u=o(e.baseUrl,n);if(i){let n=await ue(e,{url:u,method:`POST`,body:s,headers:{"X-DashScope-SSE":`enable`},stream:!0}),r=``,i=``,o=a===`text`,c=e.noColor?``:`\x1B[2m`,l=e.noColor?``:`\x1B[0m`;for await(let e of oe(n)){if(e.data===`[DONE]`)break;try{let n=JSON.parse(e.data),a=n.output?.text;if(a&&(o&&process.stdout.write(a),r+=a),n.output?.session_id&&(i=n.output.session_id),n.output?.thoughts&&t.hasThoughts)for(let e of n.output.thoughts)e.thought&&process.stderr.write(`${c}[Thinking] ${e.thought}${l}\n`),e.action_name&&process.stderr.write(`${c}[Action] ${e.action_name}: ${e.action_input||``}${l}\n`),e.observation&&process.stderr.write(`${c}[Observation] ${e.observation}${l}\n`)}catch{}}i&&!e.quiet&&process.stderr.write(`${c}Session ID: ${i}${l}\n`),a===`json`?z({text:r,session_id:i},a):process.stdout.write(`
|
|
38
|
+
`)}else{let t=await E(e,{url:u,method:`POST`,body:s}),n=t.output?.text??``;e.quiet||a===`text`?R(n):z(t,a)}}});const mn=`zeldaEasy.broadscope-bailian.app-control.list`;var hn=f({description:`List Bailian applications`,skipDefaultApiKeySetup:!0,usageArgs:`[flags]`,options:[{flag:`--name <name>`,description:`Filter by app name (keyword search)`},{flag:`--page <n>`,description:`Page number (default: 1)`,type:`number`},{flag:`--page-size <n>`,description:`Results per page (default: 30)`,type:`number`},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[``,`--name customer service`,`--page 2 --page-size 10`,`--output json`],async run(e,t){let n=t.name||``,r=t.page||1,i=t.pageSize||30,a=p(e.output),o=await O(e),s={reqDTO:{name:n,notInTypes:[10],type:5,statuses:[1,4],page_no:r,page_size:i}};if(e.dryRun){z({api:mn,data:s,token:o.token.slice(0,8)+`...`},a);return}let c=await l(e,o.token,{api:mn,data:s}),u=c?.data?.DataV2?.data?.data?.list??[];z({total:c?.data?.DataV2?.data?.data?.total??0,apps:u.map(e=>({code:e.code,name:e.name,user_prompt_params:e.config?.user_prompt_params??[]}))},a)}}),gn=f({description:`Add memory from messages or custom content`,usageArgs:`--user-id <id> [--messages <json>] [--content <text>] [flags]`,options:[{flag:`--user-id <id>`,description:`User ID (required)`,required:!0},{flag:`--messages <json>`,description:`Messages JSON array: [{"role":"user","content":"..."},...]`},{flag:`--content <text>`,description:`Custom content text to memorize`},{flag:`--profile-schema <id>`,description:`Profile schema ID for user profiling`},{flag:`--memory-library-id <id>`,description:`Memory library ID (isolate memory space)`}],exampleArgs:[`--user-id user1 --content "The user likes Python programming"`,`--user-id user1 --messages '[{"role":"user","content":"I like traveling"}]'`,`--user-id user1 --content "Lives in Beijing" --profile-schema schema_xxx`],async run(e,t){let n=t.userId;n||B(`user-id`,F(e,`--user-id <id>`));let r={user_id:n};if(t.messages)try{r.messages=JSON.parse(t.messages)}catch{process.stderr.write(`Error: --messages must be valid JSON array
|
|
39
|
+
`),process.exit(1)}t.content&&(r.custom_content=t.content),!r.messages&&!r.custom_content&&(process.stderr.write(`Error: at least one of --messages or --content is required
|
|
40
|
+
`),process.exit(1)),t.profileSchema&&(r.profile_schema=t.profileSchema),t.memoryLibraryId&&(r.memory_library_id=t.memoryLibraryId);let i=p(e.output);if(e.dryRun){z({endpoint:ne(e.baseUrl),request:r},i);return}let a=await E(e,{url:ne(e.baseUrl),method:`POST`,body:r});e.quiet||i===`text`?R(`Memory added. IDs: ${a.memory_ids?.join(`, `)||`none`}`):z(a,i)}}),_n=f({description:`Search memory nodes by query or messages`,usageArgs:`--user-id <id> [--query <text>] [flags]`,options:[{flag:`--user-id <id>`,description:`User ID (required)`,required:!0},{flag:`--query <text>`,description:`Search query text`},{flag:`--messages <json>`,description:`Messages JSON array for context-based search`},{flag:`--top-k <n>`,description:`Number of results to return (default: 10)`,type:`number`},{flag:`--memory-library-id <id>`,description:`Memory library ID`}],exampleArgs:[`--user-id user1 --query "programming preferences"`,`--user-id user1 --messages '[{"role":"user","content":"recommend a book"}]' --top-k 5`],async run(e,t){let n=t.userId;n||B(`user-id`,F(e,`--user-id <id>`));let r={user_id:n};if(t.query&&(r.query=t.query),t.messages)try{r.messages=JSON.parse(t.messages)}catch{process.stderr.write(`Error: --messages must be valid JSON array
|
|
41
|
+
`),process.exit(1)}!r.messages&&r.query&&(r.messages=[{role:`user`,content:r.query}]),!r.query&&!r.messages&&(process.stderr.write(`Error: at least one of --query or --messages is required
|
|
42
|
+
`),process.exit(1)),t.topK!==void 0&&(r.top_k=t.topK),t.memoryLibraryId&&(r.memory_library_id=t.memoryLibraryId);let i=p(e.output);if(e.dryRun){z({endpoint:ae(e.baseUrl),request:r},i);return}let a=await E(e,{url:ae(e.baseUrl),method:`POST`,body:r});if(e.quiet||i===`text`)if(!a.memory_nodes||a.memory_nodes.length===0)R(`No memory nodes found.`);else for(let e of a.memory_nodes)R(`[${e.memory_node_id}] ${e.content}`);else z(a,i)}}),vn=f({description:`List memory nodes for a user`,usageArgs:`--user-id <id> [flags]`,options:[{flag:`--user-id <id>`,description:`User ID (required)`,required:!0},{flag:`--page-size <n>`,description:`Results per page (default: 10)`,type:`number`},{flag:`--page <n>`,description:`Page number (default: 1)`,type:`number`},{flag:`--memory-library-id <id>`,description:`Memory library ID`}],exampleArgs:[`--user-id user1`,`--user-id user1 --page-size 20 --page 2`],async run(e,t){let n=t.userId;n||B(`user-id`,F(e,`--user-id <id>`));let r=p(e.output),i=new URLSearchParams;i.set(`user_id`,n),t.pageSize!==void 0&&i.set(`page_size`,String(t.pageSize)),t.page!==void 0&&i.set(`page_num`,String(t.page)),t.memoryLibraryId&&i.set(`memory_library_id`,t.memoryLibraryId);let a=`${re(e.baseUrl)}?${i.toString()}`;if(e.dryRun){z({endpoint:a,method:`GET`},r);return}let o=await E(e,{url:a,method:`GET`});if(e.quiet||r===`text`)if(!o.memory_nodes||o.memory_nodes.length===0)R(`No memory nodes found.`);else{for(let e of o.memory_nodes)R(`[${e.memory_node_id}] ${e.content}`);o.total!==void 0&&R(`\nTotal: ${o.total}`)}else z(o,r)}}),yn=f({description:`Update a memory node content`,usageArgs:`--node-id <id> --user-id <id> --content <text>`,options:[{flag:`--node-id <id>`,description:`Memory node ID (required)`,required:!0},{flag:`--user-id <id>`,description:`User ID (required)`,required:!0},{flag:`--content <text>`,description:`New content for the memory node (required)`,required:!0},{flag:`--memory-library-id <id>`,description:`Memory library ID (non-default library)`}],exampleArgs:[`--node-id node_xxx --user-id user1 --content "updated memory content"`],async run(e,t){let n=t.nodeId;n||B(`node-id`,F(e,`--node-id <id> --user-id <id> --content <text>`));let r=t.userId;r||B(`user-id`,F(e,`--node-id <id> --user-id <id> --content <text>`));let i=t.content;i||B(`content`,F(e,`--node-id <id> --user-id <id> --content <text>`));let a={user_id:r,custom_content:i};t.memoryLibraryId&&(a.memory_library_id=t.memoryLibraryId);let o=p(e.output);if(e.dryRun){z({endpoint:ie(e.baseUrl,n),method:`PATCH`,request:a},o);return}let s=await E(e,{url:ie(e.baseUrl,n),method:`PATCH`,body:a});e.quiet||o===`text`?R(`Memory node ${n} updated.`):z(s,o)}}),bn=f({description:`Delete a memory node`,usageArgs:`--node-id <id> --user-id <id>`,options:[{flag:`--node-id <id>`,description:`Memory node ID (required)`,required:!0},{flag:`--user-id <id>`,description:`User ID (required)`,required:!0},{flag:`--memory-library-id <id>`,description:`Memory library ID (non-default library)`}],exampleArgs:[`--node-id node_xxx --user-id user1`],async run(e,t){let n=t.nodeId;n||B(`node-id`,F(e,`--node-id <id> --user-id <id>`));let r=t.userId;r||B(`user-id`,F(e,`--node-id <id> --user-id <id>`));let i=p(e.output),a=new URLSearchParams({user_id:r});t.memoryLibraryId&&a.set(`memory_library_id`,t.memoryLibraryId);let o=`${ie(e.baseUrl,n)}?${a.toString()}`;if(e.dryRun){z({endpoint:o,method:`DELETE`},i);return}let s=await E(e,{url:o,method:`DELETE`});e.quiet||i===`text`?R(`Memory node ${n} deleted.`):z(s,i)}}),xn=f({description:`Create a user profile schema for memory profiling`,usageArgs:`--name <name> --attributes <json> [flags]`,options:[{flag:`--name <name>`,description:`Schema name (required)`,required:!0},{flag:`--description <text>`,description:`Schema description`},{flag:`--attributes <json>`,description:`Attributes JSON array: [{"name":"age","description":"age"}]`,required:!0}],exampleArgs:[`--name "user_basic" --attributes '[{"name":"age","description":"age"},{"name":"hobby","description":"hobby"}]'`],async run(e,t){let n=t.name;n||B(`name`,F(e,`--name <name> --attributes <json>`));let r=t.attributes;r||B(`attributes`,F(e,`--name <name> --attributes <json>`));let i;try{i=JSON.parse(r)}catch{process.stderr.write(`Error: --attributes must be valid JSON array
|
|
43
|
+
`),process.exit(1)}let a={name:n,attributes:i};t.description&&(a.description=t.description);let o=p(e.output);if(e.dryRun){z({endpoint:se(e.baseUrl),request:a},o);return}let s=await E(e,{url:se(e.baseUrl),method:`POST`,body:a});e.quiet||o===`text`?R(`Profile schema created: ${s.profile_schema_id}`):z(s,o)}}),Sn=f({description:`Get user profile by schema ID and user ID`,usageArgs:`--schema-id <id> --user-id <id>`,options:[{flag:`--schema-id <id>`,description:`Profile schema ID (required)`,required:!0},{flag:`--user-id <id>`,description:`User ID (required)`,required:!0}],exampleArgs:[`--schema-id schema_xxx --user-id user1`],async run(e,t){let n=t.schemaId;n||B(`schema-id`,F(e,`--schema-id <id> --user-id <id>`));let r=t.userId;r||B(`user-id`,F(e,`--schema-id <id> --user-id <id>`));let i=p(e.output),a=new URLSearchParams({user_id:r}),o=`${ve(e.baseUrl,n)}?${a.toString()}`;if(e.dryRun){z({endpoint:o,method:`GET`},i);return}let s=await E(e,{url:o,method:`GET`});if(e.quiet||i===`text`)if(s.profile?.attributes)for(let e of s.profile.attributes)R(`${e.name}: ${e.value??`(empty)`}`);else R(`No profile data found.`);else z(s,i)}});const Cn=`bailian.cn-beijing.aliyuncs.com`;var wn=f({description:`Retrieve from a Bailian knowledge base`,skipDefaultApiKeySetup:!0,usageArgs:`--index-id <id> --query <text> [flags]`,options:[{flag:`--index-id <id>`,description:`Knowledge base index ID (required)`,required:!0},{flag:`--query <text>`,description:`Search query (required)`,required:!0},{flag:`--dense-similarity-top-k <n>`,description:`Dense retrieval top K`,type:`number`},{flag:`--sparse-similarity-top-k <n>`,description:`Sparse retrieval top K`,type:`number`},{flag:`--rerank`,description:`Enable reranking`},{flag:`--rerank-top-n <n>`,description:`Rerank top N results`,type:`number`},{flag:`--rerank-model <name>`,description:`Rerank model, e.g. qwen3-rerank-hybrid`},{flag:`--rerank-mode <mode>`,description:`Rerank mode: qa, similar, or custom`},{flag:`--rerank-instruct <text>`,description:`Custom rerank instruction, when mode=custom`},{flag:`--top-k <n>`,description:`Number of results (deprecated, use --rerank-top-n)`,type:`number`},{flag:`--workspace-id <id>`,description:`Bailian workspace ID (only needed for deprecated AK/SK auth)`},{flag:`--access-key-id <key>`,description:`Deprecated: use global --api-key instead`},{flag:`--access-key-secret <key>`,description:`Deprecated: use global --api-key instead`}],notes:["Authentication: pass `--api-key <key>`. AK/SK auth is deprecated and will be removed in a future version.","`--workspace-id` is NOT required when using --api-key."],exampleArgs:[`--index-id idx_xxx --query "How to use Alibaba Cloud Bailian"`,`--api-key $DASHSCOPE_API_KEY --index-id idx_xxx --query "RAG retrieval" --rerank --rerank-model qwen3-rerank-hybrid`],async run(e,t){let n=t.indexId;n||B(`index-id`,F(e,`--index-id <id> --query <text>`));let r=t.query;r||B(`query`,F(e,`--index-id <id> --query <text>`));let i=p(e.output),a=!!e.apiKey,o=!!(t.accessKeyId&&t.accessKeySecret);if(a)await Tn(e,t,n,r,i);else if(o)await En(e,t,n,r,i);else{let a=!1;try{await k(e),a=!0}catch{}a?await Tn(e,t,n,r,i):await En(e,t,n,r,i)}}});async function Tn(e,t,n,r,i){t.topK!==void 0&&t.rerankTopN===void 0&&(process.stderr.write(`Warning: --top-k is deprecated. Use --rerank-top-n instead.
|
|
44
|
+
`),t.rerankTopN=t.topK);let a={index_id:n,query:r,search_filters:[]};if(t.denseSimilarityTopK!==void 0&&(a.dense_similarity_top_k=t.denseSimilarityTopK),t.sparseSimilarityTopK!==void 0&&(a.sparse_similarity_top_k=t.sparseSimilarityTopK),t.rerank&&(a.enable_reranking=!0),t.rerankTopN!==void 0&&(a.rerank_top_n=t.rerankTopN),t.rerankModel){let e={model_name:t.rerankModel};t.rerankMode&&(e.rerank_mode=t.rerankMode),t.rerankInstruct&&(e.rerank_instruct=t.rerankInstruct),a.rerank=[e]}let o=ee(e.baseUrl);if(e.dryRun){z({endpoint:o,request:a},i);return}let s=await E(e,{url:o,method:`POST`,body:a}),c=s.data?.nodes||[];e.quiet||i===`text`?Dn(c.map(e=>({text:e.text,score:e.score}))):z(s,i)}async function En(t,n,i,a,o){let s=n.accessKeyId||t.accessKeyId,c=n.accessKeySecret||t.accessKeySecret,l=n.workspaceId||t.workspaceId;if(!s||!c)throw new e(`No credentials found.
|
|
45
|
+
Preferred: set DASHSCOPE_API_KEY or pass --api-key.
|
|
46
|
+
Legacy (deprecated): set ALIBABA_CLOUD_ACCESS_KEY_ID / ALIBABA_CLOUD_ACCESS_KEY_SECRET.`,r.AUTH);if(!l)throw new e(`Knowledge retrieve requires a workspace ID.
|
|
47
|
+
Set via: --workspace-id flag, or env: BAILIAN_WORKSPACE_ID, or config: ${t.binName} config set workspace_id <id>`,r.USAGE);process.stderr.write(`Warning: AK/SK auth for knowledge retrieve is deprecated. Prefer --api-key or DASHSCOPE_API_KEY.
|
|
48
|
+
`);let u={IndexId:i,Query:a};if(n.topK!==void 0&&n.rerankTopN===void 0&&(process.stderr.write(`Warning: --top-k is deprecated. Use --rerank-top-n instead.
|
|
49
|
+
`),n.rerankTopN=n.topK),n.rerank&&(u.EnableReranking=!0),n.rerankTopN!==void 0&&(u.RerankTopN=n.rerankTopN),n.denseSimilarityTopK!==void 0&&(u.DenseSimilarityTopK=n.denseSimilarityTopK),n.sparseSimilarityTopK!==void 0&&(u.SparseSimilarityTopK=n.sparseSimilarityTopK),n.rerankModel){let e={ModelName:n.rerankModel};n.rerankMode&&(e.RerankMode=n.rerankMode),n.rerankInstruct&&(e.RerankInstruct=n.rerankInstruct),u.Rerank=[e]}let d=`/${l}/index/retrieve`;if(t.dryRun){z({endpoint:`https://${Cn}${d}`,workspaceId:l,request:u},o);return}let f=JSON.stringify(u),p=fe({accessKeyId:s,accessKeySecret:c,action:`Retrieve`,version:`2023-12-29`,body:f,host:Cn,pathname:d}),m=`https://${Cn}${d}`;t.verbose&&(process.stderr.write(`> POST ${m}\n`),process.stderr.write(`> AK: ${w(s)}\n`));let h=t.timeout*1e3,g=await fetch(m,{method:`POST`,headers:{...p,...ge()},body:f,signal:AbortSignal.timeout(h)});t.verbose&&process.stderr.write(`< ${g.status} ${g.statusText}\n`);let _=await g.json();if(!g.ok||_.Code&&_.Code!==`Success`)throw new e(`Knowledge retrieve failed: ${_.Code||g.status} - ${_.Message||g.statusText}`,r.GENERAL);let v=_.Data?.Nodes||[];t.quiet||o===`text`?Dn(v.map(e=>({text:e.Text,score:e.Score}))):z(_,o)}function Dn(e){if(e.length===0)R(`No results found.`);else for(let t=0;t<e.length;t++){let n=e[t];R(`[${t+1}] (score: ${n.score.toFixed(4)})`),R(n.text),R(``)}}function On(e){let t={};for(let n of e){let e=n.indexOf(`=`);e<=0&&(process.stderr.write(`Error: --arg must be in K=V form, got: ${n}\n`),process.exit(1));let r=n.slice(0,e).trim(),i=n.slice(e+1);try{t[r]=JSON.parse(i)}catch{t[r]=i}}return t}var kn=f({description:`Call a tool on an MCP server (tools/call)`,skipDefaultApiKeySetup:!0,usageArgs:`<server-code>.<tool> [--arg k=v ...] [--json '{...}'] [--url <url>]`,options:[{flag:`<server-code>.<tool>`,description:`Server code and tool name joined by a dot, e.g. market-cmapi00073529.SmartStockSelection`,required:!0},{flag:`--arg <kv>`,description:`Tool argument (repeatable). Values parsed as JSON if possible, else string.`,type:`array`},{flag:`--json <obj>`,description:`Full arguments object as JSON; merged with --arg (arg wins).`},{flag:`--query <text>`,description:`Shortcut for --arg query=<text> (mirrors many DashScope MCP tools).`},{flag:`--url <url>`,description:`Override the MCP endpoint URL (for non-Bailian servers)`}],exampleArgs:[`market-cmapi00073529.SmartStockSelection --query "Screen consumer stocks with ROE > 15%"`,`market-cmapi00073529.FinQuery --json '{"q":"Guizhou Maotai","limit":5}'`,`market-cmapi00073529.SmartFundSelection --arg riskLevel=R3 --arg minScale=10`],async run(e,t){let n=(t._positional??[])[0];n||B(`<server-code>.<tool>`,F(e,`<server-code>.<tool>`));let r=n.indexOf(`.`);(r<=0||r===n.length-1)&&(process.stderr.write(`Error: target must be <server-code>.<tool>, got "${n}".\n`),process.exit(1));let a=n.slice(0,r),o=n.slice(r+1),c={};if(t.json)try{let e=JSON.parse(t.json);(!e||typeof e!=`object`||Array.isArray(e))&&(process.stderr.write(`Error: --json must decode to an object.
|
|
50
|
+
`),process.exit(1)),c=e}catch(e){process.stderr.write(`Error: --json is not valid JSON — ${e.message}\n`),process.exit(1)}Object.assign(c,On(t.arg??[])),t.query!==void 0&&(c.query=t.query);let l=t.url||s(e.baseUrl,a),u=p(e.output);if(e.dryRun){z({server:a,url:l,tool:o,arguments:c},u);return}await Oe(e);let d=new i(e,l);await d.initialize();let f=await d.callTool(o,c);if(f.isError){let e=f.content.map(e=>e.text||``).join(`
|
|
51
|
+
`);process.stderr.write(`Tool error: ${e}\n`),process.exit(1)}z(f,u)}});const An=`zeldaEasy.broadscope-bailian.mcp-server.PageList`;var jn=f({description:`List MCP servers activated under your Bailian account`,skipDefaultApiKeySetup:!0,usageArgs:`[flags]`,options:[{flag:`--name <text>`,description:`Filter by server name (substring match)`},{flag:`--type <type>`,description:`Server type: OFFICIAL | PRIVATE (default: OFFICIAL)`},{flag:`--page <n>`,description:`Page number (default: 1)`,type:`number`},{flag:`--page-size <n>`,description:`Results per page (default: 30)`,type:`number`},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[``,`--name finance`,`--output json`],async run(t,n){let i=n.name||``,a=n.type||`OFFICIAL`,o=n.page||1,s=n.pageSize||30,c=p(t.output),u={reqDTO:{type:a,displayTools:!1,activated:1,pageNo:o,pageSize:s,serverName:i}};if(t.dryRun){z({api:An,data:u,...m(t)},c);return}let d=(await l(t,(await O(t)).token,{api:An,data:u}))?.data??{};if(d.success===!1){let n=d.errorCode??`UnknownError`,i=d.errorMsg??n,a=n===`BailianGateway.Login.NotLogined`?`Run \`${t.binName} auth login --console\` to refresh your console session.`:void 0;throw new e(`Console gateway: ${i}`,r.AUTH,a)}let f=(d.DataV2??{}).data?.data??{},h=f.mcpServerDetailList??[];z({total:f.total??0,servers:h.map(e=>({code:e.serverCode??``,name:e.serverName??``,description:e.description,type:e.type??``,source:e.source,bizType:e.bizType,installType:e.installType,streamable:e.streamable===!0}))},c)}}),Mn=f({description:`List tools exposed by an MCP server (tools/list)`,skipDefaultApiKeySetup:!0,usageArgs:`<server-code> [--url <url>]`,options:[{flag:`<server-code>`,description:"Server code from `mcp list` (e.g. market-cmapi00073529)",required:!0},{flag:`--url <url>`,description:`Override the MCP endpoint URL (for non-Bailian servers)`}],exampleArgs:[`market-cmapi00073529`,`market-cmapi00073529 --output json`,`my-server --url https://example.com/mcp`],async run(e,t){let n=(t._positional??[])[0];n||B(`server-code`,F(e,`<server-code>`));let r=t.url||s(e.baseUrl,n),a=p(e.output);if(e.dryRun){z({server:n,url:r,action:`tools/list`},a);return}await Oe(e);let o=new i(e,r);await o.initialize(),z({server:n,url:r,tools:await o.listTools()},a)}}),Nn=f({description:`Search the web using DashScope MCP WebSearch service`,usageArgs:`--query <text> [flags]`,options:[{flag:`--query <text>`,description:`Search query text`,required:!0},{flag:`--count <n>`,description:`Number of search results (default: 10)`,type:`number`},{flag:`--list-tools`,description:`List available MCP tools and exit`}],exampleArgs:[`--query "Alibaba Cloud Bailian latest features"`,`--query "TypeScript 5.9 new features" --count 5`,`--query "Today's news"`,`--list-tools`],async run(e,t){let n=te(e.baseUrl),r=p(e.output);if(t.listTools){if(e.dryRun){z({endpoint:n,action:`tools/list`},r);return}let t=new i(e,n);await t.initialize(),z({tools:await t.listTools()},r);return}let a=t.query;if(!a)if(S({nonInteractive:e.nonInteractive})){let e=await U({message:`Enter your search query:`});e||(process.stderr.write(`Search cancelled.
|
|
52
|
+
`),process.exit(1)),a=e}else B(`query`,F(e,`--query <text>`));if(e.dryRun){z({endpoint:n,action:`tools/call`,tool:`bailian_web_search`,arguments:{query:a,count:t.count||void 0}},r);return}let o=new i(e,n),s=Ee(`Initializing search...`);e.quiet||s.start();try{await o.initialize(),e.quiet||s.update(`Searching...`);let n={query:a};t.count&&(n.count=t.count);let i=await o.callTool(`bailian_web_search`,n);if(e.quiet||s.stop(`Done.`),i.isError){let e=i.content.map(e=>e.text||``).join(`
|
|
53
|
+
`);process.stderr.write(`Search error: ${e}\n`),process.exit(1)}if(r===`json`)z(i,r);else for(let e of i.content)if(e.type===`text`&&e.text)try{let t=JSON.parse(e.text);t.pages&&Array.isArray(t.pages)?z({pages:t.pages,total:t.pages.length},r):z(t,r)}catch{z({text:e.text},r)}}catch(e){throw s.stop(`Failed.`),e}}});const Pn=`${n.cn}/cosyvoice-clone-design-api`,Fn=[{voice:`longanyang`,name:`龙安洋`,desc:`阳光大男孩`,lang:`中文/英文`},{voice:`longanhuan`,name:`龙安欢`,desc:`欢脱元气女`,lang:`中文/英文`},{voice:`longantai_v3`,name:`龙安台`,desc:`嗲甜台湾女`,lang:`中文/英文`},{voice:`longhua_v3`,name:`龙华`,desc:`元气甜美女`,lang:`中文/英文`},{voice:`longcheng_v3`,name:`龙橙`,desc:`智慧青年男`,lang:`中文/英文`},{voice:`longze_v3`,name:`龙泽`,desc:`温暖元气男`,lang:`中文/英文`},{voice:`longzhe_v3`,name:`龙哲`,desc:`呆板大暖男`,lang:`中文/英文`},{voice:`longyan_v3`,name:`龙颜`,desc:`温暖春风女`,lang:`中文/英文`},{voice:`longxing_v3`,name:`龙星`,desc:`温婉邻家女`,lang:`中文/英文`},{voice:`longtian_v3`,name:`龙天`,desc:`磁性理智男`,lang:`中文/英文`},{voice:`longwan_v3`,name:`龙婉`,desc:`细腻柔声女`,lang:`中文/英文`},{voice:`longqiang_v3`,name:`龙嫱`,desc:`浪漫风情女`,lang:`中文/英文`},{voice:`longfeifei_v3`,name:`龙菲菲`,desc:`甜美娇气女`,lang:`中文/英文`},{voice:`longhao_v3`,name:`龙浩`,desc:`多情忧郁男`,lang:`中文/英文`},{voice:`longanrou_v3`,name:`龙安柔`,desc:`温柔娴静女`,lang:`中文/英文`},{voice:`longxiaochun_v3`,name:`龙小淳`,desc:`知性积极女`,lang:`中文/英文`},{voice:`longxiaoxia_v3`,name:`龙小夏`,desc:`沉稳权威女`,lang:`中文/英文`},{voice:`longyumi_v3`,name:`YUMI`,desc:`正经青年女`,lang:`中文/英文`},{voice:`longanyun_v3`,name:`龙安昀`,desc:`居家暖男`,lang:`中文/英文`},{voice:`longanwen_v3`,name:`龙安温`,desc:`优雅知性女`,lang:`中文/英文`},{voice:`longanli_v3`,name:`龙安莉`,desc:`利落从容女`,lang:`中文/英文`},{voice:`longanlang_v3`,name:`龙安朗`,desc:`清爽利落男`,lang:`中文/英文`},{voice:`longyingmu_v3`,name:`龙应沐`,desc:`优雅知性女`,lang:`中文/英文`},{voice:`longyingxun_v3`,name:`龙应询`,desc:`年轻青涩男`,lang:`中文/英文`},{voice:`longyingjing_v3`,name:`龙应静`,desc:`低调冷静女`,lang:`中文/英文`},{voice:`longyingling_v3`,name:`龙应聆`,desc:`温和共情女`,lang:`中文/英文`},{voice:`longyingtao_v3`,name:`龙应桃`,desc:`温柔淡定女`,lang:`中文/英文`},{voice:`longyingxiao_v3`,name:`龙应笑`,desc:`清甜推销女`,lang:`中文/英文`},{voice:`longfei_v3`,name:`龙飞`,desc:`热血磁性男`,lang:`中文/英文`},{voice:`longhuhu_v3`,name:`龙呼呼`,desc:`天真烂漫女童`,lang:`中文/英文`},{voice:`longpaopao_v3`,name:`龙泡泡`,desc:`飞天泡泡音`,lang:`中文/英文`},{voice:`longjielidou_v3`,name:`龙杰力豆`,desc:`阳光顽皮男`,lang:`中文/英文`},{voice:`longxian_v3`,name:`龙仙`,desc:`豪放可爱女`,lang:`中文/英文`},{voice:`longling_v3`,name:`龙铃`,desc:`稚气呆板女`,lang:`中文/英文`},{voice:`longshanshan_v3`,name:`龙闪闪`,desc:`戏剧化童声`,lang:`中文/英文`},{voice:`longniuniu_v3`,name:`龙牛牛`,desc:`阳光男童声`,lang:`中文/英文`},{voice:`longjiaxin_v3`,name:`龙嘉欣`,desc:`优雅粤语女`,lang:`粤语/英文`},{voice:`longjiayi_v3`,name:`龙嘉怡`,desc:`知性粤语女`,lang:`粤语/英文`},{voice:`longanyue_v3`,name:`龙安粤`,desc:`欢脱粤语男`,lang:`粤语/英文`},{voice:`longlaotie_v3`,name:`龙老铁`,desc:`东北直率男`,lang:`东北话/英文`},{voice:`longshange_v3`,name:`龙陕哥`,desc:`原味陕北男`,lang:`陕西话/英文`},{voice:`longanmin_v3`,name:`龙安闽`,desc:`清纯萝莉女`,lang:`闽南话/英文`},{voice:`loongabby_v3`,name:`loongabby`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongandy_v3`,name:`loongandy`,desc:`美式英文男`,lang:`美式英语`},{voice:`loongannie_v3`,name:`loongannie`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongava_v3`,name:`loongava`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongbeth_v3`,name:`loongbeth`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongbetty_v3`,name:`loongbetty`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongcally_v3`,name:`loongcally`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongcindy_v3`,name:`loongcindy`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongdavid_v3`,name:`loongdavid`,desc:`美式英文男`,lang:`美式英语`},{voice:`loongdonna_v3`,name:`loongdonna`,desc:`美式英文女`,lang:`美式英语`},{voice:`loongemily_v3`,name:`loongemily`,desc:`英式英文女`,lang:`英式英语`},{voice:`loongeric_v3`,name:`loongeric`,desc:`英式英文男`,lang:`英式英语`},{voice:`loongluna_v3`,name:`loongluna`,desc:`英式英文女`,lang:`英式英语`},{voice:`loongluca_v3`,name:`loongluca`,desc:`英式英文男`,lang:`英式英语`},{voice:`loongriko_v3`,name:`Riko`,desc:`二次元霓虹女`,lang:`日语`},{voice:`loongtomoka_v3`,name:`loongtomoka`,desc:`日语女`,lang:`日语`},{voice:`loongtomoya_v3`,name:`loongtomoya`,desc:`日语男`,lang:`日语`},{voice:`loongyuuna_v3`,name:`Yuuna`,desc:`日语女`,lang:`日语`},{voice:`loongyuuma_v3`,name:`Yuuma`,desc:`日语男`,lang:`日语`},{voice:`loongkyong_v3`,name:`loongkyong`,desc:`韩语女`,lang:`韩语`},{voice:`loongjihun_v3`,name:`Jihun`,desc:`韩语男`,lang:`韩语`},{voice:`loongindah_v3`,name:`loongindah`,desc:`印尼女`,lang:`印尼语`}],In={"cosyvoice-v3-flash":Fn,"cosyvoice-v3-plus":Fn,"cosyvoice-v3.5-flash":[],"cosyvoice-v3.5-plus":[],"cosyvoice-v2":[]};function Ln(e){let t=In[e];if(!t){process.stdout.write(`No built-in voice list available for model: ${e}\n`);return}if(t.length===0){process.stdout.write(`Model ${e} has no system voices.\n`),process.stdout.write(`Use clone or design voices created via the CosyVoice API.
|
|
54
|
+
`),process.stdout.write(`See: ${Pn}\n`);return}let n=(e,t)=>e.padEnd(t);process.stdout.write(`\nSystem voices for ${e}:\n`),process.stdout.write(`${n(`VOICE ID`,26)} ${n(`NAME`,10)} ${n(`DESCRIPTION`,16)} LANGUAGE\n`),process.stdout.write(`${`-`.repeat(26)} ${`-`.repeat(10)} ${`-`.repeat(16)} ${`-`.repeat(12)}\n`);for(let e of t)process.stdout.write(`${n(e.voice,26)} ${n(e.name,10)} ${n(e.desc,16)} ${e.lang}\n`);process.stdout.write(`\nTotal: ${t.length} voices\n`)}var Rn=f({description:`Synthesize speech from text (CosyVoice TTS)`,usageArgs:`--text <text> [flags]`,options:[{flag:`--text <text>`,description:`Text to synthesize into speech`,required:!0},{flag:`--text-file <path>`,description:`Read text from a file instead of --text`},{flag:`--model <model>`,description:`Model ID (default: cosyvoice-v3-flash). System voices available for cosyvoice-v3-flash`},{flag:`--voice <voice>`,description:`Voice ID. Use --list-voices to see system voices for cosyvoice-v3-flash; for v3.5-flash provide a clone/design voice ID`},{flag:`--list-voices`,description:`List available system voices for the selected model and exit`},{flag:`--format <format>`,description:`Audio format: mp3, pcm, wav, opus (default: mp3)`},{flag:`--sample-rate <rate>`,description:`Audio sample rate in Hz (e.g. 24000)`},{flag:`--volume <volume>`,description:`Volume 0-100 (default: 50)`},{flag:`--rate <rate>`,description:`Speech rate 0.5-2.0 (default: 1.0)`},{flag:`--pitch <pitch>`,description:`Pitch multiplier 0.5-2.0 (default: 1.0)`},{flag:`--seed <seed>`,description:`Random seed 0-65535 for reproducible synthesis`},{flag:`--language <lang>`,description:`Language hint (e.g. zh, en, ja, ko, fr, de)`},{flag:`--instruction <text>`,description:`Natural language instruction to control speech style (e.g. "Use a gentle tone")`},{flag:`--enable-ssml`,description:`Enable SSML markup parsing in input text`},{flag:`--out <path>`,description:`Save audio to file (default: auto-generate in temp dir)`},{flag:`--stream`,description:`Stream raw PCM audio to stdout (pipe to player)`}],exampleArgs:[`--list-voices --model cosyvoice-v3-flash`,`--text "Hello, I am Qwen" --voice <voice_id>`,`--text "Hello world" --voice <voice_id> --language en`,`--text-file script.txt --out speech.wav --voice <voice_id>`,`--text "Today is a good day" --voice <voice_id> --instruction "Use a gentle tone"`,`--text "Hello" --voice <voice_id> --format wav --sample-rate 24000`,`# Stream to audio player (macOS)`,`--text "Hello" --voice <voice_id> --stream | afplay -`,`# Pipe to ffplay`,`--text "Hello" --voice <voice_id> --stream | ffplay -nodisp -autoexit -f s16le -ar 24000 -ac 1 -`],async run(t,n){let i=n.model||t.defaultSpeechModel||`cosyvoice-v3-flash`;if(n.listVoices){Ln(i);return}let a=n.text;if(!a&&n.textFile){let t=n.textFile;try{a=Ge(t,`utf-8`).trim()}catch{throw new e(`Cannot read text file: ${t}`,r.USAGE)}}if(!a)if(S({nonInteractive:t.nonInteractive})){let e=await U({message:`Enter text to synthesize:`});e||(process.stderr.write(`Speech synthesis cancelled.
|
|
55
|
+
`),process.exit(1)),a=e}else B(`text`,F(t,`--text <text>`));let o=n.voice||void 0;if(!o)if(S({nonInteractive:t.nonInteractive})){let e=In[i];if(e&&e.length>0){let t=e[0].voice,n=e.map(e=>({value:e.voice,label:`${e.name} (${e.voice})`,hint:`${e.desc} · ${e.lang}`})),r=await Le({message:`Select a voice (default: ${t}):`,choices:n,defaultValue:t});r||(process.stderr.write(`Speech synthesis cancelled.
|
|
56
|
+
`),process.exit(1)),o=r}else{let e=await U({message:`Enter voice ID (clone/design voice):`});e||(process.stderr.write(`Speech synthesis cancelled.
|
|
57
|
+
`),process.exit(1)),o=e}}else{let n=In[i];throw n&&n.length>0?new e(`--voice is required.\nRun the following to see available voices:\n ${F(t,`--list-voices --model ${i}`)}`,r.USAGE):new e(`--voice is required. Model ${i} has no built-in system voices.\nCreate a clone or design voice first, then pass its ID via --voice <voice_id>.\nSee: ${Pn}`,r.USAGE)}let s=n.language||void 0,c=n.instruction||void 0,l=n.format||void 0,u=n.sampleRate===void 0?void 0:Number(n.sampleRate),d=n.volume===void 0?void 0:Number(n.volume),f=n.rate===void 0?void 0:Number(n.rate),m=n.pitch===void 0?void 0:Number(n.pitch),h=n.seed===void 0?void 0:Number(n.seed),g=n.enableSsml===!0?!0:void 0,_=n.stream===!0,v=p(t.output),y={model:i,input:{text:a,voice:o,format:l,sample_rate:u,volume:d,rate:f,pitch:m,seed:h,language_hints:s?[s]:void 0,instruction:c,enable_ssml:g}};if(he(y.input),t.dryRun){z({request:y},v);return}t.quiet||process.stderr.write(`[Model: ${i}] [Voice: ${o}]\n`);let b=me(t.baseUrl);_?await Bn(t,b,y,n,v):await zn(t,b,y,n,v)}});async function zn(t,n,i,a,o){let s=await W(Me(a),t,()=>E(t,{url:n,method:`POST`,body:i})),c=s.map(e=>e.output?.audio?.url).filter(Boolean);if(c.length===0)throw new e(`API returned no audio URL.`,r.GENERAL);let l=await import(`path`),u=j(t,{subDir:`speech`}),d=await De(c.map((e,t)=>{let n=a.out;if(!(n&&c.length===1)){let e=Date.now(),r=c.length>1?`_${String(t+1).padStart(3,`0`)}`:``,a=i.input.format??`mp3`;n=l.join(u,`tts_${e}${r}.${a}`)}return{url:e,destPath:n}}),L,{quiet:t.quiet});if(t.quiet)R(d.join(`
|
|
58
|
+
`));else if(d.length===1){let e=s[0].output?.audio?.expires_at;z({saved:d[0],audio_url:c[0],model:i.model,voice:i.input.voice,...e?{url_expires_at:e}:{}},o)}else z({saved:d,audio_urls:c,total:d.length,model:i.model,voice:i.input.voice},o)}async function Bn(e,t,n,r,i){let a=await ue(e,{url:t,method:`POST`,body:n,stream:!0,headers:{Accept:`text/event-stream`,"X-DashScope-SSE":`enable`}}),o=r.out,s=o?Ue(o):null,c;try{for await(let t of oe(a)){if(!t.data||t.data===`[DONE]`)continue;let n;try{n=JSON.parse(t.data)}catch{continue}let r=n.output?.audio?.data;if(r){let e=Buffer.from(r,`base64`);s?s.write(e)||await new Promise(e=>s.once(`drain`,()=>e())):process.stdout.write(e)}if(n.output?.finish_reason===`stop`){c=n.output?.audio?.url,c&&!e.quiet&&process.stderr.write(`\nFull audio URL: ${c}\n`);break}}}finally{s&&(await new Promise((e,t)=>{s.on(`finish`,e),s.on(`error`,t),s.end()}),!e.quiet&&o&&process.stderr.write(`Saved: ${o}\n`))}o&&z({saved:o,...c?{audio_url:c}:{},model:n.model,voice:n.input.voice},i)}var Vn=f({description:`Recognize speech from audio files (FunAudio-ASR)`,usageArgs:`--url <audio-url> [flags]`,options:[{flag:`--url <url>`,description:`Audio file URL or local file path (repeatable, max 100)`,required:!0,type:`array`},{flag:`--model <model>`,description:`Model ID (default: fun-asr)`},{flag:`--language <lang>`,description:`Language hint (e.g. zh, en, ja)`},{flag:`--diarization`,description:`Enable automatic speaker diarization`},{flag:`--speaker-count <n>`,description:`Expected number of speakers (requires --diarization)`,type:`number`},{flag:`--vocabulary-id <id>`,description:`Hot-word vocabulary ID for improved accuracy`},{flag:`--channel-id <n>`,description:`Audio channel ID (default: 0)`,type:`number`},{flag:`--out <path>`,description:`Save full transcription result to JSON file`},{flag:`--no-wait`,description:`Return task ID immediately without polling`},{flag:`--poll-interval <seconds>`,description:`Polling interval in seconds (default: 2)`,type:`number`}],exampleArgs:[`--url https://example.com/audio.mp3`,`--url https://example.com/a.mp3 --url https://example.com/b.mp3`,`--url https://example.com/meeting.wav --diarization --speaker-count 3`,`--url https://example.com/audio.mp3 --language zh`,`--url https://example.com/audio.mp3 --vocabulary-id vocab-abc123`,`--url https://example.com/audio.mp3 --out result.json`,`--url https://example.com/audio.mp3 --no-wait --quiet`],async run(t,n){let i=[];Array.isArray(n.url)?i=n.url:typeof n.url==`string`&&(i=[n.url]),i.length===0&&B(`url`,F(t,`--url <audio-url>`));let a=n.speakerCount,o=n.diarization===!0;if(a!==void 0&&!o)throw new e(`--speaker-count requires --diarization to be enabled.
|
|
59
|
+
Hint: Add --diarization flag to enable speaker separation.`,r.USAGE);let s=n.model||`fun-asr`,c=p(t.output),l=await k(t),u=await Promise.all(i.map(e=>A(e,l.token,s))),d=n.channelId,f=n.language,m=n.vocabularyId,h={model:s,input:{file_urls:u},parameters:{channel_id:d===void 0?[0]:[d],language_hints:f?[f]:void 0,diarization_enabled:o?!0:void 0,speaker_count:a,vocabulary_id:m}};if(he(h.parameters),t.dryRun){z({request:h,mode:`async`},c);return}t.quiet||process.stderr.write(`[Model: ${s}] [Mode: async] [Files: ${u.length}]\n`),await Hn(t,pe(t.baseUrl),h,n,c,u.length)}});async function Hn(t,n,i,a,o,s){let c=(await E(t,{url:n,method:`POST`,body:i,async:!0})).output.task_id;if(a.noWait||t.async){z({task_id:c},o);return}let l=a.pollInterval??2,u=await H(t,{url:M(t.baseUrl,c),intervalSec:l,timeoutSec:t.timeout,isComplete:e=>e.output.task_status===`SUCCEEDED`,isFailed:e=>e.output.task_status===`FAILED`,getStatus:e=>e.output.task_status,getErrorMessage:e=>e.output.message}),d=u.output.results??[];if(d.length===0){z({task_id:c,status:u.output.task_status},o);return}let f=[];for(let t=0;t<d.length;t++){let n=d[t],i=s>1;if(i&&process.stdout.write(`=== [${t+1}/${d.length}] ${n.file_url??``} ===\n`),n.subtask_status===`FAILED`){let e=n.message??n.code??`unknown error`;process.stdout.write(`[FAILED] ${n.file_url??``} — ${e}\n`),i&&process.stdout.write(`
|
|
60
|
+
`);continue}if(!n.transcription_url){i&&process.stdout.write(`
|
|
61
|
+
`);continue}let a=await fetch(n.transcription_url,{headers:ge()});if(!a.ok)throw new e(`Failed to download transcription: HTTP ${a.status}`,r.GENERAL);let o=await a.json();f.push(o);let c=o.transcripts;if(c&&c.length>0)for(let e of c)if(e.sentences&&e.sentences.length>0)for(let t of e.sentences){let e=t.speaker_id===void 0?``:` [Speaker ${t.speaker_id}]`;process.stdout.write(`${t.text}${e}\n`)}else e.text&&process.stdout.write(e.text+`
|
|
62
|
+
`);else R(JSON.stringify(o));i&&process.stdout.write(`
|
|
63
|
+
`)}if(a.out){let e=a.out,n=f.length===1?f[0]:f;Ke(e,JSON.stringify(n,null,2)+`
|
|
64
|
+
`),t.quiet||process.stderr.write(`Full result saved to: ${e}\n`)}}var Un=f({description:`Upload a local file to DashScope temporary storage (48h)`,usageArgs:`--file <path> --model <model>`,options:[{flag:`--file <path>`,description:`Local file to upload (image, video, audio)`,required:!0},{flag:`--model <model>`,description:`Target model name (file is bound to this model)`,required:!0}],exampleArgs:[`--file photo.jpg --model qwen3-vl-plus`,`--file video.mp4 --model wan2.1-t2v-plus`,`--file audio.wav --model qwen3-asr-flash`,`--file cat.png --model qwen-image-2.0`],async run(e,t){let n=t.file;n||B(`file`,F(e,`--file <path> --model <model>`));let r=t.model;r||B(`model`,F(e,`--file <path> --model <model>`));let i=p(e.output);if(e.dryRun){z({action:`upload`,file:n,model:r},i);return}let a=await _e({apiKey:(await k(e)).token,model:r,filePath:n});e.quiet?R(a):z({url:a,model:r,expires_in:`48 hours`,note:`When using this URL in API calls, add header: X-DashScope-OssResourceResolve: enable`},i)}}),Wn=f({description:`Call a Bailian console API via the CLI gateway`,skipDefaultApiKeySetup:!0,usageArgs:`--api <api> --data <json> [flags]`,options:[{flag:`--api <api>`,description:`API name (e.g. zeldaEasy.broadscope-bailian.memory-library.getLibraries)`,required:!0},{flag:`--data <json>`,description:`Request data as JSON string`,required:!0},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[`--api zeldaEasy.broadscope-bailian.freeTrial.queryFreeTierQuota --data '{"queryFreeTierQuotaRequest":{"models":["qwen3-max"]}}'`,`--api some.api.name --data '{"key":"value"}' --console-region cn-beijing`],async run(n,r){let i=r.api;i||B(`api`,F(n,`--api <api> --data <json>`));let a=r.data;a||B(`data`,F(n,`--api <api> --data <json>`));let o;try{o=JSON.parse(a)}catch{process.stderr.write(`Error: --data must be valid JSON
|
|
65
|
+
`),process.exit(1)}let s=p(n.output),c;try{c=(await O(n)).token}catch(n){if(!(n instanceof e&&n.message===t))throw n}if(n.dryRun){z({api:i,data:o,token:c?c.slice(0,8)+`...`:null,...m(n)},s);return}z(await l(n,c,{api:i,data:o}),s)}});const Gn=`zeldaEasy.broadscope-bailian.freeTrial.queryFreeTierQuota`;function Kn(e){return e.toLocaleString(`en-US`)}function qn(e){let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`}function Jn(e){return e.quotaInitTotal?`${((e.quotaInitTotal-e.quotaTotal)/e.quotaInitTotal*100).toFixed(1)}%`:`-`}const Yn={Reasoning:`Text`,TG:`Text`,VU:`Text`,IG:`Vision`,VG:`Vision`,"Realtime-Omni":`Multimodal`,"Multimodal-Omni":`Multimodal`,ASR:`Audio`,TTS:`Audio`,"Voice-Replication":`Audio`,"Realtime-Text-to-Speech":`Audio`,"Realtime-Voice-Replication":`Audio`,"Realtime-ASR":`Audio`,"Realtime-Audio-Translate":`Audio`,ME:`Embedding`,TR:`Embedding`};function Xn(e){for(let t of e){let e=Yn[t];if(e)return e}return`-`}function Zn(e,t,n,r){let i=[`Model`,`Type`,`Remaining/Total`,`Usage`,`Expires`,`Auto-Stop`],a=e.map(e=>{let r=e.quotaInitTotal!=null&&e.quotaTotal!=null,i=r?Kn(e.quotaTotal):`-`,a=r?Kn(e.quotaInitTotal):`-`,o=t.get(e.model);return[e.model,n.get(e.model)||`-`,r?`${i} / ${a}`:`-`,Jn(e),e.quotaValidityPeriod?qn(e.quotaValidityPeriod):`-`,e.quotaStatus===`UNKNOWN`?`Unsupported`:o===!0?`ON`:o===!1?`OFF`:`-`]}),o=i.map((e,t)=>Math.max(I(e),...a.map(e=>I(e[t])))),s=r?e=>e:e=>`\x1b[2m${e}\x1b[0m`,c=r?e=>e:e=>`\x1b[1m${e}\x1b[0m`,l=r?e=>e:e=>`\x1b[32m${e}\x1b[0m`,u=r?e=>e:e=>`\x1b[33m${e}\x1b[0m`,d=i.length-1,f=i.map((e,t)=>c(V(e,o[t]))).join(` `),p=o.map(e=>s(`─`.repeat(e))).join(`──`);process.stdout.write(f+`
|
|
66
|
+
`),process.stdout.write(p+`
|
|
67
|
+
`);for(let e of a){let t=e.map((e,t)=>{if(t===d){if(e===`ON`)return l(V(e,o[t]));if(e===`OFF`)return u(V(e,o[t]))}return V(e,o[t])});process.stdout.write(t.join(` `)+`
|
|
68
|
+
`)}}function Qn(e){let t=e.data;if(!t)return[];let n=t.DataV2;return n?n.data?.data?.freeTierQuotas||[]:t.data?.freeTierQuotas||[]}function $n(e){let t=e.data;if(!t)return[];let n=t.DataV2;return n?n.data?.data?.freeTierOnlyStatuses||[]:t.data?.freeTierOnlyStatuses||[]}async function er(e,t){let n=[],r=1;for(;;){let i=await h(e,t,{pageNo:r,pageSize:50});if(n.push(...i.models),n.length>=i.total)break;r++}return n.filter(e=>typeof e.model==`string`&&e.model).map(e=>({name:e.model,type:Xn(e.capabilities||[])}))}var tr=f({description:`Query free-tier quota for models (all models if --model is omitted)`,skipDefaultApiKeySetup:!0,usageArgs:`[--model <model>[,model2,...]] [flags]`,options:[{flag:`--model <model>`,description:`Model name(s) to query, comma-separated for multiple; omit for all models`},{flag:`--expiring <days>`,description:`Only show quotas expiring within N days`},{flag:`--sort <field>`,description:`Sort by: remaining (ascending), expires (ascending)`},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[``,`--model qwen3-max`,`--model qwen3-max,qwen-turbo`,`--expiring 30`,`--sort remaining`,`--model qwen-turbo --output json`,`--model qwen3-max --console-region cn-beijing`],async run(e,t){let n=t.model||void 0,r=Number(t.expiring)||0,i=[`remaining`,`expires`],a=t.sort||void 0;a&&!i.includes(a)&&(process.stderr.write(`Error: invalid --sort value "${a}". Must be one of: ${i.join(`, `)}\n`),process.exit(1));let o=p(e.output),s,c=new Map;s=n?[...new Set(n.split(`,`).map(e=>e.trim()).filter(Boolean))]:[];let u={queryFreeTierQuotaRequest:{models:s}};if(e.dryRun){z({api:Gn,data:u},o);return}let d=await O(e);if(n){let t=await Promise.all(s.map(t=>h(e,d.token,{name:t,pageSize:50})));for(let e=0;e<s.length;e++){let n=t[e].models.find(t=>t.model===s[e]);n&&c.set(s[e],Xn(n.capabilities||[]))}}else{let t=await er(e,d.token);s=t.map(e=>e.name);for(let e of t)c.set(e.name,e.type);u.queryFreeTierQuotaRequest.models=s}let[f,m]=await Promise.all([l(e,d.token,{api:Gn,data:u}),l(e,d.token,{api:`zeldaEasy.broadscope-bailian.freeTrial.queryFreeTierOnlyStatus`,data:{queryFreeTierOnlyStatusRequest:{models:s}}})]),g=Qn(f),_=n?g:g.filter(e=>e.quotaStatus===`VALID`&&e.quotaInitTotal>0);if(r>0){let e=Date.now()+r*24*60*60*1e3;_=_.filter(t=>t.quotaValidityPeriod>0&&t.quotaValidityPeriod<=e)}a===`remaining`?_.sort((e,t)=>(e.quotaInitTotal?e.quotaTotal/e.quotaInitTotal:0)-(t.quotaInitTotal?t.quotaTotal/t.quotaInitTotal:0)):a===`expires`&&_.sort((e,t)=>(e.quotaValidityPeriod??0)-(t.quotaValidityPeriod??0));let v=$n(m),y=new Map(v.map(e=>[e.model,e.freeTierOnly]));if(o===`json`){z(_.map(e=>{let t=e.quotaInitTotal!=null&&e.quotaTotal!=null,n=t?e.quotaInitTotal-e.quotaTotal:0,r=y.get(e.model),i=e.quotaStatus===`UNKNOWN`?`unsupported`:r===!0?!0:r===!1?!1:null;return{model:e.model,type:c.get(e.model)||null,remaining:t?e.quotaTotal:null,total:t?e.quotaInitTotal:null,usagePercent:t&&e.quotaInitTotal>0?Math.round(n/e.quotaInitTotal*1e3)/10:null,expires:e.quotaValidityPeriod?qn(e.quotaValidityPeriod):null,autoStop:i}}),o);return}if(_.length===0){process.stdout.write(`No free-tier quota found.
|
|
69
|
+
`);return}Zn(_,y,c,e.noColor)}});function q(e,t){let n=e[t];if(n&&typeof n==`object`&&!Array.isArray(n))return n}function nr(e){let t=q(e,`data`);if(!t)return e;let n=q(t,`DataV2`);if(n){let e=q(n,`data`);return(e?q(e,`data`):void 0)??e??n}return q(t,`data`)??t}async function rr(e,t,n,r,i){let a;for(let o=0;o<20;o++){let o=await l(e,t,{api:n,data:{[r]:a?{taskId:a}:{models:i}}}),s=nr(o);if(s.taskId&&Object.keys(s).length===1){a=s.taskId,await new Promise(e=>setTimeout(e,500));continue}return o}return null}async function ir(e,t){let n=[],r=1;for(;;){let i=await h(e,t,{pageNo:r,pageSize:50});if(n.push(...i.models),n.length>=i.total)break;r++}return n.map(e=>e.model).filter(Boolean)}var ar=f({description:`Enable or disable auto-stop for free-tier models. Enables by default; use --off to disable`,skipDefaultApiKeySetup:!0,usageArgs:`<--model <model>[,model2,...] | --all> [--off] [flags]`,options:[{flag:`--model <model>`,description:`Model name(s), comma-separated for multiple`},{flag:`--all`,description:`Apply to all free-tier models`},{flag:`--on`,description:`Enable auto-stop (default behavior)`},{flag:`--off`,description:`Disable auto-stop`},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[`--model qwen3-max`,`--model qwen3-max,qwen-turbo`,`--all`,`--on --model qwen3-max`,`--off --model qwen3-max`,`--off --all`],async run(e,t){let n=t.model||void 0,r=!!t.all,i=!!t.off,a=p(e.output);!n&&!r&&(process.stderr.write(`Error: missing required flag. Specify --model <model>[,model2,...] or --all
|
|
70
|
+
`),process.exit(1));let o;o=n?[...new Set(n.split(`,`).map(e=>e.trim()).filter(Boolean))]:[];let s=i?`zeldaEasy.broadscope-bailian.freeTrial.batchDeactivateFreeTierOnly`:`zeldaEasy.broadscope-bailian.freeTrial.batchActivateFreeTierOnly`,c=i?`BatchDeactivateFreeTierOnlyRequest`:`BatchActivateFreeTierOnlyRequest`;if(e.dryRun){z({api:s,data:{[c]:{models:o}}},a);return}let u=await O(e);if(n||(o=await ir(e,u.token)),i){let[t,n]=await Promise.all([l(e,u.token,{api:`zeldaEasy.broadscope-bailian.freeTrial.queryFreeTierQuota`,data:{queryFreeTierQuotaRequest:{models:o}}}),l(e,u.token,{api:`zeldaEasy.broadscope-bailian.freeTrial.queryFreeTierOnlyStatus`,data:{queryFreeTierOnlyStatusRequest:{models:o}}})]),r=nr(t).freeTierQuotas??[],i=new Map(r.map(e=>[e.model,e])),a=nr(n).freeTierOnlyStatuses??[],d=new Map(a.map(e=>[e.model,e.freeTierOnly]));for(let t of o){if(d.get(t)===!1){process.stderr.write(`Auto-stop is already disabled for "${t}".\n`);continue}let n=i.get(t);if(n&&n.quotaTotal>0&&d.get(t)===!0){process.stderr.write(`Cannot disable auto-stop for "${t}": free-tier quota has not been fully consumed. Please disable auto-stop after the quota is exhausted.\n`);continue}await rr(e,u.token,s,c,[t]),process.stdout.write(`Disabled auto-stop for "${t}".\n`)}return}let d=[];for(let t of o){let n=await rr(e,u.token,s,c,[t]);if(a===`json`){d.push(n);continue}if(n){let e=nr(n).failureModels??[];e.length>0?process.stderr.write(`Failed to enable auto-stop for "${t}" (${e[0].errorCode}).\n`):process.stdout.write(`Enabled auto-stop for "${t}".\n`)}else process.stderr.write(`Warning: operation timed out for "${t}".\n`)}a===`json`&&z(d,a)}});const or=`zeldaEasy.bailian-telemetry.model.getModelUsageStatistic`,sr=`zeldaEasy.bailian-telemetry.model.listModelUsageStatisticData`;function J(e,t){let n=e[t];if(n&&typeof n==`object`&&!Array.isArray(n))return n}function cr(e){let t=J(e,`data`);if(!t)return e;let n=J(t,`DataV2`);if(n){let e=J(n,`data`);return(e?J(e,`data`):void 0)??e??n}return J(t,`data`)??t}async function lr(e,t,n,r){let i;for(let a=0;a<30;a++){let a=await l(e,t,{api:n,data:i?{reqDTO:{...r,asyncTaskId:i}}:{reqDTO:r}}),o=cr(a);if(o.taskId&&Object.keys(o).length===1){i=o.taskId,await new Promise(e=>setTimeout(e,500));continue}return a}return null}function ur(e,t){if(t)return t;if(e.workspaceId)return e.workspaceId;process.stderr.write(`Error: workspace-id is required. Set via --workspace-id, BAILIAN_WORKSPACE_ID, or \`${e.binName} config set workspace_id <id>\`.\n`),process.stderr.write(`Hint: run \`${e.binName} workspace list\` to view available workspaces.\n`),process.exit(1)}function Y(e){return e.toLocaleString(`en-US`)}function X(e){let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`}function dr(e){let t=cr(e);if(t.callSuccessCount!==void 0||t.usages!==void 0)return t}function fr(e){let t=cr(e);return{list:t.list??[],totalCount:t.totalCount??0,maxResults:t.maxResults??0}}function pr(e){let t={};if(e.usages&&Array.isArray(e.usages))for(let n of e.usages)n.key&&n.value!=null&&(t[n.key]=n.value);if(e.usage&&typeof e.usage==`object`)for(let[n,r]of Object.entries(e.usage))r!=null&&(t[n]=r);return t}const mr={total_token:{en:`Total Tokens`,unit:`tokens`},input_token:{en:`Input Tokens`,unit:`tokens`},output_token:{en:`Output Tokens`,unit:`tokens`},input_token_cache:{en:`Cached Tokens`,unit:`tokens`},input_token_cache_read:{en:`Cache Read`,unit:`tokens`},input_token_cache_creation:{en:`Cache Creation`,unit:`tokens`},thinking_input_token:{en:`Thinking Input`,unit:`tokens`},thinking_output_token:{en:`Thinking Output`,unit:`tokens`},text_input_token:{en:`Text Input`,unit:`tokens`},purein_text_output_token:{en:`Text Output`,unit:`tokens`},embedding_token:{en:`Embedding`,unit:`tokens`},image_number:{en:`Images`,unit:`images`},video_duration:{en:`Video Duration`,unit:`sec`},content_duration:{en:`Audio Duration`,unit:`sec`},tts_text_number:{en:`TTS Chars`,unit:`chars`},total_token_avg:{en:`Avg Tokens/Req`}};function hr(e){let t=e.unit?` [${e.unit}]`:``;return`${e.en}${t}`}function gr(e,t,n,r,i){let a=i?e=>e:e=>`\x1b[1m${e}\x1b[0m`,o=i?e=>e:e=>`\x1b[2m${e}\x1b[0m`;process.stdout.write(`${o(`Time Range Period:`)} ${X(t)} ~ ${X(n)} ${o(`(${r} days)`)}\n\n`);let s=[[`Models Called`,Y(e.modelCount??0)],[`Successful Calls`,Y(e.callSuccessCount??0)]];for(let t of e.usages??[]){let e=mr[t.key],n=e?hr(e):t.key;s.push([n,Y(t.value)])}let c=Math.max(...s.map(([e])=>I(e)));for(let[e,t]of s)process.stdout.write(`${a(V(e,c+2))}${t}\n`)}function _r(e,t,n,r,i){let a=i?e=>e:e=>`\x1b[1m${e}\x1b[0m`,o=i?e=>e:e=>`\x1b[2m${e}\x1b[0m`;if(process.stdout.write(`${o(`Time Range Period:`)} ${X(t)} ~ ${X(n)} ${o(`(${r} days)`)}\n\n`),e.length===0){process.stdout.write(`No usage data found.
|
|
71
|
+
`);return}let s=new Set,c=e.map(e=>{let t=pr(e);for(let e of Object.keys(t))s.add(e);return t}),l=[...s].sort((e,t)=>{let n=[`total_token`,`input_token`,`output_token`,`input_token_cache`,`image_number`,`video_duration`,`content_duration`,`tts_text_number`],r=n.indexOf(e),i=n.indexOf(t);return(r===-1?999:r)-(i===-1?999:i)}),u=[`Model`,`Calls`,...l.map(e=>mr[e]?.en??e)],d=e.map((e,t)=>[e.model,Y(e.callSuccessCount??0),...l.map(e=>{let n=c[t][e];return n==null?`-`:Y(n)})]),f=u.map((e,t)=>Math.max(I(e),...d.map(e=>I(e[t])))),p=u.map((e,t)=>a(V(e,f[t]))).join(` `),m=f.map(e=>o(`─`.repeat(e))).join(`──`);process.stdout.write(p+`
|
|
72
|
+
`),process.stdout.write(m+`
|
|
73
|
+
`);for(let e of d){let t=e.map((e,t)=>V(e,f[t]));process.stdout.write(t.join(` `)+`
|
|
74
|
+
`)}process.stdout.write(o(`\nTotal: ${e.length} models`)+`
|
|
75
|
+
`)}var vr=f({description:`Query model usage statistics`,skipDefaultApiKeySetup:!0,usageArgs:`[--model <model>] [--days <days>] [flags]`,options:[{flag:`--model <model>`,description:`Model name(s), comma-separated; omit for overview`},{flag:`--days <days>`,description:`Number of days (default: 7)`},{flag:`--type <type>`,description:`Model type: Text, Vision, Multimodal, Audio, Embedding`},{flag:`--workspace-id <id>`,description:`Workspace ID (env: BAILIAN_WORKSPACE_ID)`},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[``,`--days 30`,`--model qwen-turbo`,`--model qwen-turbo --days 7`,`--model qwen3.6-plus,deepseek-v4-pro`,`--type Text --days 14`,`--output json`],async run(e,t){let n=t.model||void 0,r=Number(t.days)||7,i=t.type||void 0,a=p(e.output),o=ur(e,t.workspaceId||void 0),s=Date.now(),c=s-r*24*60*60*1e3;if(n){let t=[...new Set(n.split(`,`).map(e=>e.trim()).filter(Boolean))],l={startTime:c,endTime:s,modelCallSource:`Online`,filterWorkspaceId:o,maxResults:50,skip:0,sortField:`success_count`,sortOrder:`DESC`};if(i&&(l.obsModelType=i),e.dryRun){z({api:sr,data:{reqDTO:{...l,model:t.join(`,`)}}},a);return}let u=await O(e),d=await Promise.all(t.map(t=>lr(e,u.token,sr,{...l,model:t}))),f=[];for(let e of d){if(!e)continue;let t=fr(e);f.push(...t.list)}if(a===`json`){let e=f.map(e=>{let t=pr(e),n={model:e.model,successfulCalls:e.callSuccessCount??0};for(let[e,r]of Object.entries(t))n[e]=r;return n});z({period:{start:X(c),end:X(s),days:r},items:e},a);return}_r(f,c,s,r,e.noColor)}else{let t={startTime:c,endTime:s,modelCallSource:`Online`,filterWorkspaceId:o};if(i&&(t.obsModelType=i),e.dryRun){z({api:or,data:{reqDTO:t}},a);return}let n=await lr(e,(await O(e)).token,or,t);n||(process.stderr.write(`Error: request timed out.
|
|
76
|
+
`),process.exit(1));let l=dr(n);if(a===`json`){if(!l){z({period:{start:X(c),end:X(s),days:r},modelsCalled:0,successfulCalls:0},a);return}z({period:{start:X(c),end:X(s),days:r},modelsCalled:l.modelCount??0,successfulCalls:l.callSuccessCount??0,usages:(l.usages??[]).map(e=>({key:e.key,value:e.value,unit:e.unit,label:mr[e.key]?.en??e.key}))},a);return}if(!l){process.stdout.write(`No usage data found.
|
|
77
|
+
`);return}gr(l,c,s,r,e.noColor)}}});async function yr(e){let t=await Ye(e,`utf-8`).catch(e=>{process.stderr.write(`Error: cannot read pipeline file: ${e.message}\n`),process.exit(2)}),n=Ze(e).toLowerCase(),r;if(n===`.yaml`||n===`.yml`){let{parse:e}=await import(`yaml`);r=e(t)}else try{r=JSON.parse(t)}catch{let{parse:e}=await import(`yaml`);r=e(t)}return r}var br=f({description:`Run a pipeline workflow definition`,skipDefaultApiKeySetup:!0,usageArgs:`<file> [flags]`,options:[{flag:`--input <json>`,description:`Runtime input as inline JSON`},{flag:`--input-file <path>`,description:`Runtime input from a JSON file`},{flag:`--concurrency <n>`,description:`Max parallel steps (default: 1)`,type:`number`},{flag:`--events <format>`,description:`Emit lifecycle events: jsonl`},{flag:`--timeout <seconds>`,description:`Default step timeout in seconds`,type:`number`}],exampleArgs:[`workflow.yaml --input '{"brief":"hello"}'`,`workflow.json --input-file inputs.json --concurrency 3`,`workflow.yaml --dry-run`,`workflow.json --events jsonl`,`workflow.yaml --output json`],async run(e,t){let n=(t._positional??[])[0];n||(process.stderr.write(`Error: pipeline file is required\nUsage: ${F(e,`<file>`)}\n`),process.exit(2)),Ne();let r=t.events;r!==void 0&&r!==`jsonl`&&(process.stderr.write(`Error: unsupported --events format: ${r}. Supported: jsonl\n`),process.exit(2));let i=Qe(n),a=await yr(i),o=await xr(t),s=Xe(i);if(r===`jsonl`){for await(let e of ze(a,o,{concurrency:t.concurrency,basePath:s,dryRun:t.dryRun,timeoutSeconds:t.timeout}))process.stdout.write(JSON.stringify(e)+`
|
|
78
|
+
`);return}let c=await ke(a,o,{concurrency:t.concurrency,basePath:s,dryRun:t.dryRun,timeoutSeconds:t.timeout,onEvent:t.verbose?Sr:void 0});e.output===`json`?z(c,`json`):wr(c),c.status===`failed`&&(process.exitCode=1)}});async function xr(e){let t=e.input,n=e.inputFile;if(t&&n&&(process.stderr.write(`Error: use --input or --input-file, not both
|
|
79
|
+
`),process.exit(2)),t)return JSON.parse(t);if(n){let e=await Ye(Qe(n),`utf-8`);return JSON.parse(e)}return{}}function Sr(e){let t=`[${e.type}]`;if(`stepCount`in e){process.stderr.write(`${t} ${e.stepCount} step${e.stepCount===1?``:`s`}\n`);return}`step`in e&&e.step?process.stderr.write(`${t} ${Cr(e.step)}\n`):process.stderr.write(`${t}\n`)}function Cr(e){return`${e.index!==void 0&&e.total!==void 0?`${e.index}/${e.total} `:``}${e.id} (${e.type})`}function wr(e){let t=e.status===`succeeded`?`+`:e.status===`failed`?`x`:`~`;process.stdout.write(`\nPipeline ${e.status} [${t}]\n\n`);for(let t of e.steps){let e=` [${t.status===`succeeded`?`+`:t.status===`failed`?`x`:t.status===`skipped`?`-`:`~`}] ${t.id} (${t.type}) — ${t.status}`;t.skipReason&&(e+=` (${t.skipReason})`),t.error&&(e+=`: ${t.error.message}`),process.stdout.write(e+`
|
|
80
|
+
`)}process.stdout.write(`
|
|
81
|
+
`)}var Tr=f({description:`Validate a pipeline definition without executing`,skipDefaultApiKeySetup:!0,usageArgs:`<file>`,options:[],exampleArgs:[`workflow.yaml`,`workflow.json --output json`],async run(e,t){let n=(t._positional??[])[0];n||(process.stderr.write(`Error: pipeline file is required\nUsage: ${F(e,`<file>`)}\n`),process.exit(2)),Ne();let r=await yr(Qe(n)),i=Te(r),a=i.length===0?we(r):[];if(e.output===`json`)z({valid:i.length===0,issues:i,...a.length>0?{hints:a}:{}},`json`),i.length>0&&(process.exitCode=1);else if(i.length===0){process.stdout.write(`Pipeline definition is valid.
|
|
82
|
+
`);for(let e of a)process.stderr.write(` hint: ${e}\n`)}else{process.stderr.write(`Pipeline validation failed:
|
|
83
|
+
`);for(let e of i)process.stderr.write(` - ${e}\n`);process.exitCode=1}}});function Er(e){return e>=1e6?`${(e/1e6).toFixed(e%1e6==0?0:1)}M`:e>=1e3?`${(e/1e3).toFixed(e%1e3==0?0:1)}K`:String(e)}const Dr={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},Or={TG:`Text Gen`,VU:`Vision`,IG:`Image Gen`,VG:`Video Gen`,TTS:`Text-to-Speech`,ASR:`Speech-to-Text`,Reasoning:`Reasoning`},kr={low:`Cost-Effective`,medium:`Balanced`,high:`High Investment`},Ar={flagship:`Flagship`,balanced:`Balanced`,"cost-optimized":`Value`},jr={scoped:`Scoped`,comparison:`Comparison`,alternative:`Alternative`};function Mr(e,t){let n=t?new tt({level:0}):et,r=[];r.push(n.cyan.bold(`Intent Analysis`)),e.taskSummary&&(r.push(``),r.push(e.taskSummary)),e.scenarioHints.length&&(r.push(``),r.push(`${n.dim(`Scenario`)} ${e.scenarioHints.join(` · `)}`));let i=e.inputModality.map(e=>Dr[e]??e),a=e.outputModality.map(e=>Dr[e]??e);if(i.length||a.length){r.push(``);let e=[];i.length&&e.push(`${n.dim(`Input`)} ${i.join(`, `)}`),a.length&&e.push(`${n.dim(`Output`)} ${a.join(`, `)}`),r.push(e.join(` `))}let o=e.requiredCapabilities.map(e=>Or[e]??e);o.length&&r.push(`${n.dim(`Capabilities`)} ${o.join(`, `)}`);let s=kr[e.budget]??e.budget,c=Ar[e.qualityPreference]??e.qualityPreference;r.push(``),r.push(`${n.dim(`Budget`)} ${s} ${n.dim(`Quality`)} ${c}`);let l=e.modelPreference;if(l&&l.mode!==`unconstrained`){r.push(``);let e=jr[l.mode]??l.mode,t=[n.dim(`Mode`)+` ${n.yellow(e)}`];l.targets?.length&&t.push(n.dim(`Targets`)+` ${l.targets.join(`, `)}`),l.excludes?.length&&t.push(n.dim(`Excludes`)+` ${l.excludes.join(`, `)}`),r.push(t.join(` `))}if(e.segments?.length){r.push(``),r.push(n.dim(`Pipeline`));for(let[t,i]of e.segments.entries()){let e=i.outputModality.map(e=>Dr[e]??e).join(`, `);r.push(` ${n.dim(`${t+1}.`)} ${i.step}${e?n.dim(` → ${e}`):``}`)}}return $e(r.join(`
|
|
84
|
+
`),{padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:1,right:0},borderColor:`cyan`,borderStyle:`round`,dimBorder:!0})}const Nr=[`Best Pick`,`Runner-Up`,`Alternative`];function Pr(e,t,n){let r=[n.green.bold,n.blue.bold,n.magenta.bold][t]??n.white.bold,i=Nr[t]??`#${t+1}`,a=[];a.push(r(`⬢ #${t+1} — ${i}`)),a.push(``),a.push(`${n.bold(e.name)} ${n.dim(`(${e.model})`)}`),a.push(``),a.push(`${n.cyan(`Why`)} ${e.reason}`),e.highlights.length&&(a.push(``),a.push(e.highlights.map(e=>n.bgGray.white(` ${e} `)).join(` `)));let o=[];e.contextWindow&&o.push(`Context ${Er(e.contextWindow)}`),e.maxOutputTokens&&o.push(`Max Output ${Er(e.maxOutputTokens)}`),o.length&&(a.push(``),a.push(n.dim(o.join(` · `))));let s=c(e.docUrl);return s&&(a.push(``),a.push(n.dim(`Docs ${s}`))),$e(a.join(`
|
|
85
|
+
`),{padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:1,right:0},borderColor:`gray`,borderStyle:`round`,dimBorder:!0})}function Fr(e,t){let n=t?new tt({level:0}):et;return e.map((e,t)=>Pr(e,t,n)).join(`
|
|
86
|
+
`)}function Ir(e,t,n){let r=n?new tt({level:0}):et,i=[];i.push(` ${r.yellow.bold(`⚡ Pipeline`)} ${e}`);for(let[e,{step:n,recommendations:a,warnings:o}]of t.entries()){if(i.push(``),i.push(r.bold(` ━━━ Step ${e+1}: ${n} ━━━`)),o?.length)for(let e of o)i.push(` ${r.yellow(`⚠`)} ${r.yellow(e)}`);i.push(``),i.push(a.map((e,t)=>Pr(e,t,r)).join(`
|
|
87
|
+
`))}return i.join(`
|
|
88
|
+
`)}function Lr(e,t){return e.type===`pipeline`?Ir(e.summary,e.steps,t):Fr(e.recommendations,t)}function Rr(e){return e.type===`pipeline`?e.steps.length===0:e.recommendations.length===0}var zr=f({description:`Recommend the best models for your use case (intent analysis → candidate recall → LLM ranking)`,usageArgs:`<prompt> [flags]`,options:[{flag:`--message <text>`,description:`Describe your requirements (alternative to positional prompt)`},{flag:`--dry-run`,description:`Show intent analysis and candidate list without LLM ranking`},{flag:`--output <format>`,description:`Output format: text (default in TTY), json, yaml`}],exampleArgs:[`--message "I need a visual-understanding chatbot"`,`--message "Build an Agent that auto-generates animations"`,`--message "Legal contract review, high precision required"`,`--message "Low-cost high-concurrency online customer service" --output json`,`--message "Long document summarization" --dry-run`,` # Interactive input`],async run(e,t){let n=t._positional??[],r=t.message||n.join(` `);if(!r.trim())if(S({nonInteractive:e.nonInteractive})){let e=await U({message:`Describe your requirement:`});e||(process.stderr.write(`Cancelled.
|
|
89
|
+
`),process.exit(1)),r=e}else B(`message`,F(e,`"your requirement"`));let i=p(e.output),o={onPrepareStart:()=>process.stderr.write(`Initializing model data...
|
|
90
|
+
`)};process.stderr.write(`Analyzing your request...
|
|
91
|
+
`);let[s,c]=await Promise.all([y(e,o),a(e,r)]);c.confidence===0?process.stderr.write(`Intent analysis timed out, using defaults...
|
|
92
|
+
`):process.stderr.write(`
|
|
93
|
+
`);let l=await le(e,s,r,50,c);if(e.dryRun){z({userInput:r,intent:c,candidateCount:l.length,candidates:l.map(({model:e,score:t})=>({model:e.model,score:t})),top:3},i);return}let u=Ee(`Recommending best models...`);u.start();let d=await ce(e,l,c,r,3);if(u.stop(),Rr(d)){R(`No suitable models found for this request.`);return}if(i!==`text`){z({intent:{taskSummary:c.taskSummary,scenarioHints:c.scenarioHints,complexity:c.complexity,inputModality:c.inputModality,outputModality:c.outputModality,requiredCapabilities:c.requiredCapabilities,budget:c.budget,qualityPreference:c.qualityPreference,modelPreference:c.modelPreference?.mode===`unconstrained`?void 0:c.modelPreference,segments:c.segments},result:d,candidates:l.length},i);return}R(Mr(c,e.noColor)),R(``),R(Lr(d,e.noColor))}});const Br=`zeldaEasy.bailian-dash-workspace.space.listWorkspaces`;function Z(e,t){let n=e[t];if(n&&typeof n==`object`&&!Array.isArray(n))return n}function Vr(e){let t=Z(e,`data`);if(!t)return e;let n=Z(t,`DataV2`);if(n){let e=Z(n,`data`);return(e?Z(e,`data`):void 0)??e??n}return Z(t,`data`)??t}function Hr(e,t){let n=t?e=>e:e=>`\x1b[1m${e}\x1b[0m`,r=t?e=>e:e=>`\x1b[2m${e}\x1b[0m`,i=t?e=>e:e=>`\x1b[32m${e}\x1b[0m`,a=[`Name`,`Workspace ID`,`Default`],o=e.map(e=>[e.agentName,e.workspaceId,e.defaultAgent?`Yes`:`-`]),s=a.map((e,t)=>Math.max(I(e),...o.map(e=>I(e[t])))),c=a.map((e,t)=>n(V(e,s[t]))).join(` `),l=s.map(e=>r(`─`.repeat(e))).join(`──`);process.stdout.write(c+`
|
|
94
|
+
`),process.stdout.write(l+`
|
|
95
|
+
`);for(let e of o){let t=e.map((e,t)=>t===2&&e===`Yes`?i(V(e,s[t])):V(e,s[t]));process.stdout.write(t.join(` `)+`
|
|
96
|
+
`)}process.stdout.write(r(`\nTotal: ${e.length}`)+`
|
|
97
|
+
`)}var Ur=f({description:`List all workspaces`,skipDefaultApiKeySetup:!0,usageArgs:`[flags]`,options:[{flag:`--list <n>`,description:`Limit number of results`},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[``,`--list 5`,`--output json`],async run(e,t){let n=Number(t.list)||0,r=p(e.output),i=await O(e);if(e.dryRun){z({api:Br,data:{}},r);return}let a=Vr(await l(e,i.token,{api:Br,data:{}})).data;if(!Array.isArray(a)||a.length===0){r===`json`?z([],r):process.stdout.write(`No workspace found.
|
|
98
|
+
`);return}let o=a;if(n>0&&(o=o.slice(0,n)),r===`json`){z(o.map(e=>({workspaceId:e.workspaceId,name:e.agentName,default:e.defaultAgent})),r);return}Hr(o,e.noColor)}});const Wr=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`;function Gr(e,t){if(!e)return 0;let n=e.count_limit_period||t;return n?Math.floor(e.count_limit*60/n):0}function Kr(e,t){if(!e)return 0;let n=e.usage_limit_period||t;return n?Math.floor(e.usage_limit*60/n):0}function qr(e){return e.toLocaleString(`en-US`)}function Q(e,t){let n=e[t];if(n&&typeof n==`object`&&!Array.isArray(n))return n}function Jr(e){let t=Q(e,`data`);if(!t)return e;let n=Q(t,`DataV2`);if(n){let e=Q(n,`data`);return(e?Q(e,`data`):void 0)??e??n}return Q(t,`data`)??t}async function Yr(e,t,n){let r=[],i=1;for(;;){let a={pageNo:i,pageSize:50,group:!1,queryQpmInfo:!0,ignoreWorkspaceServiceSite:!0};n&&(a.supports={selfServiceLimitIncrease:!0});let o=Jr(await l(e,t,{api:Wr,data:{input:a}})),s=o.list??[],c=o.total??0;if(r.push(...s),r.length>=c||s.length===0)break;i++}return r}function Xr(e,t){let n=t?e=>e:e=>`\x1b[1m${e}\x1b[0m`,r=t?e=>e:e=>`\x1b[2m${e}\x1b[0m`,i=[`Model`,`Req/min`,`Token/min`,`Max TPM`],a=e.map(e=>{let t=e.qpmInfo,n=t?.[`model-default`],r=t?.[`user-spec`],i=Gr(n),a=Kr(n),o=Gr(r,n?.count_limit_period)||i,s=Kr(r,n?.usage_limit_period)||a,c=a*2;return[e.model,o>0?qr(o):`-`,s>0?qr(s):`-`,c>0?qr(c):`-`]});if(a.length===0){process.stdout.write(`No models found.
|
|
99
|
+
`);return}let o=i.map((e,t)=>Math.max(I(e),...a.map(e=>I(e[t])))),s=i.map((e,t)=>n(V(e,o[t]))).join(` `),c=o.map(e=>r(`─`.repeat(e))).join(`──`);process.stdout.write(s+`
|
|
100
|
+
`),process.stdout.write(c+`
|
|
101
|
+
`);for(let e of a)process.stdout.write(e.map((e,t)=>V(e,o[t])).join(` `)+`
|
|
102
|
+
`);process.stdout.write(r(`\nTotal: ${e.length} models`)+`
|
|
103
|
+
`)}var Zr=f({description:`View model RPM/TPM rate limits`,skipDefaultApiKeySetup:!0,usageArgs:`[--model <model>] [flags]`,options:[{flag:`--model <model>`,description:`Model name(s), comma-separated`},{flag:`--all`,description:`Show all models, not just self-service ones`},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[``,`--model qwen3.6-plus`,`--model qwen3.6-plus,qwen-turbo`,`--all`,`--output json`],async run(e,t){let n=t.model||void 0,r=!!t.all,i=p(e.output);if(e.dryRun){let e={pageNo:1,pageSize:50,group:!1,queryQpmInfo:!0,ignoreWorkspaceServiceSite:!0};r||(e.supports={selfServiceLimitIncrease:!0}),z({api:Wr,data:{input:e}},i);return}let a=await Yr(e,(await O(e)).token,!r);if(n){let e=new Set(n.split(`,`).map(e=>e.trim()).filter(Boolean));a=a.filter(t=>e.has(t.model)),a.length===0&&(process.stderr.write(`Error: no matching models found for "${n}".\n`),process.exit(1))}if(i===`json`){z(a.map(e=>{let t=e.qpmInfo,n=t?.[`model-default`],r=t?.[`user-spec`],i=Gr(n),a=Kr(n),o=Gr(r,n?.count_limit_period)||i,s=Kr(r,n?.usage_limit_period)||a,c=a*2;return{model:e.model,rpm:o>0?o:null,tpm:s>0?s:null,maxTPM:c>0?c:null}}),i);return}Xr(a,e.noColor)}});const Qr=`zeldaEasy.broadscope-platform.modelInstance.updateFoundationModelLimits`;function $r(e,t){if(!e)return 0;let n=e.usage_limit_period||t;return n?Math.floor(e.usage_limit*60/n):0}function $(e,t){let n=e[t];if(n&&typeof n==`object`&&!Array.isArray(n))return n}function ei(e){let t=$(e,`data`);if(!t)return e;let n=$(t,`DataV2`);if(n){let e=$(n,`data`);return(e?$(e,`data`):void 0)??e??n}return $(t,`data`)??t}async function ti(e,t,n){return(ei(await l(e,t,{api:`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,data:{input:{pageNo:1,pageSize:50,name:n,group:!1,queryQpmInfo:!0,ignoreWorkspaceServiceSite:!0,supports:{selfServiceLimitIncrease:!0}}}})).list??[]).find(e=>e.model===n&&e.qpmInfo)}var ni=f({description:`Request a temporary quota increase`,skipDefaultApiKeySetup:!0,usageArgs:`--model <model> --tpm <value> [flags]`,options:[{flag:`--model <model>`,description:`Model name (required)`,required:!0},{flag:`--tpm <value>`,description:`Target TPM value (required)`,required:!0},{flag:`--yes`,description:`Skip downgrade confirmation`},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[`--model qwen-turbo --tpm 100000`,`--model qwen3.6-plus --tpm 8000000 --yes`,`--model qwen-turbo --tpm 100000 --output json`],async run(t,n){let r=n.model;r||(process.stderr.write(`Error: --model is required.
|
|
104
|
+
`),process.exit(1));let i=Number(n.tpm);(!i||i<=0)&&(process.stderr.write(`Error: --tpm must be a positive number.
|
|
105
|
+
`),process.exit(1));let a=!!n.yes||t.yes,o=p(t.output);if(t.dryRun){z({api:Qr,data:{input:{model:r,limit:{usage_limit:i}}}},o);return}let s=await O(t),c=await ti(t,s.token,r);c||(process.stderr.write(`Error: model "${r}" not found or does not support self-service quota increase.\n`),process.stderr.write(`Hint: run \`${t.binName} quota list\` to view available models.\n`),process.exit(1));let u=c.qpmInfo[`model-default`],d=c.qpmInfo[`user-spec`],f=$r(u),m=$r(d,u?.usage_limit_period)||f,h=f*2;(i<f||i>h)&&(process.stderr.write(`Error: TPM value ${i.toLocaleString()} is out of range.\n Current: ${m.toLocaleString()}\n Range: ${f.toLocaleString()} ~ ${h.toLocaleString()}\n`),process.exit(1));let g={input:{model:r,limit:{usage_limit:i},originalQpmInfo:c.qpmInfo}},_=async n=>{n&&(g.input.confirmedDowngrade=!0);try{return await l(t,s.token,{api:Qr,data:g})}catch(n){throw n instanceof e&&n.message.includes(`NotLogined`)&&(process.stderr.write(`Error: session expired. Run \`${t.binName} auth login --console\` to re-authenticate.\n`),process.exit(1)),n}},v=await _(),y=ei(v);if(y.needConfirm){let e=y.confirmCode;e===`Refresh_Required`&&(process.stderr.write(`Error: rate limit has been updated externally. Please retry.
|
|
106
|
+
`),process.exit(1)),e===`Downgrade`&&(a||(process.stderr.write(`Warning: target TPM (${i.toLocaleString()}) is lower than current (${m.toLocaleString()}).\nUse --yes to confirm downgrade.
|
|
107
|
+
`),process.exit(1)),v=await _(!0))}if(o===`json`){z(v,o);return}process.stdout.write(`Quota updated for "${r}": TPM ${m.toLocaleString()} → ${i.toLocaleString()}\n`)}});const ri=`zeldaEasy.broadscope-platform.modelInstance.listModelLimitApplications`;function ii(e,t){let n=e[t];if(n&&typeof n==`object`&&!Array.isArray(n))return n}function ai(e){let t=ii(e,`data`);if(!t)return e;let n=ii(t,`DataV2`);if(n){let e=ii(n,`data`);return(e?ii(e,`data`):void 0)??e??n}return ii(t,`data`)??t}function oi(e){if(!e)return`-`;try{let t=new Date(e);return isNaN(t.getTime())?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)} ${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}catch{return e}}function si(e){return e.toLocaleString(`en-US`)}function ci(e,t,n){let r=t?e=>e:e=>`\x1b[1m${e}\x1b[0m`,i=t?e=>e:e=>`\x1b[2m${e}\x1b[0m`,a=[`Model`,`Token Limit`,`Applied At`],o=e.map(e=>[e.deployedModel,si(e.usageLimit),oi(e.gmtCreate)]),s=a.map((e,t)=>Math.max(I(e),...o.map(e=>I(e[t])))),c=a.map((e,t)=>r(V(e,s[t]))).join(` `),l=s.map(e=>i(`─`.repeat(e))).join(`──`);process.stdout.write(c+`
|
|
108
|
+
`),process.stdout.write(l+`
|
|
109
|
+
`);for(let e of o)process.stdout.write(e.map((e,t)=>V(e,s[t])).join(` `)+`
|
|
110
|
+
`);process.stdout.write(i(`\nTotal: ${n} records`)+`
|
|
111
|
+
`)}var li=f({description:`View quota change history`,skipDefaultApiKeySetup:!0,usageArgs:`[flags]`,options:[{flag:`--page <n>`,description:`Page number (default: 1)`},{flag:`--page-size <n>`,description:`Page size (default: 10)`},{flag:`--model <model>`,description:`Filter by model name`},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[``,`--page 2`,`--page-size 20`,`--model qwen-turbo`,`--output json`],async run(t,n){let r=Number(n.page)||1,i=Number(n.pageSize)||10,a=n.model||void 0,o=p(t.output),s={input:{pageNo:r,pageSize:i}};if(t.dryRun){z({api:ri,data:s},o);return}let c=await O(t),u;try{u=await l(t,c.token,{api:ri,data:s})}catch(n){throw n instanceof e&&n.message.includes(`NotLogined`)&&(process.stderr.write(`Error: session expired. Run \`${t.binName} auth login --console\` to re-authenticate.\n`),process.exit(1)),n}let d=ai(u),f=d.records??[],m=d.items??f.length;if(a&&(f=f.filter(e=>e.deployedModel===a)),o===`json`){z({records:f.map(e=>({model:e.deployedModel,tokenLimit:e.usageLimit,appliedAt:oi(e.gmtCreate)})),total:a?f.length:m},o);return}if(f.length===0){process.stdout.write(`No quota change history found.
|
|
112
|
+
`);return}ci(f,t.noColor,a?f.length:m)}});const ui=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,di=`zeldaEasy.bailian-telemetry.monitor.getMonitorData`;function fi(e,t){if(!e)return 0;let n=e.count_limit_period||t;return n?Math.floor(e.count_limit*60/n):0}function pi(e,t){if(!e)return 0;let n=e.usage_limit_period||t;return n?Math.floor(e.usage_limit*60/n):0}function mi(e){return e.toLocaleString(`en-US`)}function hi(e,t){if(t<=0)return`-`;let n=Math.round(e/t*100);return`${mi(e)}/${mi(t)} (${n}%)`}function gi(e,t){if(t<=0)return`-`;let n=e/t*100;return n>=100?`Rate Limited`:n>=80?`Near limit`:`Normal`}function _i(e,t){let n=e[t];if(n&&typeof n==`object`&&!Array.isArray(n))return n}function vi(e){let t=_i(e,`data`);if(!t)return e;let n=_i(t,`DataV2`);if(n){let e=_i(n,`data`);return(e?_i(e,`data`):void 0)??e??n}return _i(t,`data`)??t}async function yi(e,t){let n=[],r=1;for(;;){let i=vi(await l(e,t,{api:ui,data:{input:{pageNo:r,pageSize:50,group:!1,queryQpmInfo:!0,ignoreWorkspaceServiceSite:!0,supports:{selfServiceLimitIncrease:!0}}}})),a=i.list??[],o=i.total??0;if(n.push(...a),n.length>=o||a.length===0)break;r++}return n}async function bi(e,t,n,r){let i=Date.now(),a=i-r*60*1e3;try{let r=vi(await l(e,t,{api:di,data:{reqDTO:{monitorType:`Advanced`,metricFilters:[{aggMethod:`sum_pm`,metricName:`model_total_amount`},{aggMethod:`sum_pm`,metricName:`model_call_count`}],labelFilters:{resourceId:n,resourceType:`model`},startTime:a,endTime:i}}})),o=r.data??r;if(!Array.isArray(o))return{rpm:0,tpm:0};let s=0,c=0;for(let e of o){if(e.aggMethod!==`sum_pm`||!e.points?.length)continue;let t=e.points[e.points.length-1].value??0;e.metricName===`model_call_count`&&(s=Math.round(t)),e.metricName===`model_total_amount`&&(c=Math.round(t))}return{rpm:s,tpm:c}}catch{return{rpm:-1,tpm:-1}}}function xi(e,t){let n=t?e=>e:e=>`\x1b[1m${e}\x1b[0m`,r=t?e=>e:e=>`\x1b[2m${e}\x1b[0m`,i=t?e=>e:e=>`\x1b[32m${e}\x1b[0m`,a=t?e=>e:e=>`\x1b[33m${e}\x1b[0m`,o=t?e=>e:e=>`\x1b[31m${e}\x1b[0m`,s=[`Model`,`RPM Usage/Limit`,`TPM Usage/Limit`,`Status`],c=e.map(e=>{let t=e.rpmUsage<0?`-`:hi(e.rpmUsage,e.rpmLimit),n=e.tpmUsage<0?`-`:hi(e.tpmUsage,e.tpmLimit),r=Math.max(e.rpmLimit>0?e.rpmUsage/e.rpmLimit*100:0,e.tpmLimit>0?e.tpmUsage/e.tpmLimit*100:0),i=e.rpmUsage<0?`-`:gi(Math.max(e.rpmUsage,e.tpmUsage),Math.max(e.rpmLimit,e.tpmLimit));return{cells:[e.model,t,n,i],maxPct:r}});if(c.length===0){process.stdout.write(`No models found.
|
|
113
|
+
`);return}let l=s.map((e,t)=>Math.max(I(e),...c.map(e=>I(e.cells[t])))),u=s.map((e,t)=>n(V(e,l[t]))).join(` `),d=l.map(e=>r(`─`.repeat(e))).join(`──`);process.stdout.write(u+`
|
|
114
|
+
`),process.stdout.write(d+`
|
|
115
|
+
`);for(let e of c){let t=e.cells.map((e,t)=>{if(t===3){if(e===`Rate Limited`)return o(V(e,l[t]));if(e===`Near limit`)return a(V(e,l[t]));if(e===`Normal`)return i(V(e,l[t]))}return V(e,l[t])});process.stdout.write(t.join(` `)+`
|
|
116
|
+
`)}process.stdout.write(r(`\nTotal: ${e.length} models`)+`
|
|
117
|
+
`)}var Si=f({description:`Check current usage against rate limits`,skipDefaultApiKeySetup:!0,usageArgs:`[--model <model>] [flags]`,options:[{flag:`--model <model>`,description:`Model name(s), comma-separated`},{flag:`--period <minutes>`,description:`Query usage for the last N minutes (default: 2)`},{flag:`--console-region <region>`,description:`Console region`},{flag:`--console-site <site>`,description:`Console site: domestic, international`},{flag:`--console-switch-agent <uid>`,description:`Switch agent UID`,type:`number`}],exampleArgs:[``,`--model qwen3.6-plus`,`--period 5`,`--model qwen3.6-plus,qwen-turbo`,`--output json`],async run(e,t){let n=t.model||void 0,r=Number(t.period)||2;r<1&&(process.stderr.write(`Error: --period must be at least 1 minute.
|
|
118
|
+
`),process.exit(1));let i=r,a=p(e.output);if(e.dryRun){z({apis:[ui,di],...m(e)},a);return}let o=await O(e),s=await yi(e,o.token);if(n){let e=new Set(n.split(`,`).map(e=>e.trim()).filter(Boolean));s=s.filter(t=>e.has(t.model))}if(s=s.filter(e=>e.qpmInfo),s.length===0){process.stdout.write(`No models found.
|
|
119
|
+
`);return}let c=await Promise.all(s.map(t=>bi(e,o.token,t.model,i))),l=s.map((e,t)=>{let n=e.qpmInfo,r=n[`model-default`],i=n[`user-spec`],a=fi(i,r?.count_limit_period)||fi(r),o=pi(i,r?.usage_limit_period)||pi(r);return{model:e.model,rpmUsage:c[t].rpm,rpmLimit:a,tpmUsage:c[t].tpm,tpmLimit:o}});if(a===`json`){z(l,a);return}xi(l,e.noColor)}});export{zr as advisorRecommend,pn as appCall,hn as appList,xt as authLogin,jt as authLogout,kt as authStatus,cn as configSet,rn as configShow,Wn as consoleCall,Un as fileUpload,Kt as imageEdit,Ht as imageGenerate,wn as knowledgeRetrieve,kn as mcpCall,jn as mcpList,Mn as mcpTools,gn as memoryAdd,bn as memoryDelete,vn as memoryList,xn as memoryProfileCreate,Sn as memoryProfileGet,_n as memorySearch,yn as memoryUpdate,br as pipelineRun,Tr as pipelineValidate,Si as quotaCheck,li as quotaHistory,Zr as quotaList,ni as quotaRequest,Nn as searchWeb,Vn as speechRecognize,Rn as speechSynthesize,Nt as textChat,zt as textOmni,fn as update,tr as usageFree,ar as usageFreetier,vr as usageStats,Zt as videoDownload,Jt as videoEdit,qt as videoGenerate,Yt as videoRef,Xt as videoTaskGet,nn as visionDescribe,Ur as workspaceList};
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "bailian-cli-commands",
|
|
3
|
+
"version": "0.0.0-beta-46d8474-20260626",
|
|
4
|
+
"description": "Command library for bailian-cli products (knowledge, memory, media, …). See https://www.npmjs.com/package/bailian-cli for usage.",
|
|
5
|
+
"homepage": "https://bailian.console.aliyun.com/cli",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/modelstudioai/cli/issues"
|
|
8
|
+
},
|
|
9
|
+
"license": "Apache-2.0",
|
|
10
|
+
"author": "Aliyun Model Studio",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/modelstudioai/cli.git",
|
|
14
|
+
"directory": "packages/commands"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"type": "module",
|
|
20
|
+
"types": "./dist/index.d.mts",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": "./dist/index.mjs",
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public",
|
|
27
|
+
"registry": "https://registry.npmjs.org/"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"boxen": "^8.0.1",
|
|
31
|
+
"chalk": "^5.6.2",
|
|
32
|
+
"yaml": "^2.8.3",
|
|
33
|
+
"bailian-cli-runtime": "0.0.0-beta-46d8474-20260626",
|
|
34
|
+
"bailian-cli-core": "0.0.0-beta-46d8474-20260626"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/node": "^24",
|
|
38
|
+
"@typescript/native-preview": "7.0.0-dev.20260328.1",
|
|
39
|
+
"typescript": "^6.0.2",
|
|
40
|
+
"vite-plus": "0.1.22"
|
|
41
|
+
},
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=22.12.0"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "vp pack",
|
|
47
|
+
"dev": "vp pack --watch",
|
|
48
|
+
"test": "vp test",
|
|
49
|
+
"check": "vp check"
|
|
50
|
+
}
|
|
51
|
+
}
|